@backstage/plugin-auth-backend 0.24.0-next.1 → 0.24.0-next.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +31 -0
- package/dist/authPlugin.cjs.js.map +1 -1
- package/dist/database/AuthDatabase.cjs.js.map +1 -1
- package/dist/identity/DatabaseKeyStore.cjs.js.map +1 -1
- package/dist/identity/FirestoreKeyStore.cjs.js.map +1 -1
- package/dist/identity/KeyStores.cjs.js.map +1 -1
- package/dist/identity/MemoryKeyStore.cjs.js.map +1 -1
- package/dist/identity/StaticKeyStore.cjs.js.map +1 -1
- package/dist/identity/StaticTokenIssuer.cjs.js.map +1 -1
- package/dist/identity/TokenFactory.cjs.js.map +1 -1
- package/dist/identity/UserInfoDatabaseHandler.cjs.js.map +1 -1
- package/dist/identity/router.cjs.js.map +1 -1
- package/dist/lib/catalog/CatalogIdentityClient.cjs.js.map +1 -1
- package/dist/lib/flow/authFlowHelpers.cjs.js.map +1 -1
- package/dist/lib/legacy/adaptLegacyOAuthHandler.cjs.js.map +1 -1
- package/dist/lib/legacy/adaptLegacyOAuthSignInResolver.cjs.js.map +1 -1
- package/dist/lib/legacy/adaptOAuthSignInResolverToLegacy.cjs.js.map +1 -1
- package/dist/lib/oauth/OAuthAdapter.cjs.js.map +1 -1
- package/dist/lib/oauth/helpers.cjs.js.map +1 -1
- package/dist/lib/passport/PassportStrategyHelper.cjs.js.map +1 -1
- package/dist/lib/resolvers/CatalogAuthResolverContext.cjs.js.map +1 -1
- package/dist/providers/atlassian/provider.cjs.js.map +1 -1
- package/dist/providers/auth0/provider.cjs.js.map +1 -1
- package/dist/providers/aws-alb/provider.cjs.js.map +1 -1
- package/dist/providers/azure-easyauth/provider.cjs.js.map +1 -1
- package/dist/providers/bitbucket/provider.cjs.js.map +1 -1
- package/dist/providers/bitbucketServer/provider.cjs.js.map +1 -1
- package/dist/providers/cloudflare-access/provider.cjs.js.map +1 -1
- package/dist/providers/createAuthProviderIntegration.cjs.js.map +1 -1
- package/dist/providers/gcp-iap/provider.cjs.js.map +1 -1
- package/dist/providers/github/provider.cjs.js.map +1 -1
- package/dist/providers/gitlab/provider.cjs.js.map +1 -1
- package/dist/providers/google/provider.cjs.js.map +1 -1
- package/dist/providers/microsoft/provider.cjs.js.map +1 -1
- package/dist/providers/oauth2/provider.cjs.js.map +1 -1
- package/dist/providers/oauth2-proxy/provider.cjs.js.map +1 -1
- package/dist/providers/oidc/provider.cjs.js.map +1 -1
- package/dist/providers/okta/provider.cjs.js.map +1 -1
- package/dist/providers/onelogin/provider.cjs.js.map +1 -1
- package/dist/providers/providers.cjs.js.map +1 -1
- package/dist/providers/resolvers.cjs.js.map +1 -1
- package/dist/providers/router.cjs.js.map +1 -1
- package/dist/providers/saml/provider.cjs.js.map +1 -1
- package/dist/service/readBackstageTokenExpiration.cjs.js.map +1 -1
- package/dist/service/router.cjs.js.map +1 -1
- package/package.json +25 -25
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,36 @@
|
|
|
1
1
|
# @backstage/plugin-auth-backend
|
|
2
2
|
|
|
3
|
+
## 0.24.0-next.2
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- Updated dependencies
|
|
8
|
+
- @backstage/catalog-client@1.8.0-next.1
|
|
9
|
+
- @backstage/plugin-auth-node@0.5.4-next.2
|
|
10
|
+
- @backstage/plugin-catalog-node@1.14.0-next.2
|
|
11
|
+
- @backstage/backend-plugin-api@1.0.2-next.2
|
|
12
|
+
- @backstage/catalog-model@1.7.0
|
|
13
|
+
- @backstage/config@1.2.0
|
|
14
|
+
- @backstage/errors@1.2.4
|
|
15
|
+
- @backstage/types@1.1.1
|
|
16
|
+
- @backstage/plugin-auth-backend-module-atlassian-provider@0.3.2-next.2
|
|
17
|
+
- @backstage/plugin-auth-backend-module-auth0-provider@0.1.2-next.2
|
|
18
|
+
- @backstage/plugin-auth-backend-module-aws-alb-provider@0.3.0-next.2
|
|
19
|
+
- @backstage/plugin-auth-backend-module-azure-easyauth-provider@0.2.2-next.2
|
|
20
|
+
- @backstage/plugin-auth-backend-module-bitbucket-provider@0.2.2-next.2
|
|
21
|
+
- @backstage/plugin-auth-backend-module-bitbucket-server-provider@0.1.2-next.2
|
|
22
|
+
- @backstage/plugin-auth-backend-module-cloudflare-access-provider@0.3.2-next.2
|
|
23
|
+
- @backstage/plugin-auth-backend-module-gcp-iap-provider@0.3.2-next.2
|
|
24
|
+
- @backstage/plugin-auth-backend-module-github-provider@0.2.2-next.2
|
|
25
|
+
- @backstage/plugin-auth-backend-module-gitlab-provider@0.2.2-next.2
|
|
26
|
+
- @backstage/plugin-auth-backend-module-google-provider@0.2.2-next.2
|
|
27
|
+
- @backstage/plugin-auth-backend-module-microsoft-provider@0.2.2-next.2
|
|
28
|
+
- @backstage/plugin-auth-backend-module-oauth2-provider@0.3.2-next.2
|
|
29
|
+
- @backstage/plugin-auth-backend-module-oauth2-proxy-provider@0.2.2-next.2
|
|
30
|
+
- @backstage/plugin-auth-backend-module-oidc-provider@0.3.2-next.2
|
|
31
|
+
- @backstage/plugin-auth-backend-module-okta-provider@0.1.2-next.2
|
|
32
|
+
- @backstage/plugin-auth-backend-module-onelogin-provider@0.2.2-next.2
|
|
33
|
+
|
|
3
34
|
## 0.24.0-next.1
|
|
4
35
|
|
|
5
36
|
### Patch Changes
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"authPlugin.cjs.js","sources":["../src/authPlugin.ts"],"sourcesContent":["/*\n * Copyright 2023 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n coreServices,\n createBackendPlugin,\n} from '@backstage/backend-plugin-api';\nimport {\n authOwnershipResolutionExtensionPoint,\n AuthOwnershipResolver,\n AuthProviderFactory,\n authProvidersExtensionPoint,\n} from '@backstage/plugin-auth-node';\nimport { catalogServiceRef } from '@backstage/plugin-catalog-node/alpha';\nimport { createRouter } from './service/router';\n\n/**\n * Auth plugin\n *\n * @public\n */\nexport const authPlugin = createBackendPlugin({\n pluginId: 'auth',\n register(reg) {\n const providers = new Map<string, AuthProviderFactory>();\n let ownershipResolver: AuthOwnershipResolver | undefined = undefined;\n\n reg.registerExtensionPoint(authProvidersExtensionPoint, {\n registerProvider({ providerId, factory }) {\n if (providers.has(providerId)) {\n throw new Error(\n `Auth provider '${providerId}' was already registered`,\n );\n }\n providers.set(providerId, factory);\n },\n });\n\n reg.registerExtensionPoint(authOwnershipResolutionExtensionPoint, {\n setAuthOwnershipResolver(resolver) {\n if (ownershipResolver) {\n throw new Error('Auth ownership resolver is already set');\n }\n ownershipResolver = resolver;\n },\n });\n\n reg.registerInit({\n deps: {\n httpRouter: coreServices.httpRouter,\n logger: coreServices.logger,\n config: coreServices.rootConfig,\n database: coreServices.database,\n discovery: coreServices.discovery,\n auth: coreServices.auth,\n httpAuth: coreServices.httpAuth,\n catalogApi: catalogServiceRef,\n },\n async init({\n httpRouter,\n logger,\n config,\n database,\n discovery,\n auth,\n httpAuth,\n catalogApi,\n }) {\n const router = await createRouter({\n logger,\n config,\n database,\n discovery,\n auth,\n httpAuth,\n catalogApi,\n providerFactories: Object.fromEntries(providers),\n disableDefaultProviderFactories: true,\n ownershipResolver,\n });\n httpRouter.addAuthPolicy({\n path: '/',\n allow: 'unauthenticated',\n });\n httpRouter.use(router);\n },\n });\n },\n});\n"],"names":["createBackendPlugin","authProvidersExtensionPoint","authOwnershipResolutionExtensionPoint","coreServices","catalogServiceRef","router","createRouter"],"mappings":";;;;;;;AAkCO,MAAM,aAAaA,oCAAoB,CAAA;AAAA,EAC5C,QAAU,EAAA,MAAA;AAAA,EACV,SAAS,GAAK,EAAA;AACZ,IAAM,MAAA,SAAA,uBAAgB,GAAiC,EAAA
|
|
1
|
+
{"version":3,"file":"authPlugin.cjs.js","sources":["../src/authPlugin.ts"],"sourcesContent":["/*\n * Copyright 2023 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n coreServices,\n createBackendPlugin,\n} from '@backstage/backend-plugin-api';\nimport {\n authOwnershipResolutionExtensionPoint,\n AuthOwnershipResolver,\n AuthProviderFactory,\n authProvidersExtensionPoint,\n} from '@backstage/plugin-auth-node';\nimport { catalogServiceRef } from '@backstage/plugin-catalog-node/alpha';\nimport { createRouter } from './service/router';\n\n/**\n * Auth plugin\n *\n * @public\n */\nexport const authPlugin = createBackendPlugin({\n pluginId: 'auth',\n register(reg) {\n const providers = new Map<string, AuthProviderFactory>();\n let ownershipResolver: AuthOwnershipResolver | undefined = undefined;\n\n reg.registerExtensionPoint(authProvidersExtensionPoint, {\n registerProvider({ providerId, factory }) {\n if (providers.has(providerId)) {\n throw new Error(\n `Auth provider '${providerId}' was already registered`,\n );\n }\n providers.set(providerId, factory);\n },\n });\n\n reg.registerExtensionPoint(authOwnershipResolutionExtensionPoint, {\n setAuthOwnershipResolver(resolver) {\n if (ownershipResolver) {\n throw new Error('Auth ownership resolver is already set');\n }\n ownershipResolver = resolver;\n },\n });\n\n reg.registerInit({\n deps: {\n httpRouter: coreServices.httpRouter,\n logger: coreServices.logger,\n config: coreServices.rootConfig,\n database: coreServices.database,\n discovery: coreServices.discovery,\n auth: coreServices.auth,\n httpAuth: coreServices.httpAuth,\n catalogApi: catalogServiceRef,\n },\n async init({\n httpRouter,\n logger,\n config,\n database,\n discovery,\n auth,\n httpAuth,\n catalogApi,\n }) {\n const router = await createRouter({\n logger,\n config,\n database,\n discovery,\n auth,\n httpAuth,\n catalogApi,\n providerFactories: Object.fromEntries(providers),\n disableDefaultProviderFactories: true,\n ownershipResolver,\n });\n httpRouter.addAuthPolicy({\n path: '/',\n allow: 'unauthenticated',\n });\n httpRouter.use(router);\n },\n });\n },\n});\n"],"names":["createBackendPlugin","authProvidersExtensionPoint","authOwnershipResolutionExtensionPoint","coreServices","catalogServiceRef","router","createRouter"],"mappings":";;;;;;;AAkCO,MAAM,aAAaA,oCAAoB,CAAA;AAAA,EAC5C,QAAU,EAAA,MAAA;AAAA,EACV,SAAS,GAAK,EAAA;AACZ,IAAM,MAAA,SAAA,uBAAgB,GAAiC,EAAA;AACvD,IAAA,IAAI,iBAAuD,GAAA,KAAA,CAAA;AAE3D,IAAA,GAAA,CAAI,uBAAuBC,0CAA6B,EAAA;AAAA,MACtD,gBAAiB,CAAA,EAAE,UAAY,EAAA,OAAA,EAAW,EAAA;AACxC,QAAI,IAAA,SAAA,CAAU,GAAI,CAAA,UAAU,CAAG,EAAA;AAC7B,UAAA,MAAM,IAAI,KAAA;AAAA,YACR,kBAAkB,UAAU,CAAA,wBAAA;AAAA,WAC9B;AAAA;AAEF,QAAU,SAAA,CAAA,GAAA,CAAI,YAAY,OAAO,CAAA;AAAA;AACnC,KACD,CAAA;AAED,IAAA,GAAA,CAAI,uBAAuBC,oDAAuC,EAAA;AAAA,MAChE,yBAAyB,QAAU,EAAA;AACjC,QAAA,IAAI,iBAAmB,EAAA;AACrB,UAAM,MAAA,IAAI,MAAM,wCAAwC,CAAA;AAAA;AAE1D,QAAoB,iBAAA,GAAA,QAAA;AAAA;AACtB,KACD,CAAA;AAED,IAAA,GAAA,CAAI,YAAa,CAAA;AAAA,MACf,IAAM,EAAA;AAAA,QACJ,YAAYC,6BAAa,CAAA,UAAA;AAAA,QACzB,QAAQA,6BAAa,CAAA,MAAA;AAAA,QACrB,QAAQA,6BAAa,CAAA,UAAA;AAAA,QACrB,UAAUA,6BAAa,CAAA,QAAA;AAAA,QACvB,WAAWA,6BAAa,CAAA,SAAA;AAAA,QACxB,MAAMA,6BAAa,CAAA,IAAA;AAAA,QACnB,UAAUA,6BAAa,CAAA,QAAA;AAAA,QACvB,UAAY,EAAAC;AAAA,OACd;AAAA,MACA,MAAM,IAAK,CAAA;AAAA,QACT,UAAA;AAAA,QACA,MAAA;AAAA,QACA,MAAA;AAAA,QACA,QAAA;AAAA,QACA,SAAA;AAAA,QACA,IAAA;AAAA,QACA,QAAA;AAAA,QACA;AAAA,OACC,EAAA;AACD,QAAM,MAAAC,QAAA,GAAS,MAAMC,mBAAa,CAAA;AAAA,UAChC,MAAA;AAAA,UACA,MAAA;AAAA,UACA,QAAA;AAAA,UACA,SAAA;AAAA,UACA,IAAA;AAAA,UACA,QAAA;AAAA,UACA,UAAA;AAAA,UACA,iBAAA,EAAmB,MAAO,CAAA,WAAA,CAAY,SAAS,CAAA;AAAA,UAC/C,+BAAiC,EAAA,IAAA;AAAA,UACjC;AAAA,SACD,CAAA;AACD,QAAA,UAAA,CAAW,aAAc,CAAA;AAAA,UACvB,IAAM,EAAA,GAAA;AAAA,UACN,KAAO,EAAA;AAAA,SACR,CAAA;AACD,QAAA,UAAA,CAAW,IAAID,QAAM,CAAA;AAAA;AACvB,KACD,CAAA;AAAA;AAEL,CAAC;;;;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"AuthDatabase.cjs.js","sources":["../../src/database/AuthDatabase.ts"],"sourcesContent":["/*\n * Copyright 2023 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n DatabaseManager,\n PluginDatabaseManager,\n} from '@backstage/backend-common';\nimport { resolvePackagePath } from '@backstage/backend-plugin-api';\nimport { ConfigReader } from '@backstage/config';\nimport { Knex } from 'knex';\n\nconst migrationsDir = resolvePackagePath(\n '@backstage/plugin-auth-backend',\n 'migrations',\n);\n\n/**\n * Ensures that a database connection is established exactly once and only when\n * asked for, and runs migrations.\n */\nexport class AuthDatabase {\n readonly #database: PluginDatabaseManager;\n #promise: Promise<Knex> | undefined;\n\n static create(database: PluginDatabaseManager): AuthDatabase {\n return new AuthDatabase(database);\n }\n\n /** @internal */\n static forTesting(): AuthDatabase {\n const config = new ConfigReader({\n backend: {\n database: {\n client: 'better-sqlite3',\n connection: ':memory:',\n useNullAsDefault: true,\n },\n },\n });\n const database = DatabaseManager.fromConfig(config).forPlugin('auth');\n return new AuthDatabase(database);\n }\n\n static async runMigrations(knex: Knex): Promise<void> {\n await knex.migrate.latest({\n directory: migrationsDir,\n });\n }\n\n private constructor(database: PluginDatabaseManager) {\n this.#database = database;\n }\n\n get(): Promise<Knex> {\n this.#promise ??= this.#database.getClient().then(async client => {\n if (!this.#database.migrations?.skip) {\n await AuthDatabase.runMigrations(client);\n }\n return client;\n });\n\n return this.#promise;\n }\n}\n"],"names":["resolvePackagePath","config","ConfigReader","DatabaseManager"],"mappings":";;;;;;AAwBA,MAAM,aAAgB,GAAAA,mCAAA;AAAA,EACpB,gCAAA;AAAA,EACA
|
|
1
|
+
{"version":3,"file":"AuthDatabase.cjs.js","sources":["../../src/database/AuthDatabase.ts"],"sourcesContent":["/*\n * Copyright 2023 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n DatabaseManager,\n PluginDatabaseManager,\n} from '@backstage/backend-common';\nimport { resolvePackagePath } from '@backstage/backend-plugin-api';\nimport { ConfigReader } from '@backstage/config';\nimport { Knex } from 'knex';\n\nconst migrationsDir = resolvePackagePath(\n '@backstage/plugin-auth-backend',\n 'migrations',\n);\n\n/**\n * Ensures that a database connection is established exactly once and only when\n * asked for, and runs migrations.\n */\nexport class AuthDatabase {\n readonly #database: PluginDatabaseManager;\n #promise: Promise<Knex> | undefined;\n\n static create(database: PluginDatabaseManager): AuthDatabase {\n return new AuthDatabase(database);\n }\n\n /** @internal */\n static forTesting(): AuthDatabase {\n const config = new ConfigReader({\n backend: {\n database: {\n client: 'better-sqlite3',\n connection: ':memory:',\n useNullAsDefault: true,\n },\n },\n });\n const database = DatabaseManager.fromConfig(config).forPlugin('auth');\n return new AuthDatabase(database);\n }\n\n static async runMigrations(knex: Knex): Promise<void> {\n await knex.migrate.latest({\n directory: migrationsDir,\n });\n }\n\n private constructor(database: PluginDatabaseManager) {\n this.#database = database;\n }\n\n get(): Promise<Knex> {\n this.#promise ??= this.#database.getClient().then(async client => {\n if (!this.#database.migrations?.skip) {\n await AuthDatabase.runMigrations(client);\n }\n return client;\n });\n\n return this.#promise;\n }\n}\n"],"names":["resolvePackagePath","config","ConfigReader","DatabaseManager"],"mappings":";;;;;;AAwBA,MAAM,aAAgB,GAAAA,mCAAA;AAAA,EACpB,gCAAA;AAAA,EACA;AACF,CAAA;AAMO,MAAM,YAAa,CAAA;AAAA,EACf,SAAA;AAAA,EACT,QAAA;AAAA,EAEA,OAAO,OAAO,QAA+C,EAAA;AAC3D,IAAO,OAAA,IAAI,aAAa,QAAQ,CAAA;AAAA;AAClC;AAAA,EAGA,OAAO,UAA2B,GAAA;AAChC,IAAM,MAAAC,QAAA,GAAS,IAAIC,mBAAa,CAAA;AAAA,MAC9B,OAAS,EAAA;AAAA,QACP,QAAU,EAAA;AAAA,UACR,MAAQ,EAAA,gBAAA;AAAA,UACR,UAAY,EAAA,UAAA;AAAA,UACZ,gBAAkB,EAAA;AAAA;AACpB;AACF,KACD,CAAA;AACD,IAAA,MAAM,WAAWC,6BAAgB,CAAA,UAAA,CAAWF,QAAM,CAAA,CAAE,UAAU,MAAM,CAAA;AACpE,IAAO,OAAA,IAAI,aAAa,QAAQ,CAAA;AAAA;AAClC,EAEA,aAAa,cAAc,IAA2B,EAAA;AACpD,IAAM,MAAA,IAAA,CAAK,QAAQ,MAAO,CAAA;AAAA,MACxB,SAAW,EAAA;AAAA,KACZ,CAAA;AAAA;AACH,EAEQ,YAAY,QAAiC,EAAA;AACnD,IAAA,IAAA,CAAK,SAAY,GAAA,QAAA;AAAA;AACnB,EAEA,GAAqB,GAAA;AACnB,IAAA,IAAA,CAAK,aAAa,IAAK,CAAA,SAAA,CAAU,WAAY,CAAA,IAAA,CAAK,OAAM,MAAU,KAAA;AAChE,MAAA,IAAI,CAAC,IAAA,CAAK,SAAU,CAAA,UAAA,EAAY,IAAM,EAAA;AACpC,QAAM,MAAA,YAAA,CAAa,cAAc,MAAM,CAAA;AAAA;AAEzC,MAAO,OAAA,MAAA;AAAA,KACR,CAAA;AAED,IAAA,OAAO,IAAK,CAAA,QAAA;AAAA;AAEhB;;;;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"DatabaseKeyStore.cjs.js","sources":["../../src/identity/DatabaseKeyStore.ts"],"sourcesContent":["/*\n * Copyright 2020 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Knex } from 'knex';\nimport { DateTime } from 'luxon';\nimport { AnyJWK, KeyStore, StoredKey } from './types';\n\nconst TABLE = 'signing_keys';\n\ntype Row = {\n created_at: Date; // row.created_at is a string after being returned from the database\n kid: string;\n key: string;\n};\n\nconst parseDate = (date: string | Date) => {\n const parsedDate =\n typeof date === 'string'\n ? DateTime.fromSQL(date, { zone: 'UTC' })\n : DateTime.fromJSDate(date);\n\n if (!parsedDate.isValid) {\n throw new Error(\n `Failed to parse date, reason: ${parsedDate.invalidReason}, explanation: ${parsedDate.invalidExplanation}`,\n );\n }\n\n return parsedDate.toJSDate();\n};\n\nexport class DatabaseKeyStore implements KeyStore {\n constructor(private readonly client: Knex) {}\n\n async addKey(key: AnyJWK): Promise<void> {\n await this.client<Row>(TABLE).insert({\n kid: key.kid,\n key: JSON.stringify(key),\n });\n }\n\n async listKeys(): Promise<{ items: StoredKey[] }> {\n const rows = await this.client<Row>(TABLE).select();\n\n return {\n items: rows.map(row => ({\n key: JSON.parse(row.key),\n createdAt: parseDate(row.created_at),\n })),\n };\n }\n\n async removeKeys(kids: string[]): Promise<void> {\n await this.client(TABLE).delete().whereIn('kid', kids);\n }\n}\n"],"names":["DateTime"],"mappings":";;;;AAoBA,MAAM,KAAQ,GAAA,cAAA
|
|
1
|
+
{"version":3,"file":"DatabaseKeyStore.cjs.js","sources":["../../src/identity/DatabaseKeyStore.ts"],"sourcesContent":["/*\n * Copyright 2020 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Knex } from 'knex';\nimport { DateTime } from 'luxon';\nimport { AnyJWK, KeyStore, StoredKey } from './types';\n\nconst TABLE = 'signing_keys';\n\ntype Row = {\n created_at: Date; // row.created_at is a string after being returned from the database\n kid: string;\n key: string;\n};\n\nconst parseDate = (date: string | Date) => {\n const parsedDate =\n typeof date === 'string'\n ? DateTime.fromSQL(date, { zone: 'UTC' })\n : DateTime.fromJSDate(date);\n\n if (!parsedDate.isValid) {\n throw new Error(\n `Failed to parse date, reason: ${parsedDate.invalidReason}, explanation: ${parsedDate.invalidExplanation}`,\n );\n }\n\n return parsedDate.toJSDate();\n};\n\nexport class DatabaseKeyStore implements KeyStore {\n constructor(private readonly client: Knex) {}\n\n async addKey(key: AnyJWK): Promise<void> {\n await this.client<Row>(TABLE).insert({\n kid: key.kid,\n key: JSON.stringify(key),\n });\n }\n\n async listKeys(): Promise<{ items: StoredKey[] }> {\n const rows = await this.client<Row>(TABLE).select();\n\n return {\n items: rows.map(row => ({\n key: JSON.parse(row.key),\n createdAt: parseDate(row.created_at),\n })),\n };\n }\n\n async removeKeys(kids: string[]): Promise<void> {\n await this.client(TABLE).delete().whereIn('kid', kids);\n }\n}\n"],"names":["DateTime"],"mappings":";;;;AAoBA,MAAM,KAAQ,GAAA,cAAA;AAQd,MAAM,SAAA,GAAY,CAAC,IAAwB,KAAA;AACzC,EAAA,MAAM,UACJ,GAAA,OAAO,IAAS,KAAA,QAAA,GACZA,eAAS,OAAQ,CAAA,IAAA,EAAM,EAAE,IAAA,EAAM,KAAM,EAAC,CACtC,GAAAA,cAAA,CAAS,WAAW,IAAI,CAAA;AAE9B,EAAI,IAAA,CAAC,WAAW,OAAS,EAAA;AACvB,IAAA,MAAM,IAAI,KAAA;AAAA,MACR,CAAiC,8BAAA,EAAA,UAAA,CAAW,aAAa,CAAA,eAAA,EAAkB,WAAW,kBAAkB,CAAA;AAAA,KAC1G;AAAA;AAGF,EAAA,OAAO,WAAW,QAAS,EAAA;AAC7B,CAAA;AAEO,MAAM,gBAAqC,CAAA;AAAA,EAChD,YAA6B,MAAc,EAAA;AAAd,IAAA,IAAA,CAAA,MAAA,GAAA,MAAA;AAAA;AAAe,EAE5C,MAAM,OAAO,GAA4B,EAAA;AACvC,IAAA,MAAM,IAAK,CAAA,MAAA,CAAY,KAAK,CAAA,CAAE,MAAO,CAAA;AAAA,MACnC,KAAK,GAAI,CAAA,GAAA;AAAA,MACT,GAAA,EAAK,IAAK,CAAA,SAAA,CAAU,GAAG;AAAA,KACxB,CAAA;AAAA;AACH,EAEA,MAAM,QAA4C,GAAA;AAChD,IAAA,MAAM,OAAO,MAAM,IAAA,CAAK,MAAY,CAAA,KAAK,EAAE,MAAO,EAAA;AAElD,IAAO,OAAA;AAAA,MACL,KAAA,EAAO,IAAK,CAAA,GAAA,CAAI,CAAQ,GAAA,MAAA;AAAA,QACtB,GAAK,EAAA,IAAA,CAAK,KAAM,CAAA,GAAA,CAAI,GAAG,CAAA;AAAA,QACvB,SAAA,EAAW,SAAU,CAAA,GAAA,CAAI,UAAU;AAAA,OACnC,CAAA;AAAA,KACJ;AAAA;AACF,EAEA,MAAM,WAAW,IAA+B,EAAA;AAC9C,IAAM,MAAA,IAAA,CAAK,OAAO,KAAK,CAAA,CAAE,QAAS,CAAA,OAAA,CAAQ,OAAO,IAAI,CAAA;AAAA;AAEzD;;;;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"FirestoreKeyStore.cjs.js","sources":["../../src/identity/FirestoreKeyStore.ts"],"sourcesContent":["/*\n * Copyright 2021 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { LoggerService } from '@backstage/backend-plugin-api';\nimport {\n DocumentData,\n Firestore,\n QuerySnapshot,\n Settings,\n WriteResult,\n} from '@google-cloud/firestore';\n\nimport { AnyJWK, KeyStore, StoredKey } from './types';\n\nexport type FirestoreKeyStoreSettings = Settings & Options;\n\ntype Options = {\n path?: string;\n timeout?: number;\n};\n\nexport const DEFAULT_TIMEOUT_MS = 10000;\nexport const DEFAULT_DOCUMENT_PATH = 'sessions';\n\nexport class FirestoreKeyStore implements KeyStore {\n static async create(\n settings?: FirestoreKeyStoreSettings,\n ): Promise<FirestoreKeyStore> {\n const { path, timeout, ...firestoreSettings } = settings ?? {};\n const database = new Firestore(firestoreSettings);\n\n return new FirestoreKeyStore(\n database,\n path ?? DEFAULT_DOCUMENT_PATH,\n timeout ?? DEFAULT_TIMEOUT_MS,\n );\n }\n\n private constructor(\n private readonly database: Firestore,\n private readonly path: string,\n private readonly timeout: number,\n ) {}\n\n static async verifyConnection(\n keyStore: FirestoreKeyStore,\n logger?: LoggerService,\n ): Promise<void> {\n try {\n await keyStore.verify();\n } catch (error) {\n if (process.env.NODE_ENV !== 'development') {\n throw new Error(\n `Failed to connect to database: ${(error as Error).message}`,\n );\n }\n logger?.warn(\n `Failed to connect to database: ${(error as Error).message}`,\n );\n }\n }\n\n async addKey(key: AnyJWK): Promise<void> {\n await this.withTimeout<WriteResult>(\n this.database\n .collection(this.path)\n .doc(key.kid)\n .set({\n kid: key.kid,\n key: JSON.stringify(key),\n }),\n );\n }\n\n async listKeys(): Promise<{ items: StoredKey[] }> {\n const keys = await this.withTimeout<QuerySnapshot<DocumentData>>(\n this.database.collection(this.path).get(),\n );\n\n return {\n items: keys.docs.map(key => ({\n key: key.data() as AnyJWK,\n createdAt: key.createTime.toDate(),\n })),\n };\n }\n\n async removeKeys(kids: string[]): Promise<void> {\n // This is probably really slow, but it's done async in the background\n for (const kid of kids) {\n await this.withTimeout<WriteResult>(\n this.database.collection(this.path).doc(kid).delete(),\n );\n }\n\n /**\n * This could be achieved with batching but there's a couple of limitations with that:\n *\n * - A batched write can contain a maximum of 500 operations\n * https://firebase.google.com/docs/firestore/manage-data/transactions#batched-writes\n *\n * - The \"in\" operator can combine a maximum of 10 equality clauses\n * https://firebase.google.com/docs/firestore/query-data/queries#in_not-in_and_array-contains-any\n *\n * Example:\n *\n * const batch = this.database.batch();\n * const docs = await this.database\n * .collection(this.path)\n * .where('kid', 'in', kids)\n * .get();\n * docs.forEach(doc => {\n * batch.delete(doc.ref);\n * });\n * await batch.commit();\n *\n */\n }\n\n /**\n * Helper function to allow us to modify the timeout used when\n * performing Firestore database operations.\n *\n * The reason for this is that it seems that there's no other\n * practical solution to change the default timeout of 10mins\n * that Firestore has.\n *\n */\n private async withTimeout<T>(operation: Promise<T>): Promise<T> {\n const timer = new Promise<never>((_, reject) =>\n setTimeout(() => {\n reject(new Error(`Operation timed out after ${this.timeout}ms`));\n }, this.timeout),\n );\n return Promise.race<T>([operation, timer]);\n }\n\n /**\n * Used to verify that the database is reachable.\n */\n private async verify(): Promise<void> {\n await this.withTimeout(this.database.collection(this.path).limit(1).get());\n }\n}\n"],"names":["Firestore"],"mappings":";;;;AAkCO,MAAM,kBAAqB,GAAA
|
|
1
|
+
{"version":3,"file":"FirestoreKeyStore.cjs.js","sources":["../../src/identity/FirestoreKeyStore.ts"],"sourcesContent":["/*\n * Copyright 2021 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { LoggerService } from '@backstage/backend-plugin-api';\nimport {\n DocumentData,\n Firestore,\n QuerySnapshot,\n Settings,\n WriteResult,\n} from '@google-cloud/firestore';\n\nimport { AnyJWK, KeyStore, StoredKey } from './types';\n\nexport type FirestoreKeyStoreSettings = Settings & Options;\n\ntype Options = {\n path?: string;\n timeout?: number;\n};\n\nexport const DEFAULT_TIMEOUT_MS = 10000;\nexport const DEFAULT_DOCUMENT_PATH = 'sessions';\n\nexport class FirestoreKeyStore implements KeyStore {\n static async create(\n settings?: FirestoreKeyStoreSettings,\n ): Promise<FirestoreKeyStore> {\n const { path, timeout, ...firestoreSettings } = settings ?? {};\n const database = new Firestore(firestoreSettings);\n\n return new FirestoreKeyStore(\n database,\n path ?? DEFAULT_DOCUMENT_PATH,\n timeout ?? DEFAULT_TIMEOUT_MS,\n );\n }\n\n private constructor(\n private readonly database: Firestore,\n private readonly path: string,\n private readonly timeout: number,\n ) {}\n\n static async verifyConnection(\n keyStore: FirestoreKeyStore,\n logger?: LoggerService,\n ): Promise<void> {\n try {\n await keyStore.verify();\n } catch (error) {\n if (process.env.NODE_ENV !== 'development') {\n throw new Error(\n `Failed to connect to database: ${(error as Error).message}`,\n );\n }\n logger?.warn(\n `Failed to connect to database: ${(error as Error).message}`,\n );\n }\n }\n\n async addKey(key: AnyJWK): Promise<void> {\n await this.withTimeout<WriteResult>(\n this.database\n .collection(this.path)\n .doc(key.kid)\n .set({\n kid: key.kid,\n key: JSON.stringify(key),\n }),\n );\n }\n\n async listKeys(): Promise<{ items: StoredKey[] }> {\n const keys = await this.withTimeout<QuerySnapshot<DocumentData>>(\n this.database.collection(this.path).get(),\n );\n\n return {\n items: keys.docs.map(key => ({\n key: key.data() as AnyJWK,\n createdAt: key.createTime.toDate(),\n })),\n };\n }\n\n async removeKeys(kids: string[]): Promise<void> {\n // This is probably really slow, but it's done async in the background\n for (const kid of kids) {\n await this.withTimeout<WriteResult>(\n this.database.collection(this.path).doc(kid).delete(),\n );\n }\n\n /**\n * This could be achieved with batching but there's a couple of limitations with that:\n *\n * - A batched write can contain a maximum of 500 operations\n * https://firebase.google.com/docs/firestore/manage-data/transactions#batched-writes\n *\n * - The \"in\" operator can combine a maximum of 10 equality clauses\n * https://firebase.google.com/docs/firestore/query-data/queries#in_not-in_and_array-contains-any\n *\n * Example:\n *\n * const batch = this.database.batch();\n * const docs = await this.database\n * .collection(this.path)\n * .where('kid', 'in', kids)\n * .get();\n * docs.forEach(doc => {\n * batch.delete(doc.ref);\n * });\n * await batch.commit();\n *\n */\n }\n\n /**\n * Helper function to allow us to modify the timeout used when\n * performing Firestore database operations.\n *\n * The reason for this is that it seems that there's no other\n * practical solution to change the default timeout of 10mins\n * that Firestore has.\n *\n */\n private async withTimeout<T>(operation: Promise<T>): Promise<T> {\n const timer = new Promise<never>((_, reject) =>\n setTimeout(() => {\n reject(new Error(`Operation timed out after ${this.timeout}ms`));\n }, this.timeout),\n );\n return Promise.race<T>([operation, timer]);\n }\n\n /**\n * Used to verify that the database is reachable.\n */\n private async verify(): Promise<void> {\n await this.withTimeout(this.database.collection(this.path).limit(1).get());\n }\n}\n"],"names":["Firestore"],"mappings":";;;;AAkCO,MAAM,kBAAqB,GAAA;AAC3B,MAAM,qBAAwB,GAAA;AAE9B,MAAM,iBAAsC,CAAA;AAAA,EAczC,WAAA,CACW,QACA,EAAA,IAAA,EACA,OACjB,EAAA;AAHiB,IAAA,IAAA,CAAA,QAAA,GAAA,QAAA;AACA,IAAA,IAAA,CAAA,IAAA,GAAA,IAAA;AACA,IAAA,IAAA,CAAA,OAAA,GAAA,OAAA;AAAA;AAChB,EAjBH,aAAa,OACX,QAC4B,EAAA;AAC5B,IAAA,MAAM,EAAE,IAAM,EAAA,OAAA,EAAS,GAAG,iBAAkB,EAAA,GAAI,YAAY,EAAC;AAC7D,IAAM,MAAA,QAAA,GAAW,IAAIA,mBAAA,CAAU,iBAAiB,CAAA;AAEhD,IAAA,OAAO,IAAI,iBAAA;AAAA,MACT,QAAA;AAAA,MACA,IAAQ,IAAA,qBAAA;AAAA,MACR,OAAW,IAAA;AAAA,KACb;AAAA;AACF,EAQA,aAAa,gBACX,CAAA,QAAA,EACA,MACe,EAAA;AACf,IAAI,IAAA;AACF,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I,GAAG,CAAA,CAAE,MAAO;AAAA,OACtD;AAAA;AACF;AAwBF;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAWA,MAAc,YAAe,SAAmC,EAAA;AAC9D,IAAA,MAAM,QAAQ,IAAI,OAAA;AAAA,MAAe,CAAC,CAAA,EAAG,MACnC,KAAA,UAAA,CAAW,MAAM;AACf,QAAA,MAAA,CAAO,IAAI,KAAM,CAAA,CAAA,0BAAA,EAA6B,IAAK,CAAA,OAAO,IAAI,CAAC,CAAA;AAAA,OACjE,EAAG,KAAK,OAAO;AAAA,KACjB;AACA,IAAA,OAAO,OAAQ,CAAA,IAAA,CAAQ,CAAC,SAAA,EAAW,KAAK,CAAC,CAAA;AAAA;AAC3C;AAAA;AAAA;AAAA,EAKA,MAAc,MAAwB,GAAA;AACpC,IAAA,MAAM,IAAK,CAAA,WAAA,CAAY,IAAK,CAAA,QAAA,CAAS,UAAW,CAAA,IAAA,CAAK,IAAI,CAAA,CAAE,KAAM,CAAA,CAAC,CAAE,CAAA,GAAA,EAAK,CAAA;AAAA;AAE7E;;;;;;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"KeyStores.cjs.js","sources":["../../src/identity/KeyStores.ts"],"sourcesContent":["/*\n * Copyright 2021 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { pickBy } from 'lodash';\nimport { LoggerService } from '@backstage/backend-plugin-api';\n\nimport { Config } from '@backstage/config';\nimport { AuthDatabase } from '../database/AuthDatabase';\nimport { DatabaseKeyStore } from './DatabaseKeyStore';\nimport { FirestoreKeyStore } from './FirestoreKeyStore';\nimport { MemoryKeyStore } from './MemoryKeyStore';\nimport { KeyStore } from './types';\nimport { StaticKeyStore } from './StaticKeyStore';\n\ntype Options = {\n logger: LoggerService;\n database: AuthDatabase;\n};\n\nexport class KeyStores {\n /**\n * Looks at the `auth.keyStore` section in the application configuration\n * and returns a KeyStore store. Defaults to `database`\n *\n * @returns a KeyStore store\n */\n static async fromConfig(config: Config, options: Options): Promise<KeyStore> {\n const { logger, database } = options;\n\n const ks = config.getOptionalConfig('auth.keyStore');\n const provider = ks?.getOptionalString('provider') ?? 'database';\n\n logger.info(`Configuring \"${provider}\" as KeyStore provider`);\n\n if (provider === 'database') {\n return new DatabaseKeyStore(await database.get());\n }\n\n if (provider === 'memory') {\n return new MemoryKeyStore();\n }\n\n if (provider === 'firestore') {\n const settings = ks?.getConfig(provider);\n\n const keyStore = await FirestoreKeyStore.create(\n pickBy(\n {\n projectId: settings?.getOptionalString('projectId'),\n keyFilename: settings?.getOptionalString('keyFilename'),\n host: settings?.getOptionalString('host'),\n port: settings?.getOptionalNumber('port'),\n ssl: settings?.getOptionalBoolean('ssl'),\n path: settings?.getOptionalString('path'),\n timeout: settings?.getOptionalNumber('timeout'),\n },\n value => value !== undefined,\n ),\n );\n await FirestoreKeyStore.verifyConnection(keyStore, logger);\n\n return keyStore;\n }\n\n if (provider === 'static') {\n return await StaticKeyStore.fromConfig(config);\n }\n\n throw new Error(`Unknown KeyStore provider: ${provider}`);\n }\n}\n"],"names":["DatabaseKeyStore","MemoryKeyStore","FirestoreKeyStore","pickBy","StaticKeyStore"],"mappings":";;;;;;;;AAgCO,MAAM,SAAU,CAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOrB,aAAa,UAAW,CAAA,MAAA,EAAgB,OAAqC,EAAA;AAC3E,IAAM,MAAA,EAAE,MAAQ,EAAA,QAAA,EAAa,GAAA,OAAA
|
|
1
|
+
{"version":3,"file":"KeyStores.cjs.js","sources":["../../src/identity/KeyStores.ts"],"sourcesContent":["/*\n * Copyright 2021 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { pickBy } from 'lodash';\nimport { LoggerService } from '@backstage/backend-plugin-api';\n\nimport { Config } from '@backstage/config';\nimport { AuthDatabase } from '../database/AuthDatabase';\nimport { DatabaseKeyStore } from './DatabaseKeyStore';\nimport { FirestoreKeyStore } from './FirestoreKeyStore';\nimport { MemoryKeyStore } from './MemoryKeyStore';\nimport { KeyStore } from './types';\nimport { StaticKeyStore } from './StaticKeyStore';\n\ntype Options = {\n logger: LoggerService;\n database: AuthDatabase;\n};\n\nexport class KeyStores {\n /**\n * Looks at the `auth.keyStore` section in the application configuration\n * and returns a KeyStore store. Defaults to `database`\n *\n * @returns a KeyStore store\n */\n static async fromConfig(config: Config, options: Options): Promise<KeyStore> {\n const { logger, database } = options;\n\n const ks = config.getOptionalConfig('auth.keyStore');\n const provider = ks?.getOptionalString('provider') ?? 'database';\n\n logger.info(`Configuring \"${provider}\" as KeyStore provider`);\n\n if (provider === 'database') {\n return new DatabaseKeyStore(await database.get());\n }\n\n if (provider === 'memory') {\n return new MemoryKeyStore();\n }\n\n if (provider === 'firestore') {\n const settings = ks?.getConfig(provider);\n\n const keyStore = await FirestoreKeyStore.create(\n pickBy(\n {\n projectId: settings?.getOptionalString('projectId'),\n keyFilename: settings?.getOptionalString('keyFilename'),\n host: settings?.getOptionalString('host'),\n port: settings?.getOptionalNumber('port'),\n ssl: settings?.getOptionalBoolean('ssl'),\n path: settings?.getOptionalString('path'),\n timeout: settings?.getOptionalNumber('timeout'),\n },\n value => value !== undefined,\n ),\n );\n await FirestoreKeyStore.verifyConnection(keyStore, logger);\n\n return keyStore;\n }\n\n if (provider === 'static') {\n return await StaticKeyStore.fromConfig(config);\n }\n\n throw new Error(`Unknown KeyStore provider: ${provider}`);\n }\n}\n"],"names":["DatabaseKeyStore","MemoryKeyStore","FirestoreKeyStore","pickBy","StaticKeyStore"],"mappings":";;;;;;;;AAgCO,MAAM,SAAU,CAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOrB,aAAa,UAAW,CAAA,MAAA,EAAgB,OAAqC,EAAA;AAC3E,IAAM,MAAA,EAAE,MAAQ,EAAA,QAAA,EAAa,GAAA,OAAA;AAE7B,IAAM,MAAA,EAAA,GAAK,MAAO,CAAA,iBAAA,CAAkB,eAAe,CAAA;AACnD,IAAA,MAAM,QAAW,GAAA,EAAA,EAAI,iBAAkB,CAAA,UAAU,CAAK,IAAA,UAAA;AAEtD,IAAO,MAAA,CAAA,IAAA,CAAK,CAAgB,aAAA,EAAA,QAAQ,CAAwB,sBAAA,CAAA,CAAA;AAE5D,IAAA,IAAI,aAAa,UAAY,EAAA;AAC3B,MAAA,OAAO,IAAIA,iCAAA,CAAiB,MAAM,QAAA,CAAS,KAAK,CAAA;AAAA;AAGlD,IAAA,IAAI,aAAa,QAAU,EAAA;AACzB,MAAA,OAAO,IAAIC,6BAAe,EAAA;AAAA;AAG5B,IAAA,IAAI,aAAa,WAAa,EAAA;AAC5B,MAAM,MAAA,QAAA,GAAW,EAAI,EAAA,SAAA,CAAU,QAAQ,CAAA;AAEvC,MAAM,MAAA,QAAA,GAAW,MAAMC,mCAAkB,CAAA,MAAA;AAAA,QACvCC,aAAA;AAAA,UACE;AAAA,YACE,SAAA,EAAW,QAAU,EAAA,iBAAA,CAAkB,WAAW,CAAA;AAAA,YAClD,WAAA,EAAa,QAAU,EAAA,iBAAA,CAAkB,aAAa,CAAA;AAAA,YACtD,IAAA,EAAM,QAAU,EAAA,iBAAA,CAAkB,MAAM,CAAA;AAAA,YACxC,IAAA,EAAM,QAAU,EAAA,iBAAA,CAAkB,MAAM,CAAA;AAAA,YACxC,GAAA,EAAK,QAAU,EAAA,kBAAA,CAAmB,KAAK,CAAA;AAAA,YACvC,IAAA,EAAM,QAAU,EAAA,iBAAA,CAAkB,MAAM,CAAA;AAAA,YACxC,OAAA,EAAS,QAAU,EAAA,iBAAA,CAAkB,SAAS;AAAA,WAChD;AAAA,UACA,WAAS,KAAU,KAAA,KAAA;AAAA;AACrB,OACF;AACA,MAAM,MAAAD,mCAAA,CAAkB,gBAAiB,CAAA,QAAA,EAAU,MAAM,CAAA;AAEzD,MAAO,OAAA,QAAA;AAAA;AAGT,IAAA,IAAI,aAAa,QAAU,EAAA;AACzB,MAAO,OAAA,MAAME,6BAAe,CAAA,UAAA,CAAW,MAAM,CAAA;AAAA;AAG/C,IAAA,MAAM,IAAI,KAAA,CAAM,CAA8B,2BAAA,EAAA,QAAQ,CAAE,CAAA,CAAA;AAAA;AAE5D;;;;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"MemoryKeyStore.cjs.js","sources":["../../src/identity/MemoryKeyStore.ts"],"sourcesContent":["/*\n * Copyright 2020 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { KeyStore, AnyJWK, StoredKey } from './types';\nimport { DateTime } from 'luxon';\n\nexport class MemoryKeyStore implements KeyStore {\n private readonly keys = new Map<string, { createdAt: Date; key: string }>();\n\n async addKey(key: AnyJWK): Promise<void> {\n this.keys.set(key.kid, {\n createdAt: DateTime.utc().toJSDate(),\n key: JSON.stringify(key),\n });\n }\n\n async removeKeys(kids: string[]): Promise<void> {\n for (const kid of kids) {\n this.keys.delete(kid);\n }\n }\n\n async listKeys(): Promise<{ items: StoredKey[] }> {\n return {\n items: Array.from(this.keys).map(([, { createdAt, key: keyStr }]) => ({\n createdAt,\n key: JSON.parse(keyStr),\n })),\n };\n }\n}\n"],"names":["DateTime"],"mappings":";;;;AAmBO,MAAM,cAAmC,CAAA;AAAA,EAC7B,IAAA,uBAAW,GAA8C,EAAA
|
|
1
|
+
{"version":3,"file":"MemoryKeyStore.cjs.js","sources":["../../src/identity/MemoryKeyStore.ts"],"sourcesContent":["/*\n * Copyright 2020 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { KeyStore, AnyJWK, StoredKey } from './types';\nimport { DateTime } from 'luxon';\n\nexport class MemoryKeyStore implements KeyStore {\n private readonly keys = new Map<string, { createdAt: Date; key: string }>();\n\n async addKey(key: AnyJWK): Promise<void> {\n this.keys.set(key.kid, {\n createdAt: DateTime.utc().toJSDate(),\n key: JSON.stringify(key),\n });\n }\n\n async removeKeys(kids: string[]): Promise<void> {\n for (const kid of kids) {\n this.keys.delete(kid);\n }\n }\n\n async listKeys(): Promise<{ items: StoredKey[] }> {\n return {\n items: Array.from(this.keys).map(([, { createdAt, key: keyStr }]) => ({\n createdAt,\n key: JSON.parse(keyStr),\n })),\n };\n }\n}\n"],"names":["DateTime"],"mappings":";;;;AAmBO,MAAM,cAAmC,CAAA;AAAA,EAC7B,IAAA,uBAAW,GAA8C,EAAA;AAAA,EAE1E,MAAM,OAAO,GAA4B,EAAA;AACvC,IAAK,IAAA,CAAA,IAAA,CAAK,GAAI,CAAA,GAAA,CAAI,GAAK,EAAA;AAAA,MACrB,SAAW,EAAAA,cAAA,CAAS,GAAI,EAAA,CAAE,QAAS,EAAA;AAAA,MACnC,GAAA,EAAK,IAAK,CAAA,SAAA,CAAU,GAAG;AAAA,KACxB,CAAA;AAAA;AACH,EAEA,MAAM,WAAW,IAA+B,EAAA;AAC9C,IAAA,KAAA,MAAW,OAAO,IAAM,EAAA;AACtB,MAAK,IAAA,CAAA,IAAA,CAAK,OAAO,GAAG,CAAA;AAAA;AACtB;AACF,EAEA,MAAM,QAA4C,GAAA;AAChD,IAAO,OAAA;AAAA,MACL,KAAO,EAAA,KAAA,CAAM,IAAK,CAAA,IAAA,CAAK,IAAI,CAAE,CAAA,GAAA,CAAI,CAAC,GAAG,EAAE,SAAA,EAAW,GAAK,EAAA,MAAA,EAAQ,CAAO,MAAA;AAAA,QACpE,SAAA;AAAA,QACA,GAAA,EAAK,IAAK,CAAA,KAAA,CAAM,MAAM;AAAA,OACtB,CAAA;AAAA,KACJ;AAAA;AAEJ;;;;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"StaticKeyStore.cjs.js","sources":["../../src/identity/StaticKeyStore.ts"],"sourcesContent":["/*\n * Copyright 2023 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { AnyJWK, KeyStore, StoredKey } from './types';\nimport { exportJWK, importPKCS8, importSPKI, JWK } from 'jose';\nimport { KeyLike } from 'jose/dist/types/types';\nimport { promises as fs } from 'fs';\nimport { Config } from '@backstage/config';\n\nexport type KeyPair = {\n publicKey: JWK;\n privateKey: JWK;\n};\n\nexport type StaticKeyConfig = {\n publicKeyFile: string;\n privateKeyFile: string;\n keyId: string;\n algorithm: string;\n};\n\nconst DEFAULT_ALGORITHM = 'ES256';\n\n/**\n * Key store that loads predefined public/private key pairs from disk\n *\n * The private key should be represented using the PKCS#8 format,\n * while the public key should be in the SPKI format.\n *\n * @remarks\n *\n * You can generate a public and private key pair, using\n * openssl:\n *\n * Generate a private key using the ES256 algorithm\n * ```sh\n * openssl ecparam -name prime256v1 -genkey -out private.ec.key\n * ```\n * Convert it to PKCS#8 format\n * ```sh\n * openssl pkcs8 -topk8 -inform PEM -outform PEM -nocrypt -in private.ec.key -out private.key\n * ```\n * Extract the public key\n * ```sh\n * openssl ec -inform PEM -outform PEM -pubout -in private.key -out public.key\n * ```\n *\n * Provide the paths to private.key and public.key as the respective\n * private and public key paths in the StaticKeyStore.create(...) method.\n */\nexport class StaticKeyStore implements KeyStore {\n private readonly keyPairs: KeyPair[];\n private readonly createdAt: Date;\n\n private constructor(keyPairs: KeyPair[]) {\n if (keyPairs.length === 0) {\n throw new Error('Should provide at least one key pair');\n }\n\n this.keyPairs = keyPairs;\n this.createdAt = new Date();\n }\n\n public static async fromConfig(config: Config): Promise<StaticKeyStore> {\n const keyConfigs = config\n .getConfigArray('auth.keyStore.static.keys')\n .map(c => {\n const staticKeyConfig: StaticKeyConfig = {\n publicKeyFile: c.getString('publicKeyFile'),\n privateKeyFile: c.getString('privateKeyFile'),\n keyId: c.getString('keyId'),\n algorithm: c.getOptionalString('algorithm') ?? DEFAULT_ALGORITHM,\n };\n\n return staticKeyConfig;\n });\n\n const keyPairs = await Promise.all(\n keyConfigs.map(async k => await this.loadKeyPair(k)),\n );\n\n return new StaticKeyStore(keyPairs);\n }\n\n addKey(_key: AnyJWK): Promise<void> {\n throw new Error('Cannot add keys to the static key store');\n }\n\n listKeys(): Promise<{ items: StoredKey[] }> {\n const keys = this.keyPairs.map(k => this.keyPairToStoredKey(k));\n return Promise.resolve({ items: keys });\n }\n\n getPrivateKey(keyId: string): JWK {\n const keyPair = this.keyPairs.find(k => k.publicKey.kid === keyId);\n if (keyPair === undefined) {\n throw new Error(`Could not find key with keyId: ${keyId}`);\n }\n\n return keyPair.privateKey;\n }\n\n removeKeys(_kids: string[]): Promise<void> {\n throw new Error('Cannot remove keys from the static key store');\n }\n\n private keyPairToStoredKey(keyPair: KeyPair): StoredKey {\n const publicKey = {\n ...keyPair.publicKey,\n use: 'sig',\n };\n\n return {\n key: publicKey as AnyJWK,\n createdAt: this.createdAt,\n };\n }\n\n private static async loadKeyPair(options: StaticKeyConfig): Promise<KeyPair> {\n const algorithm = options.algorithm;\n const keyId = options.keyId;\n const publicKey = await this.loadPublicKeyFromFile(\n options.publicKeyFile,\n keyId,\n algorithm,\n );\n const privateKey = await this.loadPrivateKeyFromFile(\n options.privateKeyFile,\n keyId,\n algorithm,\n );\n\n return { publicKey, privateKey };\n }\n\n private static async loadPublicKeyFromFile(\n path: string,\n keyId: string,\n algorithm: string,\n ): Promise<JWK> {\n return this.loadKeyFromFile(path, keyId, algorithm, importSPKI);\n }\n\n private static async loadPrivateKeyFromFile(\n path: string,\n keyId: string,\n algorithm: string,\n ): Promise<JWK> {\n return this.loadKeyFromFile(path, keyId, algorithm, importPKCS8);\n }\n\n private static async loadKeyFromFile(\n path: string,\n keyId: string,\n algorithm: string,\n importer: (content: string, algorithm: string) => Promise<KeyLike>,\n ): Promise<JWK> {\n const content = await fs.readFile(path, { encoding: 'utf8', flag: 'r' });\n const key = await importer(content, algorithm);\n const jwk = await exportJWK(key);\n jwk.kid = keyId;\n jwk.alg = algorithm;\n\n return jwk;\n }\n}\n"],"names":["importSPKI","importPKCS8","fs","exportJWK"],"mappings":";;;;;AAiCA,MAAM,iBAAoB,GAAA,OAAA
|
|
1
|
+
{"version":3,"file":"StaticKeyStore.cjs.js","sources":["../../src/identity/StaticKeyStore.ts"],"sourcesContent":["/*\n * Copyright 2023 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { AnyJWK, KeyStore, StoredKey } from './types';\nimport { exportJWK, importPKCS8, importSPKI, JWK } from 'jose';\nimport { KeyLike } from 'jose/dist/types/types';\nimport { promises as fs } from 'fs';\nimport { Config } from '@backstage/config';\n\nexport type KeyPair = {\n publicKey: JWK;\n privateKey: JWK;\n};\n\nexport type StaticKeyConfig = {\n publicKeyFile: string;\n privateKeyFile: string;\n keyId: string;\n algorithm: string;\n};\n\nconst DEFAULT_ALGORITHM = 'ES256';\n\n/**\n * Key store that loads predefined public/private key pairs from disk\n *\n * The private key should be represented using the PKCS#8 format,\n * while the public key should be in the SPKI format.\n *\n * @remarks\n *\n * You can generate a public and private key pair, using\n * openssl:\n *\n * Generate a private key using the ES256 algorithm\n * ```sh\n * openssl ecparam -name prime256v1 -genkey -out private.ec.key\n * ```\n * Convert it to PKCS#8 format\n * ```sh\n * openssl pkcs8 -topk8 -inform PEM -outform PEM -nocrypt -in private.ec.key -out private.key\n * ```\n * Extract the public key\n * ```sh\n * openssl ec -inform PEM -outform PEM -pubout -in private.key -out public.key\n * ```\n *\n * Provide the paths to private.key and public.key as the respective\n * private and public key paths in the StaticKeyStore.create(...) method.\n */\nexport class StaticKeyStore implements KeyStore {\n private readonly keyPairs: KeyPair[];\n private readonly createdAt: Date;\n\n private constructor(keyPairs: KeyPair[]) {\n if (keyPairs.length === 0) {\n throw new Error('Should provide at least one key pair');\n }\n\n this.keyPairs = keyPairs;\n this.createdAt = new Date();\n }\n\n public static async fromConfig(config: Config): Promise<StaticKeyStore> {\n const keyConfigs = config\n .getConfigArray('auth.keyStore.static.keys')\n .map(c => {\n const staticKeyConfig: StaticKeyConfig = {\n publicKeyFile: c.getString('publicKeyFile'),\n privateKeyFile: c.getString('privateKeyFile'),\n keyId: c.getString('keyId'),\n algorithm: c.getOptionalString('algorithm') ?? DEFAULT_ALGORITHM,\n };\n\n return staticKeyConfig;\n });\n\n const keyPairs = await Promise.all(\n keyConfigs.map(async k => await this.loadKeyPair(k)),\n );\n\n return new StaticKeyStore(keyPairs);\n }\n\n addKey(_key: AnyJWK): Promise<void> {\n throw new Error('Cannot add keys to the static key store');\n }\n\n listKeys(): Promise<{ items: StoredKey[] }> {\n const keys = this.keyPairs.map(k => this.keyPairToStoredKey(k));\n return Promise.resolve({ items: keys });\n }\n\n getPrivateKey(keyId: string): JWK {\n const keyPair = this.keyPairs.find(k => k.publicKey.kid === keyId);\n if (keyPair === undefined) {\n throw new Error(`Could not find key with keyId: ${keyId}`);\n }\n\n return keyPair.privateKey;\n }\n\n removeKeys(_kids: string[]): Promise<void> {\n throw new Error('Cannot remove keys from the static key store');\n }\n\n private keyPairToStoredKey(keyPair: KeyPair): StoredKey {\n const publicKey = {\n ...keyPair.publicKey,\n use: 'sig',\n };\n\n return {\n key: publicKey as AnyJWK,\n createdAt: this.createdAt,\n };\n }\n\n private static async loadKeyPair(options: StaticKeyConfig): Promise<KeyPair> {\n const algorithm = options.algorithm;\n const keyId = options.keyId;\n const publicKey = await this.loadPublicKeyFromFile(\n options.publicKeyFile,\n keyId,\n algorithm,\n );\n const privateKey = await this.loadPrivateKeyFromFile(\n options.privateKeyFile,\n keyId,\n algorithm,\n );\n\n return { publicKey, privateKey };\n }\n\n private static async loadPublicKeyFromFile(\n path: string,\n keyId: string,\n algorithm: string,\n ): Promise<JWK> {\n return this.loadKeyFromFile(path, keyId, algorithm, importSPKI);\n }\n\n private static async loadPrivateKeyFromFile(\n path: string,\n keyId: string,\n algorithm: string,\n ): Promise<JWK> {\n return this.loadKeyFromFile(path, keyId, algorithm, importPKCS8);\n }\n\n private static async loadKeyFromFile(\n path: string,\n keyId: string,\n algorithm: string,\n importer: (content: string, algorithm: string) => Promise<KeyLike>,\n ): Promise<JWK> {\n const content = await fs.readFile(path, { encoding: 'utf8', flag: 'r' });\n const key = await importer(content, algorithm);\n const jwk = await exportJWK(key);\n jwk.kid = keyId;\n jwk.alg = algorithm;\n\n return jwk;\n }\n}\n"],"names":["importSPKI","importPKCS8","fs","exportJWK"],"mappings":";;;;;AAiCA,MAAM,iBAAoB,GAAA,OAAA;AA6BnB,MAAM,cAAmC,CAAA;AAAA,EAC7B,QAAA;AAAA,EACA,SAAA;AAAA,EAET,YAAY,QAAqB,EAAA;AACvC,IAAI,IAAA,QAAA,CAAS,WAAW,CAAG,EAAA;AACzB,MAAM,MAAA,IAAI,MAAM,sCAAsC,CAAA;AAAA;AAGxD,IAAA,IAAA,CAAK,QAAW,GAAA,QAAA;AAChB,IAAK,IAAA,CAAA,SAAA,uBAAgB,IAAK,EAAA;AAAA;AAC5B,EAEA,aAAoB,WAAW,MAAyC,EAAA;AACtE,IAAA,MAAM,aAAa,MAChB,CAAA,cAAA,CAAe,2BAA2B,CAAA,CAC1C,IAAI,CAAK,CAAA,KAAA;AACR,MAAA,MAAM,eAAmC,GAAA;AAAA,QACvC,aAAA,EAAe,CAAE,CAAA,SAAA,CAAU,eAAe,CAAA;AAAA,QAC1C,cAAA,EAAgB,CAAE,CAAA,SAAA,CAAU,gBAAgB,CAAA;AAAA,QAC5C,KAAA,EAAO,CAAE,CAAA,SAAA,CAAU,OAAO,CAAA;AAAA,QAC1B,SAAW,EAAA,CAAA,CAAE,iBAAkB,CAAA,WAAW,CAAK,IAAA;AAAA,OACjD;AAEA,MAAO,OAAA,eAAA;AAAA,KACR,CAAA;AAEH,IAAM,MAAA,QAAA,GAAW,MAAM,OAAQ,CAAA,GAAA;AAAA,MAC7B,UAAA,CAAW,IAAI,OAAM,CAAA,KAAK,MAAM,IAAK,CAAA,WAAA,CAAY,CAAC,CAAC;AAAA,KACrD;AAEA,IAAO,OAAA,IAAI,eAAe,QAAQ,CAAA;AAAA;A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A;AAAA,MAC5B,OAAQ,CAAA,cAAA;AAAA,MACR,KAAA;AAAA,MACA;AAAA,KACF;AAEA,IAAO,OAAA,EAAE,WAAW,UAAW,EAAA;AAAA;AACjC,EAEA,aAAqB,qBAAA,CACnB,IACA,EAAA,KAAA,EACA,SACc,EAAA;AACd,IAAA,OAAO,IAAK,CAAA,eAAA,CAAgB,IAAM,EAAA,KAAA,EAAO,WAAWA,eAAU,CAAA;AAAA;AAChE,EAEA,aAAqB,sBAAA,CACnB,IACA,EAAA,KAAA,EACA,SACc,EAAA;AACd,IAAA,OAAO,IAAK,CAAA,eAAA,CAAgB,IAAM,EAAA,KAAA,EAAO,WAAWC,gBAAW,CAAA;AAAA;AACjE,EAEA,aAAqB,eAAA,CACnB,IACA,EAAA,KAAA,EACA,WACA,QACc,EAAA;AACd,IAAM,MAAA,OAAA,GAAU,MAAMC,WAAA,CAAG,QAAS,CAAA,IAAA,EAAM,EAAE,QAAU,EAAA,MAAA,EAAQ,IAAM,EAAA,GAAA,EAAK,CAAA;AACvE,IAAA,MAAM,GAAM,GAAA,MAAM,QAAS,CAAA,OAAA,EAAS,SAAS,CAAA;AAC7C,IAAM,MAAA,GAAA,GAAM,MAAMC,cAAA,CAAU,GAAG,CAAA;AAC/B,IAAA,GAAA,CAAI,GAAM,GAAA,KAAA;AACV,IAAA,GAAA,CAAI,GAAM,GAAA,SAAA;AAEV,IAAO,OAAA,GAAA;AAAA;AAEX;;;;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"StaticTokenIssuer.cjs.js","sources":["../../src/identity/StaticTokenIssuer.ts"],"sourcesContent":["/*\n * Copyright 2023 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { AnyJWK, TokenIssuer } from './types';\nimport { SignJWT, importJWK, JWK } from 'jose';\nimport { parseEntityRef } from '@backstage/catalog-model';\nimport { AuthenticationError } from '@backstage/errors';\nimport { LoggerService } from '@backstage/backend-plugin-api';\nimport { StaticKeyStore } from './StaticKeyStore';\nimport { TokenParams } from '@backstage/plugin-auth-node';\n\nconst MS_IN_S = 1000;\n\nexport type Config = {\n publicKeyFile: string;\n privateKeyFile: string;\n keyId: string;\n algorithm?: string;\n};\n\nexport type Options = {\n logger: LoggerService;\n /** Value of the issuer claim in issued tokens */\n issuer: string;\n /** Expiration time of the JWT in seconds */\n sessionExpirationSeconds: number;\n};\n\n/**\n * A token issuer that issues tokens from predefined\n * public/private key pair stored in the static key store.\n */\nexport class StaticTokenIssuer implements TokenIssuer {\n private readonly issuer: string;\n private readonly logger: LoggerService;\n private readonly keyStore: StaticKeyStore;\n private readonly sessionExpirationSeconds: number;\n\n public constructor(options: Options, keyStore: StaticKeyStore) {\n this.issuer = options.issuer;\n this.logger = options.logger;\n this.sessionExpirationSeconds = options.sessionExpirationSeconds;\n this.keyStore = keyStore;\n }\n\n public async issueToken(params: TokenParams): Promise<string> {\n const key = await this.getSigningKey();\n\n // TODO: code shared with TokenFactory.ts\n const iss = this.issuer;\n const { sub, ent, ...additionalClaims } = params.claims;\n const aud = 'backstage';\n const iat = Math.floor(Date.now() / MS_IN_S);\n const exp = iat + this.sessionExpirationSeconds;\n\n // Validate that the subject claim is a valid EntityRef\n try {\n parseEntityRef(sub);\n } catch (error) {\n throw new Error(\n '\"sub\" claim provided by the auth resolver is not a valid EntityRef.',\n );\n }\n\n this.logger.info(`Issuing token for ${sub}, with entities ${ent ?? []}`);\n\n if (!key.alg) {\n throw new AuthenticationError('No algorithm was provided in the key');\n }\n\n return new SignJWT({ ...additionalClaims, iss, sub, ent, aud, iat, exp })\n .setProtectedHeader({ alg: key.alg, kid: key.kid })\n .setIssuer(iss)\n .setAudience(aud)\n .setSubject(sub)\n .setIssuedAt(iat)\n .setExpirationTime(exp)\n .sign(await importJWK(key));\n }\n\n private async getSigningKey(): Promise<JWK> {\n const { items: keys } = await this.keyStore.listKeys();\n if (keys.length >= 1) {\n return this.keyStore.getPrivateKey(keys[0].key.kid);\n }\n throw new Error('Keystore should hold at least 1 key');\n }\n\n public async listPublicKeys(): Promise<{ keys: AnyJWK[] }> {\n const { items: keys } = await this.keyStore.listKeys();\n return { keys: keys.map(({ key }) => key) };\n }\n}\n"],"names":["parseEntityRef","AuthenticationError","SignJWT","importJWK"],"mappings":";;;;;;AAwBA,MAAM,OAAU,GAAA,GAAA
|
|
1
|
+
{"version":3,"file":"StaticTokenIssuer.cjs.js","sources":["../../src/identity/StaticTokenIssuer.ts"],"sourcesContent":["/*\n * Copyright 2023 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { AnyJWK, TokenIssuer } from './types';\nimport { SignJWT, importJWK, JWK } from 'jose';\nimport { parseEntityRef } from '@backstage/catalog-model';\nimport { AuthenticationError } from '@backstage/errors';\nimport { LoggerService } from '@backstage/backend-plugin-api';\nimport { StaticKeyStore } from './StaticKeyStore';\nimport { TokenParams } from '@backstage/plugin-auth-node';\n\nconst MS_IN_S = 1000;\n\nexport type Config = {\n publicKeyFile: string;\n privateKeyFile: string;\n keyId: string;\n algorithm?: string;\n};\n\nexport type Options = {\n logger: LoggerService;\n /** Value of the issuer claim in issued tokens */\n issuer: string;\n /** Expiration time of the JWT in seconds */\n sessionExpirationSeconds: number;\n};\n\n/**\n * A token issuer that issues tokens from predefined\n * public/private key pair stored in the static key store.\n */\nexport class StaticTokenIssuer implements TokenIssuer {\n private readonly issuer: string;\n private readonly logger: LoggerService;\n private readonly keyStore: StaticKeyStore;\n private readonly sessionExpirationSeconds: number;\n\n public constructor(options: Options, keyStore: StaticKeyStore) {\n this.issuer = options.issuer;\n this.logger = options.logger;\n this.sessionExpirationSeconds = options.sessionExpirationSeconds;\n this.keyStore = keyStore;\n }\n\n public async issueToken(params: TokenParams): Promise<string> {\n const key = await this.getSigningKey();\n\n // TODO: code shared with TokenFactory.ts\n const iss = this.issuer;\n const { sub, ent, ...additionalClaims } = params.claims;\n const aud = 'backstage';\n const iat = Math.floor(Date.now() / MS_IN_S);\n const exp = iat + this.sessionExpirationSeconds;\n\n // Validate that the subject claim is a valid EntityRef\n try {\n parseEntityRef(sub);\n } catch (error) {\n throw new Error(\n '\"sub\" claim provided by the auth resolver is not a valid EntityRef.',\n );\n }\n\n this.logger.info(`Issuing token for ${sub}, with entities ${ent ?? []}`);\n\n if (!key.alg) {\n throw new AuthenticationError('No algorithm was provided in the key');\n }\n\n return new SignJWT({ ...additionalClaims, iss, sub, ent, aud, iat, exp })\n .setProtectedHeader({ alg: key.alg, kid: key.kid })\n .setIssuer(iss)\n .setAudience(aud)\n .setSubject(sub)\n .setIssuedAt(iat)\n .setExpirationTime(exp)\n .sign(await importJWK(key));\n }\n\n private async getSigningKey(): Promise<JWK> {\n const { items: keys } = await this.keyStore.listKeys();\n if (keys.length >= 1) {\n return this.keyStore.getPrivateKey(keys[0].key.kid);\n }\n throw new Error('Keystore should hold at least 1 key');\n }\n\n public async listPublicKeys(): Promise<{ keys: AnyJWK[] }> {\n const { items: keys } = await this.keyStore.listKeys();\n return { keys: keys.map(({ key }) => key) };\n }\n}\n"],"names":["parseEntityRef","AuthenticationError","SignJWT","importJWK"],"mappings":";;;;;;AAwBA,MAAM,OAAU,GAAA,GAAA;AAqBT,MAAM,iBAAyC,CAAA;AAAA,EACnC,MAAA;AA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AAK,GAAI,CAAA,GAAA,EAAK,CAAA,CACjD,UAAU,GAAG,CAAA,CACb,YAAY,GAAG,CAAA,CACf,WAAW,GAAG,CAAA,CACd,YAAY,GAAG,CAAA,CACf,kBAAkB,GAAG,CAAA,CACrB,KAAK,MAAMC,cAAA,CAAU,GAAG,CAAC,CAAA;AAAA;AAC9B,EAEA,MAAc,aAA8B,GAAA;AAC1C,IAAA,MAAM,EAAE,KAAO,EAAA,IAAA,KAAS,MAAM,IAAA,CAAK,SAAS,QAAS,EAAA;AACrD,IAAI,IAAA,IAAA,CAAK,UAAU,CAAG,EAAA;AACpB,MAAA,OAAO,KAAK,QAAS,CAAA,aAAA,CAAc,KAAK,CAAC,CAAA,CAAE,IAAI,GAAG,CAAA;AAAA;AAEpD,IAAM,MAAA,IAAI,MAAM,qCAAqC,CAAA;AAAA;AACvD,EAEA,MAAa,cAA8C,GAAA;AACzD,IAAA,MAAM,EAAE,KAAO,EAAA,IAAA,KAAS,MAAM,IAAA,CAAK,SAAS,QAAS,EAAA;AACrD,IAAO,OAAA,EAAE,MAAM,IAAK,CAAA,GAAA,CAAI,CAAC,EAAE,GAAA,EAAU,KAAA,GAAG,CAAE,EAAA;AAAA;AAE9C;;;;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"TokenFactory.cjs.js","sources":["../../src/identity/TokenFactory.ts"],"sourcesContent":["/*\n * Copyright 2020 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { parseEntityRef } from '@backstage/catalog-model';\nimport { AuthenticationError } from '@backstage/errors';\nimport {\n exportJWK,\n generateKeyPair,\n importJWK,\n JWK,\n SignJWT,\n GeneralSign,\n KeyLike,\n} from 'jose';\nimport { omit } from 'lodash';\nimport { DateTime } from 'luxon';\nimport { v4 as uuid } from 'uuid';\nimport { LoggerService } from '@backstage/backend-plugin-api';\nimport { TokenParams, tokenTypes } from '@backstage/plugin-auth-node';\nimport { AnyJWK, KeyStore, TokenIssuer } from './types';\nimport { JsonValue } from '@backstage/types';\nimport { UserInfoDatabaseHandler } from './UserInfoDatabaseHandler';\n\nconst MS_IN_S = 1000;\nconst MAX_TOKEN_LENGTH = 32768; // At 64 bytes per entity ref this still leaves room for about 500 entities\n\n/**\n * The payload contents of a valid Backstage JWT token\n */\nexport interface BackstageTokenPayload {\n /**\n * The issuer of the token, currently the discovery URL of the auth backend\n */\n iss: string;\n\n /**\n * The entity ref of the user\n */\n sub: string;\n\n /**\n * The entity refs that the user claims ownership througg\n */\n ent: string[];\n\n /**\n * A hard coded audience string\n */\n aud: typeof tokenTypes.user.audClaim;\n\n /**\n * Standard expiry in epoch seconds\n */\n exp: number;\n\n /**\n * Standard issue time in epoch seconds\n */\n iat: number;\n\n /**\n * A separate user identity proof that the auth service can convert to a limited user token\n */\n uip: string;\n\n /**\n * Any other custom claims that the adopter may have added\n */\n [claim: string]: JsonValue;\n}\n\n/**\n * The payload contents of a valid Backstage user identity claim token\n *\n * @internal\n */\ninterface BackstageUserIdentityProofPayload {\n /**\n * The entity ref of the user\n */\n sub: string;\n\n /**\n * Standard expiry in epoch seconds\n */\n exp: number;\n\n /**\n * Standard issue time in epoch seconds\n */\n iat: number;\n}\n\ntype Options = {\n logger: LoggerService;\n /** Value of the issuer claim in issued tokens */\n issuer: string;\n /** Key store used for storing signing keys */\n keyStore: KeyStore;\n /** Expiration time of signing keys in seconds */\n keyDurationSeconds: number;\n /** JWS \"alg\" (Algorithm) Header Parameter value. Defaults to ES256.\n * Must match one of the algorithms defined for IdentityClient.\n * When setting a different algorithm, check if the `key` field\n * of the `signing_keys` table can fit the length of the generated keys.\n * If not, add a knex migration file in the migrations folder.\n * More info on supported algorithms: https://github.com/panva/jose */\n algorithm?: string;\n userInfoDatabaseHandler: UserInfoDatabaseHandler;\n};\n\n/**\n * A token issuer that is able to issue tokens in a distributed system\n * backed by a single database. Tokens are issued using lazily generated\n * signing keys, where each running instance of the auth service uses its own\n * signing key.\n *\n * The public parts of the keys are all stored in the shared key storage,\n * and any of the instances of the auth service will return the full list\n * of public keys that are currently in storage.\n *\n * Signing keys are automatically rotated at the same interval as the token\n * duration. Expired keys are kept in storage until there are no valid tokens\n * in circulation that could have been signed by that key.\n */\nexport class TokenFactory implements TokenIssuer {\n private readonly issuer: string;\n private readonly logger: LoggerService;\n private readonly keyStore: KeyStore;\n private readonly keyDurationSeconds: number;\n private readonly algorithm: string;\n private readonly userInfoDatabaseHandler: UserInfoDatabaseHandler;\n\n private keyExpiry?: Date;\n private privateKeyPromise?: Promise<JWK>;\n\n constructor(options: Options) {\n this.issuer = options.issuer;\n this.logger = options.logger;\n this.keyStore = options.keyStore;\n this.keyDurationSeconds = options.keyDurationSeconds;\n this.algorithm = options.algorithm ?? 'ES256';\n this.userInfoDatabaseHandler = options.userInfoDatabaseHandler;\n }\n\n async issueToken(params: TokenParams): Promise<string> {\n const key = await this.getKey();\n\n const iss = this.issuer;\n const { sub, ent = [sub], ...additionalClaims } = params.claims;\n const aud = tokenTypes.user.audClaim;\n const iat = Math.floor(Date.now() / MS_IN_S);\n const exp = iat + this.keyDurationSeconds;\n\n try {\n // The subject must be a valid entity ref\n parseEntityRef(sub);\n } catch (error) {\n throw new Error(\n '\"sub\" claim provided by the auth resolver is not a valid EntityRef.',\n );\n }\n\n if (!key.alg) {\n throw new AuthenticationError('No algorithm was provided in the key');\n }\n\n this.logger.info(`Issuing token for ${sub}, with entities ${ent}`);\n\n const signingKey = await importJWK(key);\n\n const uip = await this.createUserIdentityClaim({\n header: {\n typ: tokenTypes.limitedUser.typParam,\n alg: key.alg,\n kid: key.kid,\n },\n payload: { sub, iat, exp },\n key: signingKey,\n });\n\n const claims: BackstageTokenPayload = {\n ...additionalClaims,\n iss,\n sub,\n ent,\n aud,\n iat,\n exp,\n uip,\n };\n\n const token = await new SignJWT(claims)\n .setProtectedHeader({\n typ: tokenTypes.user.typParam,\n alg: key.alg,\n kid: key.kid,\n })\n .sign(signingKey);\n\n if (token.length > MAX_TOKEN_LENGTH) {\n throw new Error(\n `Failed to issue a new user token. The resulting token is excessively large, with either too many ownership claims or too large custom claims. You likely have a bug either in the sign-in resolver or catalog data. The following claims were requested: '${JSON.stringify(\n claims,\n )}'`,\n );\n }\n\n // Store the user info in the database upon successful token\n // issuance so that it can be retrieved later by limited user tokens\n await this.userInfoDatabaseHandler.addUserInfo({\n claims: omit(claims, ['aud', 'iat', 'iss', 'uip']),\n });\n\n return token;\n }\n\n // This will be called by other services that want to verify ID tokens.\n // It is important that it returns a list of all public keys that could\n // have been used to sign tokens that have not yet expired.\n async listPublicKeys(): Promise<{ keys: AnyJWK[] }> {\n const { items: keys } = await this.keyStore.listKeys();\n\n const validKeys = [];\n const expiredKeys = [];\n\n for (const key of keys) {\n // Allow for a grace period of another full key duration before we remove the keys from the database\n const expireAt = DateTime.fromJSDate(key.createdAt).plus({\n seconds: 3 * this.keyDurationSeconds,\n });\n if (expireAt < DateTime.local()) {\n expiredKeys.push(key);\n } else {\n validKeys.push(key);\n }\n }\n\n // Lazily prune expired keys. This may cause duplicate removals if we have concurrent callers, but w/e\n if (expiredKeys.length > 0) {\n const kids = expiredKeys.map(({ key }) => key.kid);\n\n this.logger.info(`Removing expired signing keys, '${kids.join(\"', '\")}'`);\n\n // We don't await this, just let it run in the background\n this.keyStore.removeKeys(kids).catch(error => {\n this.logger.error(`Failed to remove expired keys, ${error}`);\n });\n }\n\n // NOTE: we're currently only storing public keys, but if we start storing private keys we'd have to convert here\n return { keys: validKeys.map(({ key }) => key) };\n }\n\n private async getKey(): Promise<JWK> {\n // Make sure that we only generate one key at a time\n if (this.privateKeyPromise) {\n if (\n this.keyExpiry &&\n DateTime.fromJSDate(this.keyExpiry) > DateTime.local()\n ) {\n return this.privateKeyPromise;\n }\n this.logger.info(`Signing key has expired, generating new key`);\n delete this.privateKeyPromise;\n }\n\n this.keyExpiry = DateTime.utc()\n .plus({\n seconds: this.keyDurationSeconds,\n })\n .toJSDate();\n const promise = (async () => {\n // This generates a new signing key to be used to sign tokens until the next key rotation\n const key = await generateKeyPair(this.algorithm);\n const publicKey = await exportJWK(key.publicKey);\n const privateKey = await exportJWK(key.privateKey);\n publicKey.kid = privateKey.kid = uuid();\n publicKey.alg = privateKey.alg = this.algorithm;\n\n // We're not allowed to use the key until it has been successfully stored\n // TODO: some token verification implementations aggressively cache the list of keys, and\n // don't attempt to fetch new ones even if they encounter an unknown kid. Therefore we\n // may want to keep using the existing key for some period of time until we switch to\n // the new one. This also needs to be implemented cross-service though, meaning new services\n // that boot up need to be able to grab an existing key to use for signing.\n this.logger.info(`Created new signing key ${publicKey.kid}`);\n await this.keyStore.addKey(publicKey as AnyJWK);\n\n // At this point we are allowed to start using the new key\n return privateKey;\n })();\n\n this.privateKeyPromise = promise;\n\n try {\n // If we fail to generate a new key, we need to clear the state so that\n // the next caller will try to generate another key.\n await promise;\n } catch (error) {\n this.logger.error(`Failed to generate new signing key, ${error}`);\n delete this.keyExpiry;\n delete this.privateKeyPromise;\n }\n\n return promise;\n }\n\n // Creates a string claim that can be used as part of reconstructing a limited\n // user token. The output of this function is only the signature part of a\n // JWS.\n private async createUserIdentityClaim(options: {\n header: {\n typ: string;\n alg: string;\n kid?: string;\n };\n payload: BackstageUserIdentityProofPayload;\n key: KeyLike | Uint8Array;\n }): Promise<string> {\n // NOTE: We reconstruct the header and payload structures carefully to\n // perfectly guarantee ordering. The reason for this is that we store only\n // the signature part of these to reduce duplication within the Backstage\n // token. Anyone who wants to make an actual JWT based on all this must be\n // able to do the EXACT reconstruction of the header and payload parts, to\n // then append the signature.\n\n const header = {\n typ: options.header.typ,\n alg: options.header.alg,\n ...(options.header.kid ? { kid: options.header.kid } : {}),\n };\n\n const payload = {\n sub: options.payload.sub,\n iat: options.payload.iat,\n exp: options.payload.exp,\n };\n\n const jws = await new GeneralSign(\n new TextEncoder().encode(JSON.stringify(payload)),\n )\n .addSignature(options.key)\n .setProtectedHeader(header)\n .done()\n .sign();\n\n return jws.signatures[0].signature;\n }\n}\n"],"names":["tokenTypes","parseEntityRef","AuthenticationError","importJWK","SignJWT","omit","DateTime","generateKeyPair","exportJWK","uuid","GeneralSign"],"mappings":";;;;;;;;;;AAoCA,MAAM,OAAU,GAAA,GAAA,CAAA;AAChB,MAAM,gBAAmB,GAAA,KAAA,CAAA;AAqGlB,MAAM,YAAoC,CAAA;AAAA,EAC9B,MAAA,CAAA;AAAA,EACA,MAAA,CAAA;AAAA,EACA,QAAA,CAAA;AAAA,EACA,kBAAA,CAAA;AAAA,EACA,SAAA,CAAA;AAAA,EACA,uBAAA,CAAA;AAAA,EAET,SAAA,CAAA;AAAA,EACA,iBAAA,CAAA;AAAA,EAER,YAAY,OAAkB,EAAA;AAC5B,IAAA,IAAA,CAAK,SAAS,OAAQ,CAAA,MAAA,CAAA;AACtB,IAAA,IAAA,CAAK,SAAS,OAAQ,CAAA,MAAA,CAAA;AACtB,IAAA,IAAA,CAAK,WAAW,OAAQ,CAAA,QAAA,CAAA;AACxB,IAAA,IAAA,CAAK,qBAAqB,OAAQ,CAAA,kBAAA,CAAA;AAClC,IAAK,IAAA,CAAA,SAAA,GAAY,QAAQ,SAAa,IAAA,OAAA,CAAA;AACtC,IAAA,IAAA,CAAK,0BAA0B,OAAQ,CAAA,uBAAA,CAAA;AAAA,GACzC;AAAA,EAEA,MAAM,WAAW,MAAsC,EAAA;AACrD,IAAM,MAAA,GAAA,GAAM,MAAM,IAAA,CAAK,MAAO,EAAA,CAAA;AAE9B,IAAA,MAAM,MAAM,IAAK,CAAA,MAAA,CAAA;AACjB,IAAM,MAAA,EAAE,KAAK,GAAM,GAAA,CAAC,GAAG,CAAG,EAAA,GAAG,gBA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M,GAAA,EAAE,KAAK,OAAQ,CAAA,MAAA,CAAO,GAAI,EAAA,GAAI,EAAC;AAAA,KAC1D,CAAA;AAEA,IAAA,MAAM,OAAU,GAAA;AAAA,MACd,GAAA,EAAK,QAAQ,OAAQ,CAAA,GAAA;AAAA,MACrB,GAAA,EAAK,QAAQ,OAAQ,CAAA,GAAA;AAAA,MACrB,GAAA,EAAK,QAAQ,OAAQ,CAAA,GAAA;AAAA,KACvB,CAAA;AAEA,IAAM,MAAA,GAAA,GAAM,MAAM,IAAIC,gBAAA;AAAA,MACpB,IAAI,WAAY,EAAA,CAAE,OAAO,IAAK,CAAA,SAAA,CAAU,OAAO,CAAC,CAAA;AAAA,KAClD,CACG,YAAa,CAAA,OAAA,CAAQ,GAAG,CAAA,CACxB,mBAAmB,MAAM,CAAA,CACzB,IAAK,EAAA,CACL,IAAK,EAAA,CAAA;AAER,IAAO,OAAA,GAAA,CAAI,UAAW,CAAA,CAAC,CAAE,CAAA,SAAA,CAAA;AAAA,GAC3B;AACF;;;;"}
|
|
1
|
+
{"version":3,"file":"TokenFactory.cjs.js","sources":["../../src/identity/TokenFactory.ts"],"sourcesContent":["/*\n * Copyright 2020 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { parseEntityRef } from '@backstage/catalog-model';\nimport { AuthenticationError } from '@backstage/errors';\nimport {\n exportJWK,\n generateKeyPair,\n importJWK,\n JWK,\n SignJWT,\n GeneralSign,\n KeyLike,\n} from 'jose';\nimport { omit } from 'lodash';\nimport { DateTime } from 'luxon';\nimport { v4 as uuid } from 'uuid';\nimport { LoggerService } from '@backstage/backend-plugin-api';\nimport { TokenParams, tokenTypes } from '@backstage/plugin-auth-node';\nimport { AnyJWK, KeyStore, TokenIssuer } from './types';\nimport { JsonValue } from '@backstage/types';\nimport { UserInfoDatabaseHandler } from './UserInfoDatabaseHandler';\n\nconst MS_IN_S = 1000;\nconst MAX_TOKEN_LENGTH = 32768; // At 64 bytes per entity ref this still leaves room for about 500 entities\n\n/**\n * The payload contents of a valid Backstage JWT token\n */\nexport interface BackstageTokenPayload {\n /**\n * The issuer of the token, currently the discovery URL of the auth backend\n */\n iss: string;\n\n /**\n * The entity ref of the user\n */\n sub: string;\n\n /**\n * The entity refs that the user claims ownership througg\n */\n ent: string[];\n\n /**\n * A hard coded audience string\n */\n aud: typeof tokenTypes.user.audClaim;\n\n /**\n * Standard expiry in epoch seconds\n */\n exp: number;\n\n /**\n * Standard issue time in epoch seconds\n */\n iat: number;\n\n /**\n * A separate user identity proof that the auth service can convert to a limited user token\n */\n uip: string;\n\n /**\n * Any other custom claims that the adopter may have added\n */\n [claim: string]: JsonValue;\n}\n\n/**\n * The payload contents of a valid Backstage user identity claim token\n *\n * @internal\n */\ninterface BackstageUserIdentityProofPayload {\n /**\n * The entity ref of the user\n */\n sub: string;\n\n /**\n * Standard expiry in epoch seconds\n */\n exp: number;\n\n /**\n * Standard issue time in epoch seconds\n */\n iat: number;\n}\n\ntype Options = {\n logger: LoggerService;\n /** Value of the issuer claim in issued tokens */\n issuer: string;\n /** Key store used for storing signing keys */\n keyStore: KeyStore;\n /** Expiration time of signing keys in seconds */\n keyDurationSeconds: number;\n /** JWS \"alg\" (Algorithm) Header Parameter value. Defaults to ES256.\n * Must match one of the algorithms defined for IdentityClient.\n * When setting a different algorithm, check if the `key` field\n * of the `signing_keys` table can fit the length of the generated keys.\n * If not, add a knex migration file in the migrations folder.\n * More info on supported algorithms: https://github.com/panva/jose */\n algorithm?: string;\n userInfoDatabaseHandler: UserInfoDatabaseHandler;\n};\n\n/**\n * A token issuer that is able to issue tokens in a distributed system\n * backed by a single database. Tokens are issued using lazily generated\n * signing keys, where each running instance of the auth service uses its own\n * signing key.\n *\n * The public parts of the keys are all stored in the shared key storage,\n * and any of the instances of the auth service will return the full list\n * of public keys that are currently in storage.\n *\n * Signing keys are automatically rotated at the same interval as the token\n * duration. Expired keys are kept in storage until there are no valid tokens\n * in circulation that could have been signed by that key.\n */\nexport class TokenFactory implements TokenIssuer {\n private readonly issuer: string;\n private readonly logger: LoggerService;\n private readonly keyStore: KeyStore;\n private readonly keyDurationSeconds: number;\n private readonly algorithm: string;\n private readonly userInfoDatabaseHandler: UserInfoDatabaseHandler;\n\n private keyExpiry?: Date;\n private privateKeyPromise?: Promise<JWK>;\n\n constructor(options: Options) {\n this.issuer = options.issuer;\n this.logger = options.logger;\n this.keyStore = options.keyStore;\n this.keyDurationSeconds = options.keyDurationSeconds;\n this.algorithm = options.algorithm ?? 'ES256';\n this.userInfoDatabaseHandler = options.userInfoDatabaseHandler;\n }\n\n async issueToken(params: TokenParams): Promise<string> {\n const key = await this.getKey();\n\n const iss = this.issuer;\n const { sub, ent = [sub], ...additionalClaims } = params.claims;\n const aud = tokenTypes.user.audClaim;\n const iat = Math.floor(Date.now() / MS_IN_S);\n const exp = iat + this.keyDurationSeconds;\n\n try {\n // The subject must be a valid entity ref\n parseEntityRef(sub);\n } catch (error) {\n throw new Error(\n '\"sub\" claim provided by the auth resolver is not a valid EntityRef.',\n );\n }\n\n if (!key.alg) {\n throw new AuthenticationError('No algorithm was provided in the key');\n }\n\n this.logger.info(`Issuing token for ${sub}, with entities ${ent}`);\n\n const signingKey = await importJWK(key);\n\n const uip = await this.createUserIdentityClaim({\n header: {\n typ: tokenTypes.limitedUser.typParam,\n alg: key.alg,\n kid: key.kid,\n },\n payload: { sub, iat, exp },\n key: signingKey,\n });\n\n const claims: BackstageTokenPayload = {\n ...additionalClaims,\n iss,\n sub,\n ent,\n aud,\n iat,\n exp,\n uip,\n };\n\n const token = await new SignJWT(claims)\n .setProtectedHeader({\n typ: tokenTypes.user.typParam,\n alg: key.alg,\n kid: key.kid,\n })\n .sign(signingKey);\n\n if (token.length > MAX_TOKEN_LENGTH) {\n throw new Error(\n `Failed to issue a new user token. The resulting token is excessively large, with either too many ownership claims or too large custom claims. You likely have a bug either in the sign-in resolver or catalog data. The following claims were requested: '${JSON.stringify(\n claims,\n )}'`,\n );\n }\n\n // Store the user info in the database upon successful token\n // issuance so that it can be retrieved later by limited user tokens\n await this.userInfoDatabaseHandler.addUserInfo({\n claims: omit(claims, ['aud', 'iat', 'iss', 'uip']),\n });\n\n return token;\n }\n\n // This will be called by other services that want to verify ID tokens.\n // It is important that it returns a list of all public keys that could\n // have been used to sign tokens that have not yet expired.\n async listPublicKeys(): Promise<{ keys: AnyJWK[] }> {\n const { items: keys } = await this.keyStore.listKeys();\n\n const validKeys = [];\n const expiredKeys = [];\n\n for (const key of keys) {\n // Allow for a grace period of another full key duration before we remove the keys from the database\n const expireAt = DateTime.fromJSDate(key.createdAt).plus({\n seconds: 3 * this.keyDurationSeconds,\n });\n if (expireAt < DateTime.local()) {\n expiredKeys.push(key);\n } else {\n validKeys.push(key);\n }\n }\n\n // Lazily prune expired keys. This may cause duplicate removals if we have concurrent callers, but w/e\n if (expiredKeys.length > 0) {\n const kids = expiredKeys.map(({ key }) => key.kid);\n\n this.logger.info(`Removing expired signing keys, '${kids.join(\"', '\")}'`);\n\n // We don't await this, just let it run in the background\n this.keyStore.removeKeys(kids).catch(error => {\n this.logger.error(`Failed to remove expired keys, ${error}`);\n });\n }\n\n // NOTE: we're currently only storing public keys, but if we start storing private keys we'd have to convert here\n return { keys: validKeys.map(({ key }) => key) };\n }\n\n private async getKey(): Promise<JWK> {\n // Make sure that we only generate one key at a time\n if (this.privateKeyPromise) {\n if (\n this.keyExpiry &&\n DateTime.fromJSDate(this.keyExpiry) > DateTime.local()\n ) {\n return this.privateKeyPromise;\n }\n this.logger.info(`Signing key has expired, generating new key`);\n delete this.privateKeyPromise;\n }\n\n this.keyExpiry = DateTime.utc()\n .plus({\n seconds: this.keyDurationSeconds,\n })\n .toJSDate();\n const promise = (async () => {\n // This generates a new signing key to be used to sign tokens until the next key rotation\n const key = await generateKeyPair(this.algorithm);\n const publicKey = await exportJWK(key.publicKey);\n const privateKey = await exportJWK(key.privateKey);\n publicKey.kid = privateKey.kid = uuid();\n publicKey.alg = privateKey.alg = this.algorithm;\n\n // We're not allowed to use the key until it has been successfully stored\n // TODO: some token verification implementations aggressively cache the list of keys, and\n // don't attempt to fetch new ones even if they encounter an unknown kid. Therefore we\n // may want to keep using the existing key for some period of time until we switch to\n // the new one. This also needs to be implemented cross-service though, meaning new services\n // that boot up need to be able to grab an existing key to use for signing.\n this.logger.info(`Created new signing key ${publicKey.kid}`);\n await this.keyStore.addKey(publicKey as AnyJWK);\n\n // At this point we are allowed to start using the new key\n return privateKey;\n })();\n\n this.privateKeyPromise = promise;\n\n try {\n // If we fail to generate a new key, we need to clear the state so that\n // the next caller will try to generate another key.\n await promise;\n } catch (error) {\n this.logger.error(`Failed to generate new signing key, ${error}`);\n delete this.keyExpiry;\n delete this.privateKeyPromise;\n }\n\n return promise;\n }\n\n // Creates a string claim that can be used as part of reconstructing a limited\n // user token. The output of this function is only the signature part of a\n // JWS.\n private async createUserIdentityClaim(options: {\n header: {\n typ: string;\n alg: string;\n kid?: string;\n };\n payload: BackstageUserIdentityProofPayload;\n key: KeyLike | Uint8Array;\n }): Promise<string> {\n // NOTE: We reconstruct the header and payload structures carefully to\n // perfectly guarantee ordering. The reason for this is that we store only\n // the signature part of these to reduce duplication within the Backstage\n // token. Anyone who wants to make an actual JWT based on all this must be\n // able to do the EXACT reconstruction of the header and payload parts, to\n // then append the signature.\n\n const header = {\n typ: options.header.typ,\n alg: options.header.alg,\n ...(options.header.kid ? { kid: options.header.kid } : {}),\n };\n\n const payload = {\n sub: options.payload.sub,\n iat: options.payload.iat,\n exp: options.payload.exp,\n };\n\n const jws = await new GeneralSign(\n new TextEncoder().encode(JSON.stringify(payload)),\n )\n .addSignature(options.key)\n .setProtectedHeader(header)\n .done()\n .sign();\n\n return jws.signatures[0].signature;\n }\n}\n"],"names":["tokenTypes","parseEntityRef","AuthenticationError","importJWK","SignJWT","omit","DateTime","generateKeyPair","exportJWK","uuid","GeneralSign"],"mappings":";;;;;;;;;;AAoCA,MAAM,OAAU,GAAA,GAAA;AAChB,MAAM,gBAAmB,GAAA,KAAA;AAqGlB,MAAM,YAAoC,CAAA;AAAA,EAC9B,MAAA;AAAA,EACA,MAAA;AAAA,EACA,QAAA;AAAA,EACA,kBAAA;AAAA,EACA,SAAA;AAAA,EACA,uBAAA;AAAA,EAET,SAAA;AAAA,EACA,iBAAA;AAAA,EAER,YAAY,OAAkB,EAAA;AAC5B,IAAA,IAAA,CAAK,SAAS,OAAQ,CAAA,MAAA;AACtB,IAAA,IAAA,CAAK,SAAS,OAAQ,CAAA,MAAA;AACtB,IAAA,IAAA,CAAK,WAAW,OAAQ,CAAA,QAAA;AACxB,IAAA,IAAA,CAAK,qBAAqB,OAAQ,CAAA,kBAAA;AAClC,IAAK,IAAA,CAAA,SAAA,GAAY,QAAQ,SAAa,IAAA,OAAA;AACtC,IAAA,IAAA,CAAK,0BAA0B,OAAQ,CAAA,uBAAA;AAAA;AACzC,EAEA,MAAM,WAAW,MAAsC,EAAA;AACrD,IAAM,MAAA,GAAA,GAAM,MAAM,IAAA,CAAK,MAAO,EAAA;AAE9B,IAAA,MAAM,MAAM,IAAK,CAAA,MAAA;AACjB,IAAM,MAAA,EAAE,KAAK,GAAM,GAAA,CAAC,GAAG,CAAG,EAAA,GAAG,gBAAiB,EAAA,GAAI,MAAO,CAAA,MAAA;AACzD,IAAM,MAAA,GAAA,GAAMA,0BAAW,IAAK,CAAA,QAAA;AAC5B,IAAA,MAAM,MAAM,IAAK,CAAA,KAAA,CAAM,IAAK,CAAA,GAAA,KAAQ,OAAO,CAAA;AAC3C,IAAM,MAAA,GAAA,GAAM,MAAM,IAAK,CAAA,kBAAA;AAEvB,IAAI,IAAA;AA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andler.cjs.js","sources":["../../src/identity/UserInfoDatabaseHandler.ts"],"sourcesContent":["/*\n * Copyright 2024 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { DateTime } from 'luxon';\nimport { Knex } from 'knex';\n\nimport { BackstageTokenPayload } from './TokenFactory';\n\nconst TABLE = 'user_info';\n\ntype Row = {\n user_entity_ref: string;\n user_info: string;\n exp: string;\n};\n\ntype UserInfo = {\n claims: Omit<BackstageTokenPayload, 'aud' | 'iat' | 'iss' | 'uip'>;\n};\n\nexport class UserInfoDatabaseHandler {\n constructor(private readonly client: Knex) {}\n\n async addUserInfo(userInfo: UserInfo): Promise<void> {\n await this.client<Row>(TABLE)\n .insert({\n user_entity_ref: userInfo.claims.sub as string,\n user_info: JSON.stringify(userInfo),\n exp: DateTime.fromSeconds(userInfo.claims.exp as number, {\n zone: 'utc',\n }).toSQL({ includeOffset: false }),\n })\n .onConflict('user_entity_ref')\n .merge();\n }\n\n async getUserInfo(userEntityRef: string): Promise<UserInfo | undefined> {\n const info = await this.client<Row>(TABLE)\n .where({ user_entity_ref: userEntityRef })\n .first();\n\n if (!info) {\n return undefined;\n }\n\n const userInfo = JSON.parse(info.user_info);\n return userInfo;\n }\n}\n"],"names":["DateTime"],"mappings":";;;;AAqBA,MAAM,KAAQ,GAAA,WAAA
|
|
1
|
+
{"version":3,"file":"UserInfoDatabaseHandler.cjs.js","sources":["../../src/identity/UserInfoDatabaseHandler.ts"],"sourcesContent":["/*\n * Copyright 2024 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { DateTime } from 'luxon';\nimport { Knex } from 'knex';\n\nimport { BackstageTokenPayload } from './TokenFactory';\n\nconst TABLE = 'user_info';\n\ntype Row = {\n user_entity_ref: string;\n user_info: string;\n exp: string;\n};\n\ntype UserInfo = {\n claims: Omit<BackstageTokenPayload, 'aud' | 'iat' | 'iss' | 'uip'>;\n};\n\nexport class UserInfoDatabaseHandler {\n constructor(private readonly client: Knex) {}\n\n async addUserInfo(userInfo: UserInfo): Promise<void> {\n await this.client<Row>(TABLE)\n .insert({\n user_entity_ref: userInfo.claims.sub as string,\n user_info: JSON.stringify(userInfo),\n exp: DateTime.fromSeconds(userInfo.claims.exp as number, {\n zone: 'utc',\n }).toSQL({ includeOffset: false }),\n })\n .onConflict('user_entity_ref')\n .merge();\n }\n\n async getUserInfo(userEntityRef: string): Promise<UserInfo | undefined> {\n const info = await this.client<Row>(TABLE)\n .where({ user_entity_ref: userEntityRef })\n .first();\n\n if (!info) {\n return undefined;\n }\n\n const userInfo = JSON.parse(info.user_info);\n return userInfo;\n }\n}\n"],"names":["DateTime"],"mappings":";;;;AAqBA,MAAM,KAAQ,GAAA,WAAA;AAYP,MAAM,uBAAwB,CAAA;AAAA,EACnC,YAA6B,MAAc,EAAA;AAAd,IAAA,IAAA,CAAA,MAAA,GAAA,MAAA;AAAA;AAAe,EAE5C,MAAM,YAAY,QAAmC,EAAA;AACnD,IAAA,MAAM,IAAK,CAAA,MAAA,CAAY,KAAK,CAAA,CACzB,MAAO,CAAA;AAAA,MACN,eAAA,EAAiB,SAAS,MAAO,CAAA,GAAA;AAAA,MACjC,SAAA,EAAW,IAAK,CAAA,SAAA,CAAU,QAAQ,CAAA;AAAA,MAClC,GAAK,EAAAA,cAAA,CAAS,WAAY,CAAA,QAAA,CAAS,OAAO,GAAe,EAAA;AAAA,QACvD,IAAM,EAAA;AAAA,OACP,CAAE,CAAA,KAAA,CAAM,EAAE,aAAA,EAAe,OAAO;AAAA,KAClC,CAAA,CACA,UAAW,CAAA,iBAAiB,EAC5B,KAAM,EAAA;AAAA;AACX,EAEA,MAAM,YAAY,aAAsD,EAAA;AACtE,IAAA,MAAM,IAAO,GAAA,MAAM,IAAK,CAAA,MAAA,CAAY,KAAK,CAAA,CACtC,KAAM,CAAA,EAAE,eAAiB,EAAA,aAAA,EAAe,CAAA,CACxC,KAAM,EAAA;AAET,IAAA,IAAI,CAAC,IAAM,EAAA;AACT,MAAO,OAAA,KAAA,CAAA;AAAA;AAGT,IAAA,MAAM,QAAW,GAAA,IAAA,CAAK,KAAM,CAAA,IAAA,CAAK,SAAS,CAAA;AAC1C,IAAO,OAAA,QAAA;AAAA;AAEX;;;;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"router.cjs.js","sources":["../../src/identity/router.ts"],"sourcesContent":["/*\n * Copyright 2020 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport express from 'express';\nimport Router from 'express-promise-router';\nimport { TokenIssuer } from './types';\nimport { AuthService } from '@backstage/backend-plugin-api';\nimport { decodeJwt } from 'jose';\nimport { AuthenticationError, InputError } from '@backstage/errors';\nimport { UserInfoDatabaseHandler } from './UserInfoDatabaseHandler';\n\nexport function bindOidcRouter(\n targetRouter: express.Router,\n options: {\n baseUrl: string;\n auth: AuthService;\n tokenIssuer: TokenIssuer;\n userInfoDatabaseHandler: UserInfoDatabaseHandler;\n },\n) {\n const { baseUrl, auth, tokenIssuer, userInfoDatabaseHandler } = options;\n\n const router = Router();\n targetRouter.use(router);\n\n const config = {\n issuer: baseUrl,\n token_endpoint: `${baseUrl}/v1/token`,\n userinfo_endpoint: `${baseUrl}/v1/userinfo`,\n jwks_uri: `${baseUrl}/.well-known/jwks.json`,\n response_types_supported: ['id_token'],\n subject_types_supported: ['public'],\n id_token_signing_alg_values_supported: [\n 'RS256',\n 'RS384',\n 'RS512',\n 'ES256',\n 'ES384',\n 'ES512',\n 'PS256',\n 'PS384',\n 'PS512',\n 'EdDSA',\n ],\n scopes_supported: ['openid'],\n token_endpoint_auth_methods_supported: [],\n claims_supported: ['sub', 'ent'],\n grant_types_supported: [],\n };\n\n router.get('/.well-known/openid-configuration', (_req, res) => {\n res.json(config);\n });\n\n router.get('/.well-known/jwks.json', async (_req, res) => {\n const { keys } = await tokenIssuer.listPublicKeys();\n res.json({ keys });\n });\n\n router.get('/v1/token', (_req, res) => {\n res.status(501).send('Not Implemented');\n });\n\n // This endpoint doesn't use the regular HttpAuthService, since the contract\n // is specifically for the header to be communicated in the Authorization\n // header, regardless of token type\n router.get('/v1/userinfo', async (req, res) => {\n const matches = req.headers.authorization?.match(/^Bearer[ ]+(\\S+)$/i);\n const token = matches?.[1];\n if (!token) {\n throw new AuthenticationError('No token provided');\n }\n\n const credentials = await auth.authenticate(token, {\n allowLimitedAccess: true,\n });\n if (!auth.isPrincipal(credentials, 'user')) {\n throw new InputError(\n 'Userinfo endpoint must be called with a token that represents a user principal',\n );\n }\n\n const { sub: userEntityRef } = decodeJwt(token);\n\n if (typeof userEntityRef !== 'string') {\n throw new Error('Invalid user token, user entity ref must be a string');\n }\n\n const userInfo = await userInfoDatabaseHandler.getUserInfo(userEntityRef);\n if (!userInfo) {\n res.status(404).send('User info not found');\n return;\n }\n\n res.json(userInfo);\n });\n}\n"],"names":["Router","AuthenticationError","InputError","decodeJwt"],"mappings":";;;;;;;;;;AAwBgB,SAAA,cAAA,CACd,cACA,OAMA,EAAA;AACA,EAAA,MAAM,EAAE,OAAA,EAAS,IAAM,EAAA,WAAA,EAAa,yBAA4B,GAAA,OAAA
|
|
1
|
+
{"version":3,"file":"router.cjs.js","sources":["../../src/identity/router.ts"],"sourcesContent":["/*\n * Copyright 2020 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport express from 'express';\nimport Router from 'express-promise-router';\nimport { TokenIssuer } from './types';\nimport { AuthService } from '@backstage/backend-plugin-api';\nimport { decodeJwt } from 'jose';\nimport { AuthenticationError, InputError } from '@backstage/errors';\nimport { UserInfoDatabaseHandler } from './UserInfoDatabaseHandler';\n\nexport function bindOidcRouter(\n targetRouter: express.Router,\n options: {\n baseUrl: string;\n auth: AuthService;\n tokenIssuer: TokenIssuer;\n userInfoDatabaseHandler: UserInfoDatabaseHandler;\n },\n) {\n const { baseUrl, auth, tokenIssuer, userInfoDatabaseHandler } = options;\n\n const router = Router();\n targetRouter.use(router);\n\n const config = {\n issuer: baseUrl,\n token_endpoint: `${baseUrl}/v1/token`,\n userinfo_endpoint: `${baseUrl}/v1/userinfo`,\n jwks_uri: `${baseUrl}/.well-known/jwks.json`,\n response_types_supported: ['id_token'],\n subject_types_supported: ['public'],\n id_token_signing_alg_values_supported: [\n 'RS256',\n 'RS384',\n 'RS512',\n 'ES256',\n 'ES384',\n 'ES512',\n 'PS256',\n 'PS384',\n 'PS512',\n 'EdDSA',\n ],\n scopes_supported: ['openid'],\n token_endpoint_auth_methods_supported: [],\n claims_supported: ['sub', 'ent'],\n grant_types_supported: [],\n };\n\n router.get('/.well-known/openid-configuration', (_req, res) => {\n res.json(config);\n });\n\n router.get('/.well-known/jwks.json', async (_req, res) => {\n const { keys } = await tokenIssuer.listPublicKeys();\n res.json({ keys });\n });\n\n router.get('/v1/token', (_req, res) => {\n res.status(501).send('Not Implemented');\n });\n\n // This endpoint doesn't use the regular HttpAuthService, since the contract\n // is specifically for the header to be communicated in the Authorization\n // header, regardless of token type\n router.get('/v1/userinfo', async (req, res) => {\n const matches = req.headers.authorization?.match(/^Bearer[ ]+(\\S+)$/i);\n const token = matches?.[1];\n if (!token) {\n throw new AuthenticationError('No token provided');\n }\n\n const credentials = await auth.authenticate(token, {\n allowLimitedAccess: true,\n });\n if (!auth.isPrincipal(credentials, 'user')) {\n throw new InputError(\n 'Userinfo endpoint must be called with a token that represents a user principal',\n );\n }\n\n const { sub: userEntityRef } = decodeJwt(token);\n\n if (typeof userEntityRef !== 'string') {\n throw new Error('Invalid user token, user entity ref must be a string');\n }\n\n const userInfo = await userInfoDatabaseHandler.getUserInfo(userEntityRef);\n if (!userInfo) {\n res.status(404).send('User info not found');\n return;\n }\n\n res.json(userInfo);\n });\n}\n"],"names":["Router","AuthenticationError","InputError","decodeJwt"],"mappings":";;;;;;;;;;AAwBgB,SAAA,cAAA,CACd,cACA,OAMA,EAAA;AACA,EAAA,MAAM,EAAE,OAAA,EAAS,IAAM,EAAA,WAAA,EAAa,yBAA4B,GAAA,OAAA;AAEhE,EAAA,MAAM,SAASA,uBAAO,EAAA;AACtB,EAAA,YAAA,CAAa,IAAI,MAAM,CAAA;AAEvB,EAAA,MAAM,MAAS,GAAA;AAAA,IACb,MAAQ,EAAA,OAAA;AAAA,IACR,cAAA,EAAgB,GAAG,OAAO,CAAA,SAAA,CAAA;AAAA,IAC1B,iBAAA,EAAmB,GAAG,OAAO,CAAA,YAAA,CAAA;AAAA,IAC7B,QAAA,EAAU,GAAG,OAAO,CAAA,sBAAA,CAAA;AAAA,IACpB,wBAAA,EAA0B,CAA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AM,MAAA,IAAIC,2BAAoB,mBAAmB,CAAA;AAAA;AAGnD,IAAA,MAAM,WAAc,GAAA,MAAM,IAAK,CAAA,YAAA,CAAa,KAAO,EAAA;AAAA,MACjD,kBAAoB,EAAA;AAAA,KACrB,CAAA;AACD,IAAA,IAAI,CAAC,IAAA,CAAK,WAAY,CAAA,WAAA,EAAa,MAAM,CAAG,EAAA;AAC1C,MAAA,MAAM,IAAIC,iBAAA;AAAA,QACR;AAAA,OACF;AAAA;AAGF,IAAA,MAAM,EAAE,GAAA,EAAK,aAAc,EAAA,GAAIC,eAAU,KAAK,CAAA;AAE9C,IAAI,IAAA,OAAO,kBAAkB,QAAU,EAAA;AACrC,MAAM,MAAA,IAAI,MAAM,sDAAsD,CAAA;AAAA;AAGxE,IAAA,MAAM,QAAW,GAAA,MAAM,uBAAwB,CAAA,WAAA,CAAY,aAAa,CAAA;AACxE,IAAA,IAAI,CAAC,QAAU,EAAA;AACb,MAAA,GAAA,CAAI,MAAO,CAAA,GAAG,CAAE,CAAA,IAAA,CAAK,qBAAqB,CAAA;AAC1C,MAAA;AAAA;AAGF,IAAA,GAAA,CAAI,KAAK,QAAQ,CAAA;AAAA,GAClB,CAAA;AACH;;;;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"CatalogIdentityClient.cjs.js","sources":["../../../src/lib/catalog/CatalogIdentityClient.ts"],"sourcesContent":["/*\n * Copyright 2020 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n AuthService,\n DiscoveryService,\n HttpAuthService,\n LoggerService,\n} from '@backstage/backend-plugin-api';\nimport { ConflictError, NotFoundError } from '@backstage/errors';\nimport { CatalogApi } from '@backstage/catalog-client';\nimport {\n CompoundEntityRef,\n parseEntityRef,\n RELATION_MEMBER_OF,\n stringifyEntityRef,\n UserEntity,\n} from '@backstage/catalog-model';\nimport {\n TokenManager,\n createLegacyAuthAdapters,\n} from '@backstage/backend-common';\n\n/**\n * A catalog client tailored for reading out identity data from the catalog.\n *\n * @public\n */\nexport class CatalogIdentityClient {\n private readonly catalogApi: CatalogApi;\n private readonly auth: AuthService;\n\n constructor(options: {\n catalogApi: CatalogApi;\n tokenManager?: TokenManager;\n discovery: DiscoveryService;\n auth?: AuthService;\n httpAuth?: HttpAuthService;\n }) {\n this.catalogApi = options.catalogApi;\n\n const { auth } = createLegacyAuthAdapters({\n auth: options.auth,\n httpAuth: options.httpAuth,\n discovery: options.discovery,\n tokenManager: options.tokenManager,\n });\n\n this.auth = auth;\n }\n\n /**\n * Looks up a single user using a query.\n *\n * Throws a NotFoundError or ConflictError if 0 or multiple users are found.\n */\n async findUser(query: {\n annotations: Record<string, string>;\n }): Promise<UserEntity> {\n const filter: Record<string, string> = {\n kind: 'user',\n };\n for (const [key, value] of Object.entries(query.annotations)) {\n filter[`metadata.annotations.${key}`] = value;\n }\n\n const { token } = await this.auth.getPluginRequestToken({\n onBehalfOf: await this.auth.getOwnServiceCredentials(),\n targetPluginId: 'catalog',\n });\n\n const { items } = await this.catalogApi.getEntities({ filter }, { token });\n\n if (items.length !== 1) {\n if (items.length > 1) {\n throw new ConflictError('User lookup resulted in multiple matches');\n } else {\n throw new NotFoundError('User not found');\n }\n }\n\n return items[0] as UserEntity;\n }\n\n /**\n * Resolve additional entity claims from the catalog, using the passed-in entity names. Designed\n * to be used within a `signInResolver` where additional entity claims might be provided, but\n * group membership and transient group membership lean on imported catalog relations.\n *\n * Returns a superset of the entity names that can be passed directly to `issueToken` as `ent`.\n */\n async resolveCatalogMembership(query: {\n entityRefs: string[];\n logger?: LoggerService;\n }): Promise<string[]> {\n const { entityRefs, logger } = query;\n const resolvedEntityRefs = entityRefs\n .map((ref: string) => {\n try {\n const parsedRef = parseEntityRef(ref.toLocaleLowerCase('en-US'), {\n defaultKind: 'user',\n defaultNamespace: 'default',\n });\n return parsedRef;\n } catch {\n logger?.warn(`Failed to parse entityRef from ${ref}, ignoring`);\n return null;\n }\n })\n .filter((ref): ref is CompoundEntityRef => ref !== null);\n\n const filter = resolvedEntityRefs.map(ref => ({\n kind: ref.kind,\n 'metadata.namespace': ref.namespace,\n 'metadata.name': ref.name,\n }));\n\n const { token } = await this.auth.getPluginRequestToken({\n onBehalfOf: await this.auth.getOwnServiceCredentials(),\n targetPluginId: 'catalog',\n });\n\n const entities = await this.catalogApi\n .getEntities({ filter }, { token })\n .then(r => r.items);\n\n if (entityRefs.length !== entities.length) {\n const foundEntityNames = entities.map(stringifyEntityRef);\n const missingEntityNames = resolvedEntityRefs\n .map(stringifyEntityRef)\n .filter(s => !foundEntityNames.includes(s));\n logger?.debug(`Entities not found for refs ${missingEntityNames.join()}`);\n }\n\n const memberOf = entities.flatMap(\n e =>\n e!.relations\n ?.filter(r => r.type === RELATION_MEMBER_OF)\n .map(r => r.targetRef) ?? [],\n );\n\n const newEntityRefs = [\n ...new Set(resolvedEntityRefs.map(stringifyEntityRef).concat(memberOf)),\n ];\n\n logger?.debug(`Found catalog membership: ${newEntityRefs.join()}`);\n return newEntityRefs;\n }\n}\n"],"names":["createLegacyAuthAdapters","ConflictError","NotFoundError","parseEntityRef","stringifyEntityRef","RELATION_MEMBER_OF"],"mappings":";;;;;;AAyCO,MAAM,qBAAsB,CAAA;AAAA,EAChB,UAAA
|
|
1
|
+
{"version":3,"file":"CatalogIdentityClient.cjs.js","sources":["../../../src/lib/catalog/CatalogIdentityClient.ts"],"sourcesContent":["/*\n * Copyright 2020 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n AuthService,\n DiscoveryService,\n HttpAuthService,\n LoggerService,\n} from '@backstage/backend-plugin-api';\nimport { ConflictError, NotFoundError } from '@backstage/errors';\nimport { CatalogApi } from '@backstage/catalog-client';\nimport {\n CompoundEntityRef,\n parseEntityRef,\n RELATION_MEMBER_OF,\n stringifyEntityRef,\n UserEntity,\n} from '@backstage/catalog-model';\nimport {\n TokenManager,\n createLegacyAuthAdapters,\n} from '@backstage/backend-common';\n\n/**\n * A catalog client tailored for reading out identity data from the catalog.\n *\n * @public\n */\nexport class CatalogIdentityClient {\n private readonly catalogApi: CatalogApi;\n private readonly auth: AuthService;\n\n constructor(options: {\n catalogApi: CatalogApi;\n tokenManager?: TokenManager;\n discovery: DiscoveryService;\n auth?: AuthService;\n httpAuth?: HttpAuthService;\n }) {\n this.catalogApi = options.catalogApi;\n\n const { auth } = createLegacyAuthAdapters({\n auth: options.auth,\n httpAuth: options.httpAuth,\n discovery: options.discovery,\n tokenManager: options.tokenManager,\n });\n\n this.auth = auth;\n }\n\n /**\n * Looks up a single user using a query.\n *\n * Throws a NotFoundError or ConflictError if 0 or multiple users are found.\n */\n async findUser(query: {\n annotations: Record<string, string>;\n }): Promise<UserEntity> {\n const filter: Record<string, string> = {\n kind: 'user',\n };\n for (const [key, value] of Object.entries(query.annotations)) {\n filter[`metadata.annotations.${key}`] = value;\n }\n\n const { token } = await this.auth.getPluginRequestToken({\n onBehalfOf: await this.auth.getOwnServiceCredentials(),\n targetPluginId: 'catalog',\n });\n\n const { items } = await this.catalogApi.getEntities({ filter }, { token });\n\n if (items.length !== 1) {\n if (items.length > 1) {\n throw new ConflictError('User lookup resulted in multiple matches');\n } else {\n throw new NotFoundError('User not found');\n }\n }\n\n return items[0] as UserEntity;\n }\n\n /**\n * Resolve additional entity claims from the catalog, using the passed-in entity names. Designed\n * to be used within a `signInResolver` where additional entity claims might be provided, but\n * group membership and transient group membership lean on imported catalog relations.\n *\n * Returns a superset of the entity names that can be passed directly to `issueToken` as `ent`.\n */\n async resolveCatalogMembership(query: {\n entityRefs: string[];\n logger?: LoggerService;\n }): Promise<string[]> {\n const { entityRefs, logger } = query;\n const resolvedEntityRefs = entityRefs\n .map((ref: string) => {\n try {\n const parsedRef = parseEntityRef(ref.toLocaleLowerCase('en-US'), {\n defaultKind: 'user',\n defaultNamespace: 'default',\n });\n return parsedRef;\n } catch {\n logger?.warn(`Failed to parse entityRef from ${ref}, ignoring`);\n return null;\n }\n })\n .filter((ref): ref is CompoundEntityRef => ref !== null);\n\n const filter = resolvedEntityRefs.map(ref => ({\n kind: ref.kind,\n 'metadata.namespace': ref.namespace,\n 'metadata.name': ref.name,\n }));\n\n const { token } = await this.auth.getPluginRequestToken({\n onBehalfOf: await this.auth.getOwnServiceCredentials(),\n targetPluginId: 'catalog',\n });\n\n const entities = await this.catalogApi\n .getEntities({ filter }, { token })\n .then(r => r.items);\n\n if (entityRefs.length !== entities.length) {\n const foundEntityNames = entities.map(stringifyEntityRef);\n const missingEntityNames = resolvedEntityRefs\n .map(stringifyEntityRef)\n .filter(s => !foundEntityNames.includes(s));\n logger?.debug(`Entities not found for refs ${missingEntityNames.join()}`);\n }\n\n const memberOf = entities.flatMap(\n e =>\n e!.relations\n ?.filter(r => r.type === RELATION_MEMBER_OF)\n .map(r => r.targetRef) ?? [],\n );\n\n const newEntityRefs = [\n ...new Set(resolvedEntityRefs.map(stringifyEntityRef).concat(memberOf)),\n ];\n\n logger?.debug(`Found catalog membership: ${newEntityRefs.join()}`);\n return newEntityRefs;\n }\n}\n"],"names":["createLegacyAuthAdapters","ConflictError","NotFoundError","parseEntityRef","stringifyEntityRef","RELATION_MEMBER_OF"],"mappings":";;;;;;AAyCO,MAAM,qBAAsB,CAAA;AAAA,EAChB,UAAA;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A;AAEpB,IAAI,IAAA,UAAA,CAAW,MAAW,KAAA,QAAA,CAAS,MAAQ,EAAA;AACzC,MAAM,MAAA,gBAAA,GAAmB,QAAS,CAAA,GAAA,CAAIC,+BAAkB,CAAA;AACxD,MAAM,MAAA,kBAAA,GAAqB,kBACxB,CAAA,GAAA,CAAIA,+BAAkB,CAAA,CACtB,MAAO,CAAA,CAAA,CAAA,KAAK,CAAC,gBAAA,CAAiB,QAAS,CAAA,CAAC,CAAC,CAAA;AAC5C,MAAA,MAAA,EAAQ,KAAM,CAAA,CAAA,4BAAA,EAA+B,kBAAmB,CAAA,IAAA,EAAM,CAAE,CAAA,CAAA;AAAA;AAG1E,IAAA,MAAM,WAAW,QAAS,CAAA,OAAA;AAAA,MACxB,CACE,CAAA,KAAA,CAAA,CAAG,SACC,EAAA,MAAA,CAAO,OAAK,CAAE,CAAA,IAAA,KAASC,+BAAkB,CAAA,CAC1C,GAAI,CAAA,CAAA,CAAA,KAAK,CAAE,CAAA,SAAS,KAAK;AAAC,KACjC;AAEA,IAAA,MAAM,aAAgB,GAAA;AAAA,MACpB,GAAG,IAAI,GAAI,CAAA,kBAAA,CAAmB,IAAID,+BAAkB,CAAA,CAAE,MAAO,CAAA,QAAQ,CAAC;AAAA,KACxE;AAEA,IAAA,MAAA,EAAQ,KAAM,CAAA,CAAA,0BAAA,EAA6B,aAAc,CAAA,IAAA,EAAM,CAAE,CAAA,CAAA;AACjE,IAAO,OAAA,aAAA;AAAA;AAEX;;;;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"authFlowHelpers.cjs.js","sources":["../../../src/lib/flow/authFlowHelpers.ts"],"sourcesContent":["/*\n * Copyright 2020 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport express from 'express';\nimport crypto from 'crypto';\nimport { WebMessageResponse } from './types';\n\nexport const safelyEncodeURIComponent = (value: string) => {\n // Note the g at the end of the regex; all occurrences of single quotes must\n // be replaced, which encodeURIComponent does not do itself by default\n return encodeURIComponent(value).replace(/'/g, '%27');\n};\n\n/**\n * @public\n * @deprecated Use `sendWebMessageResponse` from `@backstage/plugin-auth-node` instead\n */\nexport const postMessageResponse = (\n res: express.Response,\n appOrigin: string,\n response: WebMessageResponse,\n) => {\n const jsonData = JSON.stringify(response);\n const base64Data = safelyEncodeURIComponent(jsonData);\n const base64Origin = safelyEncodeURIComponent(appOrigin);\n\n // NOTE: It is absolutely imperative that we use the safe encoder above, to\n // be sure that the js code below does not allow the injection of malicious\n // data.\n\n // TODO: Make target app origin configurable globally\n\n //\n // postMessage fails silently if the targetOrigin is disallowed.\n // So 2 postMessages are sent from the popup to the parent window.\n // First, the origin being used to post the actual authorization response is\n // shared with the parent window with a postMessage with targetOrigin '*'.\n // Second, the actual authorization response is sent with the app origin\n // as the targetOrigin.\n // If the first message was received but the actual auth response was\n // never received, the event listener can conclude that targetOrigin\n // was disallowed, indicating potential misconfiguration.\n //\n const script = `\n var authResponse = decodeURIComponent('${base64Data}');\n var origin = decodeURIComponent('${base64Origin}');\n var originInfo = {'type': 'config_info', 'targetOrigin': origin};\n (window.opener || window.parent).postMessage(originInfo, '*');\n (window.opener || window.parent).postMessage(JSON.parse(authResponse), origin);\n setTimeout(() => {\n window.close();\n }, 100); // same as the interval of the core-app-api lib/loginPopup.ts (to address race conditions)\n `;\n const hash = crypto.createHash('sha256').update(script).digest('base64');\n\n res.setHeader('Content-Type', 'text/html');\n res.setHeader('X-Frame-Options', 'sameorigin');\n res.setHeader('Content-Security-Policy', `script-src 'sha256-${hash}'`);\n res.end(`<html><body><script>${script}</script></body></html>`);\n};\n\n/**\n * @public\n * @deprecated Use inline logic to check that the `X-Requested-With` header is set to `'XMLHttpRequest'` instead.\n */\nexport const ensuresXRequestedWith = (req: express.Request) => {\n const requiredHeader = req.header('X-Requested-With');\n if (!requiredHeader || requiredHeader !== 'XMLHttpRequest') {\n return false;\n }\n return true;\n};\n"],"names":["crypto"],"mappings":";;;;;;;;AAoBa,MAAA,wBAAA,GAA2B,CAAC,KAAkB,KAAA;AAGzD,EAAA,OAAO,kBAAmB,CAAA,KAAK,CAAE,CAAA,OAAA,CAAQ,MAAM,KAAK,CAAA
|
|
1
|
+
{"version":3,"file":"authFlowHelpers.cjs.js","sources":["../../../src/lib/flow/authFlowHelpers.ts"],"sourcesContent":["/*\n * Copyright 2020 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport express from 'express';\nimport crypto from 'crypto';\nimport { WebMessageResponse } from './types';\n\nexport const safelyEncodeURIComponent = (value: string) => {\n // Note the g at the end of the regex; all occurrences of single quotes must\n // be replaced, which encodeURIComponent does not do itself by default\n return encodeURIComponent(value).replace(/'/g, '%27');\n};\n\n/**\n * @public\n * @deprecated Use `sendWebMessageResponse` from `@backstage/plugin-auth-node` instead\n */\nexport const postMessageResponse = (\n res: express.Response,\n appOrigin: string,\n response: WebMessageResponse,\n) => {\n const jsonData = JSON.stringify(response);\n const base64Data = safelyEncodeURIComponent(jsonData);\n const base64Origin = safelyEncodeURIComponent(appOrigin);\n\n // NOTE: It is absolutely imperative that we use the safe encoder above, to\n // be sure that the js code below does not allow the injection of malicious\n // data.\n\n // TODO: Make target app origin configurable globally\n\n //\n // postMessage fails silently if the targetOrigin is disallowed.\n // So 2 postMessages are sent from the popup to the parent window.\n // First, the origin being used to post the actual authorization response is\n // shared with the parent window with a postMessage with targetOrigin '*'.\n // Second, the actual authorization response is sent with the app origin\n // as the targetOrigin.\n // If the first message was received but the actual auth response was\n // never received, the event listener can conclude that targetOrigin\n // was disallowed, indicating potential misconfiguration.\n //\n const script = `\n var authResponse = decodeURIComponent('${base64Data}');\n var origin = decodeURIComponent('${base64Origin}');\n var originInfo = {'type': 'config_info', 'targetOrigin': origin};\n (window.opener || window.parent).postMessage(originInfo, '*');\n (window.opener || window.parent).postMessage(JSON.parse(authResponse), origin);\n setTimeout(() => {\n window.close();\n }, 100); // same as the interval of the core-app-api lib/loginPopup.ts (to address race conditions)\n `;\n const hash = crypto.createHash('sha256').update(script).digest('base64');\n\n res.setHeader('Content-Type', 'text/html');\n res.setHeader('X-Frame-Options', 'sameorigin');\n res.setHeader('Content-Security-Policy', `script-src 'sha256-${hash}'`);\n res.end(`<html><body><script>${script}</script></body></html>`);\n};\n\n/**\n * @public\n * @deprecated Use inline logic to check that the `X-Requested-With` header is set to `'XMLHttpRequest'` instead.\n */\nexport const ensuresXRequestedWith = (req: express.Request) => {\n const requiredHeader = req.header('X-Requested-With');\n if (!requiredHeader || requiredHeader !== 'XMLHttpRequest') {\n return false;\n }\n return true;\n};\n"],"names":["crypto"],"mappings":";;;;;;;;AAoBa,MAAA,wBAAA,GAA2B,CAAC,KAAkB,KAAA;AAGzD,EAAA,OAAO,kBAAmB,CAAA,KAAK,CAAE,CAAA,OAAA,CAAQ,MAAM,KAAK,CAAA;AACtD;AAMO,MAAM,mBAAsB,GAAA,CACjC,GACA,EAAA,SAAA,EACA,QACG,KAAA;AACH,EAAM,MAAA,QAAA,GAAW,IAAK,CAAA,SAAA,CAAU,QAAQ,CAAA;AACxC,EAAM,MAAA,UAAA,GAAa,yBAAyB,QAAQ,CAAA;AACpD,EAAM,MAAA,YAAA,GAAe,yBAAyB,SAAS,CAAA;AAmBvD,EAAA,MAAM,MAAS,GAAA;AAAA,2CAAA,EAC4B,UAAU,CAAA;AAAA,qCAAA,EAChB,YAAY,CAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAAA,CAAA;AAQjD,EAAM,MAAA,IAAA,GAAOA,wBAAO,UAAW,CAAA,QAAQ,EAAE,MAAO,CAAA,MAAM,CAAE,CAAA,MAAA,CAAO,QAAQ,CAAA;AAEvE,EAAI,GAAA,CAAA,SAAA,CAAU,gBAAgB,WAAW,CAAA;AACzC,EAAI,GAAA,CAAA,SAAA,CAAU,mBAAmB,YAAY,CAAA;AAC7C,EAAA,GAAA,CAAI,SAAU,CAAA,yBAAA,EAA2B,CAAsB,mBAAA,EAAA,IAAI,CAAG,CAAA,CAAA,CAAA;AACtE,EAAI,GAAA,CAAA,GAAA,CAAI,CAAuB,oBAAA,EAAA,MAAM,CAAyB,wBAAA,CAAA,CAAA;AAChE;AAMa,MAAA,qBAAA,GAAwB,CAAC,GAAyB,KAAA;AAC7D,EAAM,MAAA,cAAA,GAAiB,GAAI,CAAA,MAAA,CAAO,kBAAkB,CAAA;AACpD,EAAI,IAAA,CAAC,cAAkB,IAAA,cAAA,KAAmB,gBAAkB,EAAA;AAC1D,IAAO,OAAA,KAAA;AAAA;AAET,EAAO,OAAA,IAAA;AACT;;;;;;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"adaptLegacyOAuthHandler.cjs.js","sources":["../../../src/lib/legacy/adaptLegacyOAuthHandler.ts"],"sourcesContent":["/*\n * Copyright 2023 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n OAuthAuthenticatorResult,\n ProfileTransform,\n} from '@backstage/plugin-auth-node';\nimport { AuthHandler } from '../../providers';\nimport { OAuthResult } from '../oauth';\nimport { PassportProfile } from '../passport/types';\n\n/** @internal */\nexport function adaptLegacyOAuthHandler(\n authHandler?: AuthHandler<OAuthResult>,\n): ProfileTransform<OAuthAuthenticatorResult<PassportProfile>> | undefined {\n return (\n authHandler &&\n (async (result, ctx) =>\n authHandler(\n {\n fullProfile: result.fullProfile,\n accessToken: result.session.accessToken,\n params: {\n scope: result.session.scope,\n id_token: result.session.idToken,\n token_type: result.session.tokenType,\n expires_in: result.session.expiresInSeconds!,\n },\n },\n ctx,\n ))\n );\n}\n"],"names":[],"mappings":";;AAyBO,SAAS,wBACd,WACyE,EAAA;AACzE,EACE,OAAA,WAAA,KACC,OAAO,MAAA,EAAQ,GACd,KAAA,WAAA;AAAA,IACE;AAAA,MACE,aAAa,MAAO,CAAA,WAAA;AAAA,MACpB,WAAA,EAAa,OAAO,OAAQ,CAAA,WAAA;AAAA,MAC5B,MAAQ,EAAA;AAAA,QACN,KAAA,EAAO,OAAO,OAAQ,CAAA,KAAA;AAAA,QACtB,QAAA,EAAU,OAAO,OAAQ,CAAA,OAAA;AAAA,QACzB,UAAA,EAAY,OAAO,OAAQ,CAAA,SAAA;AAAA,QAC3B,UAAA,EAAY,OAAO,OAAQ,CAAA
|
|
1
|
+
{"version":3,"file":"adaptLegacyOAuthHandler.cjs.js","sources":["../../../src/lib/legacy/adaptLegacyOAuthHandler.ts"],"sourcesContent":["/*\n * Copyright 2023 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n OAuthAuthenticatorResult,\n ProfileTransform,\n} from '@backstage/plugin-auth-node';\nimport { AuthHandler } from '../../providers';\nimport { OAuthResult } from '../oauth';\nimport { PassportProfile } from '../passport/types';\n\n/** @internal */\nexport function adaptLegacyOAuthHandler(\n authHandler?: AuthHandler<OAuthResult>,\n): ProfileTransform<OAuthAuthenticatorResult<PassportProfile>> | undefined {\n return (\n authHandler &&\n (async (result, ctx) =>\n authHandler(\n {\n fullProfile: result.fullProfile,\n accessToken: result.session.accessToken,\n params: {\n scope: result.session.scope,\n id_token: result.session.idToken,\n token_type: result.session.tokenType,\n expires_in: result.session.expiresInSeconds!,\n },\n },\n ctx,\n ))\n );\n}\n"],"names":[],"mappings":";;AAyBO,SAAS,wBACd,WACyE,EAAA;AACzE,EACE,OAAA,WAAA,KACC,OAAO,MAAA,EAAQ,GACd,KAAA,WAAA;AAAA,IACE;AAAA,MACE,aAAa,MAAO,CAAA,WAAA;AAAA,MACpB,WAAA,EAAa,OAAO,OAAQ,CAAA,WAAA;AAAA,MAC5B,MAAQ,EAAA;AAAA,QACN,KAAA,EAAO,OAAO,OAAQ,CAAA,KAAA;AAAA,QACtB,QAAA,EAAU,OAAO,OAAQ,CAAA,OAAA;AAAA,QACzB,UAAA,EAAY,OAAO,OAAQ,CAAA,SAAA;AAAA,QAC3B,UAAA,EAAY,OAAO,OAAQ,CAAA;AAAA;AAC7B,KACF;AAAA,IACA;AAAA,GACF,CAAA;AAEN;;;;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"adaptLegacyOAuthSignInResolver.cjs.js","sources":["../../../src/lib/legacy/adaptLegacyOAuthSignInResolver.ts"],"sourcesContent":["/*\n * Copyright 2023 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n OAuthAuthenticatorResult,\n PassportProfile,\n SignInResolver,\n} from '@backstage/plugin-auth-node';\nimport { OAuthResult } from '../oauth';\n\n/** @internal */\nexport function adaptLegacyOAuthSignInResolver(\n signInResolver?: SignInResolver<OAuthResult>,\n): SignInResolver<OAuthAuthenticatorResult<PassportProfile>> | undefined {\n return (\n signInResolver &&\n (async (input, ctx) =>\n signInResolver(\n {\n profile: input.profile,\n result: {\n fullProfile: input.result.fullProfile,\n accessToken: input.result.session.accessToken,\n refreshToken: input.result.session.refreshToken,\n params: {\n scope: input.result.session.scope,\n id_token: input.result.session.idToken,\n token_type: input.result.session.tokenType,\n expires_in: input.result.session.expiresInSeconds!,\n },\n },\n },\n ctx,\n ))\n );\n}\n"],"names":[],"mappings":";;AAwBO,SAAS,+BACd,cACuE,EAAA;AACvE,EACE,OAAA,cAAA,KACC,OAAO,KAAA,EAAO,GACb,KAAA,cAAA;AAAA,IACE;AAAA,MACE,SAAS,KAAM,CAAA,OAAA;AAAA,MACf,MAAQ,EAAA;AAAA,QACN,WAAA,EAAa,MAAM,MAAO,CAAA,WAAA;AAAA,QAC1B,WAAA,EAAa,KAAM,CAAA,MAAA,CAAO,OAAQ,CAAA,WAAA;AAAA,QAClC,YAAA,EAAc,KAAM,CAAA,MAAA,CAAO,OAAQ,CAAA,YAAA;AAAA,QACnC,MAAQ,EAAA;AAAA,UACN,KAAA,EAAO,KAAM,CAAA,MAAA,CAAO,OAAQ,CAAA,KAAA;AAAA,UAC5B,QAAA,EAAU,KAAM,CAAA,MAAA,CAAO,OAAQ,CAAA,OAAA;AAAA,UAC/B,UAAA,EAAY,KAAM,CAAA,MAAA,CAAO,OAAQ,CAAA,SAAA;AAAA,UACjC,UAAA,EAAY,KAAM,CAAA,MAAA,CAAO,OAAQ,CAAA
|
|
1
|
+
{"version":3,"file":"adaptLegacyOAuthSignInResolver.cjs.js","sources":["../../../src/lib/legacy/adaptLegacyOAuthSignInResolver.ts"],"sourcesContent":["/*\n * Copyright 2023 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n OAuthAuthenticatorResult,\n PassportProfile,\n SignInResolver,\n} from '@backstage/plugin-auth-node';\nimport { OAuthResult } from '../oauth';\n\n/** @internal */\nexport function adaptLegacyOAuthSignInResolver(\n signInResolver?: SignInResolver<OAuthResult>,\n): SignInResolver<OAuthAuthenticatorResult<PassportProfile>> | undefined {\n return (\n signInResolver &&\n (async (input, ctx) =>\n signInResolver(\n {\n profile: input.profile,\n result: {\n fullProfile: input.result.fullProfile,\n accessToken: input.result.session.accessToken,\n refreshToken: input.result.session.refreshToken,\n params: {\n scope: input.result.session.scope,\n id_token: input.result.session.idToken,\n token_type: input.result.session.tokenType,\n expires_in: input.result.session.expiresInSeconds!,\n },\n },\n },\n ctx,\n ))\n );\n}\n"],"names":[],"mappings":";;AAwBO,SAAS,+BACd,cACuE,EAAA;AACvE,EACE,OAAA,cAAA,KACC,OAAO,KAAA,EAAO,GACb,KAAA,cAAA;AAAA,IACE;AAAA,MACE,SAAS,KAAM,CAAA,OAAA;AAAA,MACf,MAAQ,EAAA;AAAA,QACN,WAAA,EAAa,MAAM,MAAO,CAAA,WAAA;AAAA,QAC1B,WAAA,EAAa,KAAM,CAAA,MAAA,CAAO,OAAQ,CAAA,WAAA;AAAA,QAClC,YAAA,EAAc,KAAM,CAAA,MAAA,CAAO,OAAQ,CAAA,YAAA;AAAA,QACnC,MAAQ,EAAA;AAAA,UACN,KAAA,EAAO,KAAM,CAAA,MAAA,CAAO,OAAQ,CAAA,KAAA;AAAA,UAC5B,QAAA,EAAU,KAAM,CAAA,MAAA,CAAO,OAAQ,CAAA,OAAA;AAAA,UAC/B,UAAA,EAAY,KAAM,CAAA,MAAA,CAAO,OAAQ,CAAA,SAAA;AAAA,UACjC,UAAA,EAAY,KAAM,CAAA,MAAA,CAAO,OAAQ,CAAA;AAAA;AACnC;AACF,KACF;AAAA,IACA;AAAA,GACF,CAAA;AAEN;;;;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"adaptOAuthSignInResolverToLegacy.cjs.js","sources":["../../../src/lib/legacy/adaptOAuthSignInResolverToLegacy.ts"],"sourcesContent":["/*\n * Copyright 2023 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n OAuthAuthenticatorResult,\n PassportProfile,\n SignInResolver,\n} from '@backstage/plugin-auth-node';\nimport { OAuthResult } from '../oauth';\n\n/** @internal */\nexport function adaptOAuthSignInResolverToLegacy<\n TKeys extends string,\n>(resolvers: {\n [key in TKeys]: SignInResolver<OAuthAuthenticatorResult<PassportProfile>>;\n}): { [key in TKeys]: () => SignInResolver<OAuthResult> } {\n const legacyResolvers = {} as {\n [key in TKeys]: () => SignInResolver<OAuthResult>;\n };\n for (const name of Object.keys(resolvers) as TKeys[]) {\n const resolver = resolvers[name];\n legacyResolvers[name] = () => async (input, ctx) =>\n resolver(\n {\n profile: input.profile,\n result: {\n fullProfile: input.result.fullProfile,\n session: {\n accessToken: input.result.accessToken,\n expiresInSeconds: input.result.params.expires_in,\n scope: input.result.params.scope,\n idToken: input.result.params.id_token,\n tokenType: input.result.params.token_type ?? 'bearer',\n refreshToken: input.result.refreshToken,\n },\n },\n },\n ctx,\n );\n }\n return legacyResolvers;\n}\n"],"names":[],"mappings":";;AAwBO,SAAS,iCAEd,SAEwD,EAAA;AACxD,EAAA,MAAM,kBAAkB,EAAC
|
|
1
|
+
{"version":3,"file":"adaptOAuthSignInResolverToLegacy.cjs.js","sources":["../../../src/lib/legacy/adaptOAuthSignInResolverToLegacy.ts"],"sourcesContent":["/*\n * Copyright 2023 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n OAuthAuthenticatorResult,\n PassportProfile,\n SignInResolver,\n} from '@backstage/plugin-auth-node';\nimport { OAuthResult } from '../oauth';\n\n/** @internal */\nexport function adaptOAuthSignInResolverToLegacy<\n TKeys extends string,\n>(resolvers: {\n [key in TKeys]: SignInResolver<OAuthAuthenticatorResult<PassportProfile>>;\n}): { [key in TKeys]: () => SignInResolver<OAuthResult> } {\n const legacyResolvers = {} as {\n [key in TKeys]: () => SignInResolver<OAuthResult>;\n };\n for (const name of Object.keys(resolvers) as TKeys[]) {\n const resolver = resolvers[name];\n legacyResolvers[name] = () => async (input, ctx) =>\n resolver(\n {\n profile: input.profile,\n result: {\n fullProfile: input.result.fullProfile,\n session: {\n accessToken: input.result.accessToken,\n expiresInSeconds: input.result.params.expires_in,\n scope: input.result.params.scope,\n idToken: input.result.params.id_token,\n tokenType: input.result.params.token_type ?? 'bearer',\n refreshToken: input.result.refreshToken,\n },\n },\n },\n ctx,\n );\n }\n return legacyResolvers;\n}\n"],"names":[],"mappings":";;AAwBO,SAAS,iCAEd,SAEwD,EAAA;AACxD,EAAA,MAAM,kBAAkB,EAAC;AAGzB,EAAA,KAAA,MAAW,IAAQ,IAAA,MAAA,CAAO,IAAK,CAAA,SAAS,CAAc,EAAA;AACpD,IAAM,MAAA,QAAA,GAAW,UAAU,IAAI,CAAA;AAC/B,IAAA,eAAA,CAAgB,IAAI,CAAA,GAAI,MAAM,OAAO,OAAO,GAC1C,KAAA,QAAA;AAAA,MACE;AAAA,QACE,SAAS,KAAM,CAAA,OAAA;AAAA,QACf,MAAQ,EAAA;AAAA,UACN,WAAA,EAAa,MAAM,MAAO,CAAA,WAAA;AAAA,UAC1B,OAAS,EAAA;AAAA,YACP,WAAA,EAAa,MAAM,MAAO,CAAA,WAAA;AAAA,YAC1B,gBAAA,EAAkB,KAAM,CAAA,MAAA,CAAO,MAAO,CAAA,UAAA;AAAA,YACtC,KAAA,EAAO,KAAM,CAAA,MAAA,CAAO,MAAO,CAAA,KAAA;AAAA,YAC3B,OAAA,EAAS,KAAM,CAAA,MAAA,CAAO,MAAO,CAAA,QAAA;AAAA,YAC7B,SAAW,EAAA,KAAA,CAAM,MAAO,CAAA,MAAA,CAAO,UAAc,IAAA,QAAA;AAAA,YAC7C,YAAA,EAAc,MAAM,MAAO,CAAA;AAAA;AAC7B;AACF,OACF;AAAA,MACA;AAAA,KACF;AAAA;AAEJ,EAAO,OAAA,eAAA;AACT;;;;"}
|