@backstage/plugin-auth-backend 0.25.6-next.0 → 0.25.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +30 -0
- package/config.d.ts +24 -0
- package/dist/service/OidcRouter.cjs.js +4 -1
- package/dist/service/OidcRouter.cjs.js.map +1 -1
- package/dist/service/OidcService.cjs.js +2 -2
- package/dist/service/OidcService.cjs.js.map +1 -1
- package/dist/service/readTokenExpiration.cjs.js +44 -0
- package/dist/service/readTokenExpiration.cjs.js.map +1 -0
- package/dist/service/router.cjs.js +28 -19
- package/dist/service/router.cjs.js.map +1 -1
- package/migrations/20251118120000_oauth_state_text.js +41 -0
- package/package.json +13 -13
- package/dist/service/readBackstageTokenExpiration.cjs.js +0 -27
- package/dist/service/readBackstageTokenExpiration.cjs.js.map +0 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,35 @@
|
|
|
1
1
|
# @backstage/plugin-auth-backend
|
|
2
2
|
|
|
3
|
+
## 0.25.6
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- a9315d0: Change internal `state` column to `text` to support state of over 255 characters
|
|
8
|
+
- 05f60e1: Refactored constructor parameter properties to explicit property declarations for compatibility with TypeScript's `erasableSyntaxOnly` setting. This internal refactoring maintains all existing functionality while ensuring TypeScript compilation compatibility.
|
|
9
|
+
- 51ff7d8: Allow configuring dynamic client registration token expiration with config `auth.experimentalDynamicClientRegistration.tokenExpiration`.
|
|
10
|
+
|
|
11
|
+
Maximum expiration for the DCR token is 24 hours. Default expiration is 1 hour.
|
|
12
|
+
|
|
13
|
+
- Updated dependencies
|
|
14
|
+
- @backstage/plugin-catalog-node@1.20.0
|
|
15
|
+
- @backstage/backend-plugin-api@1.5.0
|
|
16
|
+
- @backstage/plugin-auth-node@0.6.9
|
|
17
|
+
- @backstage/config@1.3.6
|
|
18
|
+
- @backstage/catalog-model@1.7.6
|
|
19
|
+
|
|
20
|
+
## 0.25.6-next.1
|
|
21
|
+
|
|
22
|
+
### Patch Changes
|
|
23
|
+
|
|
24
|
+
- 51ff7d8: Allow configuring dynamic client registration token expiration with config `auth.experimentalDynamicClientRegistration.tokenExpiration`.
|
|
25
|
+
|
|
26
|
+
Maximum expiration for the DCR token is 24 hours. Default expiration is 1 hour.
|
|
27
|
+
|
|
28
|
+
- Updated dependencies
|
|
29
|
+
- @backstage/plugin-catalog-node@1.20.0-next.1
|
|
30
|
+
- @backstage/backend-plugin-api@1.5.0-next.1
|
|
31
|
+
- @backstage/plugin-auth-node@0.6.9-next.1
|
|
32
|
+
|
|
3
33
|
## 0.25.6-next.0
|
|
4
34
|
|
|
5
35
|
### Patch Changes
|
package/config.d.ts
CHANGED
|
@@ -95,6 +95,7 @@ export interface Config {
|
|
|
95
95
|
|
|
96
96
|
/**
|
|
97
97
|
* The backstage token expiration.
|
|
98
|
+
* Defaults to 1 hour (3600s). Maximum allowed is 24 hours.
|
|
98
99
|
*/
|
|
99
100
|
backstageTokenExpiration?: HumanDuration | string;
|
|
100
101
|
|
|
@@ -102,5 +103,28 @@ export interface Config {
|
|
|
102
103
|
* Additional app origins to allow for authenticating
|
|
103
104
|
*/
|
|
104
105
|
experimentalExtraAllowedOrigins?: string[];
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* Configuration for dynamic client registration
|
|
109
|
+
*/
|
|
110
|
+
experimentalDynamicClientRegistration?: {
|
|
111
|
+
/**
|
|
112
|
+
* Whether to enable dynamic client registration
|
|
113
|
+
* Defaults to false
|
|
114
|
+
*/
|
|
115
|
+
enabled?: boolean;
|
|
116
|
+
|
|
117
|
+
/**
|
|
118
|
+
* A list of allowed URI patterns to use for redirect URIs during
|
|
119
|
+
* dynamic client registration. Defaults to '[*]' which allows any redirect URI.
|
|
120
|
+
*/
|
|
121
|
+
allowedRedirectUriPatterns?: string[];
|
|
122
|
+
|
|
123
|
+
/**
|
|
124
|
+
* The expiration time for the client registration access tokens.
|
|
125
|
+
* Defaults to 1 hour (3600s). Maximum allowed is 24 hours.
|
|
126
|
+
*/
|
|
127
|
+
tokenExpiration?: HumanDuration | string;
|
|
128
|
+
};
|
|
105
129
|
};
|
|
106
130
|
}
|
|
@@ -4,6 +4,7 @@ var Router = require('express-promise-router');
|
|
|
4
4
|
var OidcService = require('./OidcService.cjs.js');
|
|
5
5
|
var errors = require('@backstage/errors');
|
|
6
6
|
var express = require('express');
|
|
7
|
+
var readTokenExpiration = require('./readTokenExpiration.cjs.js');
|
|
7
8
|
|
|
8
9
|
function _interopDefaultCompat (e) { return e && typeof e === 'object' && 'default' in e ? e : { default: e }; }
|
|
9
10
|
|
|
@@ -241,12 +242,14 @@ class OidcRouter {
|
|
|
241
242
|
error_description: "Missing required parameters"
|
|
242
243
|
});
|
|
243
244
|
}
|
|
245
|
+
const expiresIn = readTokenExpiration.readDcrTokenExpiration(this.config);
|
|
244
246
|
try {
|
|
245
247
|
const result = await this.oidc.exchangeCodeForToken({
|
|
246
248
|
code,
|
|
247
249
|
redirectUri,
|
|
248
250
|
codeVerifier,
|
|
249
|
-
grantType
|
|
251
|
+
grantType,
|
|
252
|
+
expiresIn
|
|
250
253
|
});
|
|
251
254
|
return res.json({
|
|
252
255
|
access_token: result.accessToken,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"OidcRouter.cjs.js","sources":["../../src/service/OidcRouter.ts"],"sourcesContent":["/*\n * Copyright 2025 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 Router from 'express-promise-router';\nimport { OidcService } from './OidcService';\nimport { AuthenticationError, isError } from '@backstage/errors';\nimport {\n AuthService,\n HttpAuthService,\n LoggerService,\n RootConfigService,\n} from '@backstage/backend-plugin-api';\nimport { TokenIssuer } from '../identity/types';\nimport { UserInfoDatabase } from '../database/UserInfoDatabase';\nimport { OidcDatabase } from '../database/OidcDatabase';\nimport { json } from 'express';\n\nexport class OidcRouter {\n private readonly oidc: OidcService;\n private readonly logger: LoggerService;\n private readonly auth: AuthService;\n private readonly appUrl: string;\n private readonly httpAuth: HttpAuthService;\n private readonly config: RootConfigService;\n\n private constructor(\n oidc: OidcService,\n logger: LoggerService,\n auth: AuthService,\n appUrl: string,\n httpAuth: HttpAuthService,\n config: RootConfigService,\n ) {\n this.oidc = oidc;\n this.logger = logger;\n this.auth = auth;\n this.appUrl = appUrl;\n this.httpAuth = httpAuth;\n this.config = config;\n }\n\n static create(options: {\n auth: AuthService;\n tokenIssuer: TokenIssuer;\n baseUrl: string;\n appUrl: string;\n logger: LoggerService;\n userInfo: UserInfoDatabase;\n oidc: OidcDatabase;\n httpAuth: HttpAuthService;\n config: RootConfigService;\n }) {\n return new OidcRouter(\n OidcService.create(options),\n options.logger,\n options.auth,\n options.appUrl,\n options.httpAuth,\n options.config,\n );\n }\n\n public getRouter() {\n const router = Router();\n\n router.use(json());\n\n // OpenID Provider Configuration endpoint\n // https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderConfig\n // Returns the OpenID Provider Configuration document containing metadata about the provider\n router.get('/.well-known/openid-configuration', (_req, res) => {\n res.json(this.oidc.getConfiguration());\n });\n\n // JSON Web Key Set endpoint\n // https://openid.net/specs/openid-connect-core-1_0.html#rfc.section.10.1.1\n // Returns the public keys used to verify JWTs issued by this provider\n router.get('/.well-known/jwks.json', async (_req, res) => {\n const { keys } = await this.oidc.listPublicKeys();\n res.json({ keys });\n });\n\n // UserInfo endpoint\n // https://openid.net/specs/openid-connect-core-1_0.html#UserInfo\n // Returns claims about the authenticated user using an access token\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 userInfo = await this.oidc.getUserInfo({ token });\n\n if (!userInfo) {\n res.status(404).send('User info not found');\n return;\n }\n\n res.json(userInfo);\n });\n\n if (\n this.config.getOptionalBoolean(\n 'auth.experimentalDynamicClientRegistration.enabled',\n )\n ) {\n // Authorization endpoint\n // https://openid.net/specs/openid-connect-core-1_0.html#AuthRequest\n // Handles the initial authorization request from the client, validates parameters,\n // and redirects to the Authorization Session page for user approval\n router.get('/v1/authorize', async (req, res) => {\n // todo(blam): maybe add zod types for validating input\n const {\n client_id: clientId,\n redirect_uri: redirectUri,\n response_type: responseType,\n scope,\n state,\n nonce,\n code_challenge: codeChallenge,\n code_challenge_method: codeChallengeMethod,\n } = req.query;\n\n if (!clientId || !redirectUri || !responseType) {\n this.logger.error(`Failed to authorize: Missing required parameters`);\n return res.status(400).json({\n error: 'invalid_request',\n error_description:\n 'Missing required parameters: client_id, redirect_uri, response_type',\n });\n }\n\n try {\n const result = await this.oidc.createAuthorizationSession({\n clientId: clientId as string,\n redirectUri: redirectUri as string,\n responseType: responseType as string,\n scope: scope as string | undefined,\n state: state as string | undefined,\n nonce: nonce as string | undefined,\n codeChallenge: codeChallenge as string | undefined,\n codeChallengeMethod: codeChallengeMethod as string | undefined,\n });\n\n // todo(blam): maybe this URL could be overridable by config if\n // the plugin is mounted somewhere else?\n // support slashes in baseUrl?\n const authSessionRedirectUrl = new URL(\n `./oauth2/authorize/${result.id}`,\n ensureTrailingSlash(this.appUrl),\n );\n\n return res.redirect(authSessionRedirectUrl.toString());\n } catch (error) {\n const errorParams = new URLSearchParams();\n errorParams.append(\n 'error',\n isError(error) ? error.name : 'server_error',\n );\n errorParams.append(\n 'error_description',\n isError(error) ? error.message : 'Unknown error',\n );\n if (state) {\n errorParams.append('state', state as string);\n }\n\n const redirectUrl = new URL(redirectUri as string);\n redirectUrl.search = errorParams.toString();\n return res.redirect(redirectUrl.toString());\n }\n });\n\n // Authorization Session request details endpoint\n // Returns Authorization Session request details for the frontend\n router.get('/v1/sessions/:sessionId', async (req, res) => {\n const { sessionId } = req.params;\n\n if (!sessionId) {\n return res.status(400).json({\n error: 'invalid_request',\n error_description: 'Missing Authorization Session ID',\n });\n }\n\n try {\n const session = await this.oidc.getAuthorizationSession({\n sessionId,\n });\n\n return res.json({\n id: session.id,\n clientName: session.clientName,\n scope: session.scope,\n redirectUri: session.redirectUri,\n });\n } catch (error) {\n const description = isError(error) ? error.message : 'Unknown error';\n this.logger.error(\n `Failed to get authorization session: ${description}`,\n error,\n );\n return res.status(404).json({\n error: 'not_found',\n error_description: description,\n });\n }\n });\n\n // Authorization Session approval endpoint\n // Handles user approval of Authorization Session requests and generates authorization codes\n router.post('/v1/sessions/:sessionId/approve', async (req, res) => {\n const { sessionId } = req.params;\n\n if (!sessionId) {\n return res.status(400).json({\n error: 'invalid_request',\n error_description: 'Missing authorization session ID',\n });\n }\n\n try {\n const httpCredentials = await this.httpAuth.credentials(req);\n\n if (!this.auth.isPrincipal(httpCredentials, 'user')) {\n return res.status(401).json({\n error: 'unauthorized',\n error_description: 'Authentication required',\n });\n }\n\n const { userEntityRef } = httpCredentials.principal;\n\n const result = await this.oidc.approveAuthorizationSession({\n sessionId,\n userEntityRef,\n });\n\n return res.json({\n redirectUrl: result.redirectUrl,\n });\n } catch (error) {\n const description = isError(error) ? error.message : 'Unknown error';\n this.logger.error(\n `Failed to approve authorization session: ${description}`,\n error,\n );\n return res.status(400).json({\n error: 'invalid_request',\n error_description: description,\n });\n }\n });\n\n // Authorization Session rejection endpoint\n // Handles user rejection of Authorization Session requests and redirects with error\n router.post('/v1/sessions/:sessionId/reject', async (req, res) => {\n const { sessionId } = req.params;\n\n if (!sessionId) {\n return res.status(400).json({\n error: 'invalid_request',\n error_description: 'Missing authorization session ID',\n });\n }\n\n const httpCredentials = await this.httpAuth.credentials(req);\n\n if (!this.auth.isPrincipal(httpCredentials, 'user')) {\n return res.status(401).json({\n error: 'unauthorized',\n error_description: 'Authentication required',\n });\n }\n\n const { userEntityRef } = httpCredentials.principal;\n try {\n const session = await this.oidc.getAuthorizationSession({\n sessionId,\n });\n\n await this.oidc.rejectAuthorizationSession({\n sessionId,\n userEntityRef,\n });\n\n const errorParams = new URLSearchParams();\n errorParams.append('error', 'access_denied');\n errorParams.append('error_description', 'User denied the request');\n if (session.state) {\n errorParams.append('state', session.state);\n }\n\n const redirectUrl = new URL(session.redirectUri);\n redirectUrl.search = errorParams.toString();\n\n return res.json({\n redirectUrl: redirectUrl.toString(),\n });\n } catch (error) {\n const description = isError(error) ? error.message : 'Unknown error';\n this.logger.error(\n `Failed to reject authorization session: ${description}`,\n error,\n );\n\n return res.status(400).json({\n error: 'invalid_request',\n error_description: description,\n });\n }\n });\n\n // Token endpoint\n // https://openid.net/specs/openid-connect-core-1_0.html#TokenRequest\n // Exchanges authorization codes for access tokens and ID tokens\n router.post('/v1/token', async (req, res) => {\n // todo(blam): maybe add zod types for validating input\n const {\n grant_type: grantType,\n code,\n redirect_uri: redirectUri,\n code_verifier: codeVerifier,\n } = req.body;\n\n if (!grantType || !code || !redirectUri) {\n this.logger.error(\n `Failed to exchange code for token: Missing required parameters`,\n );\n return res.status(400).json({\n error: 'invalid_request',\n error_description: 'Missing required parameters',\n });\n }\n\n try {\n const result = await this.oidc.exchangeCodeForToken({\n code,\n redirectUri,\n codeVerifier,\n grantType,\n });\n\n return res.json({\n access_token: result.accessToken,\n token_type: result.tokenType,\n expires_in: result.expiresIn,\n id_token: result.idToken,\n scope: result.scope,\n });\n } catch (error) {\n const description = isError(error) ? error.message : 'Unknown error';\n this.logger.error(\n `Failed to exchange code for token: ${description}`,\n error,\n );\n\n if (isError(error)) {\n if (error.name === 'AuthenticationError') {\n return res.status(401).json({\n error: 'invalid_client',\n error_description: error.message,\n });\n }\n if (error.name === 'InputError') {\n return res.status(400).json({\n error: 'invalid_request',\n error_description: error.message,\n });\n }\n }\n\n return res.status(500).json({\n error: 'server_error',\n error_description: description,\n });\n }\n });\n\n // Dynamic Client Registration endpoint\n // https://openid.net/specs/openid-connect-registration-1_0.html#ClientRegistration\n // Allows clients to register themselves dynamically with the provider\n router.post('/v1/register', async (req, res) => {\n // todo(blam): maybe add zod types for validating input\n const {\n client_name: clientName,\n redirect_uris: redirectUris,\n response_types: responseTypes,\n grant_types: grantTypes,\n scope,\n } = req.body;\n\n if (!redirectUris?.length) {\n res.status(400).json({\n error: 'invalid_request',\n error_description: 'redirect_uris is required',\n });\n return;\n }\n\n try {\n const client = await this.oidc.registerClient({\n clientName,\n redirectUris,\n responseTypes,\n grantTypes,\n scope,\n });\n\n res.status(201).json({\n client_id: client.clientId,\n redirect_uris: client.redirectUris,\n client_secret: client.clientSecret,\n });\n } catch (e) {\n const description = isError(e) ? e.message : 'Unknown error';\n this.logger.error(`Failed to register client: ${description}`, e);\n\n res.status(500).json({\n error: 'server_error',\n error_description: `Failed to register client: ${description}`,\n });\n }\n });\n }\n\n return router;\n }\n}\nfunction ensureTrailingSlash(appUrl: string): string | URL | undefined {\n if (appUrl.endsWith('/')) {\n return appUrl;\n }\n return `${appUrl}/`;\n}\n"],"names":["OidcService","Router","json","AuthenticationError","isError"],"mappings":";;;;;;;;;;;AA6BO,MAAM,UAAA,CAAW;AAAA,EACL,IAAA;AAAA,EACA,MAAA;AAAA,EACA,IAAA;AAAA,EACA,MAAA;AAAA,EACA,QAAA;AAAA,EACA,MAAA;AAAA,EAET,YACN,IAAA,EACA,MAAA,EACA,IAAA,EACA,MAAA,EACA,UACA,MAAA,EACA;AACA,IAAA,IAAA,CAAK,IAAA,GAAO,IAAA;AACZ,IAAA,IAAA,CAAK,MAAA,GAAS,MAAA;AACd,IAAA,IAAA,CAAK,IAAA,GAAO,IAAA;AACZ,IAAA,IAAA,CAAK,MAAA,GAAS,MAAA;AACd,IAAA,IAAA,CAAK,QAAA,GAAW,QAAA;AAChB,IAAA,IAAA,CAAK,MAAA,GAAS,MAAA;AAAA,E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;AAAA,YACA,YAAA;AAAA,YACA,aAAA;AAAA,YACA,UAAA;AAAA,YACA;AAAA,WACD,CAAA;AAED,UAAA,GAAA,CAAI,MAAA,CAAO,GAAG,CAAA,CAAE,IAAA,CAAK;AAAA,YACnB,WAAW,MAAA,CAAO,QAAA;AAAA,YAClB,eAAe,MAAA,CAAO,YAAA;AAAA,YACtB,eAAe,MAAA,CAAO;AAAA,WACvB,CAAA;AAAA,QACH,SAAS,CAAA,EAAG;AACV,UAAA,MAAM,WAAA,GAAcA,cAAA,CAAQ,CAAC,CAAA,GAAI,EAAE,OAAA,GAAU,eAAA;AAC7C,UAAA,IAAA,CAAK,MAAA,CAAO,KAAA,CAAM,CAAA,2BAAA,EAA8B,WAAW,IAAI,CAAC,CAAA;AAEhE,UAAA,GAAA,CAAI,MAAA,CAAO,GAAG,CAAA,CAAE,IAAA,CAAK;AAAA,YACnB,KAAA,EAAO,cAAA;AAAA,YACP,iBAAA,EAAmB,8BAA8B,WAAW,CAAA;AAAA,WAC7D,CAAA;AAAA,QACH;AAAA,MACF,CAAC,CAAA;AAAA,IACH;AAEA,IAAA,OAAO,MAAA;AAAA,EACT;AACF;AACA,SAAS,oBAAoB,MAAA,EAA0C;AACrE,EAAA,IAAI,MAAA,CAAO,QAAA,CAAS,GAAG,CAAA,EAAG;AACxB,IAAA,OAAO,MAAA;AAAA,EACT;AACA,EAAA,OAAO,GAAG,MAAM,CAAA,CAAA,CAAA;AAClB;;;;"}
|
|
1
|
+
{"version":3,"file":"OidcRouter.cjs.js","sources":["../../src/service/OidcRouter.ts"],"sourcesContent":["/*\n * Copyright 2025 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 Router from 'express-promise-router';\nimport { OidcService } from './OidcService';\nimport { AuthenticationError, isError } from '@backstage/errors';\nimport {\n AuthService,\n HttpAuthService,\n LoggerService,\n RootConfigService,\n} from '@backstage/backend-plugin-api';\nimport { TokenIssuer } from '../identity/types';\nimport { UserInfoDatabase } from '../database/UserInfoDatabase';\nimport { OidcDatabase } from '../database/OidcDatabase';\nimport { json } from 'express';\nimport { readDcrTokenExpiration } from './readTokenExpiration.ts';\n\nexport class OidcRouter {\n private readonly oidc: OidcService;\n private readonly logger: LoggerService;\n private readonly auth: AuthService;\n private readonly appUrl: string;\n private readonly httpAuth: HttpAuthService;\n private readonly config: RootConfigService;\n\n private constructor(\n oidc: OidcService,\n logger: LoggerService,\n auth: AuthService,\n appUrl: string,\n httpAuth: HttpAuthService,\n config: RootConfigService,\n ) {\n this.oidc = oidc;\n this.logger = logger;\n this.auth = auth;\n this.appUrl = appUrl;\n this.httpAuth = httpAuth;\n this.config = config;\n }\n\n static create(options: {\n auth: AuthService;\n tokenIssuer: TokenIssuer;\n baseUrl: string;\n appUrl: string;\n logger: LoggerService;\n userInfo: UserInfoDatabase;\n oidc: OidcDatabase;\n httpAuth: HttpAuthService;\n config: RootConfigService;\n }) {\n return new OidcRouter(\n OidcService.create(options),\n options.logger,\n options.auth,\n options.appUrl,\n options.httpAuth,\n options.config,\n );\n }\n\n public getRouter() {\n const router = Router();\n\n router.use(json());\n\n // OpenID Provider Configuration endpoint\n // https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderConfig\n // Returns the OpenID Provider Configuration document containing metadata about the provider\n router.get('/.well-known/openid-configuration', (_req, res) => {\n res.json(this.oidc.getConfiguration());\n });\n\n // JSON Web Key Set endpoint\n // https://openid.net/specs/openid-connect-core-1_0.html#rfc.section.10.1.1\n // Returns the public keys used to verify JWTs issued by this provider\n router.get('/.well-known/jwks.json', async (_req, res) => {\n const { keys } = await this.oidc.listPublicKeys();\n res.json({ keys });\n });\n\n // UserInfo endpoint\n // https://openid.net/specs/openid-connect-core-1_0.html#UserInfo\n // Returns claims about the authenticated user using an access token\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 userInfo = await this.oidc.getUserInfo({ token });\n\n if (!userInfo) {\n res.status(404).send('User info not found');\n return;\n }\n\n res.json(userInfo);\n });\n\n if (\n this.config.getOptionalBoolean(\n 'auth.experimentalDynamicClientRegistration.enabled',\n )\n ) {\n // Authorization endpoint\n // https://openid.net/specs/openid-connect-core-1_0.html#AuthRequest\n // Handles the initial authorization request from the client, validates parameters,\n // and redirects to the Authorization Session page for user approval\n router.get('/v1/authorize', async (req, res) => {\n // todo(blam): maybe add zod types for validating input\n const {\n client_id: clientId,\n redirect_uri: redirectUri,\n response_type: responseType,\n scope,\n state,\n nonce,\n code_challenge: codeChallenge,\n code_challenge_method: codeChallengeMethod,\n } = req.query;\n\n if (!clientId || !redirectUri || !responseType) {\n this.logger.error(`Failed to authorize: Missing required parameters`);\n return res.status(400).json({\n error: 'invalid_request',\n error_description:\n 'Missing required parameters: client_id, redirect_uri, response_type',\n });\n }\n\n try {\n const result = await this.oidc.createAuthorizationSession({\n clientId: clientId as string,\n redirectUri: redirectUri as string,\n responseType: responseType as string,\n scope: scope as string | undefined,\n state: state as string | undefined,\n nonce: nonce as string | undefined,\n codeChallenge: codeChallenge as string | undefined,\n codeChallengeMethod: codeChallengeMethod as string | undefined,\n });\n\n // todo(blam): maybe this URL could be overridable by config if\n // the plugin is mounted somewhere else?\n // support slashes in baseUrl?\n const authSessionRedirectUrl = new URL(\n `./oauth2/authorize/${result.id}`,\n ensureTrailingSlash(this.appUrl),\n );\n\n return res.redirect(authSessionRedirectUrl.toString());\n } catch (error) {\n const errorParams = new URLSearchParams();\n errorParams.append(\n 'error',\n isError(error) ? error.name : 'server_error',\n );\n errorParams.append(\n 'error_description',\n isError(error) ? error.message : 'Unknown error',\n );\n if (state) {\n errorParams.append('state', state as string);\n }\n\n const redirectUrl = new URL(redirectUri as string);\n redirectUrl.search = errorParams.toString();\n return res.redirect(redirectUrl.toString());\n }\n });\n\n // Authorization Session request details endpoint\n // Returns Authorization Session request details for the frontend\n router.get('/v1/sessions/:sessionId', async (req, res) => {\n const { sessionId } = req.params;\n\n if (!sessionId) {\n return res.status(400).json({\n error: 'invalid_request',\n error_description: 'Missing Authorization Session ID',\n });\n }\n\n try {\n const session = await this.oidc.getAuthorizationSession({\n sessionId,\n });\n\n return res.json({\n id: session.id,\n clientName: session.clientName,\n scope: session.scope,\n redirectUri: session.redirectUri,\n });\n } catch (error) {\n const description = isError(error) ? error.message : 'Unknown error';\n this.logger.error(\n `Failed to get authorization session: ${description}`,\n error,\n );\n return res.status(404).json({\n error: 'not_found',\n error_description: description,\n });\n }\n });\n\n // Authorization Session approval endpoint\n // Handles user approval of Authorization Session requests and generates authorization codes\n router.post('/v1/sessions/:sessionId/approve', async (req, res) => {\n const { sessionId } = req.params;\n\n if (!sessionId) {\n return res.status(400).json({\n error: 'invalid_request',\n error_description: 'Missing authorization session ID',\n });\n }\n\n try {\n const httpCredentials = await this.httpAuth.credentials(req);\n\n if (!this.auth.isPrincipal(httpCredentials, 'user')) {\n return res.status(401).json({\n error: 'unauthorized',\n error_description: 'Authentication required',\n });\n }\n\n const { userEntityRef } = httpCredentials.principal;\n\n const result = await this.oidc.approveAuthorizationSession({\n sessionId,\n userEntityRef,\n });\n\n return res.json({\n redirectUrl: result.redirectUrl,\n });\n } catch (error) {\n const description = isError(error) ? error.message : 'Unknown error';\n this.logger.error(\n `Failed to approve authorization session: ${description}`,\n error,\n );\n return res.status(400).json({\n error: 'invalid_request',\n error_description: description,\n });\n }\n });\n\n // Authorization Session rejection endpoint\n // Handles user rejection of Authorization Session requests and redirects with error\n router.post('/v1/sessions/:sessionId/reject', async (req, res) => {\n const { sessionId } = req.params;\n\n if (!sessionId) {\n return res.status(400).json({\n error: 'invalid_request',\n error_description: 'Missing authorization session ID',\n });\n }\n\n const httpCredentials = await this.httpAuth.credentials(req);\n\n if (!this.auth.isPrincipal(httpCredentials, 'user')) {\n return res.status(401).json({\n error: 'unauthorized',\n error_description: 'Authentication required',\n });\n }\n\n const { userEntityRef } = httpCredentials.principal;\n try {\n const session = await this.oidc.getAuthorizationSession({\n sessionId,\n });\n\n await this.oidc.rejectAuthorizationSession({\n sessionId,\n userEntityRef,\n });\n\n const errorParams = new URLSearchParams();\n errorParams.append('error', 'access_denied');\n errorParams.append('error_description', 'User denied the request');\n if (session.state) {\n errorParams.append('state', session.state);\n }\n\n const redirectUrl = new URL(session.redirectUri);\n redirectUrl.search = errorParams.toString();\n\n return res.json({\n redirectUrl: redirectUrl.toString(),\n });\n } catch (error) {\n const description = isError(error) ? error.message : 'Unknown error';\n this.logger.error(\n `Failed to reject authorization session: ${description}`,\n error,\n );\n\n return res.status(400).json({\n error: 'invalid_request',\n error_description: description,\n });\n }\n });\n\n // Token endpoint\n // https://openid.net/specs/openid-connect-core-1_0.html#TokenRequest\n // Exchanges authorization codes for access tokens and ID tokens\n router.post('/v1/token', async (req, res) => {\n // todo(blam): maybe add zod types for validating input\n const {\n grant_type: grantType,\n code,\n redirect_uri: redirectUri,\n code_verifier: codeVerifier,\n } = req.body;\n\n if (!grantType || !code || !redirectUri) {\n this.logger.error(\n `Failed to exchange code for token: Missing required parameters`,\n );\n return res.status(400).json({\n error: 'invalid_request',\n error_description: 'Missing required parameters',\n });\n }\n\n const expiresIn = readDcrTokenExpiration(this.config);\n\n try {\n const result = await this.oidc.exchangeCodeForToken({\n code,\n redirectUri,\n codeVerifier,\n grantType,\n expiresIn,\n });\n\n return res.json({\n access_token: result.accessToken,\n token_type: result.tokenType,\n expires_in: result.expiresIn,\n id_token: result.idToken,\n scope: result.scope,\n });\n } catch (error) {\n const description = isError(error) ? error.message : 'Unknown error';\n this.logger.error(\n `Failed to exchange code for token: ${description}`,\n error,\n );\n\n if (isError(error)) {\n if (error.name === 'AuthenticationError') {\n return res.status(401).json({\n error: 'invalid_client',\n error_description: error.message,\n });\n }\n if (error.name === 'InputError') {\n return res.status(400).json({\n error: 'invalid_request',\n error_description: error.message,\n });\n }\n }\n\n return res.status(500).json({\n error: 'server_error',\n error_description: description,\n });\n }\n });\n\n // Dynamic Client Registration endpoint\n // https://openid.net/specs/openid-connect-registration-1_0.html#ClientRegistration\n // Allows clients to register themselves dynamically with the provider\n router.post('/v1/register', async (req, res) => {\n // todo(blam): maybe add zod types for validating input\n const {\n client_name: clientName,\n redirect_uris: redirectUris,\n response_types: responseTypes,\n grant_types: grantTypes,\n scope,\n } = req.body;\n\n if (!redirectUris?.length) {\n res.status(400).json({\n error: 'invalid_request',\n error_description: 'redirect_uris is required',\n });\n return;\n }\n\n try {\n const client = await this.oidc.registerClient({\n clientName,\n redirectUris,\n responseTypes,\n grantTypes,\n scope,\n });\n\n res.status(201).json({\n client_id: client.clientId,\n redirect_uris: client.redirectUris,\n client_secret: client.clientSecret,\n });\n } catch (e) {\n const description = isError(e) ? e.message : 'Unknown error';\n this.logger.error(`Failed to register client: ${description}`, e);\n\n res.status(500).json({\n error: 'server_error',\n error_description: `Failed to register client: ${description}`,\n });\n }\n });\n }\n\n return router;\n }\n}\nfunction ensureTrailingSlash(appUrl: string): string | URL | undefined {\n if (appUrl.endsWith('/')) {\n return appUrl;\n }\n return `${appUrl}/`;\n}\n"],"names":["OidcService","Router","json","AuthenticationError","isError","readDcrTokenExpiration"],"mappings":";;;;;;;;;;;;AA8BO,MAAM,UAAA,CAAW;AAAA,EACL,IAAA;AAAA,EACA,MAAA;AAAA,EACA,IAAA;AAAA,EACA,MAAA;AAAA,EACA,QAAA;AAAA,EACA,MAAA;AAAA,EAET,YACN,IAAA,EACA,MAAA,EACA,IAAA,EACA,MAAA,EACA,UACA,MAAA,EACA;AACA,IAAA,IAAA,CAAK,IAAA,GAAO,IAAA;AACZ,IAAA,IAAA,C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
244
|
});
|
|
245
245
|
}
|
|
246
246
|
async exchangeCodeForToken(params) {
|
|
247
|
-
const { code, redirectUri, codeVerifier, grantType } = params;
|
|
247
|
+
const { code, redirectUri, codeVerifier, grantType, expiresIn } = params;
|
|
248
248
|
if (grantType !== "authorization_code") {
|
|
249
249
|
throw new errors.InputError("Unsupported grant type");
|
|
250
250
|
}
|
|
@@ -297,7 +297,7 @@ class OidcService {
|
|
|
297
297
|
return {
|
|
298
298
|
accessToken: token,
|
|
299
299
|
tokenType: "Bearer",
|
|
300
|
-
expiresIn
|
|
300
|
+
expiresIn,
|
|
301
301
|
idToken: token,
|
|
302
302
|
scope: session.scope || "openid"
|
|
303
303
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"OidcService.cjs.js","sources":["../../src/service/OidcService.ts"],"sourcesContent":["/*\n * Copyright 2025 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 { AuthService, RootConfigService } from '@backstage/backend-plugin-api';\nimport { TokenIssuer } from '../identity/types';\nimport { UserInfoDatabase } from '../database/UserInfoDatabase';\nimport {\n InputError,\n AuthenticationError,\n NotFoundError,\n} from '@backstage/errors';\nimport { decodeJwt } from 'jose';\nimport crypto from 'crypto';\nimport { OidcDatabase } from '../database/OidcDatabase';\nimport { DateTime } from 'luxon';\nimport matcher from 'matcher';\n\nexport class OidcService {\n private readonly auth: AuthService;\n private readonly tokenIssuer: TokenIssuer;\n private readonly baseUrl: string;\n private readonly userInfo: UserInfoDatabase;\n private readonly oidc: OidcDatabase;\n private readonly config: RootConfigService;\n\n private constructor(\n auth: AuthService,\n tokenIssuer: TokenIssuer,\n baseUrl: string,\n userInfo: UserInfoDatabase,\n oidc: OidcDatabase,\n config: RootConfigService,\n ) {\n this.auth = auth;\n this.tokenIssuer = tokenIssuer;\n this.baseUrl = baseUrl;\n this.userInfo = userInfo;\n this.oidc = oidc;\n this.config = config;\n }\n\n static create(options: {\n auth: AuthService;\n tokenIssuer: TokenIssuer;\n baseUrl: string;\n userInfo: UserInfoDatabase;\n oidc: OidcDatabase;\n config: RootConfigService;\n }) {\n return new OidcService(\n options.auth,\n options.tokenIssuer,\n options.baseUrl,\n options.userInfo,\n options.oidc,\n options.config,\n );\n }\n\n public getConfiguration() {\n return {\n issuer: this.baseUrl,\n token_endpoint: `${this.baseUrl}/v1/token`,\n userinfo_endpoint: `${this.baseUrl}/v1/userinfo`,\n jwks_uri: `${this.baseUrl}/.well-known/jwks.json`,\n response_types_supported: ['code', '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 'client_secret_basic',\n 'client_secret_post',\n ],\n claims_supported: ['sub', 'ent'],\n grant_types_supported: ['authorization_code'],\n authorization_endpoint: `${this.baseUrl}/v1/authorize`,\n registration_endpoint: `${this.baseUrl}/v1/register`,\n code_challenge_methods_supported: ['S256', 'plain'],\n };\n }\n\n public async listPublicKeys() {\n return await this.tokenIssuer.listPublicKeys();\n }\n\n public async getUserInfo({ token }: { token: string }) {\n const credentials = await this.auth.authenticate(token, {\n allowLimitedAccess: true,\n });\n if (!this.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 return await this.userInfo.getUserInfo(userEntityRef);\n }\n\n public async registerClient(opts: {\n responseTypes?: string[];\n grantTypes?: string[];\n clientName: string;\n redirectUris?: string[];\n scope?: string;\n }) {\n const generatedClientId = crypto.randomUUID();\n const generatedClientSecret = crypto.randomUUID();\n\n const allowedRedirectUriPatterns = this.config.getOptionalStringArray(\n 'auth.experimentalDynamicClientRegistration.allowedRedirectUriPatterns',\n ) ?? ['*'];\n\n for (const redirectUri of opts.redirectUris ?? []) {\n if (\n !allowedRedirectUriPatterns.some(pattern =>\n matcher.isMatch(redirectUri, pattern),\n )\n ) {\n throw new InputError('Invalid redirect_uri');\n }\n }\n\n return await this.oidc.createClient({\n clientId: generatedClientId,\n clientName: opts.clientName,\n clientSecret: generatedClientSecret,\n redirectUris: opts.redirectUris ?? [],\n responseTypes: opts.responseTypes ?? ['code'],\n grantTypes: opts.grantTypes ?? ['authorization_code'],\n scope: opts.scope,\n });\n }\n\n public async createAuthorizationSession(opts: {\n clientId: string;\n redirectUri: string;\n responseType: string;\n scope?: string;\n state?: string;\n nonce?: string;\n codeChallenge?: string;\n codeChallengeMethod?: string;\n }) {\n const {\n clientId,\n redirectUri,\n responseType,\n scope,\n state,\n nonce,\n codeChallenge,\n codeChallengeMethod,\n } = opts;\n\n if (responseType !== 'code') {\n throw new InputError('Only authorization code flow is supported');\n }\n\n const client = await this.oidc.getClient({ clientId });\n if (!client) {\n throw new InputError('Invalid client_id');\n }\n\n if (!client.redirectUris.includes(redirectUri)) {\n throw new InputError('Invalid redirect_uri');\n }\n\n if (codeChallenge) {\n if (\n !codeChallengeMethod ||\n !['S256', 'plain'].includes(codeChallengeMethod)\n ) {\n throw new InputError('Invalid code_challenge_method');\n }\n }\n\n const sessionId = crypto.randomUUID();\n const sessionExpiresAt = DateTime.now().plus({ hours: 1 }).toJSDate();\n\n await this.oidc.createAuthorizationSession({\n id: sessionId,\n clientId,\n redirectUri,\n responseType,\n scope,\n state,\n codeChallenge,\n codeChallengeMethod,\n nonce,\n expiresAt: sessionExpiresAt,\n });\n\n return {\n id: sessionId,\n clientName: client.clientName,\n scope,\n redirectUri,\n };\n }\n\n public async approveAuthorizationSession(opts: {\n sessionId: string;\n userEntityRef: string;\n }) {\n const { sessionId, userEntityRef } = opts;\n\n const session = await this.oidc.getAuthorizationSession({\n id: sessionId,\n });\n\n if (!session) {\n throw new NotFoundError('Invalid authorization session');\n }\n\n if (DateTime.fromJSDate(session.expiresAt) < DateTime.now()) {\n throw new InputError('Authorization session expired');\n }\n\n if (session.status !== 'pending') {\n throw new NotFoundError('Authorization session not found or expired');\n }\n\n await this.oidc.updateAuthorizationSession({\n id: session.id,\n userEntityRef,\n status: 'approved',\n });\n\n const authorizationCode = crypto.randomBytes(32).toString('base64url');\n const codeExpiresAt = DateTime.now().plus({ minutes: 10 }).toJSDate();\n\n await this.oidc.createAuthorizationCode({\n code: authorizationCode,\n sessionId: session.id,\n expiresAt: codeExpiresAt,\n });\n\n const redirectUrl = new URL(session.redirectUri);\n\n redirectUrl.searchParams.append('code', authorizationCode);\n if (session.state) {\n redirectUrl.searchParams.append('state', session.state);\n }\n\n return {\n redirectUrl: redirectUrl.toString(),\n };\n }\n\n public async getAuthorizationSession(opts: { sessionId: string }) {\n const session = await this.oidc.getAuthorizationSession({\n id: opts.sessionId,\n });\n\n if (!session) {\n throw new NotFoundError('Invalid authorization session');\n }\n\n if (DateTime.fromJSDate(session.expiresAt) < DateTime.now()) {\n throw new InputError('Authorization session expired');\n }\n\n if (session.status !== 'pending') {\n throw new NotFoundError('Authorization session not found or expired');\n }\n\n const client = await this.oidc.getClient({ clientId: session.clientId });\n if (!client) {\n throw new InputError('Invalid client_id');\n }\n\n return {\n id: session.id,\n clientId: session.clientId,\n clientName: client.clientName,\n redirectUri: session.redirectUri,\n scope: session.scope,\n state: session.state,\n responseType: session.responseType,\n codeChallenge: session.codeChallenge,\n codeChallengeMethod: session.codeChallengeMethod,\n nonce: session.nonce,\n expiresAt: session.expiresAt,\n status: session.status,\n };\n }\n\n public async rejectAuthorizationSession(opts: {\n sessionId: string;\n userEntityRef: string;\n }) {\n const { sessionId, userEntityRef } = opts;\n\n const session = await this.oidc.getAuthorizationSession({\n id: sessionId,\n });\n\n if (!session) {\n throw new NotFoundError('Invalid authorization session');\n }\n\n if (DateTime.fromJSDate(session.expiresAt) < DateTime.now()) {\n throw new InputError('Authorization session expired');\n }\n\n if (session.status !== 'pending') {\n throw new NotFoundError('Authorization session not found or expired');\n }\n\n await this.oidc.updateAuthorizationSession({\n id: session.id,\n status: 'rejected',\n userEntityRef,\n });\n }\n\n public async exchangeCodeForToken(params: {\n code: string;\n redirectUri: string;\n codeVerifier?: string;\n grantType: string;\n }) {\n const { code, redirectUri, codeVerifier, grantType } = params;\n\n if (grantType !== 'authorization_code') {\n throw new InputError('Unsupported grant type');\n }\n\n const authCode = await this.oidc.getAuthorizationCode({ code });\n if (!authCode) {\n throw new AuthenticationError('Invalid authorization code');\n }\n\n if (DateTime.fromJSDate(authCode.expiresAt) < DateTime.now()) {\n throw new AuthenticationError('Authorization code expired');\n }\n\n if (authCode.used) {\n throw new AuthenticationError('Authorization code already used');\n }\n\n const session = await this.oidc.getAuthorizationSession({\n id: authCode.sessionId,\n });\n\n if (!session) {\n throw new NotFoundError('Invalid authorization session');\n }\n\n if (session.redirectUri !== redirectUri) {\n throw new AuthenticationError('Redirect URI mismatch');\n }\n\n if (session.status !== 'approved') {\n throw new AuthenticationError('Authorization not approved');\n }\n\n if (!session.userEntityRef) {\n throw new AuthenticationError('No user associated with authorization');\n }\n\n if (session.codeChallenge) {\n if (!codeVerifier) {\n throw new AuthenticationError('Code verifier required for PKCE');\n }\n\n if (\n !this.verifyPkce(\n session.codeChallenge,\n codeVerifier,\n session.codeChallengeMethod,\n )\n ) {\n throw new AuthenticationError('Invalid code verifier');\n }\n }\n\n await this.oidc.updateAuthorizationCode({\n code,\n used: true,\n });\n\n const { token } = await this.tokenIssuer.issueToken({\n claims: {\n sub: session.userEntityRef,\n },\n });\n\n return {\n accessToken: token,\n tokenType: 'Bearer',\n expiresIn: 3600,\n idToken: token,\n scope: session.scope || 'openid',\n };\n }\n\n private verifyPkce(\n codeChallenge: string,\n codeVerifier: string,\n method?: string,\n ): boolean {\n if (!method || method === 'plain') {\n return codeChallenge === codeVerifier;\n }\n\n if (method === 'S256') {\n const hash = crypto.createHash('sha256').update(codeVerifier).digest();\n const base64urlHash = hash.toString('base64url');\n return codeChallenge === base64urlHash;\n }\n\n return false;\n }\n}\n"],"names":["InputError","decodeJwt","crypto","matcher","DateTime","NotFoundError","AuthenticationError"],"mappings":";;;;;;;;;;;;;AA6BO,MAAM,WAAA,CAAY;AAAA,EACN,IAAA;AAAA,EACA,WAAA;AAAA,EACA,OAAA;AAAA,EACA,QAAA;AAAA,EACA,IAAA;AAAA,EACA,MAAA;AAAA,EAET,YACN,IAAA,EACA,WAAA,EACA,OAAA,EACA,QAAA,EACA,MACA,MAAA,EACA;AACA,IAAA,IAAA,CAAK,IAAA,GAAO,IAAA;AACZ,IAAA,IAAA,CAAK,WAAA,GAAc,WAAA;AACnB,IAAA,IAAA,CAAK,OAAA,GAAU,OAAA;AACf,IAAA,IAAA,CAAK,QAAA,GAAW,QAAA;AAChB,IAAA,IAAA,CAAK,IAAA,GAAO,IAAA;AACZ,IAAA,IAAA,CAAK,MAAA,GAAS,MAAA;AAAA,EAChB;AAAA,EAEA,OAAO,OAAO,OAAA,EAOX;AACD,IAAA,OAAO,IAAI,WAAA;AAAA,MACT,OAAA,CAAQ,IAAA;AAAA,MACR,OAAA,CAAQ,WAAA;AAAA,MACR,OAAA,CAAQ,OAAA;AAAA,MACR,OAAA,CAAQ,QAAA;AAAA,MACR,OAAA,CAAQ,IAAA;AAAA,MACR,OAAA,CAAQ;AAAA,KACV;AAAA,EACF;AAAA,EAEO,gBAAA,GAAmB;AACxB,IAAA,OAAO;AAAA,MACL,QAAQ,IAAA,CAAK,OAAA;AAAA,MACb,cAAA,EAAgB,CAAA,EAAG,IAAA,CAAK,OAAO,CAAA,SAAA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copyright 2025 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 { AuthService, RootConfigService } from '@backstage/backend-plugin-api';\nimport { TokenIssuer } from '../identity/types';\nimport { UserInfoDatabase } from '../database/UserInfoDatabase';\nimport {\n AuthenticationError,\n InputError,\n NotFoundError,\n} from '@backstage/errors';\nimport { decodeJwt } from 'jose';\nimport crypto from 'crypto';\nimport { OidcDatabase } from '../database/OidcDatabase';\nimport { DateTime } from 'luxon';\nimport matcher from 'matcher';\n\nexport class OidcService {\n private readonly auth: AuthService;\n private readonly tokenIssuer: TokenIssuer;\n private readonly baseUrl: string;\n private readonly userInfo: UserInfoDatabase;\n private readonly oidc: OidcDatabase;\n private readonly config: RootConfigService;\n\n private constructor(\n auth: AuthService,\n tokenIssuer: TokenIssuer,\n baseUrl: string,\n userInfo: UserInfoDatabase,\n oidc: OidcDatabase,\n config: RootConfigService,\n ) {\n this.auth = auth;\n this.tokenIssuer = tokenIssuer;\n this.baseUrl = baseUrl;\n this.userInfo = userInfo;\n this.oidc = oidc;\n this.config = config;\n }\n\n static create(options: {\n auth: AuthService;\n tokenIssuer: TokenIssuer;\n baseUrl: string;\n userInfo: UserInfoDatabase;\n oidc: OidcDatabase;\n config: RootConfigService;\n }) {\n return new OidcService(\n options.auth,\n options.tokenIssuer,\n options.baseUrl,\n options.userInfo,\n options.oidc,\n options.config,\n );\n }\n\n public getConfiguration() {\n return {\n issuer: this.baseUrl,\n token_endpoint: `${this.baseUrl}/v1/token`,\n userinfo_endpoint: `${this.baseUrl}/v1/userinfo`,\n jwks_uri: `${this.baseUrl}/.well-known/jwks.json`,\n response_types_supported: ['code', '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 'client_secret_basic',\n 'client_secret_post',\n ],\n claims_supported: ['sub', 'ent'],\n grant_types_supported: ['authorization_code'],\n authorization_endpoint: `${this.baseUrl}/v1/authorize`,\n registration_endpoint: `${this.baseUrl}/v1/register`,\n code_challenge_methods_supported: ['S256', 'plain'],\n };\n }\n\n public async listPublicKeys() {\n return await this.tokenIssuer.listPublicKeys();\n }\n\n public async getUserInfo({ token }: { token: string }) {\n const credentials = await this.auth.authenticate(token, {\n allowLimitedAccess: true,\n });\n if (!this.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 return await this.userInfo.getUserInfo(userEntityRef);\n }\n\n public async registerClient(opts: {\n responseTypes?: string[];\n grantTypes?: string[];\n clientName: string;\n redirectUris?: string[];\n scope?: string;\n }) {\n const generatedClientId = crypto.randomUUID();\n const generatedClientSecret = crypto.randomUUID();\n\n const allowedRedirectUriPatterns = this.config.getOptionalStringArray(\n 'auth.experimentalDynamicClientRegistration.allowedRedirectUriPatterns',\n ) ?? ['*'];\n\n for (const redirectUri of opts.redirectUris ?? []) {\n if (\n !allowedRedirectUriPatterns.some(pattern =>\n matcher.isMatch(redirectUri, pattern),\n )\n ) {\n throw new InputError('Invalid redirect_uri');\n }\n }\n\n return await this.oidc.createClient({\n clientId: generatedClientId,\n clientName: opts.clientName,\n clientSecret: generatedClientSecret,\n redirectUris: opts.redirectUris ?? [],\n responseTypes: opts.responseTypes ?? ['code'],\n grantTypes: opts.grantTypes ?? ['authorization_code'],\n scope: opts.scope,\n });\n }\n\n public async createAuthorizationSession(opts: {\n clientId: string;\n redirectUri: string;\n responseType: string;\n scope?: string;\n state?: string;\n nonce?: string;\n codeChallenge?: string;\n codeChallengeMethod?: string;\n }) {\n const {\n clientId,\n redirectUri,\n responseType,\n scope,\n state,\n nonce,\n codeChallenge,\n codeChallengeMethod,\n } = opts;\n\n if (responseType !== 'code') {\n throw new InputError('Only authorization code flow is supported');\n }\n\n const client = await this.oidc.getClient({ clientId });\n if (!client) {\n throw new InputError('Invalid client_id');\n }\n\n if (!client.redirectUris.includes(redirectUri)) {\n throw new InputError('Invalid redirect_uri');\n }\n\n if (codeChallenge) {\n if (\n !codeChallengeMethod ||\n !['S256', 'plain'].includes(codeChallengeMethod)\n ) {\n throw new InputError('Invalid code_challenge_method');\n }\n }\n\n const sessionId = crypto.randomUUID();\n const sessionExpiresAt = DateTime.now().plus({ hours: 1 }).toJSDate();\n\n await this.oidc.createAuthorizationSession({\n id: sessionId,\n clientId,\n redirectUri,\n responseType,\n scope,\n state,\n codeChallenge,\n codeChallengeMethod,\n nonce,\n expiresAt: sessionExpiresAt,\n });\n\n return {\n id: sessionId,\n clientName: client.clientName,\n scope,\n redirectUri,\n };\n }\n\n public async approveAuthorizationSession(opts: {\n sessionId: string;\n userEntityRef: string;\n }) {\n const { sessionId, userEntityRef } = opts;\n\n const session = await this.oidc.getAuthorizationSession({\n id: sessionId,\n });\n\n if (!session) {\n throw new NotFoundError('Invalid authorization session');\n }\n\n if (DateTime.fromJSDate(session.expiresAt) < DateTime.now()) {\n throw new InputError('Authorization session expired');\n }\n\n if (session.status !== 'pending') {\n throw new NotFoundError('Authorization session not found or expired');\n }\n\n await this.oidc.updateAuthorizationSession({\n id: session.id,\n userEntityRef,\n status: 'approved',\n });\n\n const authorizationCode = crypto.randomBytes(32).toString('base64url');\n const codeExpiresAt = DateTime.now().plus({ minutes: 10 }).toJSDate();\n\n await this.oidc.createAuthorizationCode({\n code: authorizationCode,\n sessionId: session.id,\n expiresAt: codeExpiresAt,\n });\n\n const redirectUrl = new URL(session.redirectUri);\n\n redirectUrl.searchParams.append('code', authorizationCode);\n if (session.state) {\n redirectUrl.searchParams.append('state', session.state);\n }\n\n return {\n redirectUrl: redirectUrl.toString(),\n };\n }\n\n public async getAuthorizationSession(opts: { sessionId: string }) {\n const session = await this.oidc.getAuthorizationSession({\n id: opts.sessionId,\n });\n\n if (!session) {\n throw new NotFoundError('Invalid authorization session');\n }\n\n if (DateTime.fromJSDate(session.expiresAt) < DateTime.now()) {\n throw new InputError('Authorization session expired');\n }\n\n if (session.status !== 'pending') {\n throw new NotFoundError('Authorization session not found or expired');\n }\n\n const client = await this.oidc.getClient({ clientId: session.clientId });\n if (!client) {\n throw new InputError('Invalid client_id');\n }\n\n return {\n id: session.id,\n clientId: session.clientId,\n clientName: client.clientName,\n redirectUri: session.redirectUri,\n scope: session.scope,\n state: session.state,\n responseType: session.responseType,\n codeChallenge: session.codeChallenge,\n codeChallengeMethod: session.codeChallengeMethod,\n nonce: session.nonce,\n expiresAt: session.expiresAt,\n status: session.status,\n };\n }\n\n public async rejectAuthorizationSession(opts: {\n sessionId: string;\n userEntityRef: string;\n }) {\n const { sessionId, userEntityRef } = opts;\n\n const session = await this.oidc.getAuthorizationSession({\n id: sessionId,\n });\n\n if (!session) {\n throw new NotFoundError('Invalid authorization session');\n }\n\n if (DateTime.fromJSDate(session.expiresAt) < DateTime.now()) {\n throw new InputError('Authorization session expired');\n }\n\n if (session.status !== 'pending') {\n throw new NotFoundError('Authorization session not found or expired');\n }\n\n await this.oidc.updateAuthorizationSession({\n id: session.id,\n status: 'rejected',\n userEntityRef,\n });\n }\n\n public async exchangeCodeForToken(params: {\n code: string;\n redirectUri: string;\n codeVerifier?: string;\n grantType: string;\n expiresIn: number;\n }) {\n const { code, redirectUri, codeVerifier, grantType, expiresIn } = params;\n\n if (grantType !== 'authorization_code') {\n throw new InputError('Unsupported grant type');\n }\n\n const authCode = await this.oidc.getAuthorizationCode({ code });\n if (!authCode) {\n throw new AuthenticationError('Invalid authorization code');\n }\n\n if (DateTime.fromJSDate(authCode.expiresAt) < DateTime.now()) {\n throw new AuthenticationError('Authorization code expired');\n }\n\n if (authCode.used) {\n throw new AuthenticationError('Authorization code already used');\n }\n\n const session = await this.oidc.getAuthorizationSession({\n id: authCode.sessionId,\n });\n\n if (!session) {\n throw new NotFoundError('Invalid authorization session');\n }\n\n if (session.redirectUri !== redirectUri) {\n throw new AuthenticationError('Redirect URI mismatch');\n }\n\n if (session.status !== 'approved') {\n throw new AuthenticationError('Authorization not approved');\n }\n\n if (!session.userEntityRef) {\n throw new AuthenticationError('No user associated with authorization');\n }\n\n if (session.codeChallenge) {\n if (!codeVerifier) {\n throw new AuthenticationError('Code verifier required for PKCE');\n }\n\n if (\n !this.verifyPkce(\n session.codeChallenge,\n codeVerifier,\n session.codeChallengeMethod,\n )\n ) {\n throw new AuthenticationError('Invalid code verifier');\n }\n }\n\n await this.oidc.updateAuthorizationCode({\n code,\n used: true,\n });\n\n const { token } = await this.tokenIssuer.issueToken({\n claims: {\n sub: session.userEntityRef,\n },\n });\n\n return {\n accessToken: token,\n tokenType: 'Bearer',\n expiresIn: expiresIn,\n idToken: token,\n scope: session.scope || 'openid',\n };\n }\n\n private verifyPkce(\n codeChallenge: string,\n codeVerifier: string,\n method?: string,\n ): boolean {\n if (!method || method === 'plain') {\n return codeChallenge === codeVerifier;\n }\n\n if (method === 'S256') {\n const hash = crypto.createHash('sha256').update(codeVerifier).digest();\n const base64urlHash = hash.toString('base64url');\n return codeChallenge === base64urlHash;\n }\n\n return false;\n }\n}\n"],"names":["InputError","decodeJwt","crypto","matcher","DateTime","NotFoundError","AuthenticationError"],"mappings":";;;;;;;;;;;;;AA6BO,MAAM,WAAA,CAAY;AAAA,EACN,IAAA;AAAA,EACA,WAAA;AAAA,EACA,OAAA;AAAA,EACA,QAAA;AAAA,EACA,IAAA;AAAA,EACA,MAAA;AAAA,EAET,YACN,IA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OAAO;AAAA,MACL,WAAA,EAAa,KAAA;AAAA,MACb,SAAA,EAAW,QAAA;AAAA,MACX,SAAA;AAAA,MACA,OAAA,EAAS,KAAA;AAAA,MACT,KAAA,EAAO,QAAQ,KAAA,IAAS;AAAA,KAC1B;AAAA,EACF;AAAA,EAEQ,UAAA,CACN,aAAA,EACA,YAAA,EACA,MAAA,EACS;AACT,IAAA,IAAI,CAAC,MAAA,IAAU,MAAA,KAAW,OAAA,EAAS;AACjC,MAAA,OAAO,aAAA,KAAkB,YAAA;AAAA,IAC3B;AAEA,IAAA,IAAI,WAAW,MAAA,EAAQ;AACrB,MAAA,MAAM,IAAA,GAAOJ,wBAAO,UAAA,CAAW,QAAQ,EAAE,MAAA,CAAO,YAAY,EAAE,MAAA,EAAO;AACrE,MAAA,MAAM,aAAA,GAAgB,IAAA,CAAK,QAAA,CAAS,WAAW,CAAA;AAC/C,MAAA,OAAO,aAAA,KAAkB,aAAA;AAAA,IAC3B;AAEA,IAAA,OAAO,KAAA;AAAA,EACT;AACF;;;;"}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
var config = require('@backstage/config');
|
|
4
|
+
var types = require('@backstage/types');
|
|
5
|
+
|
|
6
|
+
const TOKEN_EXP_DEFAULT_S = 3600;
|
|
7
|
+
const TOKEN_EXP_MIN_S = 600;
|
|
8
|
+
const TOKEN_EXP_MAX_S = 86400;
|
|
9
|
+
function readBackstageTokenExpiration(config) {
|
|
10
|
+
return readTokenExpiration(config, {
|
|
11
|
+
configKey: "auth.backstageTokenExpiration"
|
|
12
|
+
});
|
|
13
|
+
}
|
|
14
|
+
function readDcrTokenExpiration(config) {
|
|
15
|
+
return readTokenExpiration(config, {
|
|
16
|
+
configKey: "auth.experimentalDynamicClientRegistration.tokenExpiration"
|
|
17
|
+
});
|
|
18
|
+
}
|
|
19
|
+
function readTokenExpiration(config$1, options) {
|
|
20
|
+
const {
|
|
21
|
+
configKey,
|
|
22
|
+
maxExpiration = TOKEN_EXP_MAX_S,
|
|
23
|
+
minExpiration = TOKEN_EXP_MIN_S,
|
|
24
|
+
defaultExpiration = TOKEN_EXP_DEFAULT_S
|
|
25
|
+
} = options ?? {};
|
|
26
|
+
if (!config$1.has(configKey)) {
|
|
27
|
+
return defaultExpiration;
|
|
28
|
+
}
|
|
29
|
+
const duration = config.readDurationFromConfig(config$1, {
|
|
30
|
+
key: configKey
|
|
31
|
+
});
|
|
32
|
+
const durationS = Math.round(types.durationToMilliseconds(duration) / 1e3);
|
|
33
|
+
if (durationS < minExpiration) {
|
|
34
|
+
return minExpiration;
|
|
35
|
+
} else if (durationS > maxExpiration) {
|
|
36
|
+
return maxExpiration;
|
|
37
|
+
}
|
|
38
|
+
return durationS;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
exports.readBackstageTokenExpiration = readBackstageTokenExpiration;
|
|
42
|
+
exports.readDcrTokenExpiration = readDcrTokenExpiration;
|
|
43
|
+
exports.readTokenExpiration = readTokenExpiration;
|
|
44
|
+
//# sourceMappingURL=readTokenExpiration.cjs.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"readTokenExpiration.cjs.js","sources":["../../src/service/readTokenExpiration.ts"],"sourcesContent":["/*\n * Copyright 2024 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { 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 return readTokenExpiration(config, {\n configKey: 'auth.backstageTokenExpiration',\n });\n}\n\nexport function readDcrTokenExpiration(config: RootConfigService) {\n return readTokenExpiration(config, {\n configKey: 'auth.experimentalDynamicClientRegistration.tokenExpiration',\n });\n}\n\nexport function readTokenExpiration(\n config: RootConfigService,\n options: {\n configKey: string;\n maxExpiration?: number;\n minExpiration?: number;\n defaultExpiration?: number;\n },\n): number {\n const {\n configKey,\n maxExpiration = TOKEN_EXP_MAX_S,\n minExpiration = TOKEN_EXP_MIN_S,\n defaultExpiration = TOKEN_EXP_DEFAULT_S,\n } = options ?? {};\n if (!config.has(configKey)) {\n return defaultExpiration;\n }\n\n const duration = readDurationFromConfig(config, {\n key: configKey,\n });\n\n const durationS = Math.round(durationToMilliseconds(duration) / 1000);\n\n if (durationS < minExpiration) {\n return minExpiration;\n } else if (durationS > maxExpiration) {\n return maxExpiration;\n }\n return durationS;\n}\n"],"names":["config","readDurationFromConfig","durationToMilliseconds"],"mappings":";;;;;AAoBA,MAAM,mBAAA,GAAsB,IAAA;AAC5B,MAAM,eAAA,GAAkB,GAAA;AACxB,MAAM,eAAA,GAAkB,KAAA;AAEjB,SAAS,6BAA6B,MAAA,EAA2B;AACtE,EAAA,OAAO,oBAAoB,MAAA,EAAQ;AAAA,IACjC,SAAA,EAAW;AAAA,GACZ,CAAA;AACH;AAEO,SAAS,uBAAuB,MAAA,EAA2B;AAChE,EAAA,OAAO,oBAAoB,MAAA,EAAQ;AAAA,IACjC,SAAA,EAAW;AAAA,GACZ,CAAA;AACH;AAEO,SAAS,mBAAA,CACdA,UACA,OAAA,EAMQ;AACR,EAAA,MAAM;AAAA,IACJ,SAAA;AAAA,IACA,aAAA,GAAgB,eAAA;AAAA,IAChB,aAAA,GAAgB,eAAA;AAAA,IAChB,iBAAA,GAAoB;AAAA,GACtB,GAAI,WAAW,EAAC;AAChB,EAAA,IAAI,CAACA,QAAA,CAAO,GAAA,CAAI,SAAS,CAAA,EAAG;AAC1B,IAAA,OAAO,iBAAA;AAAA,EACT;AAEA,EAAA,MAAM,QAAA,GAAWC,8BAAuBD,QAAA,EAAQ;AAAA,IAC9C,GAAA,EAAK;AAAA,GACN,CAAA;AAED,EAAA,MAAM,YAAY,IAAA,CAAK,KAAA,CAAME,4BAAA,CAAuB,QAAQ,IAAI,GAAI,CAAA;AAEpE,EAAA,IAAI,YAAY,aAAA,EAAe;AAC7B,IAAA,OAAO,aAAA;AAAA,EACT,CAAA,MAAA,IAAW,YAAY,aAAA,EAAe;AACpC,IAAA,OAAO,aAAA;AAAA,EACT;AACA,EAAA,OAAO,SAAA;AACT;;;;;;"}
|
|
@@ -11,7 +11,7 @@ var session = require('express-session');
|
|
|
11
11
|
var connectSessionKnex = require('connect-session-knex');
|
|
12
12
|
var passport = require('passport');
|
|
13
13
|
var AuthDatabase = require('../database/AuthDatabase.cjs.js');
|
|
14
|
-
var
|
|
14
|
+
var readTokenExpiration = require('./readTokenExpiration.cjs.js');
|
|
15
15
|
var StaticTokenIssuer = require('../identity/StaticTokenIssuer.cjs.js');
|
|
16
16
|
var StaticKeyStore = require('../identity/StaticKeyStore.cjs.js');
|
|
17
17
|
var router = require('../providers/router.cjs.js');
|
|
@@ -40,7 +40,7 @@ async function createRouter(options) {
|
|
|
40
40
|
const router$1 = Router__default.default();
|
|
41
41
|
const appUrl = config.getString("app.baseUrl");
|
|
42
42
|
const authUrl = await discovery.getExternalBaseUrl("auth");
|
|
43
|
-
const backstageTokenExpiration =
|
|
43
|
+
const backstageTokenExpiration = readTokenExpiration.readBackstageTokenExpiration(config);
|
|
44
44
|
const database = AuthDatabase.AuthDatabase.create(db);
|
|
45
45
|
const keyStore = await KeyStores.KeyStores.fromConfig(config, {
|
|
46
46
|
logger,
|
|
@@ -52,27 +52,31 @@ async function createRouter(options) {
|
|
|
52
52
|
const omitClaimsFromToken = config.getOptionalBoolean(
|
|
53
53
|
"auth.omitIdentityTokenOwnershipClaim"
|
|
54
54
|
) ? ["ent"] : [];
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
55
|
+
const createTokenIssuer = (opts) => {
|
|
56
|
+
if (keyStore instanceof StaticKeyStore.StaticKeyStore) {
|
|
57
|
+
return new StaticTokenIssuer.StaticTokenIssuer(
|
|
58
|
+
{
|
|
59
|
+
logger: opts.logger,
|
|
60
|
+
issuer: authUrl,
|
|
61
|
+
sessionExpirationSeconds: opts.expirationSeconds,
|
|
62
|
+
omitClaimsFromToken
|
|
63
|
+
},
|
|
64
|
+
keyStore
|
|
65
|
+
);
|
|
66
|
+
}
|
|
67
|
+
return new TokenFactory.TokenFactory({
|
|
68
68
|
issuer: authUrl,
|
|
69
69
|
keyStore,
|
|
70
|
-
keyDurationSeconds:
|
|
71
|
-
logger: logger
|
|
70
|
+
keyDurationSeconds: opts.expirationSeconds,
|
|
71
|
+
logger: opts.logger,
|
|
72
72
|
algorithm: tokenFactoryAlgorithm ?? config.getOptionalString("auth.identityTokenAlgorithm"),
|
|
73
73
|
omitClaimsFromToken
|
|
74
74
|
});
|
|
75
|
-
}
|
|
75
|
+
};
|
|
76
|
+
const tokenIssuer = createTokenIssuer({
|
|
77
|
+
logger: logger.child({ component: "token-factory" }),
|
|
78
|
+
expirationSeconds: backstageTokenExpiration
|
|
79
|
+
});
|
|
76
80
|
const secret = config.getOptionalString("auth.session.secret");
|
|
77
81
|
if (secret) {
|
|
78
82
|
router$1.use(cookieParser__default.default(secret));
|
|
@@ -106,10 +110,15 @@ async function createRouter(options) {
|
|
|
106
110
|
auth: options.auth,
|
|
107
111
|
userInfo
|
|
108
112
|
});
|
|
113
|
+
const dcrTokenExpiration = readTokenExpiration.readDcrTokenExpiration(config);
|
|
114
|
+
const oidcTokenIssuer = createTokenIssuer({
|
|
115
|
+
logger: logger.child({ component: "oidc-token-factory" }),
|
|
116
|
+
expirationSeconds: dcrTokenExpiration
|
|
117
|
+
});
|
|
109
118
|
const oidc = await OidcDatabase.OidcDatabase.create({ database });
|
|
110
119
|
const oidcRouter = OidcRouter.OidcRouter.create({
|
|
111
120
|
auth: options.auth,
|
|
112
|
-
tokenIssuer,
|
|
121
|
+
tokenIssuer: oidcTokenIssuer,
|
|
113
122
|
baseUrl: authUrl,
|
|
114
123
|
appUrl,
|
|
115
124
|
userInfo,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"router.cjs.js","sources":["../../src/service/router.ts"],"sourcesContent":["/*\n * Copyright 2020 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport express from 'express';\nimport Router from 'express-promise-router';\nimport cookieParser from 'cookie-parser';\nimport {\n AuthService,\n DatabaseService,\n DiscoveryService,\n HttpAuthService,\n LoggerService,\n RootConfigService,\n} from '@backstage/backend-plugin-api';\nimport { AuthOwnershipResolver } from '@backstage/plugin-auth-node';\nimport { CatalogService } from '@backstage/plugin-catalog-node';\nimport { NotFoundError } from '@backstage/errors';\nimport { KeyStores } from '../identity/KeyStores';\nimport { TokenFactory } from '../identity/TokenFactory';\nimport { UserInfoDatabase } from '../database/UserInfoDatabase';\nimport session from 'express-session';\nimport connectSessionKnex from 'connect-session-knex';\nimport passport from 'passport';\nimport { AuthDatabase } from '../database/AuthDatabase';\nimport {
|
|
1
|
+
{"version":3,"file":"router.cjs.js","sources":["../../src/service/router.ts"],"sourcesContent":["/*\n * Copyright 2020 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport express from 'express';\nimport Router from 'express-promise-router';\nimport cookieParser from 'cookie-parser';\nimport {\n AuthService,\n DatabaseService,\n DiscoveryService,\n HttpAuthService,\n LoggerService,\n RootConfigService,\n} from '@backstage/backend-plugin-api';\nimport { AuthOwnershipResolver } from '@backstage/plugin-auth-node';\nimport { CatalogService } from '@backstage/plugin-catalog-node';\nimport { NotFoundError } from '@backstage/errors';\nimport { KeyStores } from '../identity/KeyStores';\nimport { TokenFactory } from '../identity/TokenFactory';\nimport { UserInfoDatabase } from '../database/UserInfoDatabase';\nimport session from 'express-session';\nimport connectSessionKnex from 'connect-session-knex';\nimport passport from 'passport';\nimport { AuthDatabase } from '../database/AuthDatabase';\nimport {\n readBackstageTokenExpiration,\n readDcrTokenExpiration,\n} from './readTokenExpiration.ts';\nimport { StaticTokenIssuer } from '../identity/StaticTokenIssuer';\nimport { StaticKeyStore } from '../identity/StaticKeyStore';\nimport { bindProviderRouters, ProviderFactories } from '../providers/router';\nimport { OidcRouter } from './OidcRouter';\nimport { OidcDatabase } from '../database/OidcDatabase';\n\ninterface RouterOptions {\n logger: LoggerService;\n database: DatabaseService;\n config: RootConfigService;\n discovery: DiscoveryService;\n auth: AuthService;\n tokenFactoryAlgorithm?: string;\n providerFactories?: ProviderFactories;\n catalog: CatalogService;\n ownershipResolver?: AuthOwnershipResolver;\n httpAuth: HttpAuthService;\n}\n\nexport async function createRouter(\n options: RouterOptions,\n): Promise<express.Router> {\n const {\n logger,\n config,\n discovery,\n database: db,\n tokenFactoryAlgorithm,\n providerFactories = {},\n httpAuth,\n } = 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 database = AuthDatabase.create(db);\n\n const keyStore = await KeyStores.fromConfig(config, {\n logger,\n database,\n });\n\n const userInfo = await UserInfoDatabase.create({\n database,\n });\n\n const omitClaimsFromToken = config.getOptionalBoolean(\n 'auth.omitIdentityTokenOwnershipClaim',\n )\n ? ['ent']\n : [];\n\n const createTokenIssuer = (opts: {\n logger: LoggerService;\n expirationSeconds: number;\n }) => {\n if (keyStore instanceof StaticKeyStore) {\n return new StaticTokenIssuer(\n {\n logger: opts.logger,\n issuer: authUrl,\n sessionExpirationSeconds: opts.expirationSeconds,\n omitClaimsFromToken,\n },\n keyStore as StaticKeyStore,\n );\n }\n return new TokenFactory({\n issuer: authUrl,\n keyStore,\n keyDurationSeconds: opts.expirationSeconds,\n logger: opts.logger,\n algorithm:\n tokenFactoryAlgorithm ??\n config.getOptionalString('auth.identityTokenAlgorithm'),\n omitClaimsFromToken,\n });\n };\n\n const tokenIssuer = createTokenIssuer({\n logger: logger.child({ component: 'token-factory' }),\n expirationSeconds: backstageTokenExpiration,\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 database.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 bindProviderRouters(router, {\n providers: providerFactories,\n appUrl,\n baseUrl: authUrl,\n tokenIssuer,\n ...options,\n auth: options.auth,\n userInfo,\n });\n\n const dcrTokenExpiration = readDcrTokenExpiration(config);\n\n const oidcTokenIssuer = createTokenIssuer({\n logger: logger.child({ component: 'oidc-token-factory' }),\n expirationSeconds: dcrTokenExpiration,\n });\n\n const oidc = await OidcDatabase.create({ database });\n\n const oidcRouter = OidcRouter.create({\n auth: options.auth,\n tokenIssuer: oidcTokenIssuer,\n baseUrl: authUrl,\n appUrl,\n userInfo,\n oidc,\n logger,\n httpAuth,\n config,\n });\n\n router.use(oidcRouter.getRouter());\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"],"names":["router","Router","readBackstageTokenExpiration","AuthDatabase","KeyStores","UserInfoDatabase","StaticKeyStore","StaticTokenIssuer","TokenFactory","cookieParser","connectSessionKnex","session","passport","express","bindProviderRouters","readDcrTokenExpiration","OidcDatabase","OidcRouter","NotFoundError"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4DA,eAAsB,aACpB,OAAA,EACyB;AACzB,EAAA,MAAM;AAAA,IACJ,MAAA;AAAA,IACA,MAAA;AAAA,IACA,SAAA;AAAA,IACA,QAAA,EAAU,EAAA;AAAA,IACV,qBAAA;AAAA,IACA,oBAAoB,EAAC;AAAA,IACrB;AAAA,GACF,GAAI,OAAA;AAEJ,EAAA,MAAMA,WAASC,uBAAA,EAAO;AAEtB,EAAA,MAAM,MAAA,GAAS,MAAA,CAAO,SAAA,CAAU,aAAa,CAAA;AAC7C,EAAA,MAAM,OAAA,GAAU,MAAM,SAAA,CAAU,kBAAA,CAAmB,MAAM,CAAA;AACzD,EAAA,MAAM,wBAAA,GAA2BC,iDAA6B,MAAM,CAAA;AACpE,EAAA,MAAM,QAAA,GAAWC,yBAAA,CAAa,MAAA,CAAO,EAAE,CAAA;AAEvC,EAAA,MAAM,QAAA,GAAW,MAAMC,mBAAA,CAAU,UAAA,CAAW,MAAA,EAAQ;AAAA,IAClD,MAAA;AAAA,IACA;AAAA,GACD,CAAA;AAED,EAAA,MAAM,QAAA,GA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A,CAAO,EAAE,UAAU,CAAA;AAEnD,EAAA,MAAM,UAAA,GAAaC,sBAAW,MAAA,CAAO;AAAA,IACnC,MAAM,OAAA,CAAQ,IAAA;AAAA,IACd,WAAA,EAAa,eAAA;AAAA,IACb,OAAA,EAAS,OAAA;AAAA,IACT,MAAA;AAAA,IACA,QAAA;AAAA,IACA,IAAA;AAAA,IACA,MAAA;AAAA,IACA,QAAA;AAAA,IACA;AAAA,GACD,CAAA;AAED,EAAAjB,QAAA,CAAO,GAAA,CAAI,UAAA,CAAW,SAAA,EAAW,CAAA;AAGjC,EAAAA,QAAA,CAAO,GAAA,CAAI,eAAe,CAAA,GAAA,KAAO;AAC/B,IAAA,MAAM,EAAE,QAAA,EAAS,GAAI,GAAA,CAAI,MAAA;AACzB,IAAA,MAAM,IAAIkB,oBAAA,CAAc,CAAA,uBAAA,EAA0B,QAAQ,CAAA,CAAA,CAAG,CAAA;AAAA,EAC/D,CAAC,CAAA;AAED,EAAA,OAAOlB,QAAA;AACT;;;;"}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* Copyright 2025 The Backstage Authors
|
|
3
|
+
*
|
|
4
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
5
|
+
* you may not use this file except in compliance with the License.
|
|
6
|
+
* You may obtain a copy of the License at
|
|
7
|
+
*
|
|
8
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
9
|
+
*
|
|
10
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
11
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
12
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
13
|
+
* See the License for the specific language governing permissions and
|
|
14
|
+
* limitations under the License.
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
// @ts-check
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* @param {import('knex').Knex} knex
|
|
21
|
+
*/
|
|
22
|
+
exports.up = async function up(knex) {
|
|
23
|
+
await knex.schema.alterTable('oauth_authorization_sessions', table => {
|
|
24
|
+
table.text('state', 'longtext').nullable().alter();
|
|
25
|
+
});
|
|
26
|
+
};
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* @param {import('knex').Knex} knex
|
|
30
|
+
*/
|
|
31
|
+
exports.down = async function down(knex) {
|
|
32
|
+
// Delete sessions with state > 255 chars since they won't fit in varchar(255)
|
|
33
|
+
// These sessions would be unusable with truncated state anyway
|
|
34
|
+
await knex('oauth_authorization_sessions')
|
|
35
|
+
.whereRaw('LENGTH(state) > 255')
|
|
36
|
+
.delete();
|
|
37
|
+
|
|
38
|
+
await knex.schema.alterTable('oauth_authorization_sessions', table => {
|
|
39
|
+
table.string('state').nullable().alter();
|
|
40
|
+
});
|
|
41
|
+
};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@backstage/plugin-auth-backend",
|
|
3
|
-
"version": "0.25.6
|
|
3
|
+
"version": "0.25.6",
|
|
4
4
|
"description": "A Backstage backend plugin that handles authentication",
|
|
5
5
|
"backstage": {
|
|
6
6
|
"role": "backend-plugin",
|
|
@@ -47,13 +47,13 @@
|
|
|
47
47
|
"test": "backstage-cli package test"
|
|
48
48
|
},
|
|
49
49
|
"dependencies": {
|
|
50
|
-
"@backstage/backend-plugin-api": "1.
|
|
51
|
-
"@backstage/catalog-model": "1.7.6
|
|
52
|
-
"@backstage/config": "1.3.6
|
|
53
|
-
"@backstage/errors": "1.2.7",
|
|
54
|
-
"@backstage/plugin-auth-node": "0.6.9
|
|
55
|
-
"@backstage/plugin-catalog-node": "1.
|
|
56
|
-
"@backstage/types": "1.2.2",
|
|
50
|
+
"@backstage/backend-plugin-api": "^1.5.0",
|
|
51
|
+
"@backstage/catalog-model": "^1.7.6",
|
|
52
|
+
"@backstage/config": "^1.3.6",
|
|
53
|
+
"@backstage/errors": "^1.2.7",
|
|
54
|
+
"@backstage/plugin-auth-node": "^0.6.9",
|
|
55
|
+
"@backstage/plugin-catalog-node": "^1.20.0",
|
|
56
|
+
"@backstage/types": "^1.2.2",
|
|
57
57
|
"@google-cloud/firestore": "^7.0.0",
|
|
58
58
|
"connect-session-knex": "^4.0.0",
|
|
59
59
|
"cookie-parser": "^1.4.5",
|
|
@@ -70,11 +70,11 @@
|
|
|
70
70
|
"uuid": "^11.0.0"
|
|
71
71
|
},
|
|
72
72
|
"devDependencies": {
|
|
73
|
-
"@backstage/backend-defaults": "0.13.1
|
|
74
|
-
"@backstage/backend-test-utils": "1.10.0
|
|
75
|
-
"@backstage/cli": "0.34.5
|
|
76
|
-
"@backstage/plugin-auth-backend-module-google-provider": "0.3.9
|
|
77
|
-
"@backstage/plugin-auth-backend-module-guest-provider": "0.2.14
|
|
73
|
+
"@backstage/backend-defaults": "^0.13.1",
|
|
74
|
+
"@backstage/backend-test-utils": "^1.10.0",
|
|
75
|
+
"@backstage/cli": "^0.34.5",
|
|
76
|
+
"@backstage/plugin-auth-backend-module-google-provider": "^0.3.9",
|
|
77
|
+
"@backstage/plugin-auth-backend-module-guest-provider": "^0.2.14",
|
|
78
78
|
"@types/cookie-parser": "^1.4.2",
|
|
79
79
|
"@types/express": "^4.17.6",
|
|
80
80
|
"@types/express-session": "^1.17.2",
|
|
@@ -1,27 +0,0 @@
|
|
|
1
|
-
'use strict';
|
|
2
|
-
|
|
3
|
-
var config = require('@backstage/config');
|
|
4
|
-
var types = require('@backstage/types');
|
|
5
|
-
|
|
6
|
-
const TOKEN_EXP_DEFAULT_S = 3600;
|
|
7
|
-
const TOKEN_EXP_MIN_S = 600;
|
|
8
|
-
const TOKEN_EXP_MAX_S = 86400;
|
|
9
|
-
function readBackstageTokenExpiration(config$1) {
|
|
10
|
-
const processingIntervalKey = "auth.backstageTokenExpiration";
|
|
11
|
-
if (!config$1.has(processingIntervalKey)) {
|
|
12
|
-
return TOKEN_EXP_DEFAULT_S;
|
|
13
|
-
}
|
|
14
|
-
const duration = config.readDurationFromConfig(config$1, {
|
|
15
|
-
key: processingIntervalKey
|
|
16
|
-
});
|
|
17
|
-
const durationS = Math.round(types.durationToMilliseconds(duration) / 1e3);
|
|
18
|
-
if (durationS < TOKEN_EXP_MIN_S) {
|
|
19
|
-
return TOKEN_EXP_MIN_S;
|
|
20
|
-
} else if (durationS > TOKEN_EXP_MAX_S) {
|
|
21
|
-
return TOKEN_EXP_MAX_S;
|
|
22
|
-
}
|
|
23
|
-
return durationS;
|
|
24
|
-
}
|
|
25
|
-
|
|
26
|
-
exports.readBackstageTokenExpiration = readBackstageTokenExpiration;
|
|
27
|
-
//# sourceMappingURL=readBackstageTokenExpiration.cjs.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"readBackstageTokenExpiration.cjs.js","sources":["../../src/service/readBackstageTokenExpiration.ts"],"sourcesContent":["/*\n * Copyright 2024 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { 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"],"names":["config","readDurationFromConfig","durationToMilliseconds"],"mappings":";;;;;AAoBA,MAAM,mBAAA,GAAsB,IAAA;AAC5B,MAAM,eAAA,GAAkB,GAAA;AACxB,MAAM,eAAA,GAAkB,KAAA;AAEjB,SAAS,6BAA6BA,QAAA,EAA2B;AACtE,EAAA,MAAM,qBAAA,GAAwB,+BAAA;AAE9B,EAAA,IAAI,CAACA,QAAA,CAAO,GAAA,CAAI,qBAAqB,CAAA,EAAG;AACtC,IAAA,OAAO,mBAAA;AAAA,EACT;AAEA,EAAA,MAAM,QAAA,GAAWC,8BAAuBD,QAAA,EAAQ;AAAA,IAC9C,GAAA,EAAK;AAAA,GACN,CAAA;AAED,EAAA,MAAM,YAAY,IAAA,CAAK,KAAA,CAAME,4BAAA,CAAuB,QAAQ,IAAI,GAAI,CAAA;AAEpE,EAAA,IAAI,YAAY,eAAA,EAAiB;AAC/B,IAAA,OAAO,eAAA;AAAA,EACT,CAAA,MAAA,IAAW,YAAY,eAAA,EAAiB;AACtC,IAAA,OAAO,eAAA;AAAA,EACT;AACA,EAAA,OAAO,SAAA;AACT;;;;"}
|