@backstage/plugin-auth-backend 0.23.1-next.0 → 0.23.1-next.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +31 -0
- package/dist/authPlugin.cjs.js +75 -0
- package/dist/authPlugin.cjs.js.map +1 -0
- package/dist/database/AuthDatabase.cjs.js +51 -0
- package/dist/database/AuthDatabase.cjs.js.map +1 -0
- package/dist/identity/DatabaseKeyStore.cjs.js +40 -0
- package/dist/identity/DatabaseKeyStore.cjs.js.map +1 -0
- package/dist/identity/FirestoreKeyStore.cjs.js +90 -0
- package/dist/identity/FirestoreKeyStore.cjs.js.map +1 -0
- package/dist/identity/KeyStores.cjs.js +54 -0
- package/dist/identity/KeyStores.cjs.js.map +1 -0
- package/dist/identity/MemoryKeyStore.cjs.js +29 -0
- package/dist/identity/MemoryKeyStore.cjs.js.map +1 -0
- package/dist/identity/StaticKeyStore.cjs.js +91 -0
- package/dist/identity/StaticKeyStore.cjs.js.map +1 -0
- package/dist/identity/StaticTokenIssuer.cjs.js +53 -0
- package/dist/identity/StaticTokenIssuer.cjs.js.map +1 -0
- package/dist/identity/TokenFactory.cjs.js +164 -0
- package/dist/identity/TokenFactory.cjs.js.map +1 -0
- package/dist/identity/UserInfoDatabaseHandler.cjs.js +30 -0
- package/dist/identity/UserInfoDatabaseHandler.cjs.js.map +1 -0
- package/dist/identity/router.cjs.js +77 -0
- package/dist/identity/router.cjs.js.map +1 -0
- package/dist/index.cjs.js +31 -1981
- package/dist/index.cjs.js.map +1 -1
- package/dist/lib/catalog/CatalogIdentityClient.cjs.js +94 -0
- package/dist/lib/catalog/CatalogIdentityClient.cjs.js.map +1 -0
- package/dist/lib/flow/authFlowHelpers.cjs.js +43 -0
- package/dist/lib/flow/authFlowHelpers.cjs.js.map +1 -0
- package/dist/lib/legacy/adaptLegacyOAuthHandler.cjs.js +20 -0
- package/dist/lib/legacy/adaptLegacyOAuthHandler.cjs.js.map +1 -0
- package/dist/lib/legacy/adaptLegacyOAuthSignInResolver.cjs.js +24 -0
- package/dist/lib/legacy/adaptLegacyOAuthSignInResolver.cjs.js.map +1 -0
- package/dist/lib/legacy/adaptOAuthSignInResolverToLegacy.cjs.js +29 -0
- package/dist/lib/legacy/adaptOAuthSignInResolverToLegacy.cjs.js.map +1 -0
- package/dist/lib/oauth/OAuthAdapter.cjs.js +220 -0
- package/dist/lib/oauth/OAuthAdapter.cjs.js.map +1 -0
- package/dist/lib/oauth/OAuthEnvironmentHandler.cjs.js +8 -0
- package/dist/lib/oauth/OAuthEnvironmentHandler.cjs.js.map +1 -0
- package/dist/lib/oauth/helpers.cjs.js +40 -0
- package/dist/lib/oauth/helpers.cjs.js.map +1 -0
- package/dist/lib/passport/PassportStrategyHelper.cjs.js +48 -0
- package/dist/lib/passport/PassportStrategyHelper.cjs.js.map +1 -0
- package/dist/lib/resolvers/CatalogAuthResolverContext.cjs.js +116 -0
- package/dist/lib/resolvers/CatalogAuthResolverContext.cjs.js.map +1 -0
- package/dist/providers/atlassian/provider.cjs.js +20 -0
- package/dist/providers/atlassian/provider.cjs.js.map +1 -0
- package/dist/providers/auth0/provider.cjs.js +20 -0
- package/dist/providers/auth0/provider.cjs.js.map +1 -0
- package/dist/providers/aws-alb/provider.cjs.js +18 -0
- package/dist/providers/aws-alb/provider.cjs.js.map +1 -0
- package/dist/providers/azure-easyauth/provider.cjs.js +18 -0
- package/dist/providers/azure-easyauth/provider.cjs.js.map +1 -0
- package/dist/providers/bitbucket/provider.cjs.js +25 -0
- package/dist/providers/bitbucket/provider.cjs.js.map +1 -0
- package/dist/providers/bitbucketServer/provider.cjs.js +46 -0
- package/dist/providers/bitbucketServer/provider.cjs.js.map +1 -0
- package/dist/providers/cloudflare-access/provider.cjs.js +22 -0
- package/dist/providers/cloudflare-access/provider.cjs.js.map +1 -0
- package/dist/providers/createAuthProviderIntegration.cjs.js +11 -0
- package/dist/providers/createAuthProviderIntegration.cjs.js.map +1 -0
- package/dist/providers/gcp-iap/provider.cjs.js +18 -0
- package/dist/providers/gcp-iap/provider.cjs.js.map +1 -0
- package/dist/providers/github/provider.cjs.js +61 -0
- package/dist/providers/github/provider.cjs.js.map +1 -0
- package/dist/providers/gitlab/provider.cjs.js +20 -0
- package/dist/providers/gitlab/provider.cjs.js.map +1 -0
- package/dist/providers/google/provider.cjs.js +26 -0
- package/dist/providers/google/provider.cjs.js.map +1 -0
- package/dist/providers/microsoft/provider.cjs.js +27 -0
- package/dist/providers/microsoft/provider.cjs.js.map +1 -0
- package/dist/providers/oauth2/provider.cjs.js +20 -0
- package/dist/providers/oauth2/provider.cjs.js.map +1 -0
- package/dist/providers/oauth2-proxy/provider.cjs.js +18 -0
- package/dist/providers/oauth2-proxy/provider.cjs.js.map +1 -0
- package/dist/providers/oidc/provider.cjs.js +37 -0
- package/dist/providers/oidc/provider.cjs.js.map +1 -0
- package/dist/providers/okta/provider.cjs.js +47 -0
- package/dist/providers/okta/provider.cjs.js.map +1 -0
- package/dist/providers/onelogin/provider.cjs.js +20 -0
- package/dist/providers/onelogin/provider.cjs.js.map +1 -0
- package/dist/providers/prepareBackstageIdentityResponse.cjs.js +8 -0
- package/dist/providers/prepareBackstageIdentityResponse.cjs.js.map +1 -0
- package/dist/providers/providers.cjs.js +62 -0
- package/dist/providers/providers.cjs.js.map +1 -0
- package/dist/providers/resolvers.cjs.js +27 -0
- package/dist/providers/resolvers.cjs.js.map +1 -0
- package/dist/providers/router.cjs.js +111 -0
- package/dist/providers/router.cjs.js.map +1 -0
- package/dist/providers/saml/provider.cjs.js +121 -0
- package/dist/providers/saml/provider.cjs.js.map +1 -0
- package/dist/service/readBackstageTokenExpiration.cjs.js +27 -0
- package/dist/service/readBackstageTokenExpiration.cjs.js.map +1 -0
- package/dist/service/router.cjs.js +127 -0
- package/dist/service/router.cjs.js.map +1 -0
- package/package.json +29 -29
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
var catalogModel = require('@backstage/catalog-model');
|
|
4
|
+
var errors = require('@backstage/errors');
|
|
5
|
+
var jose = require('jose');
|
|
6
|
+
var lodash = require('lodash');
|
|
7
|
+
var luxon = require('luxon');
|
|
8
|
+
var uuid = require('uuid');
|
|
9
|
+
var pluginAuthNode = require('@backstage/plugin-auth-node');
|
|
10
|
+
|
|
11
|
+
const MS_IN_S = 1e3;
|
|
12
|
+
const MAX_TOKEN_LENGTH = 32768;
|
|
13
|
+
class TokenFactory {
|
|
14
|
+
issuer;
|
|
15
|
+
logger;
|
|
16
|
+
keyStore;
|
|
17
|
+
keyDurationSeconds;
|
|
18
|
+
algorithm;
|
|
19
|
+
userInfoDatabaseHandler;
|
|
20
|
+
keyExpiry;
|
|
21
|
+
privateKeyPromise;
|
|
22
|
+
constructor(options) {
|
|
23
|
+
this.issuer = options.issuer;
|
|
24
|
+
this.logger = options.logger;
|
|
25
|
+
this.keyStore = options.keyStore;
|
|
26
|
+
this.keyDurationSeconds = options.keyDurationSeconds;
|
|
27
|
+
this.algorithm = options.algorithm ?? "ES256";
|
|
28
|
+
this.userInfoDatabaseHandler = options.userInfoDatabaseHandler;
|
|
29
|
+
}
|
|
30
|
+
async issueToken(params) {
|
|
31
|
+
const key = await this.getKey();
|
|
32
|
+
const iss = this.issuer;
|
|
33
|
+
const { sub, ent = [sub], ...additionalClaims } = params.claims;
|
|
34
|
+
const aud = pluginAuthNode.tokenTypes.user.audClaim;
|
|
35
|
+
const iat = Math.floor(Date.now() / MS_IN_S);
|
|
36
|
+
const exp = iat + this.keyDurationSeconds;
|
|
37
|
+
try {
|
|
38
|
+
catalogModel.parseEntityRef(sub);
|
|
39
|
+
} catch (error) {
|
|
40
|
+
throw new Error(
|
|
41
|
+
'"sub" claim provided by the auth resolver is not a valid EntityRef.'
|
|
42
|
+
);
|
|
43
|
+
}
|
|
44
|
+
if (!key.alg) {
|
|
45
|
+
throw new errors.AuthenticationError("No algorithm was provided in the key");
|
|
46
|
+
}
|
|
47
|
+
this.logger.info(`Issuing token for ${sub}, with entities ${ent}`);
|
|
48
|
+
const signingKey = await jose.importJWK(key);
|
|
49
|
+
const uip = await this.createUserIdentityClaim({
|
|
50
|
+
header: {
|
|
51
|
+
typ: pluginAuthNode.tokenTypes.limitedUser.typParam,
|
|
52
|
+
alg: key.alg,
|
|
53
|
+
kid: key.kid
|
|
54
|
+
},
|
|
55
|
+
payload: { sub, iat, exp },
|
|
56
|
+
key: signingKey
|
|
57
|
+
});
|
|
58
|
+
const claims = {
|
|
59
|
+
...additionalClaims,
|
|
60
|
+
iss,
|
|
61
|
+
sub,
|
|
62
|
+
ent,
|
|
63
|
+
aud,
|
|
64
|
+
iat,
|
|
65
|
+
exp,
|
|
66
|
+
uip
|
|
67
|
+
};
|
|
68
|
+
const token = await new jose.SignJWT(claims).setProtectedHeader({
|
|
69
|
+
typ: pluginAuthNode.tokenTypes.user.typParam,
|
|
70
|
+
alg: key.alg,
|
|
71
|
+
kid: key.kid
|
|
72
|
+
}).sign(signingKey);
|
|
73
|
+
if (token.length > MAX_TOKEN_LENGTH) {
|
|
74
|
+
throw new Error(
|
|
75
|
+
`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(
|
|
76
|
+
claims
|
|
77
|
+
)}'`
|
|
78
|
+
);
|
|
79
|
+
}
|
|
80
|
+
await this.userInfoDatabaseHandler.addUserInfo({
|
|
81
|
+
claims: lodash.omit(claims, ["aud", "iat", "iss", "uip"])
|
|
82
|
+
});
|
|
83
|
+
return token;
|
|
84
|
+
}
|
|
85
|
+
// This will be called by other services that want to verify ID tokens.
|
|
86
|
+
// It is important that it returns a list of all public keys that could
|
|
87
|
+
// have been used to sign tokens that have not yet expired.
|
|
88
|
+
async listPublicKeys() {
|
|
89
|
+
const { items: keys } = await this.keyStore.listKeys();
|
|
90
|
+
const validKeys = [];
|
|
91
|
+
const expiredKeys = [];
|
|
92
|
+
for (const key of keys) {
|
|
93
|
+
const expireAt = luxon.DateTime.fromJSDate(key.createdAt).plus({
|
|
94
|
+
seconds: 3 * this.keyDurationSeconds
|
|
95
|
+
});
|
|
96
|
+
if (expireAt < luxon.DateTime.local()) {
|
|
97
|
+
expiredKeys.push(key);
|
|
98
|
+
} else {
|
|
99
|
+
validKeys.push(key);
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
if (expiredKeys.length > 0) {
|
|
103
|
+
const kids = expiredKeys.map(({ key }) => key.kid);
|
|
104
|
+
this.logger.info(`Removing expired signing keys, '${kids.join("', '")}'`);
|
|
105
|
+
this.keyStore.removeKeys(kids).catch((error) => {
|
|
106
|
+
this.logger.error(`Failed to remove expired keys, ${error}`);
|
|
107
|
+
});
|
|
108
|
+
}
|
|
109
|
+
return { keys: validKeys.map(({ key }) => key) };
|
|
110
|
+
}
|
|
111
|
+
async getKey() {
|
|
112
|
+
if (this.privateKeyPromise) {
|
|
113
|
+
if (this.keyExpiry && luxon.DateTime.fromJSDate(this.keyExpiry) > luxon.DateTime.local()) {
|
|
114
|
+
return this.privateKeyPromise;
|
|
115
|
+
}
|
|
116
|
+
this.logger.info(`Signing key has expired, generating new key`);
|
|
117
|
+
delete this.privateKeyPromise;
|
|
118
|
+
}
|
|
119
|
+
this.keyExpiry = luxon.DateTime.utc().plus({
|
|
120
|
+
seconds: this.keyDurationSeconds
|
|
121
|
+
}).toJSDate();
|
|
122
|
+
const promise = (async () => {
|
|
123
|
+
const key = await jose.generateKeyPair(this.algorithm);
|
|
124
|
+
const publicKey = await jose.exportJWK(key.publicKey);
|
|
125
|
+
const privateKey = await jose.exportJWK(key.privateKey);
|
|
126
|
+
publicKey.kid = privateKey.kid = uuid.v4();
|
|
127
|
+
publicKey.alg = privateKey.alg = this.algorithm;
|
|
128
|
+
this.logger.info(`Created new signing key ${publicKey.kid}`);
|
|
129
|
+
await this.keyStore.addKey(publicKey);
|
|
130
|
+
return privateKey;
|
|
131
|
+
})();
|
|
132
|
+
this.privateKeyPromise = promise;
|
|
133
|
+
try {
|
|
134
|
+
await promise;
|
|
135
|
+
} catch (error) {
|
|
136
|
+
this.logger.error(`Failed to generate new signing key, ${error}`);
|
|
137
|
+
delete this.keyExpiry;
|
|
138
|
+
delete this.privateKeyPromise;
|
|
139
|
+
}
|
|
140
|
+
return promise;
|
|
141
|
+
}
|
|
142
|
+
// Creates a string claim that can be used as part of reconstructing a limited
|
|
143
|
+
// user token. The output of this function is only the signature part of a
|
|
144
|
+
// JWS.
|
|
145
|
+
async createUserIdentityClaim(options) {
|
|
146
|
+
const header = {
|
|
147
|
+
typ: options.header.typ,
|
|
148
|
+
alg: options.header.alg,
|
|
149
|
+
...options.header.kid ? { kid: options.header.kid } : {}
|
|
150
|
+
};
|
|
151
|
+
const payload = {
|
|
152
|
+
sub: options.payload.sub,
|
|
153
|
+
iat: options.payload.iat,
|
|
154
|
+
exp: options.payload.exp
|
|
155
|
+
};
|
|
156
|
+
const jws = await new jose.GeneralSign(
|
|
157
|
+
new TextEncoder().encode(JSON.stringify(payload))
|
|
158
|
+
).addSignature(options.key).setProtectedHeader(header).done().sign();
|
|
159
|
+
return jws.signatures[0].signature;
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
exports.TokenFactory = TokenFactory;
|
|
164
|
+
//# sourceMappingURL=TokenFactory.cjs.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"TokenFactory.cjs.js","sources":["../../src/identity/TokenFactory.ts"],"sourcesContent":["/*\n * Copyright 2020 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { parseEntityRef } from '@backstage/catalog-model';\nimport { AuthenticationError } from '@backstage/errors';\nimport {\n exportJWK,\n generateKeyPair,\n importJWK,\n JWK,\n SignJWT,\n GeneralSign,\n KeyLike,\n} from 'jose';\nimport { omit } from 'lodash';\nimport { DateTime } from 'luxon';\nimport { v4 as uuid } from 'uuid';\nimport { LoggerService } from '@backstage/backend-plugin-api';\nimport { TokenParams, tokenTypes } from '@backstage/plugin-auth-node';\nimport { AnyJWK, KeyStore, TokenIssuer } from './types';\nimport { JsonValue } from '@backstage/types';\nimport { UserInfoDatabaseHandler } from './UserInfoDatabaseHandler';\n\nconst MS_IN_S = 1000;\nconst MAX_TOKEN_LENGTH = 32768; // At 64 bytes per entity ref this still leaves room for about 500 entities\n\n/**\n * The payload contents of a valid Backstage JWT token\n */\nexport interface BackstageTokenPayload {\n /**\n * The issuer of the token, currently the discovery URL of the auth backend\n */\n iss: string;\n\n /**\n * The entity ref of the user\n */\n sub: string;\n\n /**\n * The entity refs that the user claims ownership througg\n */\n ent: string[];\n\n /**\n * A hard coded audience string\n */\n aud: typeof tokenTypes.user.audClaim;\n\n /**\n * Standard expiry in epoch seconds\n */\n exp: number;\n\n /**\n * Standard issue time in epoch seconds\n */\n iat: number;\n\n /**\n * A separate user identity proof that the auth service can convert to a limited user token\n */\n uip: string;\n\n /**\n * Any other custom claims that the adopter may have added\n */\n [claim: string]: JsonValue;\n}\n\n/**\n * The payload contents of a valid Backstage user identity claim token\n *\n * @internal\n */\ninterface BackstageUserIdentityProofPayload {\n /**\n * The entity ref of the user\n */\n sub: string;\n\n /**\n * Standard expiry in epoch seconds\n */\n exp: number;\n\n /**\n * Standard issue time in epoch seconds\n */\n iat: number;\n}\n\ntype Options = {\n logger: LoggerService;\n /** Value of the issuer claim in issued tokens */\n issuer: string;\n /** Key store used for storing signing keys */\n keyStore: KeyStore;\n /** Expiration time of signing keys in seconds */\n keyDurationSeconds: number;\n /** JWS \"alg\" (Algorithm) Header Parameter value. Defaults to ES256.\n * Must match one of the algorithms defined for IdentityClient.\n * When setting a different algorithm, check if the `key` field\n * of the `signing_keys` table can fit the length of the generated keys.\n * If not, add a knex migration file in the migrations folder.\n * More info on supported algorithms: https://github.com/panva/jose */\n algorithm?: string;\n userInfoDatabaseHandler: UserInfoDatabaseHandler;\n};\n\n/**\n * A token issuer that is able to issue tokens in a distributed system\n * backed by a single database. Tokens are issued using lazily generated\n * signing keys, where each running instance of the auth service uses its own\n * signing key.\n *\n * The public parts of the keys are all stored in the shared key storage,\n * and any of the instances of the auth service will return the full list\n * of public keys that are currently in storage.\n *\n * Signing keys are automatically rotated at the same interval as the token\n * duration. Expired keys are kept in storage until there are no valid tokens\n * in circulation that could have been signed by that key.\n */\nexport class TokenFactory implements TokenIssuer {\n private readonly issuer: string;\n private readonly logger: LoggerService;\n private readonly keyStore: KeyStore;\n private readonly keyDurationSeconds: number;\n private readonly algorithm: string;\n private readonly userInfoDatabaseHandler: UserInfoDatabaseHandler;\n\n private keyExpiry?: Date;\n private privateKeyPromise?: Promise<JWK>;\n\n constructor(options: Options) {\n this.issuer = options.issuer;\n this.logger = options.logger;\n this.keyStore = options.keyStore;\n this.keyDurationSeconds = options.keyDurationSeconds;\n this.algorithm = options.algorithm ?? 'ES256';\n this.userInfoDatabaseHandler = options.userInfoDatabaseHandler;\n }\n\n async issueToken(params: TokenParams): Promise<string> {\n const key = await this.getKey();\n\n const iss = this.issuer;\n const { sub, ent = [sub], ...additionalClaims } = params.claims;\n const aud = tokenTypes.user.audClaim;\n const iat = Math.floor(Date.now() / MS_IN_S);\n const exp = iat + this.keyDurationSeconds;\n\n try {\n // The subject must be a valid entity ref\n parseEntityRef(sub);\n } catch (error) {\n throw new Error(\n '\"sub\" claim provided by the auth resolver is not a valid EntityRef.',\n );\n }\n\n if (!key.alg) {\n throw new AuthenticationError('No algorithm was provided in the key');\n }\n\n this.logger.info(`Issuing token for ${sub}, with entities ${ent}`);\n\n const signingKey = await importJWK(key);\n\n const uip = await this.createUserIdentityClaim({\n header: {\n typ: tokenTypes.limitedUser.typParam,\n alg: key.alg,\n kid: key.kid,\n },\n payload: { sub, iat, exp },\n key: signingKey,\n });\n\n const claims: BackstageTokenPayload = {\n ...additionalClaims,\n iss,\n sub,\n ent,\n aud,\n iat,\n exp,\n uip,\n };\n\n const token = await new SignJWT(claims)\n .setProtectedHeader({\n typ: tokenTypes.user.typParam,\n alg: key.alg,\n kid: key.kid,\n })\n .sign(signingKey);\n\n if (token.length > MAX_TOKEN_LENGTH) {\n throw new Error(\n `Failed to issue a new user token. The resulting token is excessively large, with either too many ownership claims or too large custom claims. You likely have a bug either in the sign-in resolver or catalog data. The following claims were requested: '${JSON.stringify(\n claims,\n )}'`,\n );\n }\n\n // Store the user info in the database upon successful token\n // issuance so that it can be retrieved later by limited user tokens\n await this.userInfoDatabaseHandler.addUserInfo({\n claims: omit(claims, ['aud', 'iat', 'iss', 'uip']),\n });\n\n return token;\n }\n\n // This will be called by other services that want to verify ID tokens.\n // It is important that it returns a list of all public keys that could\n // have been used to sign tokens that have not yet expired.\n async listPublicKeys(): Promise<{ keys: AnyJWK[] }> {\n const { items: keys } = await this.keyStore.listKeys();\n\n const validKeys = [];\n const expiredKeys = [];\n\n for (const key of keys) {\n // Allow for a grace period of another full key duration before we remove the keys from the database\n const expireAt = DateTime.fromJSDate(key.createdAt).plus({\n seconds: 3 * this.keyDurationSeconds,\n });\n if (expireAt < DateTime.local()) {\n expiredKeys.push(key);\n } else {\n validKeys.push(key);\n }\n }\n\n // Lazily prune expired keys. This may cause duplicate removals if we have concurrent callers, but w/e\n if (expiredKeys.length > 0) {\n const kids = expiredKeys.map(({ key }) => key.kid);\n\n this.logger.info(`Removing expired signing keys, '${kids.join(\"', '\")}'`);\n\n // We don't await this, just let it run in the background\n this.keyStore.removeKeys(kids).catch(error => {\n this.logger.error(`Failed to remove expired keys, ${error}`);\n });\n }\n\n // NOTE: we're currently only storing public keys, but if we start storing private keys we'd have to convert here\n return { keys: validKeys.map(({ key }) => key) };\n }\n\n private async getKey(): Promise<JWK> {\n // Make sure that we only generate one key at a time\n if (this.privateKeyPromise) {\n if (\n this.keyExpiry &&\n DateTime.fromJSDate(this.keyExpiry) > DateTime.local()\n ) {\n return this.privateKeyPromise;\n }\n this.logger.info(`Signing key has expired, generating new key`);\n delete this.privateKeyPromise;\n }\n\n this.keyExpiry = DateTime.utc()\n .plus({\n seconds: this.keyDurationSeconds,\n })\n .toJSDate();\n const promise = (async () => {\n // This generates a new signing key to be used to sign tokens until the next key rotation\n const key = await generateKeyPair(this.algorithm);\n const publicKey = await exportJWK(key.publicKey);\n const privateKey = await exportJWK(key.privateKey);\n publicKey.kid = privateKey.kid = uuid();\n publicKey.alg = privateKey.alg = this.algorithm;\n\n // We're not allowed to use the key until it has been successfully stored\n // TODO: some token verification implementations aggressively cache the list of keys, and\n // don't attempt to fetch new ones even if they encounter an unknown kid. Therefore we\n // may want to keep using the existing key for some period of time until we switch to\n // the new one. This also needs to be implemented cross-service though, meaning new services\n // that boot up need to be able to grab an existing key to use for signing.\n this.logger.info(`Created new signing key ${publicKey.kid}`);\n await this.keyStore.addKey(publicKey as AnyJWK);\n\n // At this point we are allowed to start using the new key\n return privateKey;\n })();\n\n this.privateKeyPromise = promise;\n\n try {\n // If we fail to generate a new key, we need to clear the state so that\n // the next caller will try to generate another key.\n await promise;\n } catch (error) {\n this.logger.error(`Failed to generate new signing key, ${error}`);\n delete this.keyExpiry;\n delete this.privateKeyPromise;\n }\n\n return promise;\n }\n\n // Creates a string claim that can be used as part of reconstructing a limited\n // user token. The output of this function is only the signature part of a\n // JWS.\n private async createUserIdentityClaim(options: {\n header: {\n typ: string;\n alg: string;\n kid?: string;\n };\n payload: BackstageUserIdentityProofPayload;\n key: KeyLike | Uint8Array;\n }): Promise<string> {\n // NOTE: We reconstruct the header and payload structures carefully to\n // perfectly guarantee ordering. The reason for this is that we store only\n // the signature part of these to reduce duplication within the Backstage\n // token. Anyone who wants to make an actual JWT based on all this must be\n // able to do the EXACT reconstruction of the header and payload parts, to\n // then append the signature.\n\n const header = {\n typ: options.header.typ,\n alg: options.header.alg,\n ...(options.header.kid ? { kid: options.header.kid } : {}),\n };\n\n const payload = {\n sub: options.payload.sub,\n iat: options.payload.iat,\n exp: options.payload.exp,\n };\n\n const jws = await new GeneralSign(\n new TextEncoder().encode(JSON.stringify(payload)),\n )\n .addSignature(options.key)\n .setProtectedHeader(header)\n .done()\n .sign();\n\n return jws.signatures[0].signature;\n }\n}\n"],"names":["tokenTypes","parseEntityRef","AuthenticationError","importJWK","SignJWT","omit","DateTime","generateKeyPair","exportJWK","uuid","GeneralSign"],"mappings":";;;;;;;;;;AAoCA,MAAM,OAAU,GAAA,GAAA,CAAA;AAChB,MAAM,gBAAmB,GAAA,KAAA,CAAA;AAqGlB,MAAM,YAAoC,CAAA;AAAA,EAC9B,MAAA,CAAA;AAAA,EACA,MAAA,CAAA;AAAA,EACA,QAAA,CAAA;AAAA,EACA,kBAAA,CAAA;AAAA,EACA,SAAA,CAAA;AAAA,EACA,uBAAA,CAAA;AAAA,EAET,SAAA,CAAA;AAAA,EACA,iBAAA,CAAA;AAAA,EAER,YAAY,OAAkB,EAAA;AAC5B,IAAA,IAAA,CAAK,SAAS,OAAQ,CAAA,MAAA,CAAA;AACtB,IAAA,IAAA,CAAK,SAAS,OAAQ,CAAA,MAAA,CAAA;AACtB,IAAA,IAAA,CAAK,WAAW,OAAQ,CAAA,QAAA,CAAA;AACxB,IAAA,IAAA,CAAK,qBAAqB,OAAQ,CAAA,kBAAA,CAAA;AAClC,IAAK,IAAA,CAAA,SAAA,GAAY,QAAQ,SAAa,IAAA,OAAA,CAAA;AACtC,IAAA,IAAA,CAAK,0BAA0B,OAAQ,CAAA,uBAAA,CAAA;AAAA,GACzC;AAAA,EAEA,MAAM,WAAW,MAAsC,EAAA;AACrD,IAAM,MAAA,GAAA,GAAM,MAAM,IAAA,CAAK,MAAO,EAAA,CAAA;AAE9B,IAAA,MAAM,MAAM,IAAK,CAAA,MAA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GAAA,EAAK,QAAQ,MAAO,CAAA,GAAA;AAAA,MACpB,GAAI,OAAQ,CAAA,MAAA,CAAO,GAAM,GAAA,EAAE,KAAK,OAAQ,CAAA,MAAA,CAAO,GAAI,EAAA,GAAI,EAAC;AAAA,KAC1D,CAAA;AAEA,IAAA,MAAM,OAAU,GAAA;AAAA,MACd,GAAA,EAAK,QAAQ,OAAQ,CAAA,GAAA;AAAA,MACrB,GAAA,EAAK,QAAQ,OAAQ,CAAA,GAAA;AAAA,MACrB,GAAA,EAAK,QAAQ,OAAQ,CAAA,GAAA;AAAA,KACvB,CAAA;AAEA,IAAM,MAAA,GAAA,GAAM,MAAM,IAAIC,gBAAA;AAAA,MACpB,IAAI,WAAY,EAAA,CAAE,OAAO,IAAK,CAAA,SAAA,CAAU,OAAO,CAAC,CAAA;AAAA,KAClD,CACG,YAAa,CAAA,OAAA,CAAQ,GAAG,CAAA,CACxB,mBAAmB,MAAM,CAAA,CACzB,IAAK,EAAA,CACL,IAAK,EAAA,CAAA;AAER,IAAO,OAAA,GAAA,CAAI,UAAW,CAAA,CAAC,CAAE,CAAA,SAAA,CAAA;AAAA,GAC3B;AACF;;;;"}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
var luxon = require('luxon');
|
|
4
|
+
|
|
5
|
+
const TABLE = "user_info";
|
|
6
|
+
class UserInfoDatabaseHandler {
|
|
7
|
+
constructor(client) {
|
|
8
|
+
this.client = client;
|
|
9
|
+
}
|
|
10
|
+
async addUserInfo(userInfo) {
|
|
11
|
+
await this.client(TABLE).insert({
|
|
12
|
+
user_entity_ref: userInfo.claims.sub,
|
|
13
|
+
user_info: JSON.stringify(userInfo),
|
|
14
|
+
exp: luxon.DateTime.fromSeconds(userInfo.claims.exp, {
|
|
15
|
+
zone: "utc"
|
|
16
|
+
}).toSQL({ includeOffset: false })
|
|
17
|
+
}).onConflict("user_entity_ref").merge();
|
|
18
|
+
}
|
|
19
|
+
async getUserInfo(userEntityRef) {
|
|
20
|
+
const info = await this.client(TABLE).where({ user_entity_ref: userEntityRef }).first();
|
|
21
|
+
if (!info) {
|
|
22
|
+
return void 0;
|
|
23
|
+
}
|
|
24
|
+
const userInfo = JSON.parse(info.user_info);
|
|
25
|
+
return userInfo;
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
exports.UserInfoDatabaseHandler = UserInfoDatabaseHandler;
|
|
30
|
+
//# sourceMappingURL=UserInfoDatabaseHandler.cjs.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"UserInfoDatabaseHandler.cjs.js","sources":["../../src/identity/UserInfoDatabaseHandler.ts"],"sourcesContent":["/*\n * Copyright 2024 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { DateTime } from 'luxon';\nimport { Knex } from 'knex';\n\nimport { BackstageTokenPayload } from './TokenFactory';\n\nconst TABLE = 'user_info';\n\ntype Row = {\n user_entity_ref: string;\n user_info: string;\n exp: string;\n};\n\ntype UserInfo = {\n claims: Omit<BackstageTokenPayload, 'aud' | 'iat' | 'iss' | 'uip'>;\n};\n\nexport class UserInfoDatabaseHandler {\n constructor(private readonly client: Knex) {}\n\n async addUserInfo(userInfo: UserInfo): Promise<void> {\n await this.client<Row>(TABLE)\n .insert({\n user_entity_ref: userInfo.claims.sub as string,\n user_info: JSON.stringify(userInfo),\n exp: DateTime.fromSeconds(userInfo.claims.exp as number, {\n zone: 'utc',\n }).toSQL({ includeOffset: false }),\n })\n .onConflict('user_entity_ref')\n .merge();\n }\n\n async getUserInfo(userEntityRef: string): Promise<UserInfo | undefined> {\n const info = await this.client<Row>(TABLE)\n .where({ user_entity_ref: userEntityRef })\n .first();\n\n if (!info) {\n return undefined;\n }\n\n const userInfo = JSON.parse(info.user_info);\n return userInfo;\n }\n}\n"],"names":["DateTime"],"mappings":";;;;AAqBA,MAAM,KAAQ,GAAA,WAAA,CAAA;AAYP,MAAM,uBAAwB,CAAA;AAAA,EACnC,YAA6B,MAAc,EAAA;AAAd,IAAA,IAAA,CAAA,MAAA,GAAA,MAAA,CAAA;AAAA,GAAe;AAAA,EAE5C,MAAM,YAAY,QAAmC,EAAA;AACnD,IAAA,MAAM,IAAK,CAAA,MAAA,CAAY,KAAK,CAAA,CACzB,MAAO,CAAA;AAAA,MACN,eAAA,EAAiB,SAAS,MAAO,CAAA,GAAA;AAAA,MACjC,SAAA,EAAW,IAAK,CAAA,SAAA,CAAU,QAAQ,CAAA;AAAA,MAClC,GAAK,EAAAA,cAAA,CAAS,WAAY,CAAA,QAAA,CAAS,OAAO,GAAe,EAAA;AAAA,QACvD,IAAM,EAAA,KAAA;AAAA,OACP,CAAE,CAAA,KAAA,CAAM,EAAE,aAAA,EAAe,OAAO,CAAA;AAAA,KAClC,CAAA,CACA,UAAW,CAAA,iBAAiB,EAC5B,KAAM,EAAA,CAAA;AAAA,GACX;AAAA,EAEA,MAAM,YAAY,aAAsD,EAAA;AACtE,IAAA,MAAM,IAAO,GAAA,MAAM,IAAK,CAAA,MAAA,CAAY,KAAK,CAAA,CACtC,KAAM,CAAA,EAAE,eAAiB,EAAA,aAAA,EAAe,CAAA,CACxC,KAAM,EAAA,CAAA;AAET,IAAA,IAAI,CAAC,IAAM,EAAA;AACT,MAAO,OAAA,KAAA,CAAA,CAAA;AAAA,KACT;AAEA,IAAA,MAAM,QAAW,GAAA,IAAA,CAAK,KAAM,CAAA,IAAA,CAAK,SAAS,CAAA,CAAA;AAC1C,IAAO,OAAA,QAAA,CAAA;AAAA,GACT;AACF;;;;"}
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
var Router = require('express-promise-router');
|
|
4
|
+
var jose = require('jose');
|
|
5
|
+
var errors = require('@backstage/errors');
|
|
6
|
+
|
|
7
|
+
function _interopDefaultCompat (e) { return e && typeof e === 'object' && 'default' in e ? e : { default: e }; }
|
|
8
|
+
|
|
9
|
+
var Router__default = /*#__PURE__*/_interopDefaultCompat(Router);
|
|
10
|
+
|
|
11
|
+
function bindOidcRouter(targetRouter, options) {
|
|
12
|
+
const { baseUrl, auth, tokenIssuer, userInfoDatabaseHandler } = options;
|
|
13
|
+
const router = Router__default.default();
|
|
14
|
+
targetRouter.use(router);
|
|
15
|
+
const config = {
|
|
16
|
+
issuer: baseUrl,
|
|
17
|
+
token_endpoint: `${baseUrl}/v1/token`,
|
|
18
|
+
userinfo_endpoint: `${baseUrl}/v1/userinfo`,
|
|
19
|
+
jwks_uri: `${baseUrl}/.well-known/jwks.json`,
|
|
20
|
+
response_types_supported: ["id_token"],
|
|
21
|
+
subject_types_supported: ["public"],
|
|
22
|
+
id_token_signing_alg_values_supported: [
|
|
23
|
+
"RS256",
|
|
24
|
+
"RS384",
|
|
25
|
+
"RS512",
|
|
26
|
+
"ES256",
|
|
27
|
+
"ES384",
|
|
28
|
+
"ES512",
|
|
29
|
+
"PS256",
|
|
30
|
+
"PS384",
|
|
31
|
+
"PS512",
|
|
32
|
+
"EdDSA"
|
|
33
|
+
],
|
|
34
|
+
scopes_supported: ["openid"],
|
|
35
|
+
token_endpoint_auth_methods_supported: [],
|
|
36
|
+
claims_supported: ["sub", "ent"],
|
|
37
|
+
grant_types_supported: []
|
|
38
|
+
};
|
|
39
|
+
router.get("/.well-known/openid-configuration", (_req, res) => {
|
|
40
|
+
res.json(config);
|
|
41
|
+
});
|
|
42
|
+
router.get("/.well-known/jwks.json", async (_req, res) => {
|
|
43
|
+
const { keys } = await tokenIssuer.listPublicKeys();
|
|
44
|
+
res.json({ keys });
|
|
45
|
+
});
|
|
46
|
+
router.get("/v1/token", (_req, res) => {
|
|
47
|
+
res.status(501).send("Not Implemented");
|
|
48
|
+
});
|
|
49
|
+
router.get("/v1/userinfo", async (req, res) => {
|
|
50
|
+
const matches = req.headers.authorization?.match(/^Bearer[ ]+(\S+)$/i);
|
|
51
|
+
const token = matches?.[1];
|
|
52
|
+
if (!token) {
|
|
53
|
+
throw new errors.AuthenticationError("No token provided");
|
|
54
|
+
}
|
|
55
|
+
const credentials = await auth.authenticate(token, {
|
|
56
|
+
allowLimitedAccess: true
|
|
57
|
+
});
|
|
58
|
+
if (!auth.isPrincipal(credentials, "user")) {
|
|
59
|
+
throw new errors.InputError(
|
|
60
|
+
"Userinfo endpoint must be called with a token that represents a user principal"
|
|
61
|
+
);
|
|
62
|
+
}
|
|
63
|
+
const { sub: userEntityRef } = jose.decodeJwt(token);
|
|
64
|
+
if (typeof userEntityRef !== "string") {
|
|
65
|
+
throw new Error("Invalid user token, user entity ref must be a string");
|
|
66
|
+
}
|
|
67
|
+
const userInfo = await userInfoDatabaseHandler.getUserInfo(userEntityRef);
|
|
68
|
+
if (!userInfo) {
|
|
69
|
+
res.status(404).send("User info not found");
|
|
70
|
+
return;
|
|
71
|
+
}
|
|
72
|
+
res.json(userInfo);
|
|
73
|
+
});
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
exports.bindOidcRouter = bindOidcRouter;
|
|
77
|
+
//# sourceMappingURL=router.cjs.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"router.cjs.js","sources":["../../src/identity/router.ts"],"sourcesContent":["/*\n * Copyright 2020 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport express from 'express';\nimport Router from 'express-promise-router';\nimport { TokenIssuer } from './types';\nimport { AuthService } from '@backstage/backend-plugin-api';\nimport { decodeJwt } from 'jose';\nimport { AuthenticationError, InputError } from '@backstage/errors';\nimport { UserInfoDatabaseHandler } from './UserInfoDatabaseHandler';\n\nexport function bindOidcRouter(\n targetRouter: express.Router,\n options: {\n baseUrl: string;\n auth: AuthService;\n tokenIssuer: TokenIssuer;\n userInfoDatabaseHandler: UserInfoDatabaseHandler;\n },\n) {\n const { baseUrl, auth, tokenIssuer, userInfoDatabaseHandler } = options;\n\n const router = Router();\n targetRouter.use(router);\n\n const config = {\n issuer: baseUrl,\n token_endpoint: `${baseUrl}/v1/token`,\n userinfo_endpoint: `${baseUrl}/v1/userinfo`,\n jwks_uri: `${baseUrl}/.well-known/jwks.json`,\n response_types_supported: ['id_token'],\n subject_types_supported: ['public'],\n id_token_signing_alg_values_supported: [\n 'RS256',\n 'RS384',\n 'RS512',\n 'ES256',\n 'ES384',\n 'ES512',\n 'PS256',\n 'PS384',\n 'PS512',\n 'EdDSA',\n ],\n scopes_supported: ['openid'],\n token_endpoint_auth_methods_supported: [],\n claims_supported: ['sub', 'ent'],\n grant_types_supported: [],\n };\n\n router.get('/.well-known/openid-configuration', (_req, res) => {\n res.json(config);\n });\n\n router.get('/.well-known/jwks.json', async (_req, res) => {\n const { keys } = await tokenIssuer.listPublicKeys();\n res.json({ keys });\n });\n\n router.get('/v1/token', (_req, res) => {\n res.status(501).send('Not Implemented');\n });\n\n // This endpoint doesn't use the regular HttpAuthService, since the contract\n // is specifically for the header to be communicated in the Authorization\n // header, regardless of token type\n router.get('/v1/userinfo', async (req, res) => {\n const matches = req.headers.authorization?.match(/^Bearer[ ]+(\\S+)$/i);\n const token = matches?.[1];\n if (!token) {\n throw new AuthenticationError('No token provided');\n }\n\n const credentials = await auth.authenticate(token, {\n allowLimitedAccess: true,\n });\n if (!auth.isPrincipal(credentials, 'user')) {\n throw new InputError(\n 'Userinfo endpoint must be called with a token that represents a user principal',\n );\n }\n\n const { sub: userEntityRef } = decodeJwt(token);\n\n if (typeof userEntityRef !== 'string') {\n throw new Error('Invalid user token, user entity ref must be a string');\n }\n\n const userInfo = await userInfoDatabaseHandler.getUserInfo(userEntityRef);\n if (!userInfo) {\n res.status(404).send('User info not found');\n return;\n }\n\n res.json(userInfo);\n });\n}\n"],"names":["Router","AuthenticationError","InputError","decodeJwt"],"mappings":";;;;;;;;;;AAwBgB,SAAA,cAAA,CACd,cACA,OAMA,EAAA;AACA,EAAA,MAAM,EAAE,OAAA,EAAS,IAAM,EAAA,WAAA,EAAa,yBAA4B,GAAA,OAAA,CAAA;AAEhE,EAAA,MAAM,SAASA,uBAAO,EAAA,CAAA;AACtB,EAAA,YAAA,CAAa,IAAI,MAAM,CAAA,CAAA;AAEvB,EAAA,MAAM,MAAS,GAAA;AAAA,IACb,MAAQ,EAAA,OAAA;AAAA,IACR,cAAA,EAAgB,GAAG,OAAO,CAAA,SAAA,CAAA;AAAA,IAC1B,iBAAA,EAAmB,GAAG,OAAO,CAAA,YAAA,CAAA;AAAA,IAC7B,QAAA,EAAU,GAAG,OAAO,CAAA,sBAAA,CAAA;AAAA,IACpB,wBAAA,EAA0B,CAAC,UAAU,CAAA;AAAA,IACrC,uBAAA,EAAyB,CAAC,QAAQ,CAAA;AAAA,IAClC,qCAAuC,EAAA;AAAA,MACrC,OAAA;AAAA,MACA,OAAA;AAAA,MACA,OAAA;AAAA,MACA,OAAA;AAAA,MACA,OAAA;AAAA,MACA,OAAA;AAAA,MACA,OAAA;AAAA,MACA,OAAA;AAAA,MACA,OAAA;AAAA,MACA,OAAA;AAAA,KACF;AAAA,IACA,gBAAA,EAAkB,CAAC,QAAQ,CAAA;AAAA,IAC3B,uCAAuC,EAAC;AAAA,IACxC,gBAAA,EAAkB,CAAC,KAAA,EAAO,KAAK,CAAA;AAAA,IAC/B,uBAAuB,EAAC;AAAA,GAC1B,CAAA;AA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