@backstage/plugin-auth-backend 0.22.10-next.2 → 0.22.10

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.
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs.js","sources":["../src/lib/legacy/adaptLegacyOAuthHandler.ts","../src/lib/legacy/adaptLegacyOAuthSignInResolver.ts","../src/lib/legacy/adaptOAuthSignInResolverToLegacy.ts","../src/providers/createAuthProviderIntegration.ts","../src/providers/atlassian/provider.ts","../src/providers/auth0/strategy.ts","../src/lib/oauth/OAuthEnvironmentHandler.ts","../src/lib/oauth/helpers.ts","../src/lib/flow/authFlowHelpers.ts","../src/providers/prepareBackstageIdentityResponse.ts","../src/lib/oauth/OAuthAdapter.ts","../src/lib/passport/PassportStrategyHelper.ts","../src/providers/auth0/provider.ts","../src/providers/aws-alb/provider.ts","../src/providers/bitbucket/provider.ts","../src/providers/cloudflare-access/provider.ts","../src/providers/gcp-iap/provider.ts","../src/providers/github/provider.ts","../src/providers/gitlab/provider.ts","../src/providers/google/provider.ts","../src/providers/microsoft/provider.ts","../src/providers/oauth2/provider.ts","../src/providers/oauth2-proxy/provider.ts","../src/providers/resolvers.ts","../src/providers/oidc/provider.ts","../src/providers/okta/provider.ts","../src/providers/onelogin/provider.ts","../src/providers/saml/provider.ts","../src/providers/bitbucketServer/provider.ts","../src/providers/azure-easyauth/provider.ts","../src/providers/providers.ts","../src/lib/catalog/CatalogIdentityClient.ts","../src/lib/resolvers/CatalogAuthResolverContext.ts","../src/providers/router.ts","../src/identity/router.ts","../src/identity/TokenFactory.ts","../src/identity/DatabaseKeyStore.ts","../src/identity/MemoryKeyStore.ts","../src/identity/FirestoreKeyStore.ts","../src/identity/StaticKeyStore.ts","../src/identity/KeyStores.ts","../src/identity/UserInfoDatabaseHandler.ts","../src/database/AuthDatabase.ts","../src/service/readBackstageTokenExpiration.ts","../src/identity/StaticTokenIssuer.ts","../src/service/router.ts","../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 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","/*\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","/*\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","/*\n * Copyright 2022 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 AuthProviderFactory,\n SignInResolver,\n} from '@backstage/plugin-auth-node';\n\n/**\n * Creates a standardized representation of an integration with a third-party\n * auth provider.\n *\n * The returned object facilitates the creation of provider instances, and\n * supplies built-in sign-in resolvers for the specific provider.\n *\n * @public\n */\nexport function createAuthProviderIntegration<\n TCreateOptions extends unknown[],\n TResolvers extends\n | {\n [name in string]: (...args: any[]) => SignInResolver<any>;\n },\n>(config: {\n create: (...args: TCreateOptions) => AuthProviderFactory;\n resolvers?: TResolvers;\n}): Readonly<{\n create: (...args: TCreateOptions) => AuthProviderFactory;\n // If no resolvers are defined, this receives the type `never`\n resolvers: Readonly<string extends keyof TResolvers ? never : TResolvers>;\n}> {\n return Object.freeze({\n ...config,\n resolvers: Object.freeze(config.resolvers ?? ({} as any)),\n });\n}\n","/*\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 { atlassianAuthenticator } from '@backstage/plugin-auth-backend-module-atlassian-provider';\nimport {\n SignInResolver,\n createOAuthProviderFactory,\n} from '@backstage/plugin-auth-node';\nimport {\n adaptLegacyOAuthHandler,\n adaptLegacyOAuthSignInResolver,\n} from '../../lib/legacy';\nimport { OAuthResult } from '../../lib/oauth';\nimport { createAuthProviderIntegration } from '../createAuthProviderIntegration';\nimport { AuthHandler } from '../types';\n\n/**\n * Auth provider integration for Atlassian auth\n *\n * @public\n */\nexport const atlassian = createAuthProviderIntegration({\n create(options?: {\n /**\n * The profile transformation function used to verify and convert the auth response\n * into the profile that will be presented to the user.\n */\n authHandler?: AuthHandler<OAuthResult>;\n\n /**\n * Configure sign-in for this provider, without it the provider can not be used to sign users in.\n */\n signIn?: {\n resolver: SignInResolver<OAuthResult>;\n };\n }) {\n return createOAuthProviderFactory({\n authenticator: atlassianAuthenticator,\n profileTransform: adaptLegacyOAuthHandler(options?.authHandler),\n signInResolver: adaptLegacyOAuthSignInResolver(options?.signIn?.resolver),\n });\n },\n});\n","/*\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 */\nimport Auth0InternalStrategy from 'passport-auth0';\nimport { StateStore } from 'passport-oauth2';\n\nexport interface Auth0StrategyOptionsWithRequest {\n clientID: string;\n clientSecret: string;\n callbackURL: string;\n domain: string;\n passReqToCallback: true;\n store: StateStore;\n}\n\nexport default class Auth0Strategy extends Auth0InternalStrategy {\n constructor(\n options: Auth0StrategyOptionsWithRequest,\n verify: Auth0InternalStrategy.VerifyFunction,\n ) {\n const optionsWithURLs = {\n ...options,\n authorizationURL: `https://${options.domain}/authorize`,\n tokenURL: `https://${options.domain}/oauth/token`,\n userInfoURL: `https://${options.domain}/userinfo`,\n apiUrl: `https://${options.domain}/api`,\n };\n super(optionsWithURLs, verify);\n }\n}\n","/*\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 { OAuthEnvironmentHandler as _OAuthEnvironmentHandler } from '@backstage/plugin-auth-node';\n\n/**\n * @public\n * @deprecated import from `@backstage/plugin-auth-node` instead\n */\nexport const OAuthEnvironmentHandler = _OAuthEnvironmentHandler;\n","/*\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 {\n CookieConfigurer,\n OAuthState,\n decodeOAuthState,\n encodeOAuthState,\n} from '@backstage/plugin-auth-node';\n\n/**\n * @public\n * @deprecated Use `decodeOAuthState` from `@backstage/plugin-auth-node` instead\n */\nexport const readState = decodeOAuthState;\n\n/**\n * @public\n * @deprecated Use `encodeOAuthState` from `@backstage/plugin-auth-node` instead\n */\nexport const encodeState = encodeOAuthState;\n\n/**\n * @public\n * @deprecated Use inline logic to make sure the session and state nonce matches instead.\n */\nexport const verifyNonce = (req: express.Request, providerId: string) => {\n const cookieNonce = req.cookies[`${providerId}-nonce`];\n const state: OAuthState = readState(req.query.state?.toString() ?? '');\n const stateNonce = state.nonce;\n\n if (!cookieNonce) {\n throw new Error('Auth response is missing cookie nonce');\n }\n if (stateNonce.length === 0) {\n throw new Error('Auth response is missing state nonce');\n }\n if (cookieNonce !== stateNonce) {\n throw new Error('Invalid nonce');\n }\n};\n\nexport const defaultCookieConfigurer: CookieConfigurer = ({\n callbackUrl,\n providerId,\n appOrigin,\n}) => {\n const { hostname: domain, pathname, protocol } = new URL(callbackUrl);\n const secure = protocol === 'https:';\n\n // For situations where the auth-backend is running on a\n // different domain than the app, we set the SameSite attribute\n // to 'none' to allow third-party access to the cookie, but\n // only if it's in a secure context (https).\n let sameSite: ReturnType<CookieConfigurer>['sameSite'] = 'lax';\n if (new URL(appOrigin).hostname !== domain && secure) {\n sameSite = 'none';\n }\n\n // If the provider supports callbackUrls, the pathname will\n // contain the complete path to the frame handler so we need\n // to slice off the trailing part of the path.\n const path = pathname.endsWith(`${providerId}/handler/frame`)\n ? pathname.slice(0, -'/handler/frame'.length)\n : `${pathname}/${providerId}`;\n\n return { domain, path, secure, sameSite };\n};\n","/*\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","/*\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 { prepareBackstageIdentityResponse as _prepareBackstageIdentityResponse } from '@backstage/plugin-auth-node';\n\n/**\n * @public\n * @deprecated import from `@backstage/plugin-auth-node` instead\n */\nexport const prepareBackstageIdentityResponse =\n _prepareBackstageIdentityResponse;\n","/*\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, { CookieOptions } from 'express';\nimport crypto from 'crypto';\nimport { URL } from 'url';\nimport {\n AuthProviderConfig,\n AuthProviderRouteHandlers,\n BackstageIdentityResponse,\n BackstageSignInResult,\n CookieConfigurer,\n OAuthState,\n} from '@backstage/plugin-auth-node';\nimport {\n AuthenticationError,\n InputError,\n isError,\n NotAllowedError,\n} from '@backstage/errors';\nimport { defaultCookieConfigurer, readState, verifyNonce } from './helpers';\nimport {\n postMessageResponse,\n ensuresXRequestedWith,\n WebMessageResponse,\n} from '../flow';\nimport {\n OAuthHandlers,\n OAuthStartRequest,\n OAuthRefreshRequest,\n OAuthLogoutRequest,\n} from './types';\nimport { prepareBackstageIdentityResponse } from '../../providers/prepareBackstageIdentityResponse';\n\nexport const THOUSAND_DAYS_MS = 1000 * 24 * 60 * 60 * 1000;\nexport const TEN_MINUTES_MS = 600 * 1000;\n\n/**\n * @public\n * @deprecated Use `createOAuthRouteHandlers` from `@backstage/plugin-auth-node` instead\n */\nexport type OAuthAdapterOptions = {\n providerId: string;\n persistScopes?: boolean;\n appOrigin: string;\n baseUrl: string;\n cookieConfigurer: CookieConfigurer;\n isOriginAllowed: (origin: string) => boolean;\n callbackUrl: string;\n};\n\n/**\n * @public\n * @deprecated Use `createOAuthRouteHandlers` from `@backstage/plugin-auth-node` instead\n */\nexport class OAuthAdapter implements AuthProviderRouteHandlers {\n static fromConfig(\n config: AuthProviderConfig,\n handlers: OAuthHandlers,\n options: Pick<\n OAuthAdapterOptions,\n 'providerId' | 'persistScopes' | 'callbackUrl'\n >,\n ): OAuthAdapter {\n const { appUrl, baseUrl, isOriginAllowed } = config;\n const { origin: appOrigin } = new URL(appUrl);\n\n const cookieConfigurer = config.cookieConfigurer ?? defaultCookieConfigurer;\n\n return new OAuthAdapter(handlers, {\n ...options,\n appOrigin,\n baseUrl,\n cookieConfigurer,\n isOriginAllowed,\n });\n }\n\n private readonly baseCookieOptions: CookieOptions;\n\n constructor(\n private readonly handlers: OAuthHandlers,\n private readonly options: OAuthAdapterOptions,\n ) {\n this.baseCookieOptions = {\n httpOnly: true,\n sameSite: 'lax',\n };\n }\n\n async start(req: express.Request, res: express.Response): Promise<void> {\n // retrieve scopes from request\n const scope = req.query.scope?.toString() ?? '';\n const env = req.query.env?.toString();\n const origin = req.query.origin?.toString();\n const redirectUrl = req.query.redirectUrl?.toString();\n const flow = req.query.flow?.toString();\n\n if (!env) {\n throw new InputError('No env provided in request query parameters');\n }\n\n const cookieConfig = this.getCookieConfig(origin);\n\n const nonce = crypto.randomBytes(16).toString('base64');\n // set a nonce cookie before redirecting to oauth provider\n this.setNonceCookie(res, nonce, cookieConfig);\n\n const state: OAuthState = { nonce, env, origin, redirectUrl, flow };\n\n // If scopes are persisted then we pass them through the state so that we\n // can set the cookie on successful auth\n if (this.options.persistScopes) {\n state.scope = scope;\n }\n const forwardReq = Object.assign(req, { scope, state });\n\n const { url, status } = await this.handlers.start(\n forwardReq as OAuthStartRequest,\n );\n\n res.statusCode = status || 302;\n res.setHeader('Location', url);\n res.setHeader('Content-Length', '0');\n res.end();\n }\n\n async frameHandler(\n req: express.Request,\n res: express.Response,\n ): Promise<void> {\n let appOrigin = this.options.appOrigin;\n\n try {\n const state: OAuthState = readState(req.query.state?.toString() ?? '');\n\n if (state.origin) {\n try {\n appOrigin = new URL(state.origin).origin;\n } catch {\n throw new NotAllowedError('App origin is invalid, failed to parse');\n }\n if (!this.options.isOriginAllowed(appOrigin)) {\n throw new NotAllowedError(`Origin '${appOrigin}' is not allowed`);\n }\n }\n\n // verify nonce cookie and state cookie on callback\n verifyNonce(req, this.options.providerId);\n\n const { response, refreshToken } = await this.handlers.handler(req);\n\n const cookieConfig = this.getCookieConfig(appOrigin);\n\n // Store the scope that we have been granted for this session. This is useful if\n // the provider does not return granted scopes on refresh or if they are normalized.\n if (this.options.persistScopes && state.scope) {\n this.setGrantedScopeCookie(res, state.scope, cookieConfig);\n response.providerInfo.scope = state.scope;\n }\n\n if (refreshToken) {\n // set new refresh token\n this.setRefreshTokenCookie(res, refreshToken, cookieConfig);\n }\n\n const identity = await this.populateIdentity(response.backstageIdentity);\n\n const responseObj: WebMessageResponse = {\n type: 'authorization_response',\n response: { ...response, backstageIdentity: identity },\n };\n\n if (state.flow === 'redirect') {\n if (!state.redirectUrl) {\n throw new InputError(\n 'No redirectUrl provided in request query parameters',\n );\n }\n res.redirect(state.redirectUrl);\n return undefined;\n }\n // post message back to popup if successful\n return postMessageResponse(res, appOrigin, responseObj);\n } catch (error) {\n const { name, message } = isError(error)\n ? error\n : new Error('Encountered invalid error'); // Being a bit safe and not forwarding the bad value\n // post error message back to popup if failure\n return postMessageResponse(res, appOrigin, {\n type: 'authorization_response',\n error: { name, message },\n });\n }\n }\n\n async logout(req: express.Request, res: express.Response): Promise<void> {\n if (!ensuresXRequestedWith(req)) {\n throw new AuthenticationError('Invalid X-Requested-With header');\n }\n\n if (this.handlers.logout) {\n const refreshToken = this.getRefreshTokenFromCookie(req);\n const revokeRequest: OAuthLogoutRequest = Object.assign(req, {\n refreshToken,\n });\n await this.handlers.logout(revokeRequest);\n }\n\n // remove refresh token cookie if it is set\n const origin = req.get('origin');\n const cookieConfig = this.getCookieConfig(origin);\n this.removeRefreshTokenCookie(res, cookieConfig);\n\n res.status(200).end();\n }\n\n async refresh(req: express.Request, res: express.Response): Promise<void> {\n if (!ensuresXRequestedWith(req)) {\n throw new AuthenticationError('Invalid X-Requested-With header');\n }\n\n if (!this.handlers.refresh) {\n throw new InputError(\n `Refresh token is not supported for provider ${this.options.providerId}`,\n );\n }\n\n try {\n const refreshToken = this.getRefreshTokenFromCookie(req);\n\n // throw error if refresh token is missing in the request\n if (!refreshToken) {\n throw new InputError('Missing session cookie');\n }\n\n let scope = req.query.scope?.toString() ?? '';\n if (this.options.persistScopes) {\n scope = this.getGrantedScopeFromCookie(req);\n }\n const forwardReq = Object.assign(req, { scope, refreshToken });\n\n // get new access_token\n const { response, refreshToken: newRefreshToken } =\n await this.handlers.refresh(forwardReq as OAuthRefreshRequest);\n\n const backstageIdentity = await this.populateIdentity(\n response.backstageIdentity,\n );\n\n if (newRefreshToken && newRefreshToken !== refreshToken) {\n const origin = req.get('origin');\n const cookieConfig = this.getCookieConfig(origin);\n this.setRefreshTokenCookie(res, newRefreshToken, cookieConfig);\n }\n\n res.status(200).json({ ...response, backstageIdentity });\n } catch (error) {\n throw new AuthenticationError('Refresh failed', error);\n }\n }\n\n /**\n * If the response from the OAuth provider includes a Backstage identity, we\n * make sure it's populated with all the information we can derive from the user ID.\n */\n private async populateIdentity(\n identity?: BackstageSignInResult,\n ): Promise<BackstageIdentityResponse | undefined> {\n if (!identity) {\n return undefined;\n }\n if (!identity.token) {\n throw new InputError(`Identity response must return a token`);\n }\n\n return prepareBackstageIdentityResponse(identity);\n }\n\n private setNonceCookie = (\n res: express.Response,\n nonce: string,\n cookieConfig: ReturnType<CookieConfigurer>,\n ) => {\n res.cookie(`${this.options.providerId}-nonce`, nonce, {\n maxAge: TEN_MINUTES_MS,\n ...this.baseCookieOptions,\n ...cookieConfig,\n path: `${cookieConfig.path}/handler`,\n });\n };\n\n private setGrantedScopeCookie = (\n res: express.Response,\n scope: string,\n cookieConfig: ReturnType<CookieConfigurer>,\n ) => {\n res.cookie(`${this.options.providerId}-granted-scope`, scope, {\n maxAge: THOUSAND_DAYS_MS,\n ...this.baseCookieOptions,\n ...cookieConfig,\n });\n };\n\n private getRefreshTokenFromCookie = (req: express.Request) => {\n return req.cookies[`${this.options.providerId}-refresh-token`];\n };\n\n private getGrantedScopeFromCookie = (req: express.Request) => {\n return req.cookies[`${this.options.providerId}-granted-scope`];\n };\n\n private setRefreshTokenCookie = (\n res: express.Response,\n refreshToken: string,\n cookieConfig: ReturnType<CookieConfigurer>,\n ) => {\n res.cookie(`${this.options.providerId}-refresh-token`, refreshToken, {\n maxAge: THOUSAND_DAYS_MS,\n ...this.baseCookieOptions,\n ...cookieConfig,\n });\n };\n\n private removeRefreshTokenCookie = (\n res: express.Response,\n cookieConfig: ReturnType<CookieConfigurer>,\n ) => {\n res.cookie(`${this.options.providerId}-refresh-token`, '', {\n maxAge: 0,\n ...this.baseCookieOptions,\n ...cookieConfig,\n });\n };\n\n private getCookieConfig = (origin?: string) => {\n return this.options.cookieConfigurer({\n providerId: this.options.providerId,\n baseUrl: this.options.baseUrl,\n callbackUrl: this.options.callbackUrl,\n appOrigin: origin ?? this.options.appOrigin,\n });\n };\n}\n","/*\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 passport from 'passport';\nimport { decodeJwt } from 'jose';\nimport { InternalOAuthError } from 'passport-oauth2';\nimport { ProfileInfo } from '@backstage/plugin-auth-node';\nimport { PassportProfile } from './types';\nimport { OAuthStartResponse } from '../../providers/types';\n\nexport type PassportDoneCallback<Res, Private = never> = (\n err?: Error,\n response?: Res,\n privateInfo?: Private,\n) => void;\n\nexport const makeProfileInfo = (\n profile: PassportProfile,\n idToken?: string,\n): ProfileInfo => {\n let email: string | undefined = undefined;\n if (profile.emails && profile.emails.length > 0) {\n const [firstEmail] = profile.emails;\n email = firstEmail.value;\n }\n\n let picture: string | undefined = undefined;\n if (profile.avatarUrl) {\n picture = profile.avatarUrl;\n } else if (profile.photos && profile.photos.length > 0) {\n const [firstPhoto] = profile.photos;\n picture = firstPhoto.value;\n }\n\n let displayName: string | undefined =\n profile.displayName ?? profile.username ?? profile.id;\n\n if ((!email || !picture || !displayName) && idToken) {\n try {\n const decoded = decodeJwt(idToken) as {\n email?: string;\n name?: string;\n picture?: string;\n };\n if (!email && decoded.email) {\n email = decoded.email;\n }\n if (!picture && decoded.picture) {\n picture = decoded.picture;\n }\n if (!displayName && decoded.name) {\n displayName = decoded.name;\n }\n } catch (e) {\n throw new Error(`Failed to parse id token and get profile info, ${e}`);\n }\n }\n\n return {\n email,\n picture,\n displayName,\n };\n};\n\nexport const executeRedirectStrategy = async (\n req: express.Request,\n providerStrategy: passport.Strategy,\n options: Record<string, string>,\n): Promise<OAuthStartResponse> => {\n return new Promise(resolve => {\n const strategy = Object.create(providerStrategy);\n strategy.redirect = (url: string, status?: number) => {\n resolve({ url, status: status ?? undefined });\n };\n\n strategy.authenticate(req, { ...options });\n });\n};\n\nexport const executeFrameHandlerStrategy = async <Result, PrivateInfo = never>(\n req: express.Request,\n providerStrategy: passport.Strategy,\n options?: Record<string, string>,\n) => {\n return new Promise<{ result: Result; privateInfo: PrivateInfo }>(\n (resolve, reject) => {\n const strategy = Object.create(providerStrategy);\n strategy.success = (result: any, privateInfo: any) => {\n resolve({ result, privateInfo });\n };\n strategy.fail = (\n info: { type: 'success' | 'error'; message?: string },\n // _status: number,\n ) => {\n reject(new Error(`Authentication rejected, ${info.message ?? ''}`));\n };\n strategy.error = (error: InternalOAuthError) => {\n let message = `Authentication failed, ${error.message}`;\n\n if (error.oauthError?.data) {\n try {\n const errorData = JSON.parse(error.oauthError.data);\n\n if (errorData.message) {\n message += ` - ${errorData.message}`;\n }\n } catch (parseError) {\n message += ` - ${error.oauthError}`;\n }\n }\n\n reject(new Error(message));\n };\n strategy.redirect = () => {\n reject(new Error('Unexpected redirect'));\n };\n strategy.authenticate(req, { ...(options ?? {}) });\n },\n );\n};\n\ntype RefreshTokenResponse = {\n /**\n * An access token issued for the signed in user.\n */\n accessToken: string;\n /**\n * Optionally, the server can issue a new Refresh Token for the user\n */\n refreshToken?: string;\n params: any;\n};\n\nexport const executeRefreshTokenStrategy = async (\n providerStrategy: passport.Strategy,\n refreshToken: string,\n scope: string,\n): Promise<RefreshTokenResponse> => {\n return new Promise((resolve, reject) => {\n const anyStrategy = providerStrategy as any;\n const OAuth2 = anyStrategy._oauth2.constructor;\n const oauth2 = new OAuth2(\n anyStrategy._oauth2._clientId,\n anyStrategy._oauth2._clientSecret,\n anyStrategy._oauth2._baseSite,\n anyStrategy._oauth2._authorizeUrl,\n anyStrategy._refreshURL || anyStrategy._oauth2._accessTokenUrl,\n anyStrategy._oauth2._customHeaders,\n );\n\n oauth2.getOAuthAccessToken(\n refreshToken,\n {\n scope,\n grant_type: 'refresh_token',\n },\n (\n err: Error | null,\n accessToken: string,\n newRefreshToken: string,\n params: any,\n ) => {\n if (err) {\n reject(new Error(`Failed to refresh access token ${err.toString()}`));\n }\n if (!accessToken) {\n reject(\n new Error(\n `Failed to refresh access token, no access token received`,\n ),\n );\n }\n\n resolve({\n accessToken,\n refreshToken: newRefreshToken,\n params,\n });\n },\n );\n });\n};\n\ntype ProviderStrategy = {\n userProfile(accessToken: string, callback: Function): void;\n};\n\nexport const executeFetchUserProfileStrategy = async (\n providerStrategy: passport.Strategy,\n accessToken: string,\n): Promise<PassportProfile> => {\n return new Promise((resolve, reject) => {\n const anyStrategy = providerStrategy as unknown as ProviderStrategy;\n anyStrategy.userProfile(\n accessToken,\n (error: Error, rawProfile: PassportProfile) => {\n if (error) {\n reject(error);\n } else {\n resolve(rawProfile);\n }\n },\n );\n });\n};\n","/*\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 passport from 'passport';\nimport Auth0Strategy from './strategy';\nimport {\n OAuthAdapter,\n OAuthProviderOptions,\n OAuthHandlers,\n OAuthResponse,\n OAuthEnvironmentHandler,\n OAuthStartRequest,\n encodeState,\n OAuthRefreshRequest,\n OAuthResult,\n} from '../../lib/oauth';\nimport {\n executeFetchUserProfileStrategy,\n executeFrameHandlerStrategy,\n executeRedirectStrategy,\n executeRefreshTokenStrategy,\n makeProfileInfo,\n PassportDoneCallback,\n} from '../../lib/passport';\nimport { OAuthStartResponse, AuthHandler } from '../types';\nimport { createAuthProviderIntegration } from '../createAuthProviderIntegration';\nimport { StateStore } from 'passport-oauth2';\nimport {\n AuthResolverContext,\n SignInResolver,\n} from '@backstage/plugin-auth-node';\n\ntype PrivateInfo = {\n refreshToken: string;\n};\n\nexport type Auth0AuthProviderOptions = OAuthProviderOptions & {\n domain: string;\n signInResolver?: SignInResolver<OAuthResult>;\n authHandler: AuthHandler<OAuthResult>;\n resolverContext: AuthResolverContext;\n audience?: string;\n connection?: string;\n connectionScope?: string;\n};\n\nexport class Auth0AuthProvider implements OAuthHandlers {\n private readonly _strategy: Auth0Strategy;\n private readonly signInResolver?: SignInResolver<OAuthResult>;\n private readonly authHandler: AuthHandler<OAuthResult>;\n private readonly resolverContext: AuthResolverContext;\n private readonly audience?: string;\n private readonly connection?: string;\n private readonly connectionScope?: string;\n\n /**\n * Due to passport-auth0 forcing options.state = true,\n * passport-oauth2 requires express-session to be installed\n * so that the 'state' parameter of the oauth2 flow can be stored.\n * This implementation of StateStore matches the NullStore found within\n * passport-oauth2, which is the StateStore implementation used when options.state = false,\n * allowing us to avoid using express-session in order to integrate with auth0.\n */\n private store: StateStore = {\n store(_req: express.Request, cb: any) {\n cb(null, null);\n },\n verify(_req: express.Request, _state: string, cb: any) {\n cb(null, true);\n },\n };\n\n constructor(options: Auth0AuthProviderOptions) {\n this.signInResolver = options.signInResolver;\n this.authHandler = options.authHandler;\n this.resolverContext = options.resolverContext;\n this.audience = options.audience;\n this.connection = options.connection;\n this.connectionScope = options.connectionScope;\n this._strategy = new Auth0Strategy(\n {\n clientID: options.clientId,\n clientSecret: options.clientSecret,\n callbackURL: options.callbackUrl,\n domain: options.domain,\n // We need passReqToCallback set to false to get params, but there's\n // no matching type signature for that, so instead behold this beauty\n passReqToCallback: false as true,\n store: this.store,\n },\n (\n accessToken: any,\n refreshToken: any,\n params: any,\n fullProfile: passport.Profile,\n done: PassportDoneCallback<OAuthResult, PrivateInfo>,\n ) => {\n done(\n undefined,\n {\n fullProfile,\n accessToken,\n refreshToken,\n params,\n },\n {\n refreshToken,\n },\n );\n },\n );\n }\n\n async start(req: OAuthStartRequest): Promise<OAuthStartResponse> {\n return await executeRedirectStrategy(req, this._strategy, {\n accessType: 'offline',\n prompt: 'consent',\n scope: req.scope,\n state: encodeState(req.state),\n ...(this.audience ? { audience: this.audience } : {}),\n ...(this.connection ? { connection: this.connection } : {}),\n ...(this.connectionScope\n ? { connection_scope: this.connectionScope }\n : {}),\n });\n }\n\n async handler(req: express.Request) {\n const { result, privateInfo } = await executeFrameHandlerStrategy<\n OAuthResult,\n PrivateInfo\n >(req, this._strategy, {\n ...(this.audience ? { audience: this.audience } : {}),\n ...(this.connection ? { connection: this.connection } : {}),\n ...(this.connectionScope\n ? { connection_scope: this.connectionScope }\n : {}),\n });\n\n return {\n response: await this.handleResult(result),\n refreshToken: privateInfo.refreshToken,\n };\n }\n\n async refresh(req: OAuthRefreshRequest) {\n const { accessToken, refreshToken, params } =\n await executeRefreshTokenStrategy(\n this._strategy,\n req.refreshToken,\n req.scope,\n );\n\n const fullProfile = await executeFetchUserProfileStrategy(\n this._strategy,\n accessToken,\n );\n\n return {\n response: await this.handleResult({\n fullProfile,\n params,\n accessToken,\n }),\n refreshToken,\n };\n }\n\n private async handleResult(result: OAuthResult) {\n const { profile } = await this.authHandler(result, this.resolverContext);\n\n const response: OAuthResponse = {\n providerInfo: {\n idToken: result.params.id_token,\n accessToken: result.accessToken,\n scope: result.params.scope,\n expiresInSeconds: result.params.expires_in,\n },\n profile,\n };\n\n if (this.signInResolver) {\n response.backstageIdentity = await this.signInResolver(\n {\n result,\n profile,\n },\n this.resolverContext,\n );\n }\n\n return response;\n }\n}\n\n/**\n * Auth provider integration for auth0 auth\n *\n * @public\n */\nexport const auth0 = createAuthProviderIntegration({\n create(options?: {\n /**\n * The profile transformation function used to verify and convert the auth response\n * into the profile that will be presented to the user.\n */\n authHandler?: AuthHandler<OAuthResult>;\n\n /**\n * Configure sign-in for this provider, without it the provider can not be used to sign users in.\n */\n signIn?: {\n /**\n * Maps an auth result to a Backstage identity for the user.\n */\n resolver: SignInResolver<OAuthResult>;\n };\n }) {\n return ({ providerId, globalConfig, config, resolverContext }) =>\n OAuthEnvironmentHandler.mapConfig(config, envConfig => {\n const clientId = envConfig.getString('clientId');\n const clientSecret = envConfig.getString('clientSecret');\n const domain = envConfig.getString('domain');\n const customCallbackUrl = envConfig.getOptionalString('callbackUrl');\n const audience = envConfig.getOptionalString('audience');\n const connection = envConfig.getOptionalString('connection');\n const connectionScope = envConfig.getOptionalString('connectionScope');\n const callbackUrl =\n customCallbackUrl ||\n `${globalConfig.baseUrl}/${providerId}/handler/frame`;\n\n const authHandler: AuthHandler<OAuthResult> = options?.authHandler\n ? options.authHandler\n : async ({ fullProfile, params }) => ({\n profile: makeProfileInfo(fullProfile, params.id_token),\n });\n\n const signInResolver = options?.signIn?.resolver;\n\n const provider = new Auth0AuthProvider({\n clientId,\n clientSecret,\n callbackUrl,\n domain,\n authHandler,\n signInResolver,\n resolverContext,\n audience,\n connection,\n connectionScope,\n });\n\n return OAuthAdapter.fromConfig(globalConfig, provider, {\n providerId,\n callbackUrl,\n });\n });\n },\n});\n","/*\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 {\n AwsAlbResult,\n awsAlbAuthenticator,\n} from '@backstage/plugin-auth-backend-module-aws-alb-provider';\nimport {\n SignInResolver,\n createProxyAuthProviderFactory,\n} from '@backstage/plugin-auth-node';\nimport { AuthHandler } from '../types';\nimport { createAuthProviderIntegration } from '../createAuthProviderIntegration';\n\n/**\n * Auth provider integration for AWS ALB auth\n *\n * @public\n */\nexport const awsAlb = createAuthProviderIntegration({\n create(options?: {\n /**\n * The profile transformation function used to verify and convert the auth\n * response into the profile that will be presented to the user. The default\n * implementation just provides the authenticated email that the IAP\n * presented.\n */\n authHandler?: AuthHandler<AwsAlbResult>;\n /**\n * Configures sign-in for this provider.\n */\n signIn: {\n /**\n * Maps an auth result to a Backstage identity for the user.\n */\n resolver: SignInResolver<AwsAlbResult>;\n };\n }) {\n return createProxyAuthProviderFactory({\n authenticator: awsAlbAuthenticator,\n profileTransform: options?.authHandler,\n signInResolver: options?.signIn?.resolver,\n });\n },\n});\n","/*\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 bitbucketAuthenticator,\n bitbucketSignInResolvers,\n} from '@backstage/plugin-auth-backend-module-bitbucket-provider';\nimport {\n SignInResolver,\n createOAuthProviderFactory,\n} from '@backstage/plugin-auth-node';\nimport { Profile as PassportProfile } from 'passport';\nimport {\n adaptLegacyOAuthHandler,\n adaptLegacyOAuthSignInResolver,\n adaptOAuthSignInResolverToLegacy,\n} from '../../lib/legacy';\nimport { OAuthResult } from '../../lib/oauth';\nimport { createAuthProviderIntegration } from '../createAuthProviderIntegration';\nimport { AuthHandler } from '../types';\n\n/**\n * @public\n * @deprecated The Bitbucket auth provider was extracted to `@backstage/plugin-auth-backend-module-bitbucket-provider`.\n */\nexport type BitbucketOAuthResult = {\n fullProfile: BitbucketPassportProfile;\n params: {\n id_token?: string;\n scope: string;\n expires_in: number;\n };\n accessToken: string;\n refreshToken?: string;\n};\n\n/**\n * @public\n * @deprecated The Bitbucket auth provider was extracted to `@backstage/plugin-auth-backend-module-bitbucket-provider`.\n */\nexport type BitbucketPassportProfile = PassportProfile & {\n id?: string;\n displayName?: string;\n username?: string;\n avatarUrl?: string;\n _json?: {\n links?: {\n avatar?: {\n href?: string;\n };\n };\n };\n};\n\n/**\n * Auth provider integration for Bitbucket auth\n *\n * @public\n */\nexport const bitbucket = createAuthProviderIntegration({\n create(options?: {\n /**\n * The profile transformation function used to verify and convert the auth response\n * into the profile that will be presented to the user.\n */\n authHandler?: AuthHandler<OAuthResult>;\n\n /**\n * Configure sign-in for this provider, without it the provider can not be used to sign users in.\n */\n signIn?: {\n resolver: SignInResolver<OAuthResult>;\n };\n }) {\n return createOAuthProviderFactory({\n authenticator: bitbucketAuthenticator,\n profileTransform: adaptLegacyOAuthHandler(options?.authHandler),\n signInResolver: adaptLegacyOAuthSignInResolver(options?.signIn?.resolver),\n });\n },\n resolvers: adaptOAuthSignInResolverToLegacy({\n userIdMatchingUserEntityAnnotation:\n bitbucketSignInResolvers.userIdMatchingUserEntityAnnotation(),\n usernameMatchingUserEntityAnnotation:\n bitbucketSignInResolvers.usernameMatchingUserEntityAnnotation(),\n }),\n});\n","/*\n * Copyright 2022 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 { CacheClient } from '@backstage/backend-common';\nimport {\n cloudflareAccessSignInResolvers,\n createCloudflareAccessAuthenticator,\n} from '@backstage/plugin-auth-backend-module-cloudflare-access-provider';\nimport {\n SignInResolver,\n createProxyAuthProviderFactory,\n} from '@backstage/plugin-auth-node';\nimport { createAuthProviderIntegration } from '../createAuthProviderIntegration';\nimport { AuthHandler } from '../types';\n\n/**\n * CloudflareAccessClaims\n *\n * Can be used in externally provided auth handler or sign in resolver to\n * enrich user profile for sign-in user entity\n *\n * @public\n * @deprecated import from `@backstage/plugin-auth-backend-module-cloudflare-access-provider` instead\n */\nexport type CloudflareAccessClaims = {\n /**\n * `aud` identifies the application to which the JWT is issued.\n */\n aud: string[];\n /**\n * `email` contains the email address of the authenticated user.\n */\n email: string;\n /**\n * iat and exp are the issuance and expiration timestamps.\n */\n exp: number;\n iat: number;\n /**\n * `nonce` is the session identifier.\n */\n nonce: string;\n /**\n * `identity_nonce` is available in the Application Token and can be used to\n * query all group membership for a given user.\n */\n identity_nonce: string;\n /**\n * `sub` contains the identifier of the authenticated user.\n */\n sub: string;\n /**\n * `iss` the issuer is the application’s Cloudflare Access Domain URL.\n */\n iss: string;\n /**\n * `custom` contains SAML attributes in the Application Token specified by an\n * administrator in the identity provider configuration.\n */\n custom: string;\n};\n\n/**\n * CloudflareAccessGroup\n *\n * @public\n * @deprecated import from `@backstage/plugin-auth-backend-module-cloudflare-access-provider` instead\n */\nexport type CloudflareAccessGroup = {\n /**\n * Group id\n */\n id: string;\n /**\n * Name of group as defined in Cloudflare zero trust dashboard\n */\n name: string;\n /**\n * Access group email address\n */\n email: string;\n};\n\n/**\n * CloudflareAccessIdentityProfile\n *\n * Can be used in externally provided auth handler or sign in resolver to\n * enrich user profile for sign-in user entity\n *\n * @public\n * @deprecated import from `@backstage/plugin-auth-backend-module-cloudflare-access-provider` instead\n */\nexport type CloudflareAccessIdentityProfile = {\n id: string;\n name: string;\n email: string;\n groups: CloudflareAccessGroup[];\n};\n\n/**\n * @public\n * @deprecated import from `@backstage/plugin-auth-backend-module-cloudflare-access-provider` instead\n */\nexport type CloudflareAccessResult = {\n claims: CloudflareAccessClaims;\n cfIdentity: CloudflareAccessIdentityProfile;\n expiresInSeconds?: number;\n token: string;\n};\n\n/**\n * Auth provider integration for Cloudflare Access auth\n *\n * @public\n */\nexport const cfAccess = createAuthProviderIntegration({\n create(options: {\n /**\n * The profile transformation function used to verify and convert the auth response\n * into the profile that will be presented to the user.\n */\n authHandler?: AuthHandler<CloudflareAccessResult>;\n\n /**\n * Configure sign-in for this provider, without it the provider can not be used to sign users in.\n */\n signIn: {\n /**\n * Maps an auth result to a Backstage identity for the user.\n */\n resolver: SignInResolver<CloudflareAccessResult>;\n };\n\n /**\n * CacheClient object that was configured for the Backstage backend,\n * should be provided via the backend auth plugin.\n */\n cache?: CacheClient;\n }) {\n return createProxyAuthProviderFactory({\n authenticator: createCloudflareAccessAuthenticator({\n cache: options.cache,\n }),\n profileTransform: options?.authHandler,\n signInResolver: options?.signIn?.resolver,\n signInResolverFactories: cloudflareAccessSignInResolvers,\n });\n },\n resolvers: cloudflareAccessSignInResolvers,\n});\n","/*\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 { gcpIapAuthenticator } from '@backstage/plugin-auth-backend-module-gcp-iap-provider';\nimport {\n SignInResolver,\n createProxyAuthProviderFactory,\n} from '@backstage/plugin-auth-node';\nimport { createAuthProviderIntegration } from '../createAuthProviderIntegration';\nimport { AuthHandler } from '../types';\nimport { GcpIapResult } from './types';\n\n/**\n * Auth provider integration for Google Identity-Aware Proxy auth\n *\n * @public\n */\nexport const gcpIap = createAuthProviderIntegration({\n create(options: {\n /**\n * The profile transformation function used to verify and convert the auth\n * response into the profile that will be presented to the user. The default\n * implementation just provides the authenticated email that the IAP\n * presented.\n */\n authHandler?: AuthHandler<GcpIapResult>;\n\n /**\n * Configures sign-in for this provider.\n */\n signIn: {\n /**\n * Maps an auth result to a Backstage identity for the user.\n */\n resolver: SignInResolver<GcpIapResult>;\n };\n }) {\n return createProxyAuthProviderFactory({\n authenticator: gcpIapAuthenticator,\n profileTransform: options?.authHandler,\n signInResolver: options?.signIn?.resolver,\n });\n },\n});\n","/*\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 { Profile as PassportProfile } from 'passport';\nimport { AuthHandler, StateEncoder } from '../types';\nimport { createAuthProviderIntegration } from '../createAuthProviderIntegration';\nimport {\n createOAuthProviderFactory,\n OAuthAuthenticatorResult,\n ProfileTransform,\n SignInResolver,\n} from '@backstage/plugin-auth-node';\nimport { githubAuthenticator } from '@backstage/plugin-auth-backend-module-github-provider';\n\n/** @public */\nexport type GithubOAuthResult = {\n fullProfile: PassportProfile;\n params: {\n scope: string;\n expires_in?: string;\n refresh_token_expires_in?: string;\n };\n accessToken: string;\n refreshToken?: string;\n};\n\n/**\n * Auth provider integration for GitHub auth\n *\n * @public\n */\nexport const github = createAuthProviderIntegration({\n create(options?: {\n /**\n * The profile transformation function used to verify and convert the auth response\n * into the profile that will be presented to the user.\n */\n authHandler?: AuthHandler<GithubOAuthResult>;\n\n /**\n * Configure sign-in for this provider, without it the provider can not be used to sign users in.\n */\n signIn?: {\n /**\n * Maps an auth result to a Backstage identity for the user.\n */\n resolver: SignInResolver<GithubOAuthResult>;\n };\n\n /**\n * The state encoder used to encode the 'state' parameter on the OAuth request.\n *\n * It should return a string that takes the state params (from the request), url encodes the params\n * and finally base64 encodes them.\n *\n * Providing your own stateEncoder will allow you to add addition parameters to the state field.\n *\n * It is typed as follows:\n * `export type StateEncoder = (input: OAuthState) => Promise<{encodedState: string}>;`\n *\n * Note: the stateEncoder must encode a 'nonce' value and an 'env' value. Without this, the OAuth flow will fail\n * (These two values will be set by the req.state by default)\n *\n * For more information, please see the helper module in ../../oauth/helpers #readState\n */\n stateEncoder?: StateEncoder;\n }) {\n const authHandler = options?.authHandler;\n const signInResolver = options?.signIn?.resolver;\n return createOAuthProviderFactory({\n authenticator: githubAuthenticator,\n profileTransform:\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 expires_in: result.session.expiresInSeconds\n ? String(result.session.expiresInSeconds)\n : '',\n refresh_token_expires_in: result.session\n .refreshTokenExpiresInSeconds\n ? String(result.session.refreshTokenExpiresInSeconds)\n : '',\n },\n },\n ctx,\n )) as ProfileTransform<OAuthAuthenticatorResult<PassportProfile>>),\n signInResolver:\n signInResolver &&\n ((async ({ profile, result }, ctx) =>\n signInResolver(\n {\n profile: profile,\n result: {\n fullProfile: result.fullProfile,\n accessToken: result.session.accessToken,\n refreshToken: result.session.refreshToken,\n params: {\n scope: result.session.scope,\n expires_in: result.session.expiresInSeconds\n ? String(result.session.expiresInSeconds)\n : '',\n refresh_token_expires_in: result.session\n .refreshTokenExpiresInSeconds\n ? String(result.session.refreshTokenExpiresInSeconds)\n : '',\n },\n },\n },\n ctx,\n )) as SignInResolver<OAuthAuthenticatorResult<PassportProfile>>),\n });\n },\n resolvers: {\n /**\n * Looks up the user by matching their GitHub username to the entity name.\n */\n usernameMatchingUserEntityName: (): SignInResolver<GithubOAuthResult> => {\n return async (info, ctx) => {\n const { fullProfile } = info.result;\n\n const userId = fullProfile.username;\n if (!userId) {\n throw new Error(`GitHub user profile does not contain a username`);\n }\n\n return ctx.signInWithCatalogUser({ entityRef: { name: userId } });\n };\n },\n },\n});\n","/*\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 { AuthHandler } from '../types';\nimport { OAuthResult } from '../../lib/oauth';\nimport { createAuthProviderIntegration } from '../createAuthProviderIntegration';\nimport {\n SignInResolver,\n createOAuthProviderFactory,\n} from '@backstage/plugin-auth-node';\nimport {\n adaptLegacyOAuthHandler,\n adaptLegacyOAuthSignInResolver,\n} from '../../lib/legacy';\nimport { gitlabAuthenticator } from '@backstage/plugin-auth-backend-module-gitlab-provider';\n\n/**\n * Auth provider integration for GitLab auth\n *\n * @public\n */\nexport const gitlab = createAuthProviderIntegration({\n create(options?: {\n /**\n * The profile transformation function used to verify and convert the auth response\n * into the profile that will be presented to the user.\n */\n authHandler?: AuthHandler<OAuthResult>;\n\n /**\n * Configure sign-in for this provider, without it the provider can not be used to sign users in.\n */\n signIn?: {\n resolver: SignInResolver<OAuthResult>;\n };\n }) {\n return createOAuthProviderFactory({\n authenticator: gitlabAuthenticator,\n profileTransform: adaptLegacyOAuthHandler(options?.authHandler),\n signInResolver: adaptLegacyOAuthSignInResolver(options?.signIn?.resolver),\n });\n },\n});\n","/*\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 googleAuthenticator,\n googleSignInResolvers,\n} from '@backstage/plugin-auth-backend-module-google-provider';\nimport {\n SignInResolver,\n commonSignInResolvers,\n createOAuthProviderFactory,\n} from '@backstage/plugin-auth-node';\nimport {\n adaptLegacyOAuthHandler,\n adaptLegacyOAuthSignInResolver,\n adaptOAuthSignInResolverToLegacy,\n} from '../../lib/legacy';\nimport { OAuthResult } from '../../lib/oauth';\nimport { createAuthProviderIntegration } from '../createAuthProviderIntegration';\nimport { AuthHandler } from '../types';\n\n/**\n * Auth provider integration for Google auth\n *\n * @public\n */\nexport const google = createAuthProviderIntegration({\n create(options?: {\n /**\n * The profile transformation function used to verify and convert the auth response\n * into the profile that will be presented to the user.\n */\n authHandler?: AuthHandler<OAuthResult>;\n\n /**\n * Configure sign-in for this provider, without it the provider can not be used to sign users in.\n */\n signIn?: {\n /**\n * Maps an auth result to a Backstage identity for the user.\n */\n resolver: SignInResolver<OAuthResult>;\n };\n }) {\n return createOAuthProviderFactory({\n authenticator: googleAuthenticator,\n profileTransform: adaptLegacyOAuthHandler(options?.authHandler),\n signInResolver: adaptLegacyOAuthSignInResolver(options?.signIn?.resolver),\n });\n },\n resolvers: adaptOAuthSignInResolverToLegacy({\n emailLocalPartMatchingUserEntityName:\n commonSignInResolvers.emailLocalPartMatchingUserEntityName(),\n emailMatchingUserEntityProfileEmail:\n commonSignInResolvers.emailMatchingUserEntityProfileEmail(),\n emailMatchingUserEntityAnnotation:\n googleSignInResolvers.emailMatchingUserEntityAnnotation(),\n }),\n});\n","/*\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 { AuthHandler } from '../types';\nimport { OAuthResult } from '../../lib/oauth';\nimport { createAuthProviderIntegration } from '../createAuthProviderIntegration';\nimport {\n SignInResolver,\n commonSignInResolvers,\n createOAuthProviderFactory,\n} from '@backstage/plugin-auth-node';\nimport {\n adaptLegacyOAuthHandler,\n adaptLegacyOAuthSignInResolver,\n adaptOAuthSignInResolverToLegacy,\n} from '../../lib/legacy';\nimport {\n microsoftAuthenticator,\n microsoftSignInResolvers,\n} from '@backstage/plugin-auth-backend-module-microsoft-provider';\n\n/**\n * Auth provider integration for Microsoft auth\n *\n * @public\n */\nexport const microsoft = createAuthProviderIntegration({\n create(options?: {\n /**\n * The profile transformation function used to verify and convert the auth response\n * into the profile that will be presented to the user.\n */\n authHandler?: AuthHandler<OAuthResult>;\n\n /**\n * Configure sign-in for this provider, without it the provider can not be used to sign users in.\n */\n signIn?: {\n resolver: SignInResolver<OAuthResult>;\n };\n }) {\n return createOAuthProviderFactory({\n authenticator: microsoftAuthenticator,\n profileTransform: adaptLegacyOAuthHandler(options?.authHandler),\n signInResolver: adaptLegacyOAuthSignInResolver(options?.signIn?.resolver),\n });\n },\n resolvers: adaptOAuthSignInResolverToLegacy({\n emailLocalPartMatchingUserEntityName:\n commonSignInResolvers.emailLocalPartMatchingUserEntityName(),\n emailMatchingUserEntityProfileEmail:\n commonSignInResolvers.emailMatchingUserEntityProfileEmail(),\n emailMatchingUserEntityAnnotation:\n microsoftSignInResolvers.emailMatchingUserEntityAnnotation(),\n }),\n});\n","/*\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 { OAuthResult } from '../../lib/oauth';\nimport { AuthHandler } from '../types';\nimport { createAuthProviderIntegration } from '../createAuthProviderIntegration';\nimport {\n adaptLegacyOAuthHandler,\n adaptLegacyOAuthSignInResolver,\n} from '../../lib/legacy';\nimport {\n SignInResolver,\n createOAuthProviderFactory,\n} from '@backstage/plugin-auth-node';\nimport { oauth2Authenticator } from '@backstage/plugin-auth-backend-module-oauth2-provider';\n\n/**\n * Auth provider integration for generic OAuth2 auth\n *\n * @public\n */\nexport const oauth2 = createAuthProviderIntegration({\n create(options?: {\n authHandler?: AuthHandler<OAuthResult>;\n\n signIn?: {\n resolver: SignInResolver<OAuthResult>;\n };\n }) {\n return createOAuthProviderFactory({\n authenticator: oauth2Authenticator,\n profileTransform: adaptLegacyOAuthHandler(options?.authHandler),\n signInResolver: adaptLegacyOAuthSignInResolver(options?.signIn?.resolver),\n });\n },\n});\n","/*\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 {\n SignInResolver,\n createProxyAuthProviderFactory,\n} from '@backstage/plugin-auth-node';\nimport { AuthHandler } from '../types';\nimport { createAuthProviderIntegration } from '../createAuthProviderIntegration';\nimport {\n type OAuth2ProxyResult,\n oauth2ProxyAuthenticator,\n} from '@backstage/plugin-auth-backend-module-oauth2-proxy-provider';\n\n/**\n * Auth provider integration for oauth2-proxy auth\n *\n * @public\n */\nexport const oauth2Proxy = createAuthProviderIntegration({\n create(options: {\n /**\n * Configure an auth handler to generate a profile for the user.\n *\n * The default implementation uses the value of the `X-Forwarded-Preferred-Username`\n * header as the display name, falling back to `X-Forwarded-User`, and the value of\n * the `X-Forwarded-Email` header as the email address.\n */\n authHandler?: AuthHandler<OAuth2ProxyResult>;\n\n /**\n * Configure sign-in for this provider, without it the provider can not be used to sign users in.\n */\n signIn: {\n /**\n * Maps an auth result to a Backstage identity for the user.\n */\n resolver: SignInResolver<OAuth2ProxyResult>;\n };\n }) {\n return createProxyAuthProviderFactory({\n authenticator: oauth2ProxyAuthenticator,\n profileTransform: options?.authHandler,\n signInResolver: options?.signIn?.resolver,\n });\n },\n});\n","/*\n * Copyright 2022 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 { SignInResolver } from '@backstage/plugin-auth-node';\n\n/**\n * A common sign-in resolver that looks up the user using the local part of\n * their email address as the entity name.\n */\nexport const commonByEmailLocalPartResolver: SignInResolver<unknown> = async (\n info,\n ctx,\n) => {\n const { profile } = info;\n\n if (!profile.email) {\n throw new Error('Login failed, user profile does not contain an email');\n }\n const [localPart] = profile.email.split('@');\n\n return ctx.signInWithCatalogUser({\n entityRef: { name: localPart },\n });\n};\n\n/**\n * A common sign-in resolver that looks up the user using their email address\n * as email of the entity.\n */\nexport const commonByEmailResolver: SignInResolver<unknown> = async (\n info,\n ctx,\n) => {\n const { profile } = info;\n\n if (!profile.email) {\n throw new Error('Login failed, user profile does not contain an email');\n }\n\n return ctx.signInWithCatalogUser({\n filter: {\n 'spec.profile.email': profile.email,\n },\n });\n};\n","/*\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 { AuthHandler } from '../types';\nimport { createAuthProviderIntegration } from '../createAuthProviderIntegration';\nimport {\n createOAuthProviderFactory,\n AuthResolverContext,\n BackstageSignInResult,\n OAuthAuthenticatorResult,\n SignInInfo,\n SignInResolver,\n} from '@backstage/plugin-auth-node';\nimport {\n oidcAuthenticator,\n OidcAuthResult,\n} from '@backstage/plugin-auth-backend-module-oidc-provider';\nimport {\n commonByEmailLocalPartResolver,\n commonByEmailResolver,\n} from '../resolvers';\n\n/**\n * Auth provider integration for generic OpenID Connect auth\n *\n * @public\n */\nexport const oidc = createAuthProviderIntegration({\n create(options?: {\n /**\n * The profile transformation function used to verify and convert the auth response\n * into the profile that will be presented to the user.\n */\n authHandler?: AuthHandler<OidcAuthResult>;\n\n /**\n * Configure sign-in for this provider; convert user profile respones into\n * Backstage identities.\n */\n signIn?: {\n resolver: SignInResolver<OidcAuthResult>;\n };\n }) {\n const authHandler = options?.authHandler;\n const signInResolver = options?.signIn?.resolver;\n return createOAuthProviderFactory({\n authenticator: oidcAuthenticator,\n profileTransform:\n authHandler &&\n ((\n result: OAuthAuthenticatorResult<OidcAuthResult>,\n context: AuthResolverContext,\n ) => authHandler(result.fullProfile, context)),\n signInResolver:\n signInResolver &&\n ((\n info: SignInInfo<OAuthAuthenticatorResult<OidcAuthResult>>,\n context: AuthResolverContext,\n ): Promise<BackstageSignInResult> =>\n signInResolver(\n {\n result: info.result.fullProfile,\n profile: info.profile,\n },\n context,\n )),\n });\n },\n resolvers: {\n /**\n * Looks up the user by matching their email local part to the entity name.\n */\n emailLocalPartMatchingUserEntityName: () => commonByEmailLocalPartResolver,\n /**\n * Looks up the user by matching their email to the entity email.\n */\n emailMatchingUserEntityProfileEmail: () => commonByEmailResolver,\n },\n});\n","/*\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 { AuthHandler } from '../types';\nimport { OAuthResult } from '../../lib/oauth';\n\nimport { createAuthProviderIntegration } from '../createAuthProviderIntegration';\nimport {\n SignInResolver,\n createOAuthProviderFactory,\n} from '@backstage/plugin-auth-node';\nimport {\n adaptLegacyOAuthHandler,\n adaptLegacyOAuthSignInResolver,\n} from '../../lib/legacy';\nimport { oktaAuthenticator } from '@backstage/plugin-auth-backend-module-okta-provider';\nimport {\n commonByEmailLocalPartResolver,\n commonByEmailResolver,\n} from '../resolvers';\n\n/**\n * Auth provider integration for Okta auth\n *\n * @public\n */\nexport const okta = createAuthProviderIntegration({\n create(options?: {\n /**\n * The profile transformation function used to verify and convert the auth response\n * into the profile that will be presented to the user.\n */\n authHandler?: AuthHandler<OAuthResult>;\n /**\n * Configure sign-in for this provider, without it the provider can not be used to sign users in.\n */\n signIn?: {\n resolver: SignInResolver<OAuthResult>;\n };\n }) {\n return createOAuthProviderFactory({\n authenticator: oktaAuthenticator,\n profileTransform: adaptLegacyOAuthHandler(options?.authHandler),\n signInResolver: adaptLegacyOAuthSignInResolver(options?.signIn?.resolver),\n });\n },\n resolvers: {\n /**\n * Looks up the user by matching their email local part to the entity name.\n */\n emailLocalPartMatchingUserEntityName: () => commonByEmailLocalPartResolver,\n /**\n * Looks up the user by matching their email to the entity email.\n */\n emailMatchingUserEntityProfileEmail: () => commonByEmailResolver,\n /**\n * Looks up the user by matching their email to the `okta.com/email` annotation.\n */\n emailMatchingUserEntityAnnotation(): SignInResolver<OAuthResult> {\n return async (info, ctx) => {\n const { profile } = info;\n\n if (!profile.email) {\n throw new Error('Okta profile contained no email');\n }\n\n return ctx.signInWithCatalogUser({\n annotations: {\n 'okta.com/email': profile.email,\n },\n });\n };\n },\n },\n});\n","/*\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 { oneLoginAuthenticator } from '@backstage/plugin-auth-backend-module-onelogin-provider';\nimport {\n SignInResolver,\n createOAuthProviderFactory,\n} from '@backstage/plugin-auth-node';\nimport {\n adaptLegacyOAuthHandler,\n adaptLegacyOAuthSignInResolver,\n} from '../../lib/legacy';\nimport { OAuthResult } from '../../lib/oauth';\nimport { createAuthProviderIntegration } from '../createAuthProviderIntegration';\nimport { AuthHandler } from '../types';\n\n/**\n * Auth provider integration for OneLogin auth\n *\n * @public\n */\nexport const onelogin = createAuthProviderIntegration({\n create(options?: {\n /**\n * The profile transformation function used to verify and convert the auth response\n * into the profile that will be presented to the user.\n */\n authHandler?: AuthHandler<OAuthResult>;\n\n /**\n * Configure sign-in for this provider, without it the provider can not be used to sign users in.\n */\n signIn?: {\n /**\n * Maps an auth result to a Backstage identity for the user.\n */\n resolver: SignInResolver<OAuthResult>;\n };\n }) {\n return createOAuthProviderFactory({\n authenticator: oneLoginAuthenticator,\n profileTransform: adaptLegacyOAuthHandler(options?.authHandler),\n signInResolver: adaptLegacyOAuthSignInResolver(options?.signIn?.resolver),\n });\n },\n});\n","/*\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 { SamlConfig, VerifiedCallback } from '@node-saml/passport-saml';\nimport {\n Strategy as SamlStrategy,\n Profile as SamlProfile,\n VerifyWithoutRequest,\n} from '@node-saml/passport-saml';\nimport {\n executeFrameHandlerStrategy,\n executeRedirectStrategy,\n} from '../../lib/passport';\nimport { AuthHandler } from '../types';\nimport { postMessageResponse } from '../../lib/flow';\nimport { createAuthProviderIntegration } from '../createAuthProviderIntegration';\nimport { AuthenticationError, isError } from '@backstage/errors';\nimport { prepareBackstageIdentityResponse } from '../prepareBackstageIdentityResponse';\nimport {\n AuthProviderRouteHandlers,\n AuthResolverContext,\n ClientAuthResponse,\n SignInResolver,\n} from '@backstage/plugin-auth-node';\n\n/** @public */\nexport type SamlAuthResult = {\n fullProfile: any;\n};\n\ntype Options = SamlConfig & {\n signInResolver?: SignInResolver<SamlAuthResult>;\n authHandler: AuthHandler<SamlAuthResult>;\n resolverContext: AuthResolverContext;\n appUrl: string;\n};\n\nexport class SamlAuthProvider implements AuthProviderRouteHandlers {\n private readonly strategy: SamlStrategy;\n private readonly signInResolver?: SignInResolver<SamlAuthResult>;\n private readonly authHandler: AuthHandler<SamlAuthResult>;\n private readonly resolverContext: AuthResolverContext;\n private readonly appUrl: string;\n\n constructor(options: Options) {\n this.appUrl = options.appUrl;\n this.signInResolver = options.signInResolver;\n this.authHandler = options.authHandler;\n this.resolverContext = options.resolverContext;\n\n const verifier: VerifyWithoutRequest = (\n profile: SamlProfile | null,\n done: VerifiedCallback,\n ) => {\n // TODO: There's plenty more validation and profile handling to do here,\n // this provider is currently only intended to validate the provider pattern\n // for non-oauth auth flows.\n // TODO: This flow doesn't issue an identity token that can be used to validate\n // the identity of the user in other backends, which we need in some form.\n done(null, { fullProfile: profile });\n };\n this.strategy = new SamlStrategy(options, verifier, verifier);\n }\n\n async start(req: express.Request, res: express.Response): Promise<void> {\n const { url } = await executeRedirectStrategy(req, this.strategy, {});\n res.redirect(url);\n }\n\n async frameHandler(\n req: express.Request,\n res: express.Response,\n ): Promise<void> {\n try {\n const { result } = await executeFrameHandlerStrategy<SamlAuthResult>(\n req,\n this.strategy,\n );\n\n const { profile } = await this.authHandler(result, this.resolverContext);\n\n const response: ClientAuthResponse<{}> = {\n profile,\n providerInfo: {},\n };\n\n if (this.signInResolver) {\n const signInResponse = await this.signInResolver(\n {\n result,\n profile,\n },\n this.resolverContext,\n );\n\n response.backstageIdentity =\n prepareBackstageIdentityResponse(signInResponse);\n }\n\n return postMessageResponse(res, this.appUrl, {\n type: 'authorization_response',\n response,\n });\n } catch (error) {\n const { name, message } = isError(error)\n ? error\n : new Error('Encountered invalid error'); // Being a bit safe and not forwarding the bad value\n return postMessageResponse(res, this.appUrl, {\n type: 'authorization_response',\n error: { name, message },\n });\n }\n }\n\n async logout(_req: express.Request, res: express.Response): Promise<void> {\n res.end();\n }\n}\n\ntype SignatureAlgorithm = 'sha1' | 'sha256' | 'sha512';\n\n/**\n * Auth provider integration for SAML auth\n *\n * @public\n */\nexport const saml = createAuthProviderIntegration({\n create(options?: {\n /**\n * The profile transformation function used to verify and convert the auth response\n * into the profile that will be presented to the user.\n */\n authHandler?: AuthHandler<SamlAuthResult>;\n\n /**\n * Configure sign-in for this provider, without it the provider can not be used to sign users in.\n */\n signIn?: {\n /**\n * Maps an auth result to a Backstage identity for the user.\n */\n resolver: SignInResolver<SamlAuthResult>;\n };\n }) {\n return ({ providerId, globalConfig, config, resolverContext }) => {\n const authHandler: AuthHandler<SamlAuthResult> = options?.authHandler\n ? options.authHandler\n : async ({ fullProfile }) => ({\n profile: {\n email: fullProfile.email,\n displayName: fullProfile.displayName,\n },\n });\n\n return new SamlAuthProvider({\n callbackUrl: `${globalConfig.baseUrl}/${providerId}/handler/frame`,\n entryPoint: config.getString('entryPoint'),\n logoutUrl: config.getOptionalString('logoutUrl'),\n audience: config.getString('audience'),\n issuer: config.getString('issuer'),\n cert: config.getString('cert'),\n privateKey: config.getOptionalString('privateKey'),\n authnContext: config.getOptionalStringArray('authnContext'),\n identifierFormat: config.getOptionalString('identifierFormat'),\n decryptionPvk: config.getOptionalString('decryptionPvk'),\n signatureAlgorithm: config.getOptionalString('signatureAlgorithm') as\n | SignatureAlgorithm\n | undefined,\n digestAlgorithm: config.getOptionalString('digestAlgorithm'),\n acceptedClockSkewMs: config.getOptionalNumber('acceptedClockSkewMs'),\n wantAuthnResponseSigned: config.getOptionalBoolean(\n 'wantAuthnResponseSigned',\n ),\n wantAssertionsSigned: config.getOptionalBoolean('wantAssertionsSigned'),\n appUrl: globalConfig.appUrl,\n authHandler,\n signInResolver: options?.signIn?.resolver,\n resolverContext,\n });\n };\n },\n resolvers: {\n /**\n * Looks up the user by matching their nameID to the entity name.\n */\n nameIdMatchingUserEntityName(): SignInResolver<SamlAuthResult> {\n return async (info, ctx) => {\n const id = info.result.fullProfile.nameID;\n\n if (!id) {\n throw new AuthenticationError('No nameID found in SAML response');\n }\n\n return ctx.signInWithCatalogUser({\n entityRef: { name: id },\n });\n };\n },\n },\n});\n","/*\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 encodeState,\n OAuthAdapter,\n OAuthEnvironmentHandler,\n OAuthHandlers,\n OAuthProviderOptions,\n OAuthRefreshRequest,\n OAuthResponse,\n OAuthStartRequest,\n} from '../../lib/oauth';\nimport { Strategy as OAuth2Strategy, VerifyCallback } from 'passport-oauth2';\nimport {\n executeFetchUserProfileStrategy,\n executeFrameHandlerStrategy,\n executeRedirectStrategy,\n executeRefreshTokenStrategy,\n makeProfileInfo,\n} from '../../lib/passport';\nimport { AuthHandler, OAuthStartResponse } from '../types';\nimport express from 'express';\nimport { createAuthProviderIntegration } from '../createAuthProviderIntegration';\nimport { Profile as PassportProfile } from 'passport';\nimport { commonByEmailResolver } from '../resolvers';\nimport fetch from 'node-fetch';\nimport {\n AuthResolverContext,\n SignInResolver,\n} from '@backstage/plugin-auth-node';\n\ntype PrivateInfo = {\n refreshToken: string;\n};\n\n/** @public */\nexport type BitbucketServerOAuthResult = {\n fullProfile: PassportProfile;\n params: {\n scope: string;\n access_token?: string;\n token_type?: string;\n expires_in?: number;\n };\n accessToken: string;\n refreshToken?: string;\n};\n\nexport type BitbucketServerAuthProviderOptions = OAuthProviderOptions & {\n host: string;\n authorizationUrl: string;\n tokenUrl: string;\n authHandler: AuthHandler<BitbucketServerOAuthResult>;\n signInResolver?: SignInResolver<BitbucketServerOAuthResult>;\n resolverContext: AuthResolverContext;\n};\n\nexport class BitbucketServerAuthProvider implements OAuthHandlers {\n private readonly signInResolver?: SignInResolver<BitbucketServerOAuthResult>;\n private readonly authHandler: AuthHandler<BitbucketServerOAuthResult>;\n private readonly resolverContext: AuthResolverContext;\n private readonly strategy: OAuth2Strategy;\n private readonly host: string;\n\n constructor(options: BitbucketServerAuthProviderOptions) {\n this.signInResolver = options.signInResolver;\n this.authHandler = options.authHandler;\n this.resolverContext = options.resolverContext;\n this.strategy = new OAuth2Strategy(\n {\n authorizationURL: options.authorizationUrl,\n tokenURL: options.tokenUrl,\n clientID: options.clientId,\n clientSecret: options.clientSecret,\n callbackURL: options.callbackUrl,\n },\n (\n accessToken: string,\n refreshToken: string,\n params: any,\n fullProfile: PassportProfile,\n done: VerifyCallback,\n ) => {\n done(undefined, { fullProfile, params, accessToken }, { refreshToken });\n },\n );\n this.host = options.host;\n }\n\n async start(req: OAuthStartRequest): Promise<OAuthStartResponse> {\n return await executeRedirectStrategy(req, this.strategy, {\n accessType: 'offline',\n prompt: 'consent',\n scope: req.scope,\n state: encodeState(req.state),\n });\n }\n\n async handler(\n req: express.Request,\n ): Promise<{ response: OAuthResponse; refreshToken?: string }> {\n const { result, privateInfo } = await executeFrameHandlerStrategy<\n BitbucketServerOAuthResult,\n PrivateInfo\n >(req, this.strategy);\n\n return {\n response: await this.handleResult(result),\n refreshToken: privateInfo.refreshToken,\n };\n }\n\n async refresh(\n req: OAuthRefreshRequest,\n ): Promise<{ response: OAuthResponse; refreshToken?: string }> {\n const { accessToken, refreshToken, params } =\n await executeRefreshTokenStrategy(\n this.strategy,\n req.refreshToken,\n req.scope,\n );\n const fullProfile = await executeFetchUserProfileStrategy(\n this.strategy,\n accessToken,\n );\n return {\n response: await this.handleResult({\n fullProfile,\n params,\n accessToken,\n }),\n refreshToken,\n };\n }\n\n private async handleResult(\n result: BitbucketServerOAuthResult,\n ): Promise<OAuthResponse> {\n // The OAuth2 strategy does not return a user profile -> let's fetch it before calling the auth handler\n result.fullProfile = await this.fetchProfile(result);\n const { profile } = await this.authHandler(result, this.resolverContext);\n\n let backstageIdentity = undefined;\n if (this.signInResolver) {\n backstageIdentity = await this.signInResolver(\n { result, profile },\n this.resolverContext,\n );\n }\n\n return {\n providerInfo: {\n accessToken: result.accessToken,\n scope: result.params.scope,\n expiresInSeconds: result.params.expires_in,\n },\n profile,\n backstageIdentity,\n };\n }\n\n private async fetchProfile(\n result: BitbucketServerOAuthResult,\n ): Promise<PassportProfile> {\n // Get current user name\n let whoAmIResponse;\n try {\n whoAmIResponse = await fetch(\n `https://${this.host}/plugins/servlet/applinks/whoami`,\n {\n headers: {\n Authorization: `Bearer ${result.accessToken}`,\n },\n },\n );\n } catch (e) {\n throw new Error(`Failed to retrieve the username of the logged in user`);\n }\n\n // A response.ok check here would be worthless as the Bitbucket API always returns 200 OK for this call\n const username = whoAmIResponse.headers.get('X-Ausername');\n if (!username) {\n throw new Error(`Failed to retrieve the username of the logged in user`);\n }\n\n let userResponse;\n try {\n userResponse = await fetch(\n `https://${this.host}/rest/api/latest/users/${username}?avatarSize=256`,\n {\n headers: {\n Authorization: `Bearer ${result.accessToken}`,\n },\n },\n );\n } catch (e) {\n throw new Error(`Failed to retrieve the user '${username}'`);\n }\n\n if (!userResponse.ok) {\n throw new Error(`Failed to retrieve the user '${username}'`);\n }\n\n const user = await userResponse.json();\n\n const passportProfile = {\n provider: 'bitbucketServer',\n id: user.id.toString(),\n displayName: user.displayName,\n username: user.name,\n emails: [\n {\n value: user.emailAddress,\n },\n ],\n } as PassportProfile;\n\n if (user.avatarUrl) {\n passportProfile.photos = [\n { value: `https://${this.host}${user.avatarUrl}` },\n ];\n }\n\n return passportProfile;\n }\n}\n\nexport const bitbucketServer = createAuthProviderIntegration({\n create(options?: {\n /**\n * The profile transformation function used to verify and convert the auth response\n * into the profile that will be presented to the user.\n */\n authHandler?: AuthHandler<BitbucketServerOAuthResult>;\n\n /**\n * Configure sign-in for this provider, without it the provider can not be used to sign users in.\n */\n signIn?: {\n /**\n * Maps an auth result to a Backstage identity for the user.\n */\n resolver: SignInResolver<BitbucketServerOAuthResult>;\n };\n }) {\n return ({ providerId, globalConfig, config, resolverContext }) =>\n OAuthEnvironmentHandler.mapConfig(config, envConfig => {\n const clientId = envConfig.getString('clientId');\n const clientSecret = envConfig.getString('clientSecret');\n const host = envConfig.getString('host');\n const customCallbackUrl = envConfig.getOptionalString('callbackUrl');\n const callbackUrl =\n customCallbackUrl ||\n `${globalConfig.baseUrl}/${providerId}/handler/frame`;\n const authorizationUrl = `https://${host}/rest/oauth2/latest/authorize`;\n const tokenUrl = `https://${host}/rest/oauth2/latest/token`;\n\n const authHandler: AuthHandler<BitbucketServerOAuthResult> =\n options?.authHandler\n ? options.authHandler\n : async ({ fullProfile }) => ({\n profile: makeProfileInfo(fullProfile),\n });\n\n const provider = new BitbucketServerAuthProvider({\n callbackUrl,\n clientId,\n clientSecret,\n host,\n authorizationUrl,\n tokenUrl,\n authHandler,\n signInResolver: options?.signIn?.resolver,\n resolverContext,\n });\n\n return OAuthAdapter.fromConfig(globalConfig, provider, {\n providerId,\n callbackUrl,\n });\n });\n },\n resolvers: {\n /**\n * Looks up the user by matching their email to the entity email.\n */\n emailMatchingUserEntityProfileEmail:\n (): SignInResolver<BitbucketServerOAuthResult> => commonByEmailResolver,\n },\n});\n","/*\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 SignInResolver,\n createProxyAuthProviderFactory,\n} from '@backstage/plugin-auth-node';\nimport { AuthHandler } from '../types';\nimport { createAuthProviderIntegration } from '../createAuthProviderIntegration';\nimport {\n AzureEasyAuthResult,\n azureEasyAuthAuthenticator,\n} from '@backstage/plugin-auth-backend-module-azure-easyauth-provider';\n\nexport type EasyAuthResult = AzureEasyAuthResult;\n\n/**\n * Auth provider integration for Azure EasyAuth\n *\n * @public\n */\nexport const easyAuth = createAuthProviderIntegration({\n create(options?: {\n /**\n * The profile transformation function used to verify and convert the auth response\n * into the profile that will be presented to the user.\n */\n authHandler?: AuthHandler<EasyAuthResult>;\n\n /**\n * Configure sign-in for this provider, without it the provider can not be used to sign users in.\n */\n signIn: {\n /**\n * Maps an auth result to a Backstage identity for the user.\n */\n resolver: SignInResolver<EasyAuthResult>;\n };\n }) {\n return createProxyAuthProviderFactory({\n authenticator: azureEasyAuthAuthenticator,\n profileTransform: options?.authHandler,\n signInResolver: options?.signIn?.resolver,\n });\n },\n});\n","/*\n * Copyright 2022 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 { atlassian } from './atlassian';\nimport { auth0 } from './auth0';\nimport { awsAlb } from './aws-alb';\nimport { bitbucket } from './bitbucket';\nimport { cfAccess } from './cloudflare-access';\nimport { gcpIap } from './gcp-iap';\nimport { github } from './github';\nimport { gitlab } from './gitlab';\nimport { google } from './google';\nimport { microsoft } from './microsoft';\nimport { oauth2 } from './oauth2';\nimport { oauth2Proxy } from './oauth2-proxy';\nimport { oidc } from './oidc';\nimport { okta } from './okta';\nimport { onelogin } from './onelogin';\nimport { saml } from './saml';\nimport { bitbucketServer } from './bitbucketServer';\nimport { easyAuth } from './azure-easyauth';\nimport { AuthProviderFactory } from '@backstage/plugin-auth-node';\n\n/**\n * All built-in auth provider integrations.\n *\n * @public\n */\nexport const providers = Object.freeze({\n atlassian,\n auth0,\n awsAlb,\n bitbucket,\n bitbucketServer,\n cfAccess,\n gcpIap,\n github,\n gitlab,\n google,\n microsoft,\n oauth2,\n oauth2Proxy,\n oidc,\n okta,\n onelogin,\n saml,\n easyAuth,\n});\n\n/**\n * All auth provider factories that are installed by default.\n *\n * @public\n */\nexport const defaultAuthProviderFactories: {\n [providerId: string]: AuthProviderFactory;\n} = {\n google: google.create(),\n github: github.create(),\n gitlab: gitlab.create(),\n saml: saml.create(),\n okta: okta.create(),\n auth0: auth0.create(),\n microsoft: microsoft.create(),\n easyAuth: easyAuth.create(),\n oauth2: oauth2.create(),\n oidc: oidc.create(),\n onelogin: onelogin.create(),\n awsalb: awsAlb.create(),\n bitbucket: bitbucket.create(),\n bitbucketServer: bitbucketServer.create(),\n atlassian: atlassian.create(),\n};\n","/*\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","/*\n * Copyright 2022 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 { TokenManager } from '@backstage/backend-common';\nimport { CatalogApi } from '@backstage/catalog-client';\nimport {\n DEFAULT_NAMESPACE,\n Entity,\n parseEntityRef,\n RELATION_MEMBER_OF,\n stringifyEntityRef,\n} from '@backstage/catalog-model';\nimport { ConflictError, InputError, NotFoundError } from '@backstage/errors';\nimport {\n AuthService,\n DiscoveryService,\n HttpAuthService,\n LoggerService,\n} from '@backstage/backend-plugin-api';\nimport { TokenIssuer } from '../../identity/types';\nimport {\n AuthOwnershipResolver,\n AuthResolverCatalogUserQuery,\n AuthResolverContext,\n TokenParams,\n} from '@backstage/plugin-auth-node';\nimport { CatalogIdentityClient } from '../catalog';\n\n/**\n * Uses the default ownership resolution logic to return an array\n * of entity refs that the provided entity claims ownership through.\n *\n * A reference to the entity itself will also be included in the returned array.\n *\n * @public\n */\nexport function getDefaultOwnershipEntityRefs(entity: Entity) {\n const membershipRefs =\n entity.relations\n ?.filter(\n r => r.type === RELATION_MEMBER_OF && r.targetRef.startsWith('group:'),\n )\n .map(r => r.targetRef) ?? [];\n\n return Array.from(new Set([stringifyEntityRef(entity), ...membershipRefs]));\n}\n\n/**\n * @internal\n */\nexport class CatalogAuthResolverContext implements AuthResolverContext {\n static create(options: {\n logger: LoggerService;\n catalogApi: CatalogApi;\n tokenIssuer: TokenIssuer;\n tokenManager: TokenManager;\n discovery: DiscoveryService;\n auth: AuthService;\n httpAuth: HttpAuthService;\n ownershipResolver?: AuthOwnershipResolver;\n }): CatalogAuthResolverContext {\n const catalogIdentityClient = new CatalogIdentityClient({\n catalogApi: options.catalogApi,\n tokenManager: options.tokenManager,\n discovery: options.discovery,\n auth: options.auth,\n httpAuth: options.httpAuth,\n });\n\n return new CatalogAuthResolverContext(\n options.logger,\n options.tokenIssuer,\n catalogIdentityClient,\n options.catalogApi,\n options.auth,\n options.ownershipResolver,\n );\n }\n\n private constructor(\n public readonly logger: LoggerService,\n public readonly tokenIssuer: TokenIssuer,\n public readonly catalogIdentityClient: CatalogIdentityClient,\n private readonly catalogApi: CatalogApi,\n private readonly auth: AuthService,\n private readonly ownershipResolver?: AuthOwnershipResolver,\n ) {}\n\n async issueToken(params: TokenParams) {\n const token = await this.tokenIssuer.issueToken(params);\n return { token };\n }\n\n async findCatalogUser(query: AuthResolverCatalogUserQuery) {\n let result: Entity[] | Entity | undefined = undefined;\n const { token } = await this.auth.getPluginRequestToken({\n onBehalfOf: await this.auth.getOwnServiceCredentials(),\n targetPluginId: 'catalog',\n });\n\n if ('entityRef' in query) {\n const entityRef = parseEntityRef(query.entityRef, {\n defaultKind: 'User',\n defaultNamespace: DEFAULT_NAMESPACE,\n });\n result = await this.catalogApi.getEntityByRef(entityRef, { token });\n } else if ('annotations' in query) {\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 const res = await this.catalogApi.getEntities({ filter }, { token });\n result = res.items;\n } else if ('filter' in query) {\n const filter = [query.filter].flat().map(value => {\n if (\n !Object.keys(value).some(\n key => key.toLocaleLowerCase('en-US') === 'kind',\n )\n ) {\n return {\n ...value,\n kind: 'user',\n };\n }\n return value;\n });\n const res = await this.catalogApi.getEntities(\n { filter: filter },\n { token },\n );\n result = res.items;\n } else {\n throw new InputError('Invalid user lookup query');\n }\n\n if (Array.isArray(result)) {\n if (result.length > 1) {\n throw new ConflictError('User lookup resulted in multiple matches');\n }\n result = result[0];\n }\n if (!result) {\n throw new NotFoundError('User not found');\n }\n\n return { entity: result };\n }\n\n async signInWithCatalogUser(query: AuthResolverCatalogUserQuery) {\n const { entity } = await this.findCatalogUser(query);\n let ent: string[];\n if (this.ownershipResolver) {\n const { ownershipEntityRefs } =\n await this.ownershipResolver.resolveOwnershipEntityRefs(entity);\n ent = ownershipEntityRefs;\n } else {\n ent = getDefaultOwnershipEntityRefs(entity);\n }\n\n const token = await this.tokenIssuer.issueToken({\n claims: {\n sub: stringifyEntityRef(entity),\n ent,\n },\n });\n return { token };\n }\n}\n","/*\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 {\n PluginEndpointDiscovery,\n TokenManager,\n} from '@backstage/backend-common';\nimport {\n AuthService,\n HttpAuthService,\n LoggerService,\n} from '@backstage/backend-plugin-api';\nimport { CatalogApi, CatalogClient } from '@backstage/catalog-client';\nimport { Config } from '@backstage/config';\nimport { assertError, NotFoundError } from '@backstage/errors';\nimport {\n AuthOwnershipResolver,\n AuthProviderFactory,\n} from '@backstage/plugin-auth-node';\nimport express from 'express';\nimport Router from 'express-promise-router';\nimport { Minimatch } from 'minimatch';\nimport { CatalogAuthResolverContext } from '../lib/resolvers/CatalogAuthResolverContext';\nimport { TokenIssuer } from '../identity/types';\n\n/** @public */\nexport type ProviderFactories = { [s: string]: AuthProviderFactory };\n\nexport function bindProviderRouters(\n targetRouter: express.Router,\n options: {\n providers: ProviderFactories;\n appUrl: string;\n baseUrl: string;\n config: Config;\n logger: LoggerService;\n discovery: PluginEndpointDiscovery;\n auth: AuthService;\n httpAuth: HttpAuthService;\n tokenManager: TokenManager;\n tokenIssuer: TokenIssuer;\n ownershipResolver?: AuthOwnershipResolver;\n catalogApi?: CatalogApi;\n },\n) {\n const {\n providers,\n appUrl,\n baseUrl,\n config,\n logger,\n discovery,\n auth,\n httpAuth,\n tokenManager,\n tokenIssuer,\n catalogApi,\n ownershipResolver,\n } = options;\n\n const providersConfig = config.getOptionalConfig('auth.providers');\n\n const isOriginAllowed = createOriginFilter(config);\n\n for (const [providerId, providerFactory] of Object.entries(providers)) {\n if (providersConfig?.has(providerId)) {\n logger.info(`Configuring auth provider: ${providerId}`);\n try {\n const provider = providerFactory({\n providerId,\n appUrl,\n baseUrl,\n isOriginAllowed,\n globalConfig: {\n baseUrl,\n appUrl,\n isOriginAllowed,\n },\n config: providersConfig.getConfig(providerId),\n logger,\n resolverContext: CatalogAuthResolverContext.create({\n logger,\n catalogApi:\n catalogApi ?? new CatalogClient({ discoveryApi: discovery }),\n tokenIssuer,\n tokenManager,\n discovery,\n auth,\n httpAuth,\n ownershipResolver,\n }),\n });\n\n const r = Router();\n\n r.get('/start', provider.start.bind(provider));\n r.get('/handler/frame', provider.frameHandler.bind(provider));\n r.post('/handler/frame', provider.frameHandler.bind(provider));\n if (provider.logout) {\n r.post('/logout', provider.logout.bind(provider));\n }\n if (provider.refresh) {\n r.get('/refresh', provider.refresh.bind(provider));\n r.post('/refresh', provider.refresh.bind(provider));\n }\n\n targetRouter.use(`/${providerId}`, r);\n } catch (e) {\n assertError(e);\n if (process.env.NODE_ENV !== 'development') {\n throw new Error(\n `Failed to initialize ${providerId} auth provider, ${e.message}`,\n );\n }\n\n logger.warn(`Skipping ${providerId} auth provider, ${e.message}`);\n\n targetRouter.use(`/${providerId}`, () => {\n // If the user added the provider under auth.providers but the clientId and clientSecret etc. were not found.\n throw new NotFoundError(\n `Auth provider registered for '${providerId}' is misconfigured. This could mean the configs under ` +\n `auth.providers.${providerId} are missing or the environment variables used are not defined. ` +\n `Check the auth backend plugin logs when the backend starts to see more details.`,\n );\n });\n }\n } else {\n targetRouter.use(`/${providerId}`, () => {\n throw new NotFoundError(\n `No auth provider registered for '${providerId}'`,\n );\n });\n }\n }\n}\n\n/** @public */\nexport function createOriginFilter(\n config: Config,\n): (origin: string) => boolean {\n const appUrl = config.getString('app.baseUrl');\n const { origin: appOrigin } = new URL(appUrl);\n\n const allowedOrigins = config.getOptionalStringArray(\n 'auth.experimentalExtraAllowedOrigins',\n );\n\n const allowedOriginPatterns =\n allowedOrigins?.map(\n pattern => new Minimatch(pattern, { nocase: true, noglobstar: true }),\n ) ?? [];\n\n return origin => {\n if (origin === appOrigin) {\n return true;\n }\n return allowedOriginPatterns.some(pattern => pattern.match(origin));\n };\n}\n","/*\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","/*\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","/*\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","/*\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","/*\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","/*\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","/*\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","/*\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","/*\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","/*\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 { RootConfigService } from '@backstage/backend-plugin-api';\nimport { readDurationFromConfig } from '@backstage/config';\nimport { durationToMilliseconds } from '@backstage/types';\n\nconst TOKEN_EXP_DEFAULT_S = 3600;\nconst TOKEN_EXP_MIN_S = 600;\nconst TOKEN_EXP_MAX_S = 86400;\n\nexport function readBackstageTokenExpiration(config: RootConfigService) {\n const processingIntervalKey = 'auth.backstageTokenExpiration';\n\n if (!config.has(processingIntervalKey)) {\n return TOKEN_EXP_DEFAULT_S;\n }\n\n const duration = readDurationFromConfig(config, {\n key: processingIntervalKey,\n });\n\n const durationS = Math.round(durationToMilliseconds(duration) / 1000);\n\n if (durationS < TOKEN_EXP_MIN_S) {\n return TOKEN_EXP_MIN_S;\n } else if (durationS > TOKEN_EXP_MAX_S) {\n return TOKEN_EXP_MAX_S;\n }\n return durationS;\n}\n","/*\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","/*\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 cookieParser from 'cookie-parser';\nimport {\n AuthService,\n HttpAuthService,\n LoggerService,\n} from '@backstage/backend-plugin-api';\nimport { defaultAuthProviderFactories } from '../providers';\nimport { AuthOwnershipResolver } from '@backstage/plugin-auth-node';\nimport {\n createLegacyAuthAdapters,\n PluginDatabaseManager,\n PluginEndpointDiscovery,\n TokenManager,\n} from '@backstage/backend-common';\nimport { NotFoundError } from '@backstage/errors';\nimport { CatalogApi } from '@backstage/catalog-client';\nimport {\n bindOidcRouter,\n KeyStores,\n TokenFactory,\n UserInfoDatabaseHandler,\n} from '../identity';\nimport session from 'express-session';\nimport connectSessionKnex from 'connect-session-knex';\nimport passport from 'passport';\nimport { AuthDatabase } from '../database/AuthDatabase';\nimport { readBackstageTokenExpiration } from './readBackstageTokenExpiration';\nimport { TokenIssuer } from '../identity/types';\nimport { StaticTokenIssuer } from '../identity/StaticTokenIssuer';\nimport { StaticKeyStore } from '../identity/StaticKeyStore';\nimport { Config } from '@backstage/config';\nimport { bindProviderRouters, ProviderFactories } from '../providers/router';\n\n/** @public */\nexport interface RouterOptions {\n logger: LoggerService;\n database: PluginDatabaseManager;\n config: Config;\n discovery: PluginEndpointDiscovery;\n tokenManager: TokenManager;\n auth?: AuthService;\n httpAuth?: HttpAuthService;\n tokenFactoryAlgorithm?: string;\n providerFactories?: ProviderFactories;\n disableDefaultProviderFactories?: boolean;\n catalogApi?: CatalogApi;\n ownershipResolver?: AuthOwnershipResolver;\n}\n\n/** @public */\nexport async function createRouter(\n options: RouterOptions,\n): Promise<express.Router> {\n const {\n logger,\n config,\n discovery,\n database,\n tokenFactoryAlgorithm,\n providerFactories = {},\n } = options;\n\n const { auth, httpAuth } = createLegacyAuthAdapters(options);\n\n const router = Router();\n\n const appUrl = config.getString('app.baseUrl');\n const authUrl = await discovery.getExternalBaseUrl('auth');\n const backstageTokenExpiration = readBackstageTokenExpiration(config);\n const authDb = AuthDatabase.create(database);\n\n const keyStore = await KeyStores.fromConfig(config, {\n logger,\n database: authDb,\n });\n\n const userInfoDatabaseHandler = new UserInfoDatabaseHandler(\n await authDb.get(),\n );\n\n let tokenIssuer: TokenIssuer;\n if (keyStore instanceof StaticKeyStore) {\n tokenIssuer = new StaticTokenIssuer(\n {\n logger: logger.child({ component: 'token-factory' }),\n issuer: authUrl,\n sessionExpirationSeconds: backstageTokenExpiration,\n },\n keyStore as StaticKeyStore,\n );\n } else {\n tokenIssuer = new TokenFactory({\n issuer: authUrl,\n keyStore,\n keyDurationSeconds: backstageTokenExpiration,\n logger: logger.child({ component: 'token-factory' }),\n algorithm:\n tokenFactoryAlgorithm ??\n config.getOptionalString('auth.identityTokenAlgorithm'),\n userInfoDatabaseHandler,\n });\n }\n\n const secret = config.getOptionalString('auth.session.secret');\n if (secret) {\n router.use(cookieParser(secret));\n const enforceCookieSSL = authUrl.startsWith('https');\n const KnexSessionStore = connectSessionKnex(session);\n router.use(\n session({\n secret,\n saveUninitialized: false,\n resave: false,\n cookie: { secure: enforceCookieSSL ? 'auto' : false },\n store: new KnexSessionStore({\n createtable: false,\n knex: await authDb.get(),\n }),\n }),\n );\n router.use(passport.initialize());\n router.use(passport.session());\n } else {\n router.use(cookieParser());\n }\n\n router.use(express.urlencoded({ extended: false }));\n router.use(express.json());\n\n const providers = options.disableDefaultProviderFactories\n ? providerFactories\n : {\n ...defaultAuthProviderFactories,\n ...providerFactories,\n };\n\n bindProviderRouters(router, {\n providers,\n appUrl,\n baseUrl: authUrl,\n tokenIssuer,\n ...options,\n auth,\n httpAuth,\n });\n\n bindOidcRouter(router, {\n auth,\n tokenIssuer,\n baseUrl: authUrl,\n userInfoDatabaseHandler,\n });\n\n // Gives a more helpful error message than a plain 404\n router.use('/:provider/', req => {\n const { provider } = req.params;\n throw new NotFoundError(`Unknown auth provider '${provider}'`);\n });\n\n return router;\n}\n","/*\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 tokenManager: coreServices.tokenManager,\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 tokenManager,\n auth,\n httpAuth,\n catalogApi,\n }) {\n const router = await createRouter({\n logger,\n config,\n database,\n discovery,\n tokenManager,\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":["createOAuthProviderFactory","atlassianAuthenticator","Auth0InternalStrategy","_OAuthEnvironmentHandler","decodeOAuthState","encodeOAuthState","crypto","_prepareBackstageIdentityResponse","URL","InputError","NotAllowedError","isError","AuthenticationError","decodeJwt","createProxyAuthProviderFactory","awsAlbAuthenticator","bitbucketAuthenticator","bitbucketSignInResolvers","createCloudflareAccessAuthenticator","cloudflareAccessSignInResolvers","gcpIapAuthenticator","githubAuthenticator","gitlabAuthenticator","googleAuthenticator","commonSignInResolvers","googleSignInResolvers","microsoftAuthenticator","microsoftSignInResolvers","oauth2Authenticator","oauth2ProxyAuthenticator","oidcAuthenticator","oktaAuthenticator","oneLoginAuthenticator","SamlStrategy","OAuth2Strategy","fetch","azureEasyAuthAuthenticator","createLegacyAuthAdapters","ConflictError","NotFoundError","parseEntityRef","stringifyEntityRef","RELATION_MEMBER_OF","DEFAULT_NAMESPACE","CatalogClient","Router","assertError","Minimatch","MS_IN_S","tokenTypes","importJWK","SignJWT","omit","DateTime","generateKeyPair","exportJWK","uuid","GeneralSign","TABLE","Firestore","importSPKI","importPKCS8","fs","pickBy","resolvePackagePath","config","ConfigReader","DatabaseManager","readDurationFromConfig","durationToMilliseconds","cookieParser","connectSessionKnex","session","passport","express","createBackendPlugin","authProvidersExtensionPoint","authOwnershipResolutionExtensionPoint","coreServices","catalogServiceRef"],"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,OA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,UAAA;AAAA,OACC,EAAA;AACD,QAAM,MAAA,MAAA,GAAS,MAAM,YAAa,CAAA;AAAA,UAChC,MAAA;AAAA,UACA,MAAA;AAAA,UACA,QAAA;AAAA,UACA,SAAA;AAAA,UACA,YAAA;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,iBAAA;AAAA,SACD,CAAA,CAAA;AACD,QAAA,UAAA,CAAW,aAAc,CAAA;AAAA,UACvB,IAAM,EAAA,GAAA;AAAA,UACN,KAAO,EAAA,iBAAA;AAAA,SACR,CAAA,CAAA;AACD,QAAA,UAAA,CAAW,IAAI,MAAM,CAAA,CAAA;AAAA,OACvB;AAAA,KACD,CAAA,CAAA;AAAA,GACH;AACF,CAAC;;;;;;;;;;;;;;;;;;;"}
1
+ {"version":3,"file":"index.cjs.js","sources":["../src/lib/legacy/adaptLegacyOAuthHandler.ts","../src/lib/legacy/adaptLegacyOAuthSignInResolver.ts","../src/lib/legacy/adaptOAuthSignInResolverToLegacy.ts","../src/providers/createAuthProviderIntegration.ts","../src/providers/atlassian/provider.ts","../src/providers/auth0/strategy.ts","../src/lib/oauth/OAuthEnvironmentHandler.ts","../src/lib/oauth/helpers.ts","../src/lib/flow/authFlowHelpers.ts","../src/providers/prepareBackstageIdentityResponse.ts","../src/lib/oauth/OAuthAdapter.ts","../src/lib/passport/PassportStrategyHelper.ts","../src/providers/auth0/provider.ts","../src/providers/aws-alb/provider.ts","../src/providers/bitbucket/provider.ts","../src/providers/cloudflare-access/provider.ts","../src/providers/gcp-iap/provider.ts","../src/providers/github/provider.ts","../src/providers/gitlab/provider.ts","../src/providers/google/provider.ts","../src/providers/microsoft/provider.ts","../src/providers/oauth2/provider.ts","../src/providers/oauth2-proxy/provider.ts","../src/providers/resolvers.ts","../src/providers/oidc/provider.ts","../src/providers/okta/provider.ts","../src/providers/onelogin/provider.ts","../src/providers/saml/provider.ts","../src/providers/bitbucketServer/provider.ts","../src/providers/azure-easyauth/provider.ts","../src/providers/providers.ts","../src/lib/catalog/CatalogIdentityClient.ts","../src/lib/resolvers/CatalogAuthResolverContext.ts","../src/providers/router.ts","../src/identity/router.ts","../src/identity/TokenFactory.ts","../src/identity/DatabaseKeyStore.ts","../src/identity/MemoryKeyStore.ts","../src/identity/FirestoreKeyStore.ts","../src/identity/StaticKeyStore.ts","../src/identity/KeyStores.ts","../src/identity/UserInfoDatabaseHandler.ts","../src/database/AuthDatabase.ts","../src/service/readBackstageTokenExpiration.ts","../src/identity/StaticTokenIssuer.ts","../src/service/router.ts","../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 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","/*\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","/*\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","/*\n * Copyright 2022 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 AuthProviderFactory,\n SignInResolver,\n} from '@backstage/plugin-auth-node';\n\n/**\n * Creates a standardized representation of an integration with a third-party\n * auth provider.\n *\n * The returned object facilitates the creation of provider instances, and\n * supplies built-in sign-in resolvers for the specific provider.\n *\n * @public\n */\nexport function createAuthProviderIntegration<\n TCreateOptions extends unknown[],\n TResolvers extends\n | {\n [name in string]: (...args: any[]) => SignInResolver<any>;\n },\n>(config: {\n create: (...args: TCreateOptions) => AuthProviderFactory;\n resolvers?: TResolvers;\n}): Readonly<{\n create: (...args: TCreateOptions) => AuthProviderFactory;\n // If no resolvers are defined, this receives the type `never`\n resolvers: Readonly<string extends keyof TResolvers ? never : TResolvers>;\n}> {\n return Object.freeze({\n ...config,\n resolvers: Object.freeze(config.resolvers ?? ({} as any)),\n });\n}\n","/*\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 { atlassianAuthenticator } from '@backstage/plugin-auth-backend-module-atlassian-provider';\nimport {\n SignInResolver,\n createOAuthProviderFactory,\n} from '@backstage/plugin-auth-node';\nimport {\n adaptLegacyOAuthHandler,\n adaptLegacyOAuthSignInResolver,\n} from '../../lib/legacy';\nimport { OAuthResult } from '../../lib/oauth';\nimport { createAuthProviderIntegration } from '../createAuthProviderIntegration';\nimport { AuthHandler } from '../types';\n\n/**\n * Auth provider integration for Atlassian auth\n *\n * @public\n */\nexport const atlassian = createAuthProviderIntegration({\n create(options?: {\n /**\n * The profile transformation function used to verify and convert the auth response\n * into the profile that will be presented to the user.\n */\n authHandler?: AuthHandler<OAuthResult>;\n\n /**\n * Configure sign-in for this provider, without it the provider can not be used to sign users in.\n */\n signIn?: {\n resolver: SignInResolver<OAuthResult>;\n };\n }) {\n return createOAuthProviderFactory({\n authenticator: atlassianAuthenticator,\n profileTransform: adaptLegacyOAuthHandler(options?.authHandler),\n signInResolver: adaptLegacyOAuthSignInResolver(options?.signIn?.resolver),\n });\n },\n});\n","/*\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 */\nimport Auth0InternalStrategy from 'passport-auth0';\nimport { StateStore } from 'passport-oauth2';\n\nexport interface Auth0StrategyOptionsWithRequest {\n clientID: string;\n clientSecret: string;\n callbackURL: string;\n domain: string;\n passReqToCallback: true;\n store: StateStore;\n}\n\nexport default class Auth0Strategy extends Auth0InternalStrategy {\n constructor(\n options: Auth0StrategyOptionsWithRequest,\n verify: Auth0InternalStrategy.VerifyFunction,\n ) {\n const optionsWithURLs = {\n ...options,\n authorizationURL: `https://${options.domain}/authorize`,\n tokenURL: `https://${options.domain}/oauth/token`,\n userInfoURL: `https://${options.domain}/userinfo`,\n apiUrl: `https://${options.domain}/api`,\n };\n super(optionsWithURLs, verify);\n }\n}\n","/*\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 { OAuthEnvironmentHandler as _OAuthEnvironmentHandler } from '@backstage/plugin-auth-node';\n\n/**\n * @public\n * @deprecated import from `@backstage/plugin-auth-node` instead\n */\nexport const OAuthEnvironmentHandler = _OAuthEnvironmentHandler;\n","/*\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 {\n CookieConfigurer,\n OAuthState,\n decodeOAuthState,\n encodeOAuthState,\n} from '@backstage/plugin-auth-node';\n\n/**\n * @public\n * @deprecated Use `decodeOAuthState` from `@backstage/plugin-auth-node` instead\n */\nexport const readState = decodeOAuthState;\n\n/**\n * @public\n * @deprecated Use `encodeOAuthState` from `@backstage/plugin-auth-node` instead\n */\nexport const encodeState = encodeOAuthState;\n\n/**\n * @public\n * @deprecated Use inline logic to make sure the session and state nonce matches instead.\n */\nexport const verifyNonce = (req: express.Request, providerId: string) => {\n const cookieNonce = req.cookies[`${providerId}-nonce`];\n const state: OAuthState = readState(req.query.state?.toString() ?? '');\n const stateNonce = state.nonce;\n\n if (!cookieNonce) {\n throw new Error('Auth response is missing cookie nonce');\n }\n if (stateNonce.length === 0) {\n throw new Error('Auth response is missing state nonce');\n }\n if (cookieNonce !== stateNonce) {\n throw new Error('Invalid nonce');\n }\n};\n\nexport const defaultCookieConfigurer: CookieConfigurer = ({\n callbackUrl,\n providerId,\n appOrigin,\n}) => {\n const { hostname: domain, pathname, protocol } = new URL(callbackUrl);\n const secure = protocol === 'https:';\n\n // For situations where the auth-backend is running on a\n // different domain than the app, we set the SameSite attribute\n // to 'none' to allow third-party access to the cookie, but\n // only if it's in a secure context (https).\n let sameSite: ReturnType<CookieConfigurer>['sameSite'] = 'lax';\n if (new URL(appOrigin).hostname !== domain && secure) {\n sameSite = 'none';\n }\n\n // If the provider supports callbackUrls, the pathname will\n // contain the complete path to the frame handler so we need\n // to slice off the trailing part of the path.\n const path = pathname.endsWith(`${providerId}/handler/frame`)\n ? pathname.slice(0, -'/handler/frame'.length)\n : `${pathname}/${providerId}`;\n\n return { domain, path, secure, sameSite };\n};\n","/*\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","/*\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 { prepareBackstageIdentityResponse as _prepareBackstageIdentityResponse } from '@backstage/plugin-auth-node';\n\n/**\n * @public\n * @deprecated import from `@backstage/plugin-auth-node` instead\n */\nexport const prepareBackstageIdentityResponse =\n _prepareBackstageIdentityResponse;\n","/*\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, { CookieOptions } from 'express';\nimport crypto from 'crypto';\nimport { URL } from 'url';\nimport {\n AuthProviderConfig,\n AuthProviderRouteHandlers,\n BackstageIdentityResponse,\n BackstageSignInResult,\n CookieConfigurer,\n OAuthState,\n} from '@backstage/plugin-auth-node';\nimport {\n AuthenticationError,\n InputError,\n isError,\n NotAllowedError,\n} from '@backstage/errors';\nimport { defaultCookieConfigurer, readState, verifyNonce } from './helpers';\nimport {\n postMessageResponse,\n ensuresXRequestedWith,\n WebMessageResponse,\n} from '../flow';\nimport {\n OAuthHandlers,\n OAuthStartRequest,\n OAuthRefreshRequest,\n OAuthLogoutRequest,\n} from './types';\nimport { prepareBackstageIdentityResponse } from '../../providers/prepareBackstageIdentityResponse';\n\nexport const THOUSAND_DAYS_MS = 1000 * 24 * 60 * 60 * 1000;\nexport const TEN_MINUTES_MS = 600 * 1000;\n\n/**\n * @public\n * @deprecated Use `createOAuthRouteHandlers` from `@backstage/plugin-auth-node` instead\n */\nexport type OAuthAdapterOptions = {\n providerId: string;\n persistScopes?: boolean;\n appOrigin: string;\n baseUrl: string;\n cookieConfigurer: CookieConfigurer;\n isOriginAllowed: (origin: string) => boolean;\n callbackUrl: string;\n};\n\n/**\n * @public\n * @deprecated Use `createOAuthRouteHandlers` from `@backstage/plugin-auth-node` instead\n */\nexport class OAuthAdapter implements AuthProviderRouteHandlers {\n static fromConfig(\n config: AuthProviderConfig,\n handlers: OAuthHandlers,\n options: Pick<\n OAuthAdapterOptions,\n 'providerId' | 'persistScopes' | 'callbackUrl'\n >,\n ): OAuthAdapter {\n const { appUrl, baseUrl, isOriginAllowed } = config;\n const { origin: appOrigin } = new URL(appUrl);\n\n const cookieConfigurer = config.cookieConfigurer ?? defaultCookieConfigurer;\n\n return new OAuthAdapter(handlers, {\n ...options,\n appOrigin,\n baseUrl,\n cookieConfigurer,\n isOriginAllowed,\n });\n }\n\n private readonly baseCookieOptions: CookieOptions;\n\n constructor(\n private readonly handlers: OAuthHandlers,\n private readonly options: OAuthAdapterOptions,\n ) {\n this.baseCookieOptions = {\n httpOnly: true,\n sameSite: 'lax',\n };\n }\n\n async start(req: express.Request, res: express.Response): Promise<void> {\n // retrieve scopes from request\n const scope = req.query.scope?.toString() ?? '';\n const env = req.query.env?.toString();\n const origin = req.query.origin?.toString();\n const redirectUrl = req.query.redirectUrl?.toString();\n const flow = req.query.flow?.toString();\n\n if (!env) {\n throw new InputError('No env provided in request query parameters');\n }\n\n const cookieConfig = this.getCookieConfig(origin);\n\n const nonce = crypto.randomBytes(16).toString('base64');\n // set a nonce cookie before redirecting to oauth provider\n this.setNonceCookie(res, nonce, cookieConfig);\n\n const state: OAuthState = { nonce, env, origin, redirectUrl, flow };\n\n // If scopes are persisted then we pass them through the state so that we\n // can set the cookie on successful auth\n if (this.options.persistScopes) {\n state.scope = scope;\n }\n const forwardReq = Object.assign(req, { scope, state });\n\n const { url, status } = await this.handlers.start(\n forwardReq as OAuthStartRequest,\n );\n\n res.statusCode = status || 302;\n res.setHeader('Location', url);\n res.setHeader('Content-Length', '0');\n res.end();\n }\n\n async frameHandler(\n req: express.Request,\n res: express.Response,\n ): Promise<void> {\n let appOrigin = this.options.appOrigin;\n\n try {\n const state: OAuthState = readState(req.query.state?.toString() ?? '');\n\n if (state.origin) {\n try {\n appOrigin = new URL(state.origin).origin;\n } catch {\n throw new NotAllowedError('App origin is invalid, failed to parse');\n }\n if (!this.options.isOriginAllowed(appOrigin)) {\n throw new NotAllowedError(`Origin '${appOrigin}' is not allowed`);\n }\n }\n\n // verify nonce cookie and state cookie on callback\n verifyNonce(req, this.options.providerId);\n\n const { response, refreshToken } = await this.handlers.handler(req);\n\n const cookieConfig = this.getCookieConfig(appOrigin);\n\n // Store the scope that we have been granted for this session. This is useful if\n // the provider does not return granted scopes on refresh or if they are normalized.\n if (this.options.persistScopes && state.scope) {\n this.setGrantedScopeCookie(res, state.scope, cookieConfig);\n response.providerInfo.scope = state.scope;\n }\n\n if (refreshToken) {\n // set new refresh token\n this.setRefreshTokenCookie(res, refreshToken, cookieConfig);\n }\n\n const identity = await this.populateIdentity(response.backstageIdentity);\n\n const responseObj: WebMessageResponse = {\n type: 'authorization_response',\n response: { ...response, backstageIdentity: identity },\n };\n\n if (state.flow === 'redirect') {\n if (!state.redirectUrl) {\n throw new InputError(\n 'No redirectUrl provided in request query parameters',\n );\n }\n res.redirect(state.redirectUrl);\n return undefined;\n }\n // post message back to popup if successful\n return postMessageResponse(res, appOrigin, responseObj);\n } catch (error) {\n const { name, message } = isError(error)\n ? error\n : new Error('Encountered invalid error'); // Being a bit safe and not forwarding the bad value\n // post error message back to popup if failure\n return postMessageResponse(res, appOrigin, {\n type: 'authorization_response',\n error: { name, message },\n });\n }\n }\n\n async logout(req: express.Request, res: express.Response): Promise<void> {\n if (!ensuresXRequestedWith(req)) {\n throw new AuthenticationError('Invalid X-Requested-With header');\n }\n\n if (this.handlers.logout) {\n const refreshToken = this.getRefreshTokenFromCookie(req);\n const revokeRequest: OAuthLogoutRequest = Object.assign(req, {\n refreshToken,\n });\n await this.handlers.logout(revokeRequest);\n }\n\n // remove refresh token cookie if it is set\n const origin = req.get('origin');\n const cookieConfig = this.getCookieConfig(origin);\n this.removeRefreshTokenCookie(res, cookieConfig);\n\n res.status(200).end();\n }\n\n async refresh(req: express.Request, res: express.Response): Promise<void> {\n if (!ensuresXRequestedWith(req)) {\n throw new AuthenticationError('Invalid X-Requested-With header');\n }\n\n if (!this.handlers.refresh) {\n throw new InputError(\n `Refresh token is not supported for provider ${this.options.providerId}`,\n );\n }\n\n try {\n const refreshToken = this.getRefreshTokenFromCookie(req);\n\n // throw error if refresh token is missing in the request\n if (!refreshToken) {\n throw new InputError('Missing session cookie');\n }\n\n let scope = req.query.scope?.toString() ?? '';\n if (this.options.persistScopes) {\n scope = this.getGrantedScopeFromCookie(req);\n }\n const forwardReq = Object.assign(req, { scope, refreshToken });\n\n // get new access_token\n const { response, refreshToken: newRefreshToken } =\n await this.handlers.refresh(forwardReq as OAuthRefreshRequest);\n\n const backstageIdentity = await this.populateIdentity(\n response.backstageIdentity,\n );\n\n if (newRefreshToken && newRefreshToken !== refreshToken) {\n const origin = req.get('origin');\n const cookieConfig = this.getCookieConfig(origin);\n this.setRefreshTokenCookie(res, newRefreshToken, cookieConfig);\n }\n\n res.status(200).json({ ...response, backstageIdentity });\n } catch (error) {\n throw new AuthenticationError('Refresh failed', error);\n }\n }\n\n /**\n * If the response from the OAuth provider includes a Backstage identity, we\n * make sure it's populated with all the information we can derive from the user ID.\n */\n private async populateIdentity(\n identity?: BackstageSignInResult,\n ): Promise<BackstageIdentityResponse | undefined> {\n if (!identity) {\n return undefined;\n }\n if (!identity.token) {\n throw new InputError(`Identity response must return a token`);\n }\n\n return prepareBackstageIdentityResponse(identity);\n }\n\n private setNonceCookie = (\n res: express.Response,\n nonce: string,\n cookieConfig: ReturnType<CookieConfigurer>,\n ) => {\n res.cookie(`${this.options.providerId}-nonce`, nonce, {\n maxAge: TEN_MINUTES_MS,\n ...this.baseCookieOptions,\n ...cookieConfig,\n path: `${cookieConfig.path}/handler`,\n });\n };\n\n private setGrantedScopeCookie = (\n res: express.Response,\n scope: string,\n cookieConfig: ReturnType<CookieConfigurer>,\n ) => {\n res.cookie(`${this.options.providerId}-granted-scope`, scope, {\n maxAge: THOUSAND_DAYS_MS,\n ...this.baseCookieOptions,\n ...cookieConfig,\n });\n };\n\n private getRefreshTokenFromCookie = (req: express.Request) => {\n return req.cookies[`${this.options.providerId}-refresh-token`];\n };\n\n private getGrantedScopeFromCookie = (req: express.Request) => {\n return req.cookies[`${this.options.providerId}-granted-scope`];\n };\n\n private setRefreshTokenCookie = (\n res: express.Response,\n refreshToken: string,\n cookieConfig: ReturnType<CookieConfigurer>,\n ) => {\n res.cookie(`${this.options.providerId}-refresh-token`, refreshToken, {\n maxAge: THOUSAND_DAYS_MS,\n ...this.baseCookieOptions,\n ...cookieConfig,\n });\n };\n\n private removeRefreshTokenCookie = (\n res: express.Response,\n cookieConfig: ReturnType<CookieConfigurer>,\n ) => {\n res.cookie(`${this.options.providerId}-refresh-token`, '', {\n maxAge: 0,\n ...this.baseCookieOptions,\n ...cookieConfig,\n });\n };\n\n private getCookieConfig = (origin?: string) => {\n return this.options.cookieConfigurer({\n providerId: this.options.providerId,\n baseUrl: this.options.baseUrl,\n callbackUrl: this.options.callbackUrl,\n appOrigin: origin ?? this.options.appOrigin,\n });\n };\n}\n","/*\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 passport from 'passport';\nimport { decodeJwt } from 'jose';\nimport { InternalOAuthError } from 'passport-oauth2';\nimport { ProfileInfo } from '@backstage/plugin-auth-node';\nimport { PassportProfile } from './types';\nimport { OAuthStartResponse } from '../../providers/types';\n\nexport type PassportDoneCallback<Res, Private = never> = (\n err?: Error,\n response?: Res,\n privateInfo?: Private,\n) => void;\n\nexport const makeProfileInfo = (\n profile: PassportProfile,\n idToken?: string,\n): ProfileInfo => {\n let email: string | undefined = undefined;\n if (profile.emails && profile.emails.length > 0) {\n const [firstEmail] = profile.emails;\n email = firstEmail.value;\n }\n\n let picture: string | undefined = undefined;\n if (profile.avatarUrl) {\n picture = profile.avatarUrl;\n } else if (profile.photos && profile.photos.length > 0) {\n const [firstPhoto] = profile.photos;\n picture = firstPhoto.value;\n }\n\n let displayName: string | undefined =\n profile.displayName ?? profile.username ?? profile.id;\n\n if ((!email || !picture || !displayName) && idToken) {\n try {\n const decoded = decodeJwt(idToken) as {\n email?: string;\n name?: string;\n picture?: string;\n };\n if (!email && decoded.email) {\n email = decoded.email;\n }\n if (!picture && decoded.picture) {\n picture = decoded.picture;\n }\n if (!displayName && decoded.name) {\n displayName = decoded.name;\n }\n } catch (e) {\n throw new Error(`Failed to parse id token and get profile info, ${e}`);\n }\n }\n\n return {\n email,\n picture,\n displayName,\n };\n};\n\nexport const executeRedirectStrategy = async (\n req: express.Request,\n providerStrategy: passport.Strategy,\n options: Record<string, string>,\n): Promise<OAuthStartResponse> => {\n return new Promise(resolve => {\n const strategy = Object.create(providerStrategy);\n strategy.redirect = (url: string, status?: number) => {\n resolve({ url, status: status ?? undefined });\n };\n\n strategy.authenticate(req, { ...options });\n });\n};\n\nexport const executeFrameHandlerStrategy = async <Result, PrivateInfo = never>(\n req: express.Request,\n providerStrategy: passport.Strategy,\n options?: Record<string, string>,\n) => {\n return new Promise<{ result: Result; privateInfo: PrivateInfo }>(\n (resolve, reject) => {\n const strategy = Object.create(providerStrategy);\n strategy.success = (result: any, privateInfo: any) => {\n resolve({ result, privateInfo });\n };\n strategy.fail = (\n info: { type: 'success' | 'error'; message?: string },\n // _status: number,\n ) => {\n reject(new Error(`Authentication rejected, ${info.message ?? ''}`));\n };\n strategy.error = (error: InternalOAuthError) => {\n let message = `Authentication failed, ${error.message}`;\n\n if (error.oauthError?.data) {\n try {\n const errorData = JSON.parse(error.oauthError.data);\n\n if (errorData.message) {\n message += ` - ${errorData.message}`;\n }\n } catch (parseError) {\n message += ` - ${error.oauthError}`;\n }\n }\n\n reject(new Error(message));\n };\n strategy.redirect = () => {\n reject(new Error('Unexpected redirect'));\n };\n strategy.authenticate(req, { ...(options ?? {}) });\n },\n );\n};\n\ntype RefreshTokenResponse = {\n /**\n * An access token issued for the signed in user.\n */\n accessToken: string;\n /**\n * Optionally, the server can issue a new Refresh Token for the user\n */\n refreshToken?: string;\n params: any;\n};\n\nexport const executeRefreshTokenStrategy = async (\n providerStrategy: passport.Strategy,\n refreshToken: string,\n scope: string,\n): Promise<RefreshTokenResponse> => {\n return new Promise((resolve, reject) => {\n const anyStrategy = providerStrategy as any;\n const OAuth2 = anyStrategy._oauth2.constructor;\n const oauth2 = new OAuth2(\n anyStrategy._oauth2._clientId,\n anyStrategy._oauth2._clientSecret,\n anyStrategy._oauth2._baseSite,\n anyStrategy._oauth2._authorizeUrl,\n anyStrategy._refreshURL || anyStrategy._oauth2._accessTokenUrl,\n anyStrategy._oauth2._customHeaders,\n );\n\n oauth2.getOAuthAccessToken(\n refreshToken,\n {\n scope,\n grant_type: 'refresh_token',\n },\n (\n err: Error | null,\n accessToken: string,\n newRefreshToken: string,\n params: any,\n ) => {\n if (err) {\n reject(new Error(`Failed to refresh access token ${err.toString()}`));\n }\n if (!accessToken) {\n reject(\n new Error(\n `Failed to refresh access token, no access token received`,\n ),\n );\n }\n\n resolve({\n accessToken,\n refreshToken: newRefreshToken,\n params,\n });\n },\n );\n });\n};\n\ntype ProviderStrategy = {\n userProfile(accessToken: string, callback: Function): void;\n};\n\nexport const executeFetchUserProfileStrategy = async (\n providerStrategy: passport.Strategy,\n accessToken: string,\n): Promise<PassportProfile> => {\n return new Promise((resolve, reject) => {\n const anyStrategy = providerStrategy as unknown as ProviderStrategy;\n anyStrategy.userProfile(\n accessToken,\n (error: Error, rawProfile: PassportProfile) => {\n if (error) {\n reject(error);\n } else {\n resolve(rawProfile);\n }\n },\n );\n });\n};\n","/*\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 passport from 'passport';\nimport Auth0Strategy from './strategy';\nimport {\n OAuthAdapter,\n OAuthProviderOptions,\n OAuthHandlers,\n OAuthResponse,\n OAuthEnvironmentHandler,\n OAuthStartRequest,\n encodeState,\n OAuthRefreshRequest,\n OAuthResult,\n} from '../../lib/oauth';\nimport {\n executeFetchUserProfileStrategy,\n executeFrameHandlerStrategy,\n executeRedirectStrategy,\n executeRefreshTokenStrategy,\n makeProfileInfo,\n PassportDoneCallback,\n} from '../../lib/passport';\nimport { OAuthStartResponse, AuthHandler } from '../types';\nimport { createAuthProviderIntegration } from '../createAuthProviderIntegration';\nimport { StateStore } from 'passport-oauth2';\nimport {\n AuthResolverContext,\n SignInResolver,\n} from '@backstage/plugin-auth-node';\n\ntype PrivateInfo = {\n refreshToken: string;\n};\n\nexport type Auth0AuthProviderOptions = OAuthProviderOptions & {\n domain: string;\n signInResolver?: SignInResolver<OAuthResult>;\n authHandler: AuthHandler<OAuthResult>;\n resolverContext: AuthResolverContext;\n audience?: string;\n connection?: string;\n connectionScope?: string;\n};\n\nexport class Auth0AuthProvider implements OAuthHandlers {\n private readonly _strategy: Auth0Strategy;\n private readonly signInResolver?: SignInResolver<OAuthResult>;\n private readonly authHandler: AuthHandler<OAuthResult>;\n private readonly resolverContext: AuthResolverContext;\n private readonly audience?: string;\n private readonly connection?: string;\n private readonly connectionScope?: string;\n\n /**\n * Due to passport-auth0 forcing options.state = true,\n * passport-oauth2 requires express-session to be installed\n * so that the 'state' parameter of the oauth2 flow can be stored.\n * This implementation of StateStore matches the NullStore found within\n * passport-oauth2, which is the StateStore implementation used when options.state = false,\n * allowing us to avoid using express-session in order to integrate with auth0.\n */\n private store: StateStore = {\n store(_req: express.Request, cb: any) {\n cb(null, null);\n },\n verify(_req: express.Request, _state: string, cb: any) {\n cb(null, true);\n },\n };\n\n constructor(options: Auth0AuthProviderOptions) {\n this.signInResolver = options.signInResolver;\n this.authHandler = options.authHandler;\n this.resolverContext = options.resolverContext;\n this.audience = options.audience;\n this.connection = options.connection;\n this.connectionScope = options.connectionScope;\n this._strategy = new Auth0Strategy(\n {\n clientID: options.clientId,\n clientSecret: options.clientSecret,\n callbackURL: options.callbackUrl,\n domain: options.domain,\n // We need passReqToCallback set to false to get params, but there's\n // no matching type signature for that, so instead behold this beauty\n passReqToCallback: false as true,\n store: this.store,\n },\n (\n accessToken: any,\n refreshToken: any,\n params: any,\n fullProfile: passport.Profile,\n done: PassportDoneCallback<OAuthResult, PrivateInfo>,\n ) => {\n done(\n undefined,\n {\n fullProfile,\n accessToken,\n refreshToken,\n params,\n },\n {\n refreshToken,\n },\n );\n },\n );\n }\n\n async start(req: OAuthStartRequest): Promise<OAuthStartResponse> {\n return await executeRedirectStrategy(req, this._strategy, {\n accessType: 'offline',\n prompt: 'consent',\n scope: req.scope,\n state: encodeState(req.state),\n ...(this.audience ? { audience: this.audience } : {}),\n ...(this.connection ? { connection: this.connection } : {}),\n ...(this.connectionScope\n ? { connection_scope: this.connectionScope }\n : {}),\n });\n }\n\n async handler(req: express.Request) {\n const { result, privateInfo } = await executeFrameHandlerStrategy<\n OAuthResult,\n PrivateInfo\n >(req, this._strategy, {\n ...(this.audience ? { audience: this.audience } : {}),\n ...(this.connection ? { connection: this.connection } : {}),\n ...(this.connectionScope\n ? { connection_scope: this.connectionScope }\n : {}),\n });\n\n return {\n response: await this.handleResult(result),\n refreshToken: privateInfo.refreshToken,\n };\n }\n\n async refresh(req: OAuthRefreshRequest) {\n const { accessToken, refreshToken, params } =\n await executeRefreshTokenStrategy(\n this._strategy,\n req.refreshToken,\n req.scope,\n );\n\n const fullProfile = await executeFetchUserProfileStrategy(\n this._strategy,\n accessToken,\n );\n\n return {\n response: await this.handleResult({\n fullProfile,\n params,\n accessToken,\n }),\n refreshToken,\n };\n }\n\n private async handleResult(result: OAuthResult) {\n const { profile } = await this.authHandler(result, this.resolverContext);\n\n const response: OAuthResponse = {\n providerInfo: {\n idToken: result.params.id_token,\n accessToken: result.accessToken,\n scope: result.params.scope,\n expiresInSeconds: result.params.expires_in,\n },\n profile,\n };\n\n if (this.signInResolver) {\n response.backstageIdentity = await this.signInResolver(\n {\n result,\n profile,\n },\n this.resolverContext,\n );\n }\n\n return response;\n }\n}\n\n/**\n * Auth provider integration for auth0 auth\n *\n * @public\n */\nexport const auth0 = createAuthProviderIntegration({\n create(options?: {\n /**\n * The profile transformation function used to verify and convert the auth response\n * into the profile that will be presented to the user.\n */\n authHandler?: AuthHandler<OAuthResult>;\n\n /**\n * Configure sign-in for this provider, without it the provider can not be used to sign users in.\n */\n signIn?: {\n /**\n * Maps an auth result to a Backstage identity for the user.\n */\n resolver: SignInResolver<OAuthResult>;\n };\n }) {\n return ({ providerId, globalConfig, config, resolverContext }) =>\n OAuthEnvironmentHandler.mapConfig(config, envConfig => {\n const clientId = envConfig.getString('clientId');\n const clientSecret = envConfig.getString('clientSecret');\n const domain = envConfig.getString('domain');\n const customCallbackUrl = envConfig.getOptionalString('callbackUrl');\n const audience = envConfig.getOptionalString('audience');\n const connection = envConfig.getOptionalString('connection');\n const connectionScope = envConfig.getOptionalString('connectionScope');\n const callbackUrl =\n customCallbackUrl ||\n `${globalConfig.baseUrl}/${providerId}/handler/frame`;\n\n const authHandler: AuthHandler<OAuthResult> = options?.authHandler\n ? options.authHandler\n : async ({ fullProfile, params }) => ({\n profile: makeProfileInfo(fullProfile, params.id_token),\n });\n\n const signInResolver = options?.signIn?.resolver;\n\n const provider = new Auth0AuthProvider({\n clientId,\n clientSecret,\n callbackUrl,\n domain,\n authHandler,\n signInResolver,\n resolverContext,\n audience,\n connection,\n connectionScope,\n });\n\n return OAuthAdapter.fromConfig(globalConfig, provider, {\n providerId,\n callbackUrl,\n });\n });\n },\n});\n","/*\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 {\n AwsAlbResult,\n awsAlbAuthenticator,\n} from '@backstage/plugin-auth-backend-module-aws-alb-provider';\nimport {\n SignInResolver,\n createProxyAuthProviderFactory,\n} from '@backstage/plugin-auth-node';\nimport { AuthHandler } from '../types';\nimport { createAuthProviderIntegration } from '../createAuthProviderIntegration';\n\n/**\n * Auth provider integration for AWS ALB auth\n *\n * @public\n */\nexport const awsAlb = createAuthProviderIntegration({\n create(options?: {\n /**\n * The profile transformation function used to verify and convert the auth\n * response into the profile that will be presented to the user. The default\n * implementation just provides the authenticated email that the IAP\n * presented.\n */\n authHandler?: AuthHandler<AwsAlbResult>;\n /**\n * Configures sign-in for this provider.\n */\n signIn: {\n /**\n * Maps an auth result to a Backstage identity for the user.\n */\n resolver: SignInResolver<AwsAlbResult>;\n };\n }) {\n return createProxyAuthProviderFactory({\n authenticator: awsAlbAuthenticator,\n profileTransform: options?.authHandler,\n signInResolver: options?.signIn?.resolver,\n });\n },\n});\n","/*\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 bitbucketAuthenticator,\n bitbucketSignInResolvers,\n} from '@backstage/plugin-auth-backend-module-bitbucket-provider';\nimport {\n SignInResolver,\n createOAuthProviderFactory,\n} from '@backstage/plugin-auth-node';\nimport { Profile as PassportProfile } from 'passport';\nimport {\n adaptLegacyOAuthHandler,\n adaptLegacyOAuthSignInResolver,\n adaptOAuthSignInResolverToLegacy,\n} from '../../lib/legacy';\nimport { OAuthResult } from '../../lib/oauth';\nimport { createAuthProviderIntegration } from '../createAuthProviderIntegration';\nimport { AuthHandler } from '../types';\n\n/**\n * @public\n * @deprecated The Bitbucket auth provider was extracted to `@backstage/plugin-auth-backend-module-bitbucket-provider`.\n */\nexport type BitbucketOAuthResult = {\n fullProfile: BitbucketPassportProfile;\n params: {\n id_token?: string;\n scope: string;\n expires_in: number;\n };\n accessToken: string;\n refreshToken?: string;\n};\n\n/**\n * @public\n * @deprecated The Bitbucket auth provider was extracted to `@backstage/plugin-auth-backend-module-bitbucket-provider`.\n */\nexport type BitbucketPassportProfile = PassportProfile & {\n id?: string;\n displayName?: string;\n username?: string;\n avatarUrl?: string;\n _json?: {\n links?: {\n avatar?: {\n href?: string;\n };\n };\n };\n};\n\n/**\n * Auth provider integration for Bitbucket auth\n *\n * @public\n */\nexport const bitbucket = createAuthProviderIntegration({\n create(options?: {\n /**\n * The profile transformation function used to verify and convert the auth response\n * into the profile that will be presented to the user.\n */\n authHandler?: AuthHandler<OAuthResult>;\n\n /**\n * Configure sign-in for this provider, without it the provider can not be used to sign users in.\n */\n signIn?: {\n resolver: SignInResolver<OAuthResult>;\n };\n }) {\n return createOAuthProviderFactory({\n authenticator: bitbucketAuthenticator,\n profileTransform: adaptLegacyOAuthHandler(options?.authHandler),\n signInResolver: adaptLegacyOAuthSignInResolver(options?.signIn?.resolver),\n });\n },\n resolvers: adaptOAuthSignInResolverToLegacy({\n userIdMatchingUserEntityAnnotation:\n bitbucketSignInResolvers.userIdMatchingUserEntityAnnotation(),\n usernameMatchingUserEntityAnnotation:\n bitbucketSignInResolvers.usernameMatchingUserEntityAnnotation(),\n }),\n});\n","/*\n * Copyright 2022 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 { CacheClient } from '@backstage/backend-common';\nimport {\n cloudflareAccessSignInResolvers,\n createCloudflareAccessAuthenticator,\n} from '@backstage/plugin-auth-backend-module-cloudflare-access-provider';\nimport {\n SignInResolver,\n createProxyAuthProviderFactory,\n} from '@backstage/plugin-auth-node';\nimport { createAuthProviderIntegration } from '../createAuthProviderIntegration';\nimport { AuthHandler } from '../types';\n\n/**\n * CloudflareAccessClaims\n *\n * Can be used in externally provided auth handler or sign in resolver to\n * enrich user profile for sign-in user entity\n *\n * @public\n * @deprecated import from `@backstage/plugin-auth-backend-module-cloudflare-access-provider` instead\n */\nexport type CloudflareAccessClaims = {\n /**\n * `aud` identifies the application to which the JWT is issued.\n */\n aud: string[];\n /**\n * `email` contains the email address of the authenticated user.\n */\n email: string;\n /**\n * iat and exp are the issuance and expiration timestamps.\n */\n exp: number;\n iat: number;\n /**\n * `nonce` is the session identifier.\n */\n nonce: string;\n /**\n * `identity_nonce` is available in the Application Token and can be used to\n * query all group membership for a given user.\n */\n identity_nonce: string;\n /**\n * `sub` contains the identifier of the authenticated user.\n */\n sub: string;\n /**\n * `iss` the issuer is the application’s Cloudflare Access Domain URL.\n */\n iss: string;\n /**\n * `custom` contains SAML attributes in the Application Token specified by an\n * administrator in the identity provider configuration.\n */\n custom: string;\n};\n\n/**\n * CloudflareAccessGroup\n *\n * @public\n * @deprecated import from `@backstage/plugin-auth-backend-module-cloudflare-access-provider` instead\n */\nexport type CloudflareAccessGroup = {\n /**\n * Group id\n */\n id: string;\n /**\n * Name of group as defined in Cloudflare zero trust dashboard\n */\n name: string;\n /**\n * Access group email address\n */\n email: string;\n};\n\n/**\n * CloudflareAccessIdentityProfile\n *\n * Can be used in externally provided auth handler or sign in resolver to\n * enrich user profile for sign-in user entity\n *\n * @public\n * @deprecated import from `@backstage/plugin-auth-backend-module-cloudflare-access-provider` instead\n */\nexport type CloudflareAccessIdentityProfile = {\n id: string;\n name: string;\n email: string;\n groups: CloudflareAccessGroup[];\n};\n\n/**\n * @public\n * @deprecated import from `@backstage/plugin-auth-backend-module-cloudflare-access-provider` instead\n */\nexport type CloudflareAccessResult = {\n claims: CloudflareAccessClaims;\n cfIdentity: CloudflareAccessIdentityProfile;\n expiresInSeconds?: number;\n token: string;\n};\n\n/**\n * Auth provider integration for Cloudflare Access auth\n *\n * @public\n */\nexport const cfAccess = createAuthProviderIntegration({\n create(options: {\n /**\n * The profile transformation function used to verify and convert the auth response\n * into the profile that will be presented to the user.\n */\n authHandler?: AuthHandler<CloudflareAccessResult>;\n\n /**\n * Configure sign-in for this provider, without it the provider can not be used to sign users in.\n */\n signIn: {\n /**\n * Maps an auth result to a Backstage identity for the user.\n */\n resolver: SignInResolver<CloudflareAccessResult>;\n };\n\n /**\n * CacheClient object that was configured for the Backstage backend,\n * should be provided via the backend auth plugin.\n */\n cache?: CacheClient;\n }) {\n return createProxyAuthProviderFactory({\n authenticator: createCloudflareAccessAuthenticator({\n cache: options.cache,\n }),\n profileTransform: options?.authHandler,\n signInResolver: options?.signIn?.resolver,\n signInResolverFactories: cloudflareAccessSignInResolvers,\n });\n },\n resolvers: cloudflareAccessSignInResolvers,\n});\n","/*\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 { gcpIapAuthenticator } from '@backstage/plugin-auth-backend-module-gcp-iap-provider';\nimport {\n SignInResolver,\n createProxyAuthProviderFactory,\n} from '@backstage/plugin-auth-node';\nimport { createAuthProviderIntegration } from '../createAuthProviderIntegration';\nimport { AuthHandler } from '../types';\nimport { GcpIapResult } from './types';\n\n/**\n * Auth provider integration for Google Identity-Aware Proxy auth\n *\n * @public\n */\nexport const gcpIap = createAuthProviderIntegration({\n create(options: {\n /**\n * The profile transformation function used to verify and convert the auth\n * response into the profile that will be presented to the user. The default\n * implementation just provides the authenticated email that the IAP\n * presented.\n */\n authHandler?: AuthHandler<GcpIapResult>;\n\n /**\n * Configures sign-in for this provider.\n */\n signIn: {\n /**\n * Maps an auth result to a Backstage identity for the user.\n */\n resolver: SignInResolver<GcpIapResult>;\n };\n }) {\n return createProxyAuthProviderFactory({\n authenticator: gcpIapAuthenticator,\n profileTransform: options?.authHandler,\n signInResolver: options?.signIn?.resolver,\n });\n },\n});\n","/*\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 { Profile as PassportProfile } from 'passport';\nimport { AuthHandler, StateEncoder } from '../types';\nimport { createAuthProviderIntegration } from '../createAuthProviderIntegration';\nimport {\n createOAuthProviderFactory,\n OAuthAuthenticatorResult,\n ProfileTransform,\n SignInResolver,\n} from '@backstage/plugin-auth-node';\nimport { githubAuthenticator } from '@backstage/plugin-auth-backend-module-github-provider';\n\n/** @public */\nexport type GithubOAuthResult = {\n fullProfile: PassportProfile;\n params: {\n scope: string;\n expires_in?: string;\n refresh_token_expires_in?: string;\n };\n accessToken: string;\n refreshToken?: string;\n};\n\n/**\n * Auth provider integration for GitHub auth\n *\n * @public\n */\nexport const github = createAuthProviderIntegration({\n create(options?: {\n /**\n * The profile transformation function used to verify and convert the auth response\n * into the profile that will be presented to the user.\n */\n authHandler?: AuthHandler<GithubOAuthResult>;\n\n /**\n * Configure sign-in for this provider, without it the provider can not be used to sign users in.\n */\n signIn?: {\n /**\n * Maps an auth result to a Backstage identity for the user.\n */\n resolver: SignInResolver<GithubOAuthResult>;\n };\n\n /**\n * The state encoder used to encode the 'state' parameter on the OAuth request.\n *\n * It should return a string that takes the state params (from the request), url encodes the params\n * and finally base64 encodes them.\n *\n * Providing your own stateEncoder will allow you to add addition parameters to the state field.\n *\n * It is typed as follows:\n * `export type StateEncoder = (input: OAuthState) => Promise<{encodedState: string}>;`\n *\n * Note: the stateEncoder must encode a 'nonce' value and an 'env' value. Without this, the OAuth flow will fail\n * (These two values will be set by the req.state by default)\n *\n * For more information, please see the helper module in ../../oauth/helpers #readState\n */\n stateEncoder?: StateEncoder;\n }) {\n const authHandler = options?.authHandler;\n const signInResolver = options?.signIn?.resolver;\n return createOAuthProviderFactory({\n authenticator: githubAuthenticator,\n profileTransform:\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 expires_in: result.session.expiresInSeconds\n ? String(result.session.expiresInSeconds)\n : '',\n refresh_token_expires_in: result.session\n .refreshTokenExpiresInSeconds\n ? String(result.session.refreshTokenExpiresInSeconds)\n : '',\n },\n },\n ctx,\n )) as ProfileTransform<OAuthAuthenticatorResult<PassportProfile>>),\n signInResolver:\n signInResolver &&\n ((async ({ profile, result }, ctx) =>\n signInResolver(\n {\n profile: profile,\n result: {\n fullProfile: result.fullProfile,\n accessToken: result.session.accessToken,\n refreshToken: result.session.refreshToken,\n params: {\n scope: result.session.scope,\n expires_in: result.session.expiresInSeconds\n ? String(result.session.expiresInSeconds)\n : '',\n refresh_token_expires_in: result.session\n .refreshTokenExpiresInSeconds\n ? String(result.session.refreshTokenExpiresInSeconds)\n : '',\n },\n },\n },\n ctx,\n )) as SignInResolver<OAuthAuthenticatorResult<PassportProfile>>),\n });\n },\n resolvers: {\n /**\n * Looks up the user by matching their GitHub username to the entity name.\n */\n usernameMatchingUserEntityName: (): SignInResolver<GithubOAuthResult> => {\n return async (info, ctx) => {\n const { fullProfile } = info.result;\n\n const userId = fullProfile.username;\n if (!userId) {\n throw new Error(`GitHub user profile does not contain a username`);\n }\n\n return ctx.signInWithCatalogUser({ entityRef: { name: userId } });\n };\n },\n },\n});\n","/*\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 { AuthHandler } from '../types';\nimport { OAuthResult } from '../../lib/oauth';\nimport { createAuthProviderIntegration } from '../createAuthProviderIntegration';\nimport {\n SignInResolver,\n createOAuthProviderFactory,\n} from '@backstage/plugin-auth-node';\nimport {\n adaptLegacyOAuthHandler,\n adaptLegacyOAuthSignInResolver,\n} from '../../lib/legacy';\nimport { gitlabAuthenticator } from '@backstage/plugin-auth-backend-module-gitlab-provider';\n\n/**\n * Auth provider integration for GitLab auth\n *\n * @public\n */\nexport const gitlab = createAuthProviderIntegration({\n create(options?: {\n /**\n * The profile transformation function used to verify and convert the auth response\n * into the profile that will be presented to the user.\n */\n authHandler?: AuthHandler<OAuthResult>;\n\n /**\n * Configure sign-in for this provider, without it the provider can not be used to sign users in.\n */\n signIn?: {\n resolver: SignInResolver<OAuthResult>;\n };\n }) {\n return createOAuthProviderFactory({\n authenticator: gitlabAuthenticator,\n profileTransform: adaptLegacyOAuthHandler(options?.authHandler),\n signInResolver: adaptLegacyOAuthSignInResolver(options?.signIn?.resolver),\n });\n },\n});\n","/*\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 googleAuthenticator,\n googleSignInResolvers,\n} from '@backstage/plugin-auth-backend-module-google-provider';\nimport {\n SignInResolver,\n commonSignInResolvers,\n createOAuthProviderFactory,\n} from '@backstage/plugin-auth-node';\nimport {\n adaptLegacyOAuthHandler,\n adaptLegacyOAuthSignInResolver,\n adaptOAuthSignInResolverToLegacy,\n} from '../../lib/legacy';\nimport { OAuthResult } from '../../lib/oauth';\nimport { createAuthProviderIntegration } from '../createAuthProviderIntegration';\nimport { AuthHandler } from '../types';\n\n/**\n * Auth provider integration for Google auth\n *\n * @public\n */\nexport const google = createAuthProviderIntegration({\n create(options?: {\n /**\n * The profile transformation function used to verify and convert the auth response\n * into the profile that will be presented to the user.\n */\n authHandler?: AuthHandler<OAuthResult>;\n\n /**\n * Configure sign-in for this provider, without it the provider can not be used to sign users in.\n */\n signIn?: {\n /**\n * Maps an auth result to a Backstage identity for the user.\n */\n resolver: SignInResolver<OAuthResult>;\n };\n }) {\n return createOAuthProviderFactory({\n authenticator: googleAuthenticator,\n profileTransform: adaptLegacyOAuthHandler(options?.authHandler),\n signInResolver: adaptLegacyOAuthSignInResolver(options?.signIn?.resolver),\n });\n },\n resolvers: adaptOAuthSignInResolverToLegacy({\n emailLocalPartMatchingUserEntityName:\n commonSignInResolvers.emailLocalPartMatchingUserEntityName(),\n emailMatchingUserEntityProfileEmail:\n commonSignInResolvers.emailMatchingUserEntityProfileEmail(),\n emailMatchingUserEntityAnnotation:\n googleSignInResolvers.emailMatchingUserEntityAnnotation(),\n }),\n});\n","/*\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 { AuthHandler } from '../types';\nimport { OAuthResult } from '../../lib/oauth';\nimport { createAuthProviderIntegration } from '../createAuthProviderIntegration';\nimport {\n SignInResolver,\n commonSignInResolvers,\n createOAuthProviderFactory,\n} from '@backstage/plugin-auth-node';\nimport {\n adaptLegacyOAuthHandler,\n adaptLegacyOAuthSignInResolver,\n adaptOAuthSignInResolverToLegacy,\n} from '../../lib/legacy';\nimport {\n microsoftAuthenticator,\n microsoftSignInResolvers,\n} from '@backstage/plugin-auth-backend-module-microsoft-provider';\n\n/**\n * Auth provider integration for Microsoft auth\n *\n * @public\n */\nexport const microsoft = createAuthProviderIntegration({\n create(options?: {\n /**\n * The profile transformation function used to verify and convert the auth response\n * into the profile that will be presented to the user.\n */\n authHandler?: AuthHandler<OAuthResult>;\n\n /**\n * Configure sign-in for this provider, without it the provider can not be used to sign users in.\n */\n signIn?: {\n resolver: SignInResolver<OAuthResult>;\n };\n }) {\n return createOAuthProviderFactory({\n authenticator: microsoftAuthenticator,\n profileTransform: adaptLegacyOAuthHandler(options?.authHandler),\n signInResolver: adaptLegacyOAuthSignInResolver(options?.signIn?.resolver),\n });\n },\n resolvers: adaptOAuthSignInResolverToLegacy({\n emailLocalPartMatchingUserEntityName:\n commonSignInResolvers.emailLocalPartMatchingUserEntityName(),\n emailMatchingUserEntityProfileEmail:\n commonSignInResolvers.emailMatchingUserEntityProfileEmail(),\n emailMatchingUserEntityAnnotation:\n microsoftSignInResolvers.emailMatchingUserEntityAnnotation(),\n }),\n});\n","/*\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 { OAuthResult } from '../../lib/oauth';\nimport { AuthHandler } from '../types';\nimport { createAuthProviderIntegration } from '../createAuthProviderIntegration';\nimport {\n adaptLegacyOAuthHandler,\n adaptLegacyOAuthSignInResolver,\n} from '../../lib/legacy';\nimport {\n SignInResolver,\n createOAuthProviderFactory,\n} from '@backstage/plugin-auth-node';\nimport { oauth2Authenticator } from '@backstage/plugin-auth-backend-module-oauth2-provider';\n\n/**\n * Auth provider integration for generic OAuth2 auth\n *\n * @public\n */\nexport const oauth2 = createAuthProviderIntegration({\n create(options?: {\n authHandler?: AuthHandler<OAuthResult>;\n\n signIn?: {\n resolver: SignInResolver<OAuthResult>;\n };\n }) {\n return createOAuthProviderFactory({\n authenticator: oauth2Authenticator,\n profileTransform: adaptLegacyOAuthHandler(options?.authHandler),\n signInResolver: adaptLegacyOAuthSignInResolver(options?.signIn?.resolver),\n });\n },\n});\n","/*\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 {\n SignInResolver,\n createProxyAuthProviderFactory,\n} from '@backstage/plugin-auth-node';\nimport { AuthHandler } from '../types';\nimport { createAuthProviderIntegration } from '../createAuthProviderIntegration';\nimport {\n type OAuth2ProxyResult,\n oauth2ProxyAuthenticator,\n} from '@backstage/plugin-auth-backend-module-oauth2-proxy-provider';\n\n/**\n * Auth provider integration for oauth2-proxy auth\n *\n * @public\n */\nexport const oauth2Proxy = createAuthProviderIntegration({\n create(options: {\n /**\n * Configure an auth handler to generate a profile for the user.\n *\n * The default implementation uses the value of the `X-Forwarded-Preferred-Username`\n * header as the display name, falling back to `X-Forwarded-User`, and the value of\n * the `X-Forwarded-Email` header as the email address.\n */\n authHandler?: AuthHandler<OAuth2ProxyResult>;\n\n /**\n * Configure sign-in for this provider, without it the provider can not be used to sign users in.\n */\n signIn: {\n /**\n * Maps an auth result to a Backstage identity for the user.\n */\n resolver: SignInResolver<OAuth2ProxyResult>;\n };\n }) {\n return createProxyAuthProviderFactory({\n authenticator: oauth2ProxyAuthenticator,\n profileTransform: options?.authHandler,\n signInResolver: options?.signIn?.resolver,\n });\n },\n});\n","/*\n * Copyright 2022 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 { SignInResolver } from '@backstage/plugin-auth-node';\n\n/**\n * A common sign-in resolver that looks up the user using the local part of\n * their email address as the entity name.\n */\nexport const commonByEmailLocalPartResolver: SignInResolver<unknown> = async (\n info,\n ctx,\n) => {\n const { profile } = info;\n\n if (!profile.email) {\n throw new Error('Login failed, user profile does not contain an email');\n }\n const [localPart] = profile.email.split('@');\n\n return ctx.signInWithCatalogUser({\n entityRef: { name: localPart },\n });\n};\n\n/**\n * A common sign-in resolver that looks up the user using their email address\n * as email of the entity.\n */\nexport const commonByEmailResolver: SignInResolver<unknown> = async (\n info,\n ctx,\n) => {\n const { profile } = info;\n\n if (!profile.email) {\n throw new Error('Login failed, user profile does not contain an email');\n }\n\n return ctx.signInWithCatalogUser({\n filter: {\n 'spec.profile.email': profile.email,\n },\n });\n};\n","/*\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 { AuthHandler } from '../types';\nimport { createAuthProviderIntegration } from '../createAuthProviderIntegration';\nimport {\n createOAuthProviderFactory,\n AuthResolverContext,\n BackstageSignInResult,\n OAuthAuthenticatorResult,\n SignInInfo,\n SignInResolver,\n} from '@backstage/plugin-auth-node';\nimport {\n oidcAuthenticator,\n OidcAuthResult,\n} from '@backstage/plugin-auth-backend-module-oidc-provider';\nimport {\n commonByEmailLocalPartResolver,\n commonByEmailResolver,\n} from '../resolvers';\n\n/**\n * Auth provider integration for generic OpenID Connect auth\n *\n * @public\n */\nexport const oidc = createAuthProviderIntegration({\n create(options?: {\n /**\n * The profile transformation function used to verify and convert the auth response\n * into the profile that will be presented to the user.\n */\n authHandler?: AuthHandler<OidcAuthResult>;\n\n /**\n * Configure sign-in for this provider; convert user profile respones into\n * Backstage identities.\n */\n signIn?: {\n resolver: SignInResolver<OidcAuthResult>;\n };\n }) {\n const authHandler = options?.authHandler;\n const signInResolver = options?.signIn?.resolver;\n return createOAuthProviderFactory({\n authenticator: oidcAuthenticator,\n profileTransform:\n authHandler &&\n ((\n result: OAuthAuthenticatorResult<OidcAuthResult>,\n context: AuthResolverContext,\n ) => authHandler(result.fullProfile, context)),\n signInResolver:\n signInResolver &&\n ((\n info: SignInInfo<OAuthAuthenticatorResult<OidcAuthResult>>,\n context: AuthResolverContext,\n ): Promise<BackstageSignInResult> =>\n signInResolver(\n {\n result: info.result.fullProfile,\n profile: info.profile,\n },\n context,\n )),\n });\n },\n resolvers: {\n /**\n * Looks up the user by matching their email local part to the entity name.\n */\n emailLocalPartMatchingUserEntityName: () => commonByEmailLocalPartResolver,\n /**\n * Looks up the user by matching their email to the entity email.\n */\n emailMatchingUserEntityProfileEmail: () => commonByEmailResolver,\n },\n});\n","/*\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 { AuthHandler } from '../types';\nimport { OAuthResult } from '../../lib/oauth';\n\nimport { createAuthProviderIntegration } from '../createAuthProviderIntegration';\nimport {\n SignInResolver,\n createOAuthProviderFactory,\n} from '@backstage/plugin-auth-node';\nimport {\n adaptLegacyOAuthHandler,\n adaptLegacyOAuthSignInResolver,\n} from '../../lib/legacy';\nimport { oktaAuthenticator } from '@backstage/plugin-auth-backend-module-okta-provider';\nimport {\n commonByEmailLocalPartResolver,\n commonByEmailResolver,\n} from '../resolvers';\n\n/**\n * Auth provider integration for Okta auth\n *\n * @public\n */\nexport const okta = createAuthProviderIntegration({\n create(options?: {\n /**\n * The profile transformation function used to verify and convert the auth response\n * into the profile that will be presented to the user.\n */\n authHandler?: AuthHandler<OAuthResult>;\n /**\n * Configure sign-in for this provider, without it the provider can not be used to sign users in.\n */\n signIn?: {\n resolver: SignInResolver<OAuthResult>;\n };\n }) {\n return createOAuthProviderFactory({\n authenticator: oktaAuthenticator,\n profileTransform: adaptLegacyOAuthHandler(options?.authHandler),\n signInResolver: adaptLegacyOAuthSignInResolver(options?.signIn?.resolver),\n });\n },\n resolvers: {\n /**\n * Looks up the user by matching their email local part to the entity name.\n */\n emailLocalPartMatchingUserEntityName: () => commonByEmailLocalPartResolver,\n /**\n * Looks up the user by matching their email to the entity email.\n */\n emailMatchingUserEntityProfileEmail: () => commonByEmailResolver,\n /**\n * Looks up the user by matching their email to the `okta.com/email` annotation.\n */\n emailMatchingUserEntityAnnotation(): SignInResolver<OAuthResult> {\n return async (info, ctx) => {\n const { profile } = info;\n\n if (!profile.email) {\n throw new Error('Okta profile contained no email');\n }\n\n return ctx.signInWithCatalogUser({\n annotations: {\n 'okta.com/email': profile.email,\n },\n });\n };\n },\n },\n});\n","/*\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 { oneLoginAuthenticator } from '@backstage/plugin-auth-backend-module-onelogin-provider';\nimport {\n SignInResolver,\n createOAuthProviderFactory,\n} from '@backstage/plugin-auth-node';\nimport {\n adaptLegacyOAuthHandler,\n adaptLegacyOAuthSignInResolver,\n} from '../../lib/legacy';\nimport { OAuthResult } from '../../lib/oauth';\nimport { createAuthProviderIntegration } from '../createAuthProviderIntegration';\nimport { AuthHandler } from '../types';\n\n/**\n * Auth provider integration for OneLogin auth\n *\n * @public\n */\nexport const onelogin = createAuthProviderIntegration({\n create(options?: {\n /**\n * The profile transformation function used to verify and convert the auth response\n * into the profile that will be presented to the user.\n */\n authHandler?: AuthHandler<OAuthResult>;\n\n /**\n * Configure sign-in for this provider, without it the provider can not be used to sign users in.\n */\n signIn?: {\n /**\n * Maps an auth result to a Backstage identity for the user.\n */\n resolver: SignInResolver<OAuthResult>;\n };\n }) {\n return createOAuthProviderFactory({\n authenticator: oneLoginAuthenticator,\n profileTransform: adaptLegacyOAuthHandler(options?.authHandler),\n signInResolver: adaptLegacyOAuthSignInResolver(options?.signIn?.resolver),\n });\n },\n});\n","/*\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 { SamlConfig, VerifiedCallback } from '@node-saml/passport-saml';\nimport {\n Strategy as SamlStrategy,\n Profile as SamlProfile,\n VerifyWithoutRequest,\n} from '@node-saml/passport-saml';\nimport {\n executeFrameHandlerStrategy,\n executeRedirectStrategy,\n} from '../../lib/passport';\nimport { AuthHandler } from '../types';\nimport { postMessageResponse } from '../../lib/flow';\nimport { createAuthProviderIntegration } from '../createAuthProviderIntegration';\nimport { AuthenticationError, isError } from '@backstage/errors';\nimport { prepareBackstageIdentityResponse } from '../prepareBackstageIdentityResponse';\nimport {\n AuthProviderRouteHandlers,\n AuthResolverContext,\n ClientAuthResponse,\n SignInResolver,\n} from '@backstage/plugin-auth-node';\n\n/** @public */\nexport type SamlAuthResult = {\n fullProfile: any;\n};\n\ntype Options = SamlConfig & {\n signInResolver?: SignInResolver<SamlAuthResult>;\n authHandler: AuthHandler<SamlAuthResult>;\n resolverContext: AuthResolverContext;\n appUrl: string;\n};\n\nexport class SamlAuthProvider implements AuthProviderRouteHandlers {\n private readonly strategy: SamlStrategy;\n private readonly signInResolver?: SignInResolver<SamlAuthResult>;\n private readonly authHandler: AuthHandler<SamlAuthResult>;\n private readonly resolverContext: AuthResolverContext;\n private readonly appUrl: string;\n\n constructor(options: Options) {\n this.appUrl = options.appUrl;\n this.signInResolver = options.signInResolver;\n this.authHandler = options.authHandler;\n this.resolverContext = options.resolverContext;\n\n const verifier: VerifyWithoutRequest = (\n profile: SamlProfile | null,\n done: VerifiedCallback,\n ) => {\n // TODO: There's plenty more validation and profile handling to do here,\n // this provider is currently only intended to validate the provider pattern\n // for non-oauth auth flows.\n // TODO: This flow doesn't issue an identity token that can be used to validate\n // the identity of the user in other backends, which we need in some form.\n done(null, { fullProfile: profile });\n };\n this.strategy = new SamlStrategy(options, verifier, verifier);\n }\n\n async start(req: express.Request, res: express.Response): Promise<void> {\n const { url } = await executeRedirectStrategy(req, this.strategy, {});\n res.redirect(url);\n }\n\n async frameHandler(\n req: express.Request,\n res: express.Response,\n ): Promise<void> {\n try {\n const { result } = await executeFrameHandlerStrategy<SamlAuthResult>(\n req,\n this.strategy,\n );\n\n const { profile } = await this.authHandler(result, this.resolverContext);\n\n const response: ClientAuthResponse<{}> = {\n profile,\n providerInfo: {},\n };\n\n if (this.signInResolver) {\n const signInResponse = await this.signInResolver(\n {\n result,\n profile,\n },\n this.resolverContext,\n );\n\n response.backstageIdentity =\n prepareBackstageIdentityResponse(signInResponse);\n }\n\n return postMessageResponse(res, this.appUrl, {\n type: 'authorization_response',\n response,\n });\n } catch (error) {\n const { name, message } = isError(error)\n ? error\n : new Error('Encountered invalid error'); // Being a bit safe and not forwarding the bad value\n return postMessageResponse(res, this.appUrl, {\n type: 'authorization_response',\n error: { name, message },\n });\n }\n }\n\n async logout(_req: express.Request, res: express.Response): Promise<void> {\n res.end();\n }\n}\n\ntype SignatureAlgorithm = 'sha1' | 'sha256' | 'sha512';\n\n/**\n * Auth provider integration for SAML auth\n *\n * @public\n */\nexport const saml = createAuthProviderIntegration({\n create(options?: {\n /**\n * The profile transformation function used to verify and convert the auth response\n * into the profile that will be presented to the user.\n */\n authHandler?: AuthHandler<SamlAuthResult>;\n\n /**\n * Configure sign-in for this provider, without it the provider can not be used to sign users in.\n */\n signIn?: {\n /**\n * Maps an auth result to a Backstage identity for the user.\n */\n resolver: SignInResolver<SamlAuthResult>;\n };\n }) {\n return ({ providerId, globalConfig, config, resolverContext }) => {\n const authHandler: AuthHandler<SamlAuthResult> = options?.authHandler\n ? options.authHandler\n : async ({ fullProfile }) => ({\n profile: {\n email: fullProfile.email,\n displayName: fullProfile.displayName,\n },\n });\n\n return new SamlAuthProvider({\n callbackUrl: `${globalConfig.baseUrl}/${providerId}/handler/frame`,\n entryPoint: config.getString('entryPoint'),\n logoutUrl: config.getOptionalString('logoutUrl'),\n audience: config.getString('audience'),\n issuer: config.getString('issuer'),\n cert: config.getString('cert'),\n privateKey: config.getOptionalString('privateKey'),\n authnContext: config.getOptionalStringArray('authnContext'),\n identifierFormat: config.getOptionalString('identifierFormat'),\n decryptionPvk: config.getOptionalString('decryptionPvk'),\n signatureAlgorithm: config.getOptionalString('signatureAlgorithm') as\n | SignatureAlgorithm\n | undefined,\n digestAlgorithm: config.getOptionalString('digestAlgorithm'),\n acceptedClockSkewMs: config.getOptionalNumber('acceptedClockSkewMs'),\n wantAuthnResponseSigned: config.getOptionalBoolean(\n 'wantAuthnResponseSigned',\n ),\n wantAssertionsSigned: config.getOptionalBoolean('wantAssertionsSigned'),\n appUrl: globalConfig.appUrl,\n authHandler,\n signInResolver: options?.signIn?.resolver,\n resolverContext,\n });\n };\n },\n resolvers: {\n /**\n * Looks up the user by matching their nameID to the entity name.\n */\n nameIdMatchingUserEntityName(): SignInResolver<SamlAuthResult> {\n return async (info, ctx) => {\n const id = info.result.fullProfile.nameID;\n\n if (!id) {\n throw new AuthenticationError('No nameID found in SAML response');\n }\n\n return ctx.signInWithCatalogUser({\n entityRef: { name: id },\n });\n };\n },\n },\n});\n","/*\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 encodeState,\n OAuthAdapter,\n OAuthEnvironmentHandler,\n OAuthHandlers,\n OAuthProviderOptions,\n OAuthRefreshRequest,\n OAuthResponse,\n OAuthStartRequest,\n} from '../../lib/oauth';\nimport { Strategy as OAuth2Strategy, VerifyCallback } from 'passport-oauth2';\nimport {\n executeFetchUserProfileStrategy,\n executeFrameHandlerStrategy,\n executeRedirectStrategy,\n executeRefreshTokenStrategy,\n makeProfileInfo,\n} from '../../lib/passport';\nimport { AuthHandler, OAuthStartResponse } from '../types';\nimport express from 'express';\nimport { createAuthProviderIntegration } from '../createAuthProviderIntegration';\nimport { Profile as PassportProfile } from 'passport';\nimport { commonByEmailResolver } from '../resolvers';\nimport fetch from 'node-fetch';\nimport {\n AuthResolverContext,\n SignInResolver,\n} from '@backstage/plugin-auth-node';\n\ntype PrivateInfo = {\n refreshToken: string;\n};\n\n/** @public */\nexport type BitbucketServerOAuthResult = {\n fullProfile: PassportProfile;\n params: {\n scope: string;\n access_token?: string;\n token_type?: string;\n expires_in?: number;\n };\n accessToken: string;\n refreshToken?: string;\n};\n\nexport type BitbucketServerAuthProviderOptions = OAuthProviderOptions & {\n host: string;\n authorizationUrl: string;\n tokenUrl: string;\n authHandler: AuthHandler<BitbucketServerOAuthResult>;\n signInResolver?: SignInResolver<BitbucketServerOAuthResult>;\n resolverContext: AuthResolverContext;\n};\n\nexport class BitbucketServerAuthProvider implements OAuthHandlers {\n private readonly signInResolver?: SignInResolver<BitbucketServerOAuthResult>;\n private readonly authHandler: AuthHandler<BitbucketServerOAuthResult>;\n private readonly resolverContext: AuthResolverContext;\n private readonly strategy: OAuth2Strategy;\n private readonly host: string;\n\n constructor(options: BitbucketServerAuthProviderOptions) {\n this.signInResolver = options.signInResolver;\n this.authHandler = options.authHandler;\n this.resolverContext = options.resolverContext;\n this.strategy = new OAuth2Strategy(\n {\n authorizationURL: options.authorizationUrl,\n tokenURL: options.tokenUrl,\n clientID: options.clientId,\n clientSecret: options.clientSecret,\n callbackURL: options.callbackUrl,\n },\n (\n accessToken: string,\n refreshToken: string,\n params: any,\n fullProfile: PassportProfile,\n done: VerifyCallback,\n ) => {\n done(undefined, { fullProfile, params, accessToken }, { refreshToken });\n },\n );\n this.host = options.host;\n }\n\n async start(req: OAuthStartRequest): Promise<OAuthStartResponse> {\n return await executeRedirectStrategy(req, this.strategy, {\n accessType: 'offline',\n prompt: 'consent',\n scope: req.scope,\n state: encodeState(req.state),\n });\n }\n\n async handler(\n req: express.Request,\n ): Promise<{ response: OAuthResponse; refreshToken?: string }> {\n const { result, privateInfo } = await executeFrameHandlerStrategy<\n BitbucketServerOAuthResult,\n PrivateInfo\n >(req, this.strategy);\n\n return {\n response: await this.handleResult(result),\n refreshToken: privateInfo.refreshToken,\n };\n }\n\n async refresh(\n req: OAuthRefreshRequest,\n ): Promise<{ response: OAuthResponse; refreshToken?: string }> {\n const { accessToken, refreshToken, params } =\n await executeRefreshTokenStrategy(\n this.strategy,\n req.refreshToken,\n req.scope,\n );\n const fullProfile = await executeFetchUserProfileStrategy(\n this.strategy,\n accessToken,\n );\n return {\n response: await this.handleResult({\n fullProfile,\n params,\n accessToken,\n }),\n refreshToken,\n };\n }\n\n private async handleResult(\n result: BitbucketServerOAuthResult,\n ): Promise<OAuthResponse> {\n // The OAuth2 strategy does not return a user profile -> let's fetch it before calling the auth handler\n result.fullProfile = await this.fetchProfile(result);\n const { profile } = await this.authHandler(result, this.resolverContext);\n\n let backstageIdentity = undefined;\n if (this.signInResolver) {\n backstageIdentity = await this.signInResolver(\n { result, profile },\n this.resolverContext,\n );\n }\n\n return {\n providerInfo: {\n accessToken: result.accessToken,\n scope: result.params.scope,\n expiresInSeconds: result.params.expires_in,\n },\n profile,\n backstageIdentity,\n };\n }\n\n private async fetchProfile(\n result: BitbucketServerOAuthResult,\n ): Promise<PassportProfile> {\n // Get current user name\n let whoAmIResponse;\n try {\n whoAmIResponse = await fetch(\n `https://${this.host}/plugins/servlet/applinks/whoami`,\n {\n headers: {\n Authorization: `Bearer ${result.accessToken}`,\n },\n },\n );\n } catch (e) {\n throw new Error(`Failed to retrieve the username of the logged in user`);\n }\n\n // A response.ok check here would be worthless as the Bitbucket API always returns 200 OK for this call\n const username = whoAmIResponse.headers.get('X-Ausername');\n if (!username) {\n throw new Error(`Failed to retrieve the username of the logged in user`);\n }\n\n let userResponse;\n try {\n userResponse = await fetch(\n `https://${this.host}/rest/api/latest/users/${username}?avatarSize=256`,\n {\n headers: {\n Authorization: `Bearer ${result.accessToken}`,\n },\n },\n );\n } catch (e) {\n throw new Error(`Failed to retrieve the user '${username}'`);\n }\n\n if (!userResponse.ok) {\n throw new Error(`Failed to retrieve the user '${username}'`);\n }\n\n const user = await userResponse.json();\n\n const passportProfile = {\n provider: 'bitbucketServer',\n id: user.id.toString(),\n displayName: user.displayName,\n username: user.name,\n emails: [\n {\n value: user.emailAddress,\n },\n ],\n } as PassportProfile;\n\n if (user.avatarUrl) {\n passportProfile.photos = [\n { value: `https://${this.host}${user.avatarUrl}` },\n ];\n }\n\n return passportProfile;\n }\n}\n\nexport const bitbucketServer = createAuthProviderIntegration({\n create(options?: {\n /**\n * The profile transformation function used to verify and convert the auth response\n * into the profile that will be presented to the user.\n */\n authHandler?: AuthHandler<BitbucketServerOAuthResult>;\n\n /**\n * Configure sign-in for this provider, without it the provider can not be used to sign users in.\n */\n signIn?: {\n /**\n * Maps an auth result to a Backstage identity for the user.\n */\n resolver: SignInResolver<BitbucketServerOAuthResult>;\n };\n }) {\n return ({ providerId, globalConfig, config, resolverContext }) =>\n OAuthEnvironmentHandler.mapConfig(config, envConfig => {\n const clientId = envConfig.getString('clientId');\n const clientSecret = envConfig.getString('clientSecret');\n const host = envConfig.getString('host');\n const customCallbackUrl = envConfig.getOptionalString('callbackUrl');\n const callbackUrl =\n customCallbackUrl ||\n `${globalConfig.baseUrl}/${providerId}/handler/frame`;\n const authorizationUrl = `https://${host}/rest/oauth2/latest/authorize`;\n const tokenUrl = `https://${host}/rest/oauth2/latest/token`;\n\n const authHandler: AuthHandler<BitbucketServerOAuthResult> =\n options?.authHandler\n ? options.authHandler\n : async ({ fullProfile }) => ({\n profile: makeProfileInfo(fullProfile),\n });\n\n const provider = new BitbucketServerAuthProvider({\n callbackUrl,\n clientId,\n clientSecret,\n host,\n authorizationUrl,\n tokenUrl,\n authHandler,\n signInResolver: options?.signIn?.resolver,\n resolverContext,\n });\n\n return OAuthAdapter.fromConfig(globalConfig, provider, {\n providerId,\n callbackUrl,\n });\n });\n },\n resolvers: {\n /**\n * Looks up the user by matching their email to the entity email.\n */\n emailMatchingUserEntityProfileEmail:\n (): SignInResolver<BitbucketServerOAuthResult> => commonByEmailResolver,\n },\n});\n","/*\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 SignInResolver,\n createProxyAuthProviderFactory,\n} from '@backstage/plugin-auth-node';\nimport { AuthHandler } from '../types';\nimport { createAuthProviderIntegration } from '../createAuthProviderIntegration';\nimport {\n AzureEasyAuthResult,\n azureEasyAuthAuthenticator,\n} from '@backstage/plugin-auth-backend-module-azure-easyauth-provider';\n\nexport type EasyAuthResult = AzureEasyAuthResult;\n\n/**\n * Auth provider integration for Azure EasyAuth\n *\n * @public\n */\nexport const easyAuth = createAuthProviderIntegration({\n create(options?: {\n /**\n * The profile transformation function used to verify and convert the auth response\n * into the profile that will be presented to the user.\n */\n authHandler?: AuthHandler<EasyAuthResult>;\n\n /**\n * Configure sign-in for this provider, without it the provider can not be used to sign users in.\n */\n signIn: {\n /**\n * Maps an auth result to a Backstage identity for the user.\n */\n resolver: SignInResolver<EasyAuthResult>;\n };\n }) {\n return createProxyAuthProviderFactory({\n authenticator: azureEasyAuthAuthenticator,\n profileTransform: options?.authHandler,\n signInResolver: options?.signIn?.resolver,\n });\n },\n});\n","/*\n * Copyright 2022 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 { atlassian } from './atlassian';\nimport { auth0 } from './auth0';\nimport { awsAlb } from './aws-alb';\nimport { bitbucket } from './bitbucket';\nimport { cfAccess } from './cloudflare-access';\nimport { gcpIap } from './gcp-iap';\nimport { github } from './github';\nimport { gitlab } from './gitlab';\nimport { google } from './google';\nimport { microsoft } from './microsoft';\nimport { oauth2 } from './oauth2';\nimport { oauth2Proxy } from './oauth2-proxy';\nimport { oidc } from './oidc';\nimport { okta } from './okta';\nimport { onelogin } from './onelogin';\nimport { saml } from './saml';\nimport { bitbucketServer } from './bitbucketServer';\nimport { easyAuth } from './azure-easyauth';\nimport { AuthProviderFactory } from '@backstage/plugin-auth-node';\n\n/**\n * All built-in auth provider integrations.\n *\n * @public\n */\nexport const providers = Object.freeze({\n atlassian,\n auth0,\n awsAlb,\n bitbucket,\n bitbucketServer,\n cfAccess,\n gcpIap,\n github,\n gitlab,\n google,\n microsoft,\n oauth2,\n oauth2Proxy,\n oidc,\n okta,\n onelogin,\n saml,\n easyAuth,\n});\n\n/**\n * All auth provider factories that are installed by default.\n *\n * @public\n */\nexport const defaultAuthProviderFactories: {\n [providerId: string]: AuthProviderFactory;\n} = {\n google: google.create(),\n github: github.create(),\n gitlab: gitlab.create(),\n saml: saml.create(),\n okta: okta.create(),\n auth0: auth0.create(),\n microsoft: microsoft.create(),\n easyAuth: easyAuth.create(),\n oauth2: oauth2.create(),\n oidc: oidc.create(),\n onelogin: onelogin.create(),\n awsalb: awsAlb.create(),\n bitbucket: bitbucket.create(),\n bitbucketServer: bitbucketServer.create(),\n atlassian: atlassian.create(),\n};\n","/*\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","/*\n * Copyright 2022 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 { TokenManager } from '@backstage/backend-common';\nimport { CatalogApi } from '@backstage/catalog-client';\nimport {\n DEFAULT_NAMESPACE,\n Entity,\n parseEntityRef,\n RELATION_MEMBER_OF,\n stringifyEntityRef,\n} from '@backstage/catalog-model';\nimport { ConflictError, InputError, NotFoundError } from '@backstage/errors';\nimport {\n AuthService,\n DiscoveryService,\n HttpAuthService,\n LoggerService,\n} from '@backstage/backend-plugin-api';\nimport { TokenIssuer } from '../../identity/types';\nimport {\n AuthOwnershipResolver,\n AuthResolverCatalogUserQuery,\n AuthResolverContext,\n TokenParams,\n} from '@backstage/plugin-auth-node';\nimport { CatalogIdentityClient } from '../catalog';\n\n/**\n * Uses the default ownership resolution logic to return an array\n * of entity refs that the provided entity claims ownership through.\n *\n * A reference to the entity itself will also be included in the returned array.\n *\n * @public\n */\nexport function getDefaultOwnershipEntityRefs(entity: Entity) {\n const membershipRefs =\n entity.relations\n ?.filter(\n r => r.type === RELATION_MEMBER_OF && r.targetRef.startsWith('group:'),\n )\n .map(r => r.targetRef) ?? [];\n\n return Array.from(new Set([stringifyEntityRef(entity), ...membershipRefs]));\n}\n\n/**\n * @internal\n */\nexport class CatalogAuthResolverContext implements AuthResolverContext {\n static create(options: {\n logger: LoggerService;\n catalogApi: CatalogApi;\n tokenIssuer: TokenIssuer;\n tokenManager: TokenManager;\n discovery: DiscoveryService;\n auth: AuthService;\n httpAuth: HttpAuthService;\n ownershipResolver?: AuthOwnershipResolver;\n }): CatalogAuthResolverContext {\n const catalogIdentityClient = new CatalogIdentityClient({\n catalogApi: options.catalogApi,\n tokenManager: options.tokenManager,\n discovery: options.discovery,\n auth: options.auth,\n httpAuth: options.httpAuth,\n });\n\n return new CatalogAuthResolverContext(\n options.logger,\n options.tokenIssuer,\n catalogIdentityClient,\n options.catalogApi,\n options.auth,\n options.ownershipResolver,\n );\n }\n\n private constructor(\n public readonly logger: LoggerService,\n public readonly tokenIssuer: TokenIssuer,\n public readonly catalogIdentityClient: CatalogIdentityClient,\n private readonly catalogApi: CatalogApi,\n private readonly auth: AuthService,\n private readonly ownershipResolver?: AuthOwnershipResolver,\n ) {}\n\n async issueToken(params: TokenParams) {\n const token = await this.tokenIssuer.issueToken(params);\n return { token };\n }\n\n async findCatalogUser(query: AuthResolverCatalogUserQuery) {\n let result: Entity[] | Entity | undefined = undefined;\n const { token } = await this.auth.getPluginRequestToken({\n onBehalfOf: await this.auth.getOwnServiceCredentials(),\n targetPluginId: 'catalog',\n });\n\n if ('entityRef' in query) {\n const entityRef = parseEntityRef(query.entityRef, {\n defaultKind: 'User',\n defaultNamespace: DEFAULT_NAMESPACE,\n });\n result = await this.catalogApi.getEntityByRef(entityRef, { token });\n } else if ('annotations' in query) {\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 const res = await this.catalogApi.getEntities({ filter }, { token });\n result = res.items;\n } else if ('filter' in query) {\n const filter = [query.filter].flat().map(value => {\n if (\n !Object.keys(value).some(\n key => key.toLocaleLowerCase('en-US') === 'kind',\n )\n ) {\n return {\n ...value,\n kind: 'user',\n };\n }\n return value;\n });\n const res = await this.catalogApi.getEntities(\n { filter: filter },\n { token },\n );\n result = res.items;\n } else {\n throw new InputError('Invalid user lookup query');\n }\n\n if (Array.isArray(result)) {\n if (result.length > 1) {\n throw new ConflictError('User lookup resulted in multiple matches');\n }\n result = result[0];\n }\n if (!result) {\n throw new NotFoundError('User not found');\n }\n\n return { entity: result };\n }\n\n async signInWithCatalogUser(query: AuthResolverCatalogUserQuery) {\n const { entity } = await this.findCatalogUser(query);\n let ent: string[];\n if (this.ownershipResolver) {\n const { ownershipEntityRefs } =\n await this.ownershipResolver.resolveOwnershipEntityRefs(entity);\n ent = ownershipEntityRefs;\n } else {\n ent = getDefaultOwnershipEntityRefs(entity);\n }\n\n const token = await this.tokenIssuer.issueToken({\n claims: {\n sub: stringifyEntityRef(entity),\n ent,\n },\n });\n return { token };\n }\n}\n","/*\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 {\n PluginEndpointDiscovery,\n TokenManager,\n} from '@backstage/backend-common';\nimport {\n AuthService,\n HttpAuthService,\n LoggerService,\n} from '@backstage/backend-plugin-api';\nimport { CatalogApi, CatalogClient } from '@backstage/catalog-client';\nimport { Config } from '@backstage/config';\nimport { assertError, NotFoundError } from '@backstage/errors';\nimport {\n AuthOwnershipResolver,\n AuthProviderFactory,\n} from '@backstage/plugin-auth-node';\nimport express from 'express';\nimport Router from 'express-promise-router';\nimport { Minimatch } from 'minimatch';\nimport { CatalogAuthResolverContext } from '../lib/resolvers/CatalogAuthResolverContext';\nimport { TokenIssuer } from '../identity/types';\n\n/** @public */\nexport type ProviderFactories = { [s: string]: AuthProviderFactory };\n\nexport function bindProviderRouters(\n targetRouter: express.Router,\n options: {\n providers: ProviderFactories;\n appUrl: string;\n baseUrl: string;\n config: Config;\n logger: LoggerService;\n discovery: PluginEndpointDiscovery;\n auth: AuthService;\n httpAuth: HttpAuthService;\n tokenManager: TokenManager;\n tokenIssuer: TokenIssuer;\n ownershipResolver?: AuthOwnershipResolver;\n catalogApi?: CatalogApi;\n },\n) {\n const {\n providers,\n appUrl,\n baseUrl,\n config,\n logger,\n discovery,\n auth,\n httpAuth,\n tokenManager,\n tokenIssuer,\n catalogApi,\n ownershipResolver,\n } = options;\n\n const providersConfig = config.getOptionalConfig('auth.providers');\n\n const isOriginAllowed = createOriginFilter(config);\n\n for (const [providerId, providerFactory] of Object.entries(providers)) {\n if (providersConfig?.has(providerId)) {\n logger.info(`Configuring auth provider: ${providerId}`);\n try {\n const provider = providerFactory({\n providerId,\n appUrl,\n baseUrl,\n isOriginAllowed,\n globalConfig: {\n baseUrl,\n appUrl,\n isOriginAllowed,\n },\n config: providersConfig.getConfig(providerId),\n logger,\n resolverContext: CatalogAuthResolverContext.create({\n logger,\n catalogApi:\n catalogApi ?? new CatalogClient({ discoveryApi: discovery }),\n tokenIssuer,\n tokenManager,\n discovery,\n auth,\n httpAuth,\n ownershipResolver,\n }),\n });\n\n const r = Router();\n\n r.get('/start', provider.start.bind(provider));\n r.get('/handler/frame', provider.frameHandler.bind(provider));\n r.post('/handler/frame', provider.frameHandler.bind(provider));\n if (provider.logout) {\n r.post('/logout', provider.logout.bind(provider));\n }\n if (provider.refresh) {\n r.get('/refresh', provider.refresh.bind(provider));\n r.post('/refresh', provider.refresh.bind(provider));\n }\n\n targetRouter.use(`/${providerId}`, r);\n } catch (e) {\n assertError(e);\n if (process.env.NODE_ENV !== 'development') {\n throw new Error(\n `Failed to initialize ${providerId} auth provider, ${e.message}`,\n );\n }\n\n logger.warn(`Skipping ${providerId} auth provider, ${e.message}`);\n\n targetRouter.use(`/${providerId}`, () => {\n // If the user added the provider under auth.providers but the clientId and clientSecret etc. were not found.\n throw new NotFoundError(\n `Auth provider registered for '${providerId}' is misconfigured. This could mean the configs under ` +\n `auth.providers.${providerId} are missing or the environment variables used are not defined. ` +\n `Check the auth backend plugin logs when the backend starts to see more details.`,\n );\n });\n }\n } else {\n targetRouter.use(`/${providerId}`, () => {\n throw new NotFoundError(\n `No auth provider registered for '${providerId}'`,\n );\n });\n }\n }\n}\n\n/** @public */\nexport function createOriginFilter(\n config: Config,\n): (origin: string) => boolean {\n const appUrl = config.getString('app.baseUrl');\n const { origin: appOrigin } = new URL(appUrl);\n\n const allowedOrigins = config.getOptionalStringArray(\n 'auth.experimentalExtraAllowedOrigins',\n );\n\n const allowedOriginPatterns =\n allowedOrigins?.map(\n pattern => new Minimatch(pattern, { nocase: true, noglobstar: true }),\n ) ?? [];\n\n return origin => {\n if (origin === appOrigin) {\n return true;\n }\n return allowedOriginPatterns.some(pattern => pattern.match(origin));\n };\n}\n","/*\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","/*\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","/*\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","/*\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","/*\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","/*\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","/*\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","/*\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","/*\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","/*\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 { RootConfigService } from '@backstage/backend-plugin-api';\nimport { readDurationFromConfig } from '@backstage/config';\nimport { durationToMilliseconds } from '@backstage/types';\n\nconst TOKEN_EXP_DEFAULT_S = 3600;\nconst TOKEN_EXP_MIN_S = 600;\nconst TOKEN_EXP_MAX_S = 86400;\n\nexport function readBackstageTokenExpiration(config: RootConfigService) {\n const processingIntervalKey = 'auth.backstageTokenExpiration';\n\n if (!config.has(processingIntervalKey)) {\n return TOKEN_EXP_DEFAULT_S;\n }\n\n const duration = readDurationFromConfig(config, {\n key: processingIntervalKey,\n });\n\n const durationS = Math.round(durationToMilliseconds(duration) / 1000);\n\n if (durationS < TOKEN_EXP_MIN_S) {\n return TOKEN_EXP_MIN_S;\n } else if (durationS > TOKEN_EXP_MAX_S) {\n return TOKEN_EXP_MAX_S;\n }\n return durationS;\n}\n","/*\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","/*\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 cookieParser from 'cookie-parser';\nimport {\n AuthService,\n DatabaseService,\n DiscoveryService,\n HttpAuthService,\n LoggerService,\n RootConfigService,\n TokenManagerService,\n} from '@backstage/backend-plugin-api';\nimport { defaultAuthProviderFactories } from '../providers';\nimport { AuthOwnershipResolver } from '@backstage/plugin-auth-node';\nimport { createLegacyAuthAdapters } from '@backstage/backend-common';\nimport { NotFoundError } from '@backstage/errors';\nimport { CatalogApi } from '@backstage/catalog-client';\nimport {\n bindOidcRouter,\n KeyStores,\n TokenFactory,\n UserInfoDatabaseHandler,\n} from '../identity';\nimport session from 'express-session';\nimport connectSessionKnex from 'connect-session-knex';\nimport passport from 'passport';\nimport { AuthDatabase } from '../database/AuthDatabase';\nimport { readBackstageTokenExpiration } from './readBackstageTokenExpiration';\nimport { TokenIssuer } from '../identity/types';\nimport { StaticTokenIssuer } from '../identity/StaticTokenIssuer';\nimport { StaticKeyStore } from '../identity/StaticKeyStore';\nimport { bindProviderRouters, ProviderFactories } from '../providers/router';\n\n/**\n * @public\n * @deprecated Please migrate to the new backend system as this will be removed in the future.\n */\nexport interface RouterOptions {\n logger: LoggerService;\n database: DatabaseService;\n config: RootConfigService;\n discovery: DiscoveryService;\n tokenManager: TokenManagerService;\n auth?: AuthService;\n httpAuth?: HttpAuthService;\n tokenFactoryAlgorithm?: string;\n providerFactories?: ProviderFactories;\n disableDefaultProviderFactories?: boolean;\n catalogApi?: CatalogApi;\n ownershipResolver?: AuthOwnershipResolver;\n}\n\n/**\n * @public\n * @deprecated Please migrate to the new backend system as this will be removed in the future.\n */\nexport async function createRouter(\n options: RouterOptions,\n): Promise<express.Router> {\n const {\n logger,\n config,\n discovery,\n database,\n tokenFactoryAlgorithm,\n providerFactories = {},\n } = options;\n\n const { auth, httpAuth } = createLegacyAuthAdapters(options);\n\n const router = Router();\n\n const appUrl = config.getString('app.baseUrl');\n const authUrl = await discovery.getExternalBaseUrl('auth');\n const backstageTokenExpiration = readBackstageTokenExpiration(config);\n const authDb = AuthDatabase.create(database);\n\n const keyStore = await KeyStores.fromConfig(config, {\n logger,\n database: authDb,\n });\n\n const userInfoDatabaseHandler = new UserInfoDatabaseHandler(\n await authDb.get(),\n );\n\n let tokenIssuer: TokenIssuer;\n if (keyStore instanceof StaticKeyStore) {\n tokenIssuer = new StaticTokenIssuer(\n {\n logger: logger.child({ component: 'token-factory' }),\n issuer: authUrl,\n sessionExpirationSeconds: backstageTokenExpiration,\n },\n keyStore as StaticKeyStore,\n );\n } else {\n tokenIssuer = new TokenFactory({\n issuer: authUrl,\n keyStore,\n keyDurationSeconds: backstageTokenExpiration,\n logger: logger.child({ component: 'token-factory' }),\n algorithm:\n tokenFactoryAlgorithm ??\n config.getOptionalString('auth.identityTokenAlgorithm'),\n userInfoDatabaseHandler,\n });\n }\n\n const secret = config.getOptionalString('auth.session.secret');\n if (secret) {\n router.use(cookieParser(secret));\n const enforceCookieSSL = authUrl.startsWith('https');\n const KnexSessionStore = connectSessionKnex(session);\n router.use(\n session({\n secret,\n saveUninitialized: false,\n resave: false,\n cookie: { secure: enforceCookieSSL ? 'auto' : false },\n store: new KnexSessionStore({\n createtable: false,\n knex: await authDb.get(),\n }),\n }),\n );\n router.use(passport.initialize());\n router.use(passport.session());\n } else {\n router.use(cookieParser());\n }\n\n router.use(express.urlencoded({ extended: false }));\n router.use(express.json());\n\n const providers = options.disableDefaultProviderFactories\n ? providerFactories\n : {\n ...defaultAuthProviderFactories,\n ...providerFactories,\n };\n\n bindProviderRouters(router, {\n providers,\n appUrl,\n baseUrl: authUrl,\n tokenIssuer,\n ...options,\n auth,\n httpAuth,\n });\n\n bindOidcRouter(router, {\n auth,\n tokenIssuer,\n baseUrl: authUrl,\n userInfoDatabaseHandler,\n });\n\n // Gives a more helpful error message than a plain 404\n router.use('/:provider/', req => {\n const { provider } = req.params;\n throw new NotFoundError(`Unknown auth provider '${provider}'`);\n });\n\n return router;\n}\n","/*\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 tokenManager: coreServices.tokenManager,\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 tokenManager,\n auth,\n httpAuth,\n catalogApi,\n }) {\n const router = await createRouter({\n logger,\n config,\n database,\n discovery,\n tokenManager,\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":["createOAuthProviderFactory","atlassianAuthenticator","Auth0InternalStrategy","_OAuthEnvironmentHandler","decodeOAuthState","encodeOAuthState","crypto","_prepareBackstageIdentityResponse","URL","InputError","NotAllowedError","isError","AuthenticationError","decodeJwt","createProxyAuthProviderFactory","awsAlbAuthenticator","bitbucketAuthenticator","bitbucketSignInResolvers","createCloudflareAccessAuthenticator","cloudflareAccessSignInResolvers","gcpIapAuthenticator","githubAuthenticator","gitlabAuthenticator","googleAuthenticator","commonSignInResolvers","googleSignInResolvers","microsoftAuthenticator","microsoftSignInResolvers","oauth2Authenticator","oauth2ProxyAuthenticator","oidcAuthenticator","oktaAuthenticator","oneLoginAuthenticator","SamlStrategy","OAuth2Strategy","fetch","azureEasyAuthAuthenticator","createLegacyAuthAdapters","ConflictError","NotFoundError","parseEntityRef","stringifyEntityRef","RELATION_MEMBER_OF","DEFAULT_NAMESPACE","CatalogClient","Router","assertError","Minimatch","MS_IN_S","tokenTypes","importJWK","SignJWT","omit","DateTime","generateKeyPair","exportJWK","uuid","GeneralSign","TABLE","Firestore","importSPKI","importPKCS8","fs","pickBy","resolvePackagePath","config","ConfigReader","DatabaseManager","readDurationFromConfig","durationToMilliseconds","cookieParser","connectSessionKnex","session","passport","express","createBackendPlugin","authProvidersExtensionPoint","authOwnershipResolutionExtensionPoint","coreServices","catalogServiceRef"],"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,gBAAA;AAAA,OAC7B;AAAA,KACF;AAAA,IACA,GAAA;AAAA,GACF,CAAA,CAAA;AAEN;;ACrBO,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,CAA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