diff --git a/.yarnrc b/.yarnrc
index 524dcb98eb..f465c5c5e6 100644
--- a/.yarnrc
+++ b/.yarnrc
@@ -5,3 +5,4 @@
registry "https://registry.npmjs.org/"
lastUpdateCheck 1580389148099
yarn-path ".yarn/releases/yarn-1.22.1.js"
+network-timeout 600000
diff --git a/docs/FAQ.md b/docs/FAQ.md
index e38fa84e73..7d568a840e 100644
--- a/docs/FAQ.md
+++ b/docs/FAQ.md
@@ -15,11 +15,11 @@ No, but it can be! Backstage is designed to be a developer portal for all your
infrastructure tooling, services, and documentation. So, it's not a monitoring
platform — but that doesn't mean you can't integrate a monitoring tool into
Backstage by writing
-[a plugin](https://github.com/spotify/backstage/blob/master/docs/FAQ.md#what-is-a-plugin-in-backstage).
+[a plugin](/docs/FAQ.md#what-is-a-plugin-in-backstage).
### How is Backstage licensed?
-Backstage was released as open sourced software by Spotify and is licensed under
+Backstage was released as open source software by Spotify and is licensed under
[Apache License, Version 2.0](http://www.apache.org/licenses/LICENSE-2.0).
### Why did we open source Backstage?
@@ -36,16 +36,16 @@ more, read our blog post,
Yes, we've already started releasing open source versions of some of the plugins
we use here, and we'll continue to do so.
-[Plugins](https://github.com/spotify/faq#what-is-a-plugin-in-backstage) are the
+[Plugins](/docs/FAQ.md#what-is-a-plugin-in-backstage) are the
building blocks of functionality in Backstage. We have over 120 plugins inside
Spotify — many of those are specialized for our use, so will remain internal and
proprietary to us. But we estimate that about a third of our existing plugins
make good open source candidates. (And we'll probably end up writing some brand
-new ones, too.)
+new ones, too.)
### What's the roadmap for Backstage?
- We envision three phases, which you can learn about in
+We envision three phases, which you can learn about in
[our project roadmap](https://github.com/spotify/backstage#project-roadmap).
Even though the open source version of Backstage is relatively new compared to
our internal version, we have already begun work on various aspects of all three
@@ -80,142 +80,138 @@ knew that we would like to use.
It strikes a good balance between power, customizability, and ease of use. A
core focus of Backstage is to make plugin developers productive with as few
hurdles as possible. Material-UI lets plugin makers get going easily with both
-well-known tech and a large flora of components.
+well-known tech and a large flora of components.
### What technology does Backstage use?
- The code base is a large-scale React application that uses TypeScript. For
+The code base is a large-scale React application that uses TypeScript. For
[Phase 2](https://github.com/spotify/backstage#project-roadmap), we plan to use
-Node.js and GraphQL.
+Node.js and GraphQL.
### What is the end-to-end user flow? The happy path story.
- There are three main user profiles for Backstage: the integrator, the
-contributor, and the software engineer. The **integrator** hosts the Backstage
-app and configures which plugins are available to use in the app. The
-**contributor** adds functionality to the app by writing plugins. The
-**software engineer** uses the app's functionality and interacts with its
-plugins.
+There are three main user profiles for Backstage: the integrator, the
+contributor, and the software engineer.
-### What is the use of a "plugin" in Backstage?
+The **integrator** hosts the Backstage app and configures which plugins are available to use in the app.
- A Backstage Plugin adds functionality to Backstage.
+The **contributor** adds functionality to the app by writing plugins.
+The **software engineer** uses the app's functionality and interacts with its plugins.
+
+### What is a "plugin" in Backstage?
+
+Plugins are what provide the feature functionality in Backstage. They are used to integrate different systems into Backstage's frontend, so that the developer gets a consistent UX, no matter what tool or service is being accessed on the other side.
+
+Each plugin is treated as a self-contained web app and can include almost any type of content. Plugins all use a common set of platform APIs and reusable UI components. Plugins can fetch data either from the backend or an API exposed through the proxy.
+
+Learn more about [the different components](https://github.com/spotify/backstage#overview) that make up Backstage.
### Do I have to write plugins in TypeScript?
- No, you can use JavaScript if you prefer. We want to keep the Backstage core
-APIs in TypeScript, but aren't forcing it on individual plugins.
+No, you can use JavaScript if you prefer. We want to keep the Backstage core
+APIs in TypeScript, but aren't forcing it on individual plugins.
### How do I find out if a plugin already exists?
- Before you write a plugin,
+Before you write a plugin,
[search the plugin issues](https://github.com/spotify/backstage/issues?q=is%3Aissue+label%3Aplugin+)
to see if it already exists or is in the works. If no one's thought of it yet,
great! Open a new issue as
[a plugin suggestion](https://github.com/spotify/backstage/issues/new/choose)
and describe what your plugin will do. This will help coordinate our
-contributors' efforts and avoid duplicating existing functionality. In the
+contributors' efforts and avoid duplicating existing functionality. In the
future, we will create
[a plugin gallery](https://github.com/spotify/backstage/issues/260) where people
-can browse and search for all available plugins.
+can browse and search for all available plugins.
### Which plugin is used the most at Spotify?
- By far, our most-used plugin is our TechDocs plugin, which we use for creating
-technical documentation. Our philosophy at Spotify is to treat "docs like code",
-where you write documentation using the same workflow as you write your code.
-This makes it easier to create, find, and update documentation. We hope to
-release
-[the open source version](https://github.com/spotify/backstage/issues/687) in
-the future. (See also:
-"[Will Spotify's internal plugins be open sourced, too?](https://github.com/spotify/faq#will-spotifys-internal-plugins-be-open-sourced-too)"
-above)
+By far, our most-used plugin is our TechDocs plugin, which we use for creating technical documentation. Our philosophy at Spotify is to treat "docs like code", where you write documentation using the same workflow as you write your code. This makes it easier to create, find, and update documentation. We hope to release [the open source version](https://github.com/spotify/backstage/issues/687) in the future. (See also: "[Will Spotify's internal plugins be open sourced, too?](/docs/FAQ.md#will-spotifys-internal-plugins-be-open-sourced-too)" above)
### Are you planning to have plugins baked into the repo? Or should they be developed in separate repos?
- Contributors can add open source plugins to the plugins directory in
+Contributors can add open source plugins to the plugins directory in
[this monorepo](https://github.com/spotify/backstage). Integrators can then
configure which open source plugins are available to use in their instance of
the app. Open source plugins are downloaded as npm packages published in the
-open source repository. While we encourage using the open source model, we
+open source repository. While we encourage using the open source model, we
know there are cases where contributors might want to experiment internally or
keep their plugins closed source. Contributors writing closed source plugins
should develop them in the plugins directory in their own Backstage repository.
-Integrators also configure closed source plugins locally from the monorepo.
+Integrators also configure closed source plugins locally from the monorepo.
### Any plans for integrating with other repository managers, such as GitLab or Bitbucket?
- We chose GitHub because it is the tool that we are most familiar with, so that
+We chose GitHub because it is the tool that we are most familiar with, so that
will naturally lead to integrations for GitHub being developed at an early
-stage. Hosting this project on GitHub does not exclude integrations with
+stage. Hosting this project on GitHub does not exclude integrations with
alternatives, such as
[GitLab](https://github.com/spotify/backstage/issues?q=is%3Aissue+is%3Aopen+GitLab)
or Bitbucket. We believe that in time there will be plugins that will provide
-functionality for these tools as well. Hopefully, contributed by the community!
- Also note, implementations of Backstage can be hosted wherever you feel suits
-your needs best.
+functionality for these tools as well. Hopefully, contributed by the community! Also note, implementations of Backstage can be hosted wherever you feel suits
+your needs best.
### Who maintains Backstage?
- Spotify will maintain the open source core, but we envision different parts of
+Spotify will maintain the open source core, but we envision different parts of
the project being maintained by various companies and contributors. We also
envision a large, diverse ecosystem of open source plugins, which would be
-maintained by their original authors/contributors or by the community. When it
+maintained by their original authors/contributors or by the community. When it
comes to
[deployment](https://github.com/spotify/backstage/blob/master/DEPLOYMENT.md),
the system integrator (typically, the infrastructure team in your organization)
-maintains Backstage in your own environment.
+maintains Backstage in your own environment.
### Does Spotify provide a managed version of Backstage?
- No, this is not a service offering. We build the piece of software, and
+No, this is not a service offering. We build the piece of software, and
someone in your infrastructure team is responsible for
[deploying](https://github.com/spotify/backstage/blob/master/DEPLOYMENT.md) and
-maintaining it.
+maintaining it.
### How secure is Backstage?
- We take security seriously. When it comes to packages and code we scan our
+We take security seriously. When it comes to packages and code we scan our
repositories periodically and update our packages to the latest versions. When
it comes to deployment of Backstage within an organisation it depends on the
deployment and security setup in your organisation. Reach out to us on
[Discord](https://discord.gg/MUpMjP2) if you have specific queries.
Please report sensitive security issues via Spotify's
-[bug-bounty program](https://hackerone.com/spotify) rather than GitHub.
+[bug-bounty program](https://hackerone.com/spotify) rather than GitHub.
### Does Backstage collect any information that is shared with Spotify?
- No. Backstage does not collect any telemetry from any third party using the
+No. Backstage does not collect any telemetry from any third party using the
platform. Spotify, and the open source community, does have access to
[GitHub Insights](https://github.com/features/insights), which contains
-information such as contributors, commits, traffic, and dependencies.
+information such as contributors, commits, traffic, and dependencies.
Backstage is an open platform, but you are in control of your own data. You
control who has access to any data you provide to your version of Backstage and
-who that data is shared with.
+who that data is shared with.
### Can Backstage be used to build something other than a developer portal?
- Yes. The core frontend framework could be used for building any large-scale
+Yes. The core frontend framework could be used for building any large-scale
web application where (1) multiple teams are building separate parts of the app,
-and (2) you want the overall experience to be consistent. That being said, in
+and (2) you want the overall experience to be consistent. That being said, in
[Phase 2](https://github.com/spotify/backstage#project-roadmap) of the project
we will add features that are needed for developer portals and systems for
-managing software ecosystems. Our ambition will be to keep Backstage modular.
+managing software ecosystems. Our ambition will be to keep Backstage modular.
### How can I get involved?
- Jump right in! Come help us fix some of the
+Jump right in! Come help us fix some of the
[early bugs and first issues](https://github.com/spotify/backstage/labels/good%20first%20issue)
or reach [a new milestone](https://github.com/spotify/backstage/milestones). Or
write an open source plugin for Backstage, like this
[Lighthouse plugin](https://github.com/spotify/backstage/tree/master/plugins/lighthouse).
- See all the ways you can
+See all the ways you can
[contribute here](https://github.com/spotify/backstage/blob/master/CONTRIBUTING.md).
-We'd love to have you as part of the community.
+We'd love to have you as part of the community.
### Can I join the Backstage team?
- If you're interested in being part of the Backstage team, reach out to
+If you're interested in being part of the Backstage team, reach out to
[fossopportunities@spotify.com](mailto:fossopportunities@spotify.com)
diff --git a/docs/auth/README.md b/docs/auth/README.md
index 081d10add6..9809f57168 100644
--- a/docs/auth/README.md
+++ b/docs/auth/README.md
@@ -80,7 +80,7 @@ sign-in methods.
More details are provided in dedicated sections of the documentation.
-- [OAuth](./oauth): Description of the generic OAuth flow implemented by the
+- [OAuth](./oauth.md): Description of the generic OAuth flow implemented by the
[auth-backend](../../plugins/auth-backend).
-- [Glossary](./glossary): Glossary of some common terms related to the auth
+- [Glossary](./glossary.md): Glossary of some common terms related to the auth
flows.
diff --git a/packages/app/src/App.tsx b/packages/app/src/App.tsx
index f4515cbf01..ccaeb2828b 100644
--- a/packages/app/src/App.tsx
+++ b/packages/app/src/App.tsx
@@ -31,7 +31,7 @@ const app = createApp({
plugins: Object.values(plugins),
components: {
SignInPage: props => (
-
+
),
},
});
diff --git a/packages/app/src/apis.ts b/packages/app/src/apis.ts
index 5011b16eaf..d2b2706464 100644
--- a/packages/app/src/apis.ts
+++ b/packages/app/src/apis.ts
@@ -26,10 +26,12 @@ import {
FeatureFlags,
GoogleAuth,
GithubAuth,
+ OktaAuth,
oauthRequestApiRef,
OAuthRequestManager,
googleAuthApiRef,
githubAuthApiRef,
+ oktaAuthApiRef,
storageApiRef,
WebStorage,
} from '@backstage/core';
@@ -91,6 +93,15 @@ export const apis = (config: ConfigApi) => {
}),
);
+ builder.add(
+ oktaAuthApiRef,
+ OktaAuth.create({
+ apiOrigin: 'http://localhost:7000',
+ basePath: '/auth/',
+ oauthRequestApi,
+ }),
+ );
+
builder.add(
techRadarApiRef,
new TechRadar({
diff --git a/packages/backend/Dockerfile b/packages/backend/Dockerfile
new file mode 100644
index 0000000000..3e8ba36cec
--- /dev/null
+++ b/packages/backend/Dockerfile
@@ -0,0 +1,9 @@
+FROM node:12
+
+WORKDIR /usr/src/app
+
+COPY . .
+
+RUN yarn install --frozen-lockfile --production
+
+CMD ["node", "packages/backend"]
diff --git a/packages/backend/package.json b/packages/backend/package.json
index 3be1f5ee3e..64ca2c3113 100644
--- a/packages/backend/package.json
+++ b/packages/backend/package.json
@@ -10,6 +10,7 @@
},
"scripts": {
"build": "backstage-cli backend:build",
+ "build-image": "backstage-cli backend:build-image example-backend",
"start": "backstage-cli backend:dev",
"lint": "backstage-cli lint",
"test": "backstage-cli test",
diff --git a/packages/cli/src/commands/backend/build.ts b/packages/cli/src/commands/backend/build.ts
index a9cdc51fa9..ceca5b0286 100644
--- a/packages/cli/src/commands/backend/build.ts
+++ b/packages/cli/src/commands/backend/build.ts
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-import { buildPackage, Output } from '../../lib/packager';
+import { buildPackage, Output } from '../../lib/builder';
export default async () => {
await buildPackage({
diff --git a/packages/cli/src/commands/backend/buildImage.ts b/packages/cli/src/commands/backend/buildImage.ts
new file mode 100644
index 0000000000..a847f1ef54
--- /dev/null
+++ b/packages/cli/src/commands/backend/buildImage.ts
@@ -0,0 +1,39 @@
+/*
+ * Copyright 2020 Spotify AB
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import fs from 'fs-extra';
+import { createDistWorkspace } from '../../lib/packager';
+import { paths } from '../../lib/paths';
+import { run } from '../../lib/run';
+
+export default async (imageTag: string) => {
+ const tempDistWorkspace = await createDistWorkspace(['example-backend'], {
+ files: [
+ 'package.json',
+ 'yarn.lock',
+ 'app-config.yaml',
+ { src: paths.resolveTarget('Dockerfile'), dest: 'Dockerfile' },
+ ],
+ });
+
+ console.log(`Dist workspace ready at ${tempDistWorkspace}`);
+
+ await run('docker', ['build', '.', '-t', imageTag], {
+ cwd: tempDistWorkspace,
+ });
+
+ await fs.remove(tempDistWorkspace);
+};
diff --git a/packages/cli/src/commands/build.ts b/packages/cli/src/commands/build.ts
index 19e4b17352..bd5bbc5e9f 100644
--- a/packages/cli/src/commands/build.ts
+++ b/packages/cli/src/commands/build.ts
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-import { buildPackage, Output } from '../lib/packager';
+import { buildPackage, Output } from '../lib/builder';
import { Command } from 'commander';
export default async (cmd: Command) => {
diff --git a/packages/cli/src/commands/pack.ts b/packages/cli/src/commands/pack.ts
index 51c7e36086..1f81b89767 100644
--- a/packages/cli/src/commands/pack.ts
+++ b/packages/cli/src/commands/pack.ts
@@ -19,10 +19,15 @@ import { paths } from '../lib/paths';
const SKIPPED_KEYS = ['access', 'registry', 'tag'];
-export const pre = async () => {
- const pkgPath = paths.resolveTarget('package.json');
+const PKG_PATH = 'package.json';
+const PKG_BACKUP_PATH = 'package.json-prepack';
- const pkg = await fs.readJson(pkgPath);
+export const pre = async () => {
+ const pkgPath = paths.resolveTarget(PKG_PATH);
+
+ const pkgContent = await fs.readFile(pkgPath, 'utf8');
+ const pkg = JSON.parse(pkgContent);
+ await fs.writeFile(PKG_BACKUP_PATH, pkgContent);
for (const key of Object.keys(pkg.publishConfig ?? {})) {
if (!SKIPPED_KEYS.includes(key)) {
@@ -33,5 +38,6 @@ export const pre = async () => {
};
export const post = async () => {
- // postpack is a noop for now, since it's not called anyway
+ // postpack isn't called by yarn right now, so it needs to be called manually
+ await fs.move(PKG_BACKUP_PATH, PKG_PATH, { overwrite: true });
};
diff --git a/packages/cli/src/commands/plugin/build.ts b/packages/cli/src/commands/plugin/build.ts
index 7e4e5cd36a..d62ffbeebd 100644
--- a/packages/cli/src/commands/plugin/build.ts
+++ b/packages/cli/src/commands/plugin/build.ts
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-import { buildPackage, Output } from '../../lib/packager';
+import { buildPackage, Output } from '../../lib/builder';
export default async () => {
await buildPackage({
diff --git a/packages/cli/src/index.ts b/packages/cli/src/index.ts
index e67a52c795..bed32bcf8b 100644
--- a/packages/cli/src/index.ts
+++ b/packages/cli/src/index.ts
@@ -46,6 +46,15 @@ const main = (argv: string[]) => {
.description('Build a backend plugin')
.action(lazyAction(() => import('./commands/backend/build'), 'default'));
+ program
+ .command('backend:build-image ')
+ .description(
+ 'Builds a docker image from the package, with all local deps included',
+ )
+ .action(
+ lazyAction(() => import('./commands/backend/buildImage'), 'default'),
+ );
+
program
.command('backend:dev')
.description('Start local development server with HMR for the backend')
diff --git a/packages/cli/src/lib/packager/config.ts b/packages/cli/src/lib/builder/config.ts
similarity index 100%
rename from packages/cli/src/lib/packager/config.ts
rename to packages/cli/src/lib/builder/config.ts
diff --git a/packages/cli/src/lib/builder/index.ts b/packages/cli/src/lib/builder/index.ts
new file mode 100644
index 0000000000..17aae25ec4
--- /dev/null
+++ b/packages/cli/src/lib/builder/index.ts
@@ -0,0 +1,19 @@
+/*
+ * Copyright 2020 Spotify AB
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+export { buildPackage } from './packager';
+export { Output } from './types';
+export type { BuildOptions } from './types';
diff --git a/packages/cli/src/lib/packager/packager.ts b/packages/cli/src/lib/builder/packager.ts
similarity index 100%
rename from packages/cli/src/lib/packager/packager.ts
rename to packages/cli/src/lib/builder/packager.ts
diff --git a/packages/cli/src/lib/packager/types.ts b/packages/cli/src/lib/builder/types.ts
similarity index 100%
rename from packages/cli/src/lib/packager/types.ts
rename to packages/cli/src/lib/builder/types.ts
diff --git a/packages/cli/src/lib/packager/index.ts b/packages/cli/src/lib/packager/index.ts
index 17aae25ec4..5e309ab953 100644
--- a/packages/cli/src/lib/packager/index.ts
+++ b/packages/cli/src/lib/packager/index.ts
@@ -14,6 +14,133 @@
* limitations under the License.
*/
-export { buildPackage } from './packager';
-export { Output } from './types';
-export type { BuildOptions } from './types';
+import fs from 'fs-extra';
+import { resolve as resolvePath, relative as relativePath } from 'path';
+import { paths } from '../paths';
+import { run } from '../run';
+import tar from 'tar';
+import { tmpdir } from 'os';
+
+type LernaPackage = {
+ name: string;
+ private: boolean;
+ location: string;
+ scripts: Record;
+};
+
+type FileEntry =
+ | string
+ | {
+ src: string;
+ dest: string;
+ };
+
+type Options = {
+ /**
+ * Target directory for the dist workspace, defaults to a temporary directory
+ */
+ targetDir?: string;
+
+ /**
+ * Files to copy into the target workspace.
+ *
+ * Defaults to ['yarn.lock', 'package.json'].
+ */
+ files?: FileEntry[];
+};
+
+/**
+ * Uses `yarn pack` to package local packages and unpacks them into a dist workspace.
+ * The target workspace will end up containing dist version of each package and
+ * will be suitable for packaging e.g. into a docker image.
+ *
+ * This creates a structure that is functionally similar to if the packages where
+ * installed from NPM, but uses yarn workspaces to link to them at runtime.
+ */
+export async function createDistWorkspace(
+ packageNames: string[],
+ options: Options,
+) {
+ const targetDir =
+ options.targetDir ??
+ (await fs.mkdtemp(resolvePath(tmpdir(), 'dist-workspace')));
+
+ const targets = await findTargetPackages(packageNames);
+
+ await moveToDistWorkspace(targetDir, targets);
+
+ const files: FileEntry[] = options.files ?? ['yarn.lock', 'package.json'];
+
+ for (const file of files) {
+ const src = typeof file === 'string' ? file : file.src;
+ const dest = typeof file === 'string' ? file : file.dest;
+ await fs.copy(paths.resolveTargetRoot(src), resolvePath(targetDir, dest));
+ }
+ return targetDir;
+}
+
+async function moveToDistWorkspace(
+ workspaceDir: string,
+ localPackages: LernaPackage[],
+): Promise {
+ await Promise.all(
+ localPackages.map(async (target, index) => {
+ console.log(`Repacking ${target.name} into dist workspace`);
+ const archive = `temp-package-${index}.tgz`;
+ const archivePath = resolvePath(workspaceDir, archive);
+
+ await run('yarn', ['pack', '--filename', archivePath], {
+ cwd: target.location,
+ });
+ // TODO(Rugvip): yarn pack doesn't call postpack, once the bug is fixed this can be removed
+ if (target.scripts.postpack) {
+ await run('yarn', ['postpack'], { cwd: target.location });
+ }
+
+ const outputDir = relativePath(paths.targetRoot, target.location);
+ const absoluteOutputPath = resolvePath(workspaceDir, outputDir);
+ await fs.ensureDir(absoluteOutputPath);
+
+ await tar.extract({
+ file: archivePath,
+ cwd: absoluteOutputPath,
+ strip: 1,
+ });
+ await fs.remove(archivePath);
+ }),
+ );
+}
+
+async function findTargetPackages(pkgNames: string[]): Promise {
+ const LernaProject = require('@lerna/project');
+ const PackageGraph = require('@lerna/package-graph');
+
+ const project = new LernaProject(paths.targetDir);
+ const packages = await project.getPackages();
+ const graph = new PackageGraph(packages);
+
+ const targets = new Map();
+ const searchNames = pkgNames.slice();
+
+ while (searchNames.length) {
+ const name = searchNames.pop()!;
+
+ if (targets.has(name)) {
+ continue;
+ }
+
+ const node = graph.get(name);
+ if (!node) {
+ throw new Error(`Package '${name}' not found`);
+ }
+
+ const pkgDeps = Object.keys(node.pkg.dependencies);
+ const localDeps: string[] = Array.from(node.localDependencies.keys());
+ const filteredDeps = localDeps.filter(dep => pkgDeps.includes(dep));
+
+ searchNames.push(...filteredDeps);
+ targets.set(name, node.pkg);
+ }
+
+ return Array.from(targets.values());
+}
diff --git a/packages/core-api/src/apis/definitions/auth.ts b/packages/core-api/src/apis/definitions/auth.ts
index d5c0e9c0a4..a944e85a7e 100644
--- a/packages/core-api/src/apis/definitions/auth.ts
+++ b/packages/core-api/src/apis/definitions/auth.ts
@@ -233,3 +233,20 @@ export const githubAuthApiRef = createApiRef<
id: 'core.auth.github',
description: 'Provides authentication towards Github APIs',
});
+
+/**
+ * Provides authentication towards Okta APIs.
+ *
+ * See https://developer.okta.com/docs/guides/implement-oauth-for-okta/scopes/
+ * for a full list of supported scopes.
+ */
+export const oktaAuthApiRef = createApiRef<
+ OAuthApi &
+ OpenIdConnectApi &
+ ProfileInfoApi &
+ BackstageIdentityApi &
+ SessionStateApi
+>({
+ id: 'core.auth.okta',
+ description: 'Provides authentication towards Okta APIs',
+});
diff --git a/packages/core-api/src/apis/implementations/auth/index.ts b/packages/core-api/src/apis/implementations/auth/index.ts
index f13368b5c4..4fa992dfb5 100644
--- a/packages/core-api/src/apis/implementations/auth/index.ts
+++ b/packages/core-api/src/apis/implementations/auth/index.ts
@@ -16,3 +16,4 @@
export * from './google';
export * from './github';
+export * from './okta';
diff --git a/packages/core-api/src/apis/implementations/auth/okta/OktaAuth.test.ts b/packages/core-api/src/apis/implementations/auth/okta/OktaAuth.test.ts
new file mode 100644
index 0000000000..ab6c46c9b4
--- /dev/null
+++ b/packages/core-api/src/apis/implementations/auth/okta/OktaAuth.test.ts
@@ -0,0 +1,129 @@
+/*
+ * Copyright 2020 Spotify AB
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+import OktaAuth from './OktaAuth';
+
+const theFuture = new Date(Date.now() + 3600000);
+const thePast = new Date(Date.now() - 10);
+
+const PREFIX = 'okta.';
+
+describe('OktaAuth', () => {
+ it('should get refreshed access token', async () => {
+ const getSession = jest.fn().mockResolvedValue({
+ providerInfo: { accessToken: 'access-token', expiresAt: theFuture },
+ });
+ const oktaAuth = new OktaAuth({ getSession } as any);
+
+ expect(await oktaAuth.getAccessToken()).toBe('access-token');
+ expect(getSession).toBeCalledTimes(1);
+ });
+
+ it('should get refreshed id token', async () => {
+ const getSession = jest.fn().mockResolvedValue({
+ providerInfo: { idToken: 'id-token', expiresAt: theFuture },
+ });
+ const oktaAuth = new OktaAuth({ getSession } as any);
+
+ expect(await oktaAuth.getIdToken()).toBe('id-token');
+ expect(getSession).toBeCalledTimes(1);
+ });
+
+ it('should get optional id token', async () => {
+ const getSession = jest.fn().mockResolvedValue({
+ providerInfo: { idToken: 'id-token', expiresAt: theFuture },
+ });
+ const oktaAuth = new OktaAuth({ getSession } as any);
+
+ expect(await oktaAuth.getIdToken({ optional: true })).toBe('id-token');
+ expect(getSession).toBeCalledTimes(1);
+ });
+
+ it('should share popup closed errors', async () => {
+ const error = new Error('NOPE');
+ error.name = 'RejectedError';
+ const getSession = jest
+ .fn()
+ .mockResolvedValueOnce({
+ providerInfo: {
+ accessToken: 'access-token',
+ expiresAt: theFuture,
+ scopes: new Set([`not-a-scope`]),
+ },
+ })
+ .mockRejectedValue(error);
+ const oktaAuth = new OktaAuth({ getSession } as any);
+
+ // Make sure we have a session before we do the double request, so that we get past the !this.currentSession check
+ await expect(oktaAuth.getAccessToken()).resolves.toBe('access-token');
+
+ const promise1 = oktaAuth.getAccessToken('more');
+ const promise2 = oktaAuth.getAccessToken('more');
+ await expect(promise1).rejects.toBe(error);
+ await expect(promise2).rejects.toBe(error);
+ expect(getSession).toBeCalledTimes(3);
+ });
+
+ it('should wait for all session refreshes', async () => {
+ const initialSession = {
+ providerInfo: {
+ idToken: 'token1',
+ expiresAt: theFuture,
+ scopes: new Set(),
+ },
+ };
+ const getSession = jest
+ .fn()
+ .mockResolvedValueOnce(initialSession)
+ .mockResolvedValue({
+ providerInfo: {
+ idToken: 'token2',
+ expiresAt: theFuture,
+ scopes: new Set(),
+ },
+ });
+ const oktaAuth = new OktaAuth({ getSession } as any);
+
+ // Grab the expired session first
+ await expect(oktaAuth.getIdToken()).resolves.toBe('token1');
+ expect(getSession).toBeCalledTimes(1);
+
+ initialSession.providerInfo.expiresAt = thePast;
+
+ const promise1 = oktaAuth.getIdToken();
+ const promise2 = oktaAuth.getIdToken();
+ const promise3 = oktaAuth.getIdToken();
+ await expect(promise1).resolves.toBe('token2');
+ await expect(promise2).resolves.toBe('token2');
+ await expect(promise3).resolves.toBe('token2');
+ expect(getSession).toBeCalledTimes(4); // De-duping of session requests happens in client
+ });
+
+ it.each([
+ ['openid', ['openid']],
+ ['profile email', ['profile', 'email']],
+ [`${PREFIX}groups.manage`, [`${PREFIX}groups.manage`]],
+ ['groups.read', [`${PREFIX}groups.read`]],
+ [`${PREFIX}groups.manage groups.read, openid`, [`${PREFIX}groups.manage`, `${PREFIX}groups.read`, 'openid']],
+ [`email\t ${PREFIX}groups.read`, ['email', `${PREFIX}groups.read`]],
+
+ // Some incorrect scopes that we don't try to fix
+ [`${PREFIX}email`, [`${PREFIX}email`]],
+ [`${PREFIX}profile`, [`${PREFIX}profile`]],
+ [`${PREFIX}openid`, [`${PREFIX}openid`]],
+ ])(`should normalize scopes correctly - %p`, (scope, scopes) => {
+ expect(OktaAuth.normalizeScopes(scope)).toEqual(new Set(scopes));
+ });
+});
diff --git a/packages/core-api/src/apis/implementations/auth/okta/OktaAuth.ts b/packages/core-api/src/apis/implementations/auth/okta/OktaAuth.ts
new file mode 100644
index 0000000000..f10ec4ebce
--- /dev/null
+++ b/packages/core-api/src/apis/implementations/auth/okta/OktaAuth.ts
@@ -0,0 +1,186 @@
+/*
+ * Copyright 2020 Spotify AB
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import OktaIcon from '@material-ui/icons/AcUnit';
+import { DefaultAuthConnector } from '../../../../lib/AuthConnector';
+import { OktaSession } from './types';
+import {
+ OAuthApi,
+ OpenIdConnectApi,
+ ProfileInfoApi,
+ ProfileInfo,
+ SessionStateApi,
+ SessionState,
+ BackstageIdentityApi,
+ AuthRequestOptions,
+ BackstageIdentity,
+} from '../../../definitions/auth';
+import { OAuthRequestApi, AuthProvider } from '../../../definitions';
+import { SessionManager } from '../../../../lib/AuthSessionManager/types';
+import { RefreshingAuthSessionManager } from '../../../../lib/AuthSessionManager';
+import { Observable } from '../../../../types';
+
+type CreateOptions = {
+ apiOrigin: string;
+ basePath: string;
+
+ oauthRequestApi: OAuthRequestApi;
+
+ environment?: string;
+ provider?: AuthProvider & { id: string };
+};
+
+export type OktaAuthResponse = {
+ providerInfo: {
+ accessToken: string;
+ idToken: string;
+ scope: string;
+ expiresInSeconds: number;
+ };
+ profile: ProfileInfo;
+ backstageIdentity: BackstageIdentity;
+};
+
+const DEFAULT_PROVIDER = {
+ id: 'okta',
+ title: 'Okta',
+ icon: OktaIcon,
+};
+
+const OKTA_OIDC_SCOPES: Set = new Set(
+ ['openid', 'profile', 'email', 'phone', 'address', 'groups', 'offline_access']
+)
+
+const OKTA_SCOPE_PREFIX: string = 'okta.'
+
+class OktaAuth implements
+ OAuthApi,
+ OpenIdConnectApi,
+ ProfileInfoApi,
+ BackstageIdentityApi,
+ SessionStateApi
+{
+ static create({
+ apiOrigin,
+ basePath,
+ environment = 'development',
+ provider = DEFAULT_PROVIDER,
+ oauthRequestApi,
+ }: CreateOptions) {
+ const connector = new DefaultAuthConnector({
+ apiOrigin,
+ basePath,
+ environment,
+ provider,
+ oauthRequestApi: oauthRequestApi,
+ sessionTransform(res: OktaAuthResponse): OktaSession {
+ return {
+ ...res,
+ providerInfo: {
+ idToken: res.providerInfo.idToken,
+ accessToken: res.providerInfo.accessToken,
+ scopes: OktaAuth.normalizeScopes(res.providerInfo.scope),
+ expiresAt: new Date(
+ Date.now() + res.providerInfo.expiresInSeconds * 1000,
+ ),
+ },
+ };
+ },
+ });
+
+ const sessionManager = new RefreshingAuthSessionManager({
+ connector,
+ defaultScopes: new Set([
+ 'openid',
+ 'email',
+ 'profile',
+ 'offline_access',
+ ]),
+ sessionScopes: session => session.scopes,
+ sessionShouldRefresh: session => {
+ const expiresInSec =
+ (session.providerInfo.expiresAt.getTime() - Date.now()) / 1000;
+ return expiresInSec < 60 * 5;
+ },
+ });
+
+ return new OktaAuth(sessionManager);
+ }
+
+ sessionState$(): Observable {
+ return this.sessionManager.sessionState$();
+ }
+
+ constructor(private readonly sessionManager: SessionManager) {}
+
+ async getAccessToken(
+ scope?: string,
+ options?: AuthRequestOptions
+ ) {
+ const session = await this.sessionManager.getSession({
+ ...options,
+ scopes: OktaAuth.normalizeScopes(scope),
+ });
+ return session?.providerInfo.accessToken ?? '';
+ }
+
+ async getIdToken(options: AuthRequestOptions = {}) {
+ const session = await this.sessionManager.getSession(options);
+ return session?.providerInfo.idToken ?? '';
+ }
+
+ async logout() {
+ await this.sessionManager.removeSession();
+ }
+
+ async getBackstageIdentity(
+ options: AuthRequestOptions = {},
+ ): Promise {
+ const session = await this.sessionManager.getSession(options);
+ return session?.backstageIdentity;
+ }
+
+ async getProfile(options: AuthRequestOptions = {}) {
+ const session = await this.sessionManager.getSession(options);
+ return session?.profile;
+ }
+
+ static normalizeScopes(scopes?: string | string[]): Set {
+ if (!scopes) {
+ return new Set();
+ }
+
+ const scopeList = Array.isArray(scopes)
+ ? scopes
+ : scopes.split(/[\s|,]/).filter(Boolean);
+
+ const normalizedScopes = scopeList.map(scope => {
+ if (OKTA_OIDC_SCOPES.has(scope)) {
+ return scope;
+ }
+
+ if (scope.startsWith(OKTA_SCOPE_PREFIX)) {
+ return scope;
+ }
+
+ return `${OKTA_SCOPE_PREFIX}${scope}`
+ });
+
+ return new Set(normalizedScopes);
+ }
+}
+
+export default OktaAuth;
\ No newline at end of file
diff --git a/packages/core-api/src/apis/implementations/auth/okta/index.ts b/packages/core-api/src/apis/implementations/auth/okta/index.ts
new file mode 100644
index 0000000000..2bef0ce0db
--- /dev/null
+++ b/packages/core-api/src/apis/implementations/auth/okta/index.ts
@@ -0,0 +1,18 @@
+/*
+ * Copyright 2020 Spotify AB
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+export * from './types';
+export { default as OktaAuth } from './OktaAuth';
diff --git a/packages/core-api/src/apis/implementations/auth/okta/types.ts b/packages/core-api/src/apis/implementations/auth/okta/types.ts
new file mode 100644
index 0000000000..e3392ba1d6
--- /dev/null
+++ b/packages/core-api/src/apis/implementations/auth/okta/types.ts
@@ -0,0 +1,27 @@
+/*
+ * Copyright 2020 Spotify AB
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+import { ProfileInfo, BackstageIdentity } from '../../../definitions';
+
+export type OktaSession = {
+ providerInfo: {
+ idToken: string;
+ accessToken: string;
+ scopes: Set;
+ expiresAt: Date;
+ };
+ profile: ProfileInfo;
+ backstageIdentity: BackstageIdentity;
+};
diff --git a/packages/core/src/layout/Sidebar/UserSettings.tsx b/packages/core/src/layout/Sidebar/UserSettings.tsx
index 36e8e1088b..668cb1354a 100644
--- a/packages/core/src/layout/Sidebar/UserSettings.tsx
+++ b/packages/core/src/layout/Sidebar/UserSettings.tsx
@@ -23,6 +23,7 @@ import {
googleAuthApiRef,
githubAuthApiRef,
identityApiRef,
+ oktaAuthApiRef,
useApi,
} from '@backstage/core-api';
import {
@@ -56,6 +57,11 @@ export function SidebarUserSettings() {
apiRef={githubAuthApiRef}
icon={Star}
/>
+ {
+ const oktaAuthApi = useApi(oktaAuthApiRef);
+ const errorApi = useApi(errorApiRef);
+
+ const handleLogin = async () => {
+ try {
+ const identity = await oktaAuthApi.getBackstageIdentity({
+ instantPopup: true,
+ });
+
+ const profile = await oktaAuthApi.getProfile();
+
+ onResult({
+ userId: identity!.id,
+ profile: profile!,
+ getIdToken: () =>
+ oktaAuthApi.getBackstageIdentity().then(i => i!.idToken),
+ logout: async () => {
+ await oktaAuthApi.logout();
+ },
+ });
+ } catch (error) {
+ errorApi.post(error);
+ }
+ };
+
+ return (
+
+
+ Sign In
+
+ }
+ >
+ Sign In using Okta
+
+
+ );
+};
+
+const loader: ProviderLoader = async apis => {
+ const oktaAuthApi = apis.get(oktaAuthApiRef)!;
+
+ const identity = await oktaAuthApi.getBackstageIdentity({
+ optional: true,
+ });
+
+ if (!identity) {
+ return undefined;
+ }
+
+ const profile = await oktaAuthApi.getProfile();
+
+ return {
+ userId: identity.id,
+ profile: profile!,
+ getIdToken: () =>
+ oktaAuthApi.getBackstageIdentity().then(i => i!.idToken),
+ logout: async () => {
+ await oktaAuthApi.logout();
+ },
+ };
+};
+
+export const oktaProvider: SignInProvider = { Component, loader };
\ No newline at end of file
diff --git a/packages/core/src/layout/SignInPage/providers.tsx b/packages/core/src/layout/SignInPage/providers.tsx
index 96dbc30a89..a195b2042a 100644
--- a/packages/core/src/layout/SignInPage/providers.tsx
+++ b/packages/core/src/layout/SignInPage/providers.tsx
@@ -18,6 +18,7 @@ import React, { useLayoutEffect, useState, useMemo, useCallback } from 'react';
import { guestProvider } from './guestProvider';
import { googleProvider } from './googleProvider';
import { customProvider } from './customProvider';
+import { oktaProvider } from './oktaProvider';
import {
SignInPageProps,
SignInResult,
@@ -30,12 +31,13 @@ import { SignInProvider } from './types';
const PROVIDER_STORAGE_KEY = '@backstage/core:SignInPage:provider';
// Separate list here to avoid exporting internal types
-export type SignInProviderId = 'guest' | 'google' | 'custom';
+export type SignInProviderId = 'guest' | 'google' | 'custom' | 'okta';
const signInProviders: { [id in SignInProviderId]: SignInProvider } = {
guest: guestProvider,
google: googleProvider,
custom: customProvider,
+ okta: oktaProvider,
};
export const useSignInProviders = (
diff --git a/packages/storybook/.storybook/apis.js b/packages/storybook/.storybook/apis.js
index 3b61ae7af8..0d0cf74e8f 100644
--- a/packages/storybook/.storybook/apis.js
+++ b/packages/storybook/.storybook/apis.js
@@ -6,11 +6,13 @@ import {
OAuthRequestManager,
googleAuthApiRef,
githubAuthApiRef,
+ oktaAuthApiRef,
AlertApiForwarder,
ErrorApiForwarder,
ErrorAlerter,
GoogleAuth,
GithubAuth,
+ OktaAuth,
identityApiRef,
} from '@backstage/core';
@@ -50,4 +52,13 @@ builder.add(
}),
);
+builder.add(
+ oktaAuthApiRef,
+ OktaAuth.create({
+ apiOrigin: 'http://localhost:7000',
+ basePath: '/auth/',
+ oauthRequestApi,
+ }),
+);
+
export const apis = builder.build();
diff --git a/plugins/auth-backend/package.json b/plugins/auth-backend/package.json
index 2de098c7eb..a336441dc2 100644
--- a/plugins/auth-backend/package.json
+++ b/plugins/auth-backend/package.json
@@ -40,6 +40,8 @@
"passport": "^0.4.1",
"passport-github2": "^0.1.12",
"passport-google-oauth20": "^2.0.0",
+ "passport-oauth2": "^1.5.0",
+ "passport-okta-oauth": "^0.0.1",
"passport-saml": "^1.3.3",
"uuid": "^8.0.0",
"winston": "^3.2.1",
@@ -57,6 +59,7 @@
"jest-fetch-mock": "^3.0.3"
},
"files": [
- "dist"
+ "dist",
+ "migrations"
]
}
diff --git a/plugins/auth-backend/src/providers/factories.ts b/plugins/auth-backend/src/providers/factories.ts
index 5096b0698a..9feefdac9f 100644
--- a/plugins/auth-backend/src/providers/factories.ts
+++ b/plugins/auth-backend/src/providers/factories.ts
@@ -18,6 +18,7 @@ import Router from 'express-promise-router';
import { createGithubProvider } from './github';
import { createGoogleProvider } from './google';
import { createSamlProvider } from './saml';
+import { createOktaProvider } from './okta';
import { AuthProviderFactory, AuthProviderConfig } from './types';
import { Logger } from 'winston';
import { TokenIssuer } from '../identity';
@@ -26,6 +27,7 @@ const factories: { [providerId: string]: AuthProviderFactory } = {
google: createGoogleProvider,
github: createGithubProvider,
saml: createSamlProvider,
+ okta: createOktaProvider,
};
export const createAuthProviderRouter = (
diff --git a/plugins/auth-backend/src/providers/okta/index.ts b/plugins/auth-backend/src/providers/okta/index.ts
new file mode 100644
index 0000000000..bc32601ac2
--- /dev/null
+++ b/plugins/auth-backend/src/providers/okta/index.ts
@@ -0,0 +1,16 @@
+/*
+ * Copyright 2020 Spotify AB
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+export { createOktaProvider } from './provider';
diff --git a/plugins/auth-backend/src/providers/okta/provider.ts b/plugins/auth-backend/src/providers/okta/provider.ts
new file mode 100644
index 0000000000..e73843bb0c
--- /dev/null
+++ b/plugins/auth-backend/src/providers/okta/provider.ts
@@ -0,0 +1,213 @@
+/*
+ * Copyright 2020 Spotify AB
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+import express from 'express';
+import { OAuthProvider } from '../../lib/OAuthProvider';
+import { Strategy as OktaStrategy } from 'passport-okta-oauth';
+import passport from 'passport';
+import {
+ executeFrameHandlerStrategy,
+ executeRedirectStrategy,
+ executeRefreshTokenStrategy,
+ makeProfileInfo,
+ executeFetchUserProfileStrategy,
+} from '../../lib/PassportStrategyHelper';
+import {
+ OAuthProviderHandlers,
+ RedirectInfo,
+ AuthProviderConfig,
+ EnvironmentProviderConfig,
+ OAuthProviderOptions,
+ OAuthProviderConfig,
+ OAuthResponse,
+ PassportDoneCallback,
+} from '../types';
+import {
+ EnvironmentHandler,
+ EnvironmentHandlers,
+} from '../../lib/EnvironmentHandler';
+import { Logger } from 'winston';
+import { StateStore } from 'passport-oauth2';
+import { TokenIssuer } from '../../identity';
+
+type PrivateInfo = {
+ refreshToken: string;
+};
+
+export class OktaAuthProvider implements OAuthProviderHandlers {
+
+ private readonly _strategy: any;
+
+ /**
+ * Due to passport-okta-oauth forcing options.state = true,
+ * passport-oauth2 requires express-session to be installed
+ * so that the 'state' parameter of the oauth2 flow can be stored.
+ * This implementation of StateStore matches the NullStore found within
+ * passport-oauth2, which is the StateStore implementation used when options.state = false,
+ * allowing us to avoid using express-session in order to integrate with Okta.
+ */
+ private _store: StateStore = {
+ store(_req: express.Request, cb: any) {
+ cb(null, null);
+ },
+ verify(_req: express.Request, _state: string, cb: any) {
+ cb(null, true);
+ },
+ }
+
+ constructor(options: OAuthProviderOptions) {
+ this._strategy = new OktaStrategy({
+ passReqToCallback: false as true,
+ ...options,
+ store: this._store,
+ response_type: 'code',
+ }, (
+ accessToken: any,
+ refreshToken: any,
+ params: any,
+ rawProfile: passport.Profile,
+ done: PassportDoneCallback,
+ ) => {
+ const profile = makeProfileInfo(rawProfile, params.id_token);
+
+ done(
+ undefined,
+ {
+ providerInfo: {
+ idToken: params.id_token,
+ accessToken,
+ scope: params.scope,
+ expiresInSeconds: params.expires_in,
+ },
+ profile,
+ },
+ {
+ refreshToken,
+ },
+ )
+ });
+ }
+
+ async start(
+ req: express.Request,
+ options: Record
+ ): Promise {
+ const providerOptions = {
+ ...options,
+ accessType: 'offline',
+ prompt: 'consent',
+ };
+ return await executeRedirectStrategy(req, this._strategy, providerOptions);
+ }
+
+ async handler(
+ req: express.Request
+ ): Promise<{ response: OAuthResponse; refreshToken: string }> {
+ const { response, privateInfo } = await executeFrameHandlerStrategy<
+ OAuthResponse,
+ PrivateInfo
+ >(req, this._strategy);
+
+ return {
+ response: await this.populateIdentity(response),
+ refreshToken: privateInfo.refreshToken,
+ };
+ }
+
+ async refresh(refreshToken: string, scope: string): Promise {
+ const { accessToken, params } = await executeRefreshTokenStrategy(
+ this._strategy,
+ refreshToken,
+ scope,
+ );
+
+ const profile = await executeFetchUserProfileStrategy(
+ this._strategy,
+ accessToken,
+ params.id_token,
+ );
+
+ return this.populateIdentity({
+ providerInfo: {
+ accessToken,
+ idToken: params.id_token,
+ expiresInSeconds: params.expires_in,
+ scope: params.scope,
+ },
+ profile,
+ });
+
+ }
+
+ private async populateIdentity(
+ response: OAuthResponse,
+ ): Promise {
+ const { profile } = response;
+
+ if (!profile.email) {
+ throw new Error('Okta profile contained no email');
+ }
+
+ // TODO(Rugvip): Hardcoded to the local part of the email for now
+ const id = profile.email.split('@')[0];
+
+ return { ...response, backstageIdentity: { id } };
+ }
+}
+
+export function createOktaProvider(
+ { baseUrl }: AuthProviderConfig,
+ providerConfig: EnvironmentProviderConfig,
+ logger: Logger,
+ tokenIssuer: TokenIssuer,
+) {
+ const envProviders: EnvironmentHandlers = {};
+
+ for (const [env, envConfig] of Object.entries(providerConfig)) {
+ const config = (envConfig as unknown) as OAuthProviderConfig;
+ const { secure, appOrigin } = config;
+ const callbackURLParam = `?env=${env}`;
+ const opts = {
+ audience: config.audience,
+ clientID: config.clientId,
+ clientSecret: config.clientSecret,
+ callbackURL: `${baseUrl}/okta/handler/frame${callbackURLParam}`,
+ };
+
+ if (!opts.clientID || !opts.clientSecret || !opts.audience) {
+ if (process.env.NODE_ENV !== 'development') {
+ throw new Error(
+ 'Failed to initialize Okta auth provider, set AUTH_OKTA_CLIENT_ID, AUTH_OKTA_CLIENT_SECRET, and AUTH_OKTA_AUDIENCE env vars',
+ );
+ }
+
+ logger.warn(
+ 'Okta auth provider disabled, set AUTH_OKTA_CLIENT_ID, AUTH_OKTA_CLIENT_SECRET, and AUTH_OKTA_AUDIENCE env vars to enable',
+ );
+ continue;
+ }
+
+ envProviders[env] = new OAuthProvider(new OktaAuthProvider(opts), {
+ disableRefresh: false,
+ providerId: 'okta',
+ secure,
+ baseUrl,
+ appOrigin,
+ tokenIssuer,
+ });
+ }
+
+ return new EnvironmentHandler(envProviders);
+}
diff --git a/plugins/auth-backend/src/providers/okta/types.d.ts b/plugins/auth-backend/src/providers/okta/types.d.ts
new file mode 100644
index 0000000000..bed6d24043
--- /dev/null
+++ b/plugins/auth-backend/src/providers/okta/types.d.ts
@@ -0,0 +1,22 @@
+/*
+ * Copyright 2020 Spotify AB
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+declare module 'passport-okta-oauth' {
+
+ export class Strategy {
+ constructor(options: any, verify: any)
+ }
+}
+
\ No newline at end of file
diff --git a/plugins/auth-backend/src/providers/types.ts b/plugins/auth-backend/src/providers/types.ts
index 56d4db79fa..aec4f9dfd0 100644
--- a/plugins/auth-backend/src/providers/types.ts
+++ b/plugins/auth-backend/src/providers/types.ts
@@ -55,6 +55,10 @@ export type OAuthProviderConfig = {
* Client Secret of the auth provider.
*/
clientSecret: string;
+ /**
+ * The location of the OAuth Authorization Server
+ */
+ audience?: string;
};
export type EnvironmentProviderConfig = {
diff --git a/plugins/auth-backend/src/service/router.ts b/plugins/auth-backend/src/service/router.ts
index 28718e85a1..b9c0ff4496 100644
--- a/plugins/auth-backend/src/service/router.ts
+++ b/plugins/auth-backend/src/service/router.ts
@@ -82,6 +82,15 @@ export async function createRouter(
issuer: 'passport-saml',
},
},
+ okta: {
+ development: {
+ appOrigin: 'http://localhost:3000',
+ secure: false,
+ clientId: process.env.AUTH_OKTA_CLIENT_ID!,
+ clientSecret: process.env.AUTH_OKTA_CLIENT_SECRET!,
+ audience: process.env.AUTH_OKTA_AUDIENCE,
+ }
+ }
},
},
};
diff --git a/plugins/scaffolder-backend/sample-templates/react-ssr-template/template.yaml b/plugins/scaffolder-backend/sample-templates/react-ssr-template/template.yaml
index 6834f0d1b6..124d1575ce 100644
--- a/plugins/scaffolder-backend/sample-templates/react-ssr-template/template.yaml
+++ b/plugins/scaffolder-backend/sample-templates/react-ssr-template/template.yaml
@@ -4,6 +4,10 @@ metadata:
name: react-ssr-template
title: React SSR Template
description: Next.js application skeleton for creating isomorphic web applications.
+ tags:
+ - Recommended
+ - React
spec:
- type: cookiecutter
+ processor: cookiecutter
+ type: website
path: '.'
diff --git a/plugins/scaffolder-backend/sample-templates/springboot-template/template.yaml b/plugins/scaffolder-backend/sample-templates/springboot-template/template.yaml
new file mode 100644
index 0000000000..681e8e7f51
--- /dev/null
+++ b/plugins/scaffolder-backend/sample-templates/springboot-template/template.yaml
@@ -0,0 +1,13 @@
+apiVersion: backstage.io/v1alpha1
+kind: Template
+metadata:
+ name: springboot-template
+ title: Spring Boot Service
+ description: Standard Spring Boot (Java) microservice with recommended configuration.
+ tags:
+ - Recommended
+ - Java
+spec:
+ processor: cookiecutter
+ type: service
+ path: '.'
diff --git a/plugins/scaffolder-backend/scripts/mock-data b/plugins/scaffolder-backend/scripts/mock-data
index be3fa2b6cf..594bd76607 100755
--- a/plugins/scaffolder-backend/scripts/mock-data
+++ b/plugins/scaffolder-backend/scripts/mock-data
@@ -1,8 +1,12 @@
#!/usr/bin/env bash
-curl \
---location \
---request POST 'localhost:7000/catalog/locations' \
---header 'Content-Type: application/json' \
---data-raw "{\"type\": \"file\", \"target\": \"$(pwd)/sample-templates/react-ssr-template/template.yaml\"}"
-
+for URL in \
+ 'react-ssr-template' \
+ 'springboot-template' \
+; do \
+ curl \
+ --location \
+ --request POST 'localhost:7000/catalog/locations' \
+ --header 'Content-Type: application/json' \
+ --data-raw "{\"type\": \"file\", \"target\": \"$(pwd)/sample-templates/${URL}/template.yaml\"}"
+done
diff --git a/plugins/scaffolder/package.json b/plugins/scaffolder/package.json
index 65322c31d6..1bccd6a738 100644
--- a/plugins/scaffolder/package.json
+++ b/plugins/scaffolder/package.json
@@ -21,6 +21,8 @@
"clean": "backstage-cli clean"
},
"dependencies": {
+ "@backstage/catalog-model": "^0.1.1-alpha.12",
+ "@backstage/plugin-catalog": "^0.1.1-alpha.12",
"@backstage/core": "^0.1.1-alpha.12",
"@backstage/theme": "^0.1.1-alpha.12",
"@material-ui/core": "^4.9.1",
@@ -29,7 +31,8 @@
"react": "^16.13.1",
"react-dom": "^16.13.1",
"react-router-dom": "6.0.0-alpha.5",
- "react-use": "^14.2.0"
+ "react-use": "^14.2.0",
+ "swr": "^0.2.2"
},
"devDependencies": {
"@backstage/cli": "^0.1.1-alpha.12",
diff --git a/plugins/scaffolder/src/components/ScaffolderPage/index.tsx b/plugins/scaffolder/src/components/ScaffolderPage/index.tsx
index d675b59f52..2f9774757b 100644
--- a/plugins/scaffolder/src/components/ScaffolderPage/index.tsx
+++ b/plugins/scaffolder/src/components/ScaffolderPage/index.tsx
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-import React from 'react';
+import React, { useEffect } from 'react';
import {
Lifecycle,
Content,
@@ -23,33 +23,39 @@ import {
SupportButton,
Page,
pageTheme,
+ useApi,
+ errorApiRef,
} from '@backstage/core';
-import { Button, Grid, Link, Typography } from '@material-ui/core';
+import { catalogApiRef } from '@backstage/plugin-catalog';
+import {
+ Typography,
+ Link,
+ Button,
+ Grid,
+ LinearProgress,
+} from '@material-ui/core';
import { Link as RouterLink } from 'react-router-dom';
import TemplateCard from '../TemplateCard';
+import useStaleWhileRevalidate from 'swr';
+import { TemplateEntityV1alpha1 } from '@backstage/catalog-model';
-// TODO(blam): Connect to backend
-const STATIC_DATA = [
- {
- id: 'springboot-template',
- type: 'service',
- name: 'Spring Boot Service',
- tags: ['Recommended', 'Java'],
- description:
- 'Standard Spring Boot (Java) microservice with recommended configuration.',
- ownerId: 'spotify',
- },
- {
- id: 'react-ssr-template',
- type: 'website',
- name: 'SSR React Website',
- tags: ['Recommended', 'React'],
- description:
- 'Next.js application skeleton for creating isomorphic web applications.',
- ownerId: 'spotify',
- },
-];
const ScaffolderPage: React.FC<{}> = () => {
+ const catalogApi = useApi(catalogApiRef);
+ const errorApi = useApi(errorApiRef);
+
+ const { data: templates, isValidating, error } = useStaleWhileRevalidate(
+ 'templates/all',
+ async () =>
+ catalogApi.getEntities({ kind: 'Template' }) as Promise<
+ TemplateEntityV1alpha1[]
+ >,
+ );
+
+ useEffect(() => {
+ if (!error) return;
+ errorApi.post(error);
+ }, [error, errorApi]);
+
return (
= () => {
.
+ {!templates && isValidating && }
- {STATIC_DATA.map(item => {
- return (
-
- );
- })}
+ {templates &&
+ templates.map(template => {
+ return (
+
+
+
+ );
+ })}
diff --git a/plugins/scaffolder/src/components/TemplateCard.tsx b/plugins/scaffolder/src/components/TemplateCard.tsx
index 56d8907f7b..6d47f05693 100644
--- a/plugins/scaffolder/src/components/TemplateCard.tsx
+++ b/plugins/scaffolder/src/components/TemplateCard.tsx
@@ -14,14 +14,7 @@
* limitations under the License.
*/
import React, { FC } from 'react';
-import {
- Button,
- Card,
- Chip,
- Grid,
- Typography,
- makeStyles,
-} from '@material-ui/core';
+import { Button, Card, Chip, Typography, makeStyles } from '@material-ui/core';
const useStyles = makeStyles(theme => ({
header: {
@@ -59,25 +52,23 @@ const TemplateCard: FC = ({
const classes = useStyles();
return (
-
-
-