@backstage/plugin-auth-backend 0.25.0-next.0 → 0.25.0-next.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +56 -0
- package/config.d.ts +9 -0
- package/dist/identity/StaticTokenIssuer.cjs.js +14 -21
- package/dist/identity/StaticTokenIssuer.cjs.js.map +1 -1
- package/dist/identity/TokenFactory.cjs.js +11 -76
- package/dist/identity/TokenFactory.cjs.js.map +1 -1
- package/dist/identity/issueUserToken.cjs.js +98 -0
- package/dist/identity/issueUserToken.cjs.js.map +1 -0
- package/dist/lib/resolvers/CatalogAuthResolverContext.cjs.js +29 -13
- package/dist/lib/resolvers/CatalogAuthResolverContext.cjs.js.map +1 -1
- package/dist/service/router.cjs.js +8 -2
- package/dist/service/router.cjs.js.map +1 -1
- package/package.json +9 -8
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,61 @@
|
|
|
1
1
|
# @backstage/plugin-auth-backend
|
|
2
2
|
|
|
3
|
+
## 0.25.0-next.2
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- ab53e6f: Added support for the new `dangerousEntityRefFallback` option for `signInWithCatalogUser` in `AuthResolverContext`.
|
|
8
|
+
- Updated dependencies
|
|
9
|
+
- @backstage/plugin-auth-node@0.6.3-next.2
|
|
10
|
+
- @backstage/backend-plugin-api@1.3.1-next.2
|
|
11
|
+
- @backstage/catalog-model@1.7.3
|
|
12
|
+
- @backstage/config@1.3.2
|
|
13
|
+
- @backstage/errors@1.2.7
|
|
14
|
+
- @backstage/types@1.2.1
|
|
15
|
+
- @backstage/plugin-catalog-node@1.17.0-next.2
|
|
16
|
+
|
|
17
|
+
## 0.25.0-next.1
|
|
18
|
+
|
|
19
|
+
### Patch Changes
|
|
20
|
+
|
|
21
|
+
- 0d606ac: Added the configuration flag `auth.omitIdentityTokenOwnershipClaim` that causes issued user tokens to no longer contain the `ent` claim that represents the ownership references of the user.
|
|
22
|
+
|
|
23
|
+
The benefit of this new flag is that issued user tokens will be much smaller in
|
|
24
|
+
size, but they will no longer be self-contained. This means that any consumers
|
|
25
|
+
of the token that require access to the ownership claims now need to call the
|
|
26
|
+
`/api/auth/v1/userinfo` endpoint instead. Within the Backstage ecosystem this is
|
|
27
|
+
done automatically, as clients will still receive the full set of claims during
|
|
28
|
+
authentication, while plugin backends will need to use the `UserInfoService`
|
|
29
|
+
which already calls the user info endpoint if necessary.
|
|
30
|
+
|
|
31
|
+
When enabling this flag, it is important that any custom sign-in resolvers directly return the result of the sign-in method. For example, the following would not work:
|
|
32
|
+
|
|
33
|
+
```ts
|
|
34
|
+
const { token } = await ctx.issueToken({
|
|
35
|
+
claims: { sub: entityRef, ent: [entityRef] },
|
|
36
|
+
});
|
|
37
|
+
return { token }; // WARNING: This will not work with the flag enabled
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
Instead, the sign-in resolver should directly return the result:
|
|
41
|
+
|
|
42
|
+
```ts
|
|
43
|
+
return ctx.issueToken({
|
|
44
|
+
claims: { sub: entityRef, ent: [entityRef] },
|
|
45
|
+
});
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
- 72d019d: Removed various typos
|
|
49
|
+
- b128ed9: The `static` key store now issues tokens with the same structure as other key stores. Tokens now include the `typ` field in the header and the `uip` (user identity proof) in the payload.
|
|
50
|
+
- Updated dependencies
|
|
51
|
+
- @backstage/plugin-catalog-node@1.17.0-next.1
|
|
52
|
+
- @backstage/plugin-auth-node@0.6.3-next.1
|
|
53
|
+
- @backstage/backend-plugin-api@1.3.1-next.1
|
|
54
|
+
- @backstage/catalog-model@1.7.3
|
|
55
|
+
- @backstage/config@1.3.2
|
|
56
|
+
- @backstage/errors@1.2.7
|
|
57
|
+
- @backstage/types@1.2.1
|
|
58
|
+
|
|
3
59
|
## 0.25.0-next.0
|
|
4
60
|
|
|
5
61
|
### Minor Changes
|
package/config.d.ts
CHANGED
|
@@ -43,6 +43,15 @@ export interface Config {
|
|
|
43
43
|
*/
|
|
44
44
|
identityTokenAlgorithm?: string;
|
|
45
45
|
|
|
46
|
+
/**
|
|
47
|
+
* Whether to omit the entity ownership references (`ent`) claim from the
|
|
48
|
+
* identity token. If this is enabled the `ent` claim will only be available
|
|
49
|
+
* via the user info endpoint and the `UserInfoService`.
|
|
50
|
+
*
|
|
51
|
+
* Defaults to `false`.
|
|
52
|
+
*/
|
|
53
|
+
omitIdentityTokenOwnershipClaim?: boolean;
|
|
54
|
+
|
|
46
55
|
/** To control how to store JWK data in auth-backend */
|
|
47
56
|
keyStore?: {
|
|
48
57
|
provider?: 'database' | 'memory' | 'firestore' | 'static';
|
|
@@ -1,40 +1,33 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
-
var
|
|
4
|
-
var catalogModel = require('@backstage/catalog-model');
|
|
5
|
-
var errors = require('@backstage/errors');
|
|
3
|
+
var issueUserToken = require('./issueUserToken.cjs.js');
|
|
6
4
|
|
|
7
|
-
const MS_IN_S = 1e3;
|
|
8
5
|
class StaticTokenIssuer {
|
|
9
6
|
issuer;
|
|
10
7
|
logger;
|
|
11
8
|
keyStore;
|
|
12
9
|
sessionExpirationSeconds;
|
|
10
|
+
omitClaimsFromToken;
|
|
11
|
+
userInfoDatabaseHandler;
|
|
13
12
|
constructor(options, keyStore) {
|
|
14
13
|
this.issuer = options.issuer;
|
|
15
14
|
this.logger = options.logger;
|
|
16
15
|
this.sessionExpirationSeconds = options.sessionExpirationSeconds;
|
|
17
16
|
this.keyStore = keyStore;
|
|
17
|
+
this.omitClaimsFromToken = options.omitClaimsFromToken;
|
|
18
|
+
this.userInfoDatabaseHandler = options.userInfoDatabaseHandler;
|
|
18
19
|
}
|
|
19
20
|
async issueToken(params) {
|
|
20
21
|
const key = await this.getSigningKey();
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
'"sub" claim provided by the auth resolver is not a valid EntityRef.'
|
|
31
|
-
);
|
|
32
|
-
}
|
|
33
|
-
this.logger.info(`Issuing token for ${sub}, with entities ${ent ?? []}`);
|
|
34
|
-
if (!key.alg) {
|
|
35
|
-
throw new errors.AuthenticationError("No algorithm was provided in the key");
|
|
36
|
-
}
|
|
37
|
-
return new jose.SignJWT({ ...additionalClaims, iss, sub, ent, aud, iat, exp }).setProtectedHeader({ alg: key.alg, kid: key.kid }).setIssuer(iss).setAudience(aud).setSubject(sub).setIssuedAt(iat).setExpirationTime(exp).sign(await jose.importJWK(key));
|
|
22
|
+
return issueUserToken.issueUserToken({
|
|
23
|
+
issuer: this.issuer,
|
|
24
|
+
key,
|
|
25
|
+
keyDurationSeconds: this.sessionExpirationSeconds,
|
|
26
|
+
logger: this.logger,
|
|
27
|
+
omitClaimsFromToken: this.omitClaimsFromToken,
|
|
28
|
+
params,
|
|
29
|
+
userInfoDatabaseHandler: this.userInfoDatabaseHandler
|
|
30
|
+
});
|
|
38
31
|
}
|
|
39
32
|
async getSigningKey() {
|
|
40
33
|
const { items: keys } = await this.keyStore.listKeys();
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"StaticTokenIssuer.cjs.js","sources":["../../src/identity/StaticTokenIssuer.ts"],"sourcesContent":["/*\n * Copyright 2023 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { AnyJWK, TokenIssuer } from './types';\nimport {
|
|
1
|
+
{"version":3,"file":"StaticTokenIssuer.cjs.js","sources":["../../src/identity/StaticTokenIssuer.ts"],"sourcesContent":["/*\n * Copyright 2023 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { AnyJWK, TokenIssuer } from './types';\nimport { JWK } from 'jose';\nimport { LoggerService } from '@backstage/backend-plugin-api';\nimport { StaticKeyStore } from './StaticKeyStore';\nimport {\n BackstageSignInResult,\n TokenParams,\n} from '@backstage/plugin-auth-node';\nimport { UserInfoDatabaseHandler } from './UserInfoDatabaseHandler';\nimport { issueUserToken } from './issueUserToken';\n\nexport type Config = {\n publicKeyFile: string;\n privateKeyFile: string;\n keyId: string;\n algorithm?: string;\n};\n\nexport type Options = {\n logger: LoggerService;\n /** Value of the issuer claim in issued tokens */\n issuer: string;\n /** Expiration time of the JWT in seconds */\n sessionExpirationSeconds: number;\n /**\n * A list of claims to omit from issued tokens and only store in the user info database\n */\n omitClaimsFromToken?: string[];\n userInfoDatabaseHandler: UserInfoDatabaseHandler;\n};\n\n/**\n * A token issuer that issues tokens from predefined\n * public/private key pair stored in the static key store.\n */\nexport class StaticTokenIssuer implements TokenIssuer {\n private readonly issuer: string;\n private readonly logger: LoggerService;\n private readonly keyStore: StaticKeyStore;\n private readonly sessionExpirationSeconds: number;\n private readonly omitClaimsFromToken?: string[];\n private readonly userInfoDatabaseHandler: UserInfoDatabaseHandler;\n\n public constructor(options: Options, keyStore: StaticKeyStore) {\n this.issuer = options.issuer;\n this.logger = options.logger;\n this.sessionExpirationSeconds = options.sessionExpirationSeconds;\n this.keyStore = keyStore;\n this.omitClaimsFromToken = options.omitClaimsFromToken;\n this.userInfoDatabaseHandler = options.userInfoDatabaseHandler;\n }\n\n public async issueToken(params: TokenParams): Promise<BackstageSignInResult> {\n const key = await this.getSigningKey();\n\n return issueUserToken({\n issuer: this.issuer,\n key,\n keyDurationSeconds: this.sessionExpirationSeconds,\n logger: this.logger,\n omitClaimsFromToken: this.omitClaimsFromToken,\n params,\n userInfoDatabaseHandler: this.userInfoDatabaseHandler,\n });\n }\n\n private async getSigningKey(): Promise<JWK> {\n const { items: keys } = await this.keyStore.listKeys();\n if (keys.length >= 1) {\n return this.keyStore.getPrivateKey(keys[0].key.kid);\n }\n throw new Error('Keystore should hold at least 1 key');\n }\n\n public async listPublicKeys(): Promise<{ keys: AnyJWK[] }> {\n const { items: keys } = await this.keyStore.listKeys();\n return { keys: keys.map(({ key }) => key) };\n }\n}\n"],"names":["issueUserToken"],"mappings":";;;;AAmDO,MAAM,iBAAyC,CAAA;AAAA,EACnC,MAAA;AAAA,EACA,MAAA;AAAA,EACA,QAAA;AAAA,EACA,wBAAA;AAAA,EACA,mBAAA;AAAA,EACA,uBAAA;AAAA,EAEV,WAAA,CAAY,SAAkB,QAA0B,EAAA;AAC7D,IAAA,IAAA,CAAK,SAAS,OAAQ,CAAA,MAAA;AACtB,IAAA,IAAA,CAAK,SAAS,OAAQ,CAAA,MAAA;AACtB,IAAA,IAAA,CAAK,2BAA2B,OAAQ,CAAA,wBAAA;AACxC,IAAA,IAAA,CAAK,QAAW,GAAA,QAAA;AAChB,IAAA,IAAA,CAAK,sBAAsB,OAAQ,CAAA,mBAAA;AACnC,IAAA,IAAA,CAAK,0BAA0B,OAAQ,CAAA,uBAAA;AAAA;AACzC,EAEA,MAAa,WAAW,MAAqD,EAAA;AAC3E,IAAM,MAAA,GAAA,GAAM,MAAM,IAAA,CAAK,aAAc,EAAA;AAErC,IAAA,OAAOA,6BAAe,CAAA;AAAA,MACpB,QAAQ,IAAK,CAAA,MAAA;AAAA,MACb,GAAA;AAAA,MACA,oBAAoB,IAAK,CAAA,wBAAA;AAAA,MACzB,QAAQ,IAAK,CAAA,MAAA;AAAA,MACb,qBAAqB,IAAK,CAAA,mBAAA;AAAA,MAC1B,MAAA;AAAA,MACA,yBAAyB,IAAK,CAAA;AAAA,KAC/B,CAAA;AAAA;AACH,EAEA,MAAc,aAA8B,GAAA;AAC1C,IAAA,MAAM,EAAE,KAAO,EAAA,IAAA,KAAS,MAAM,IAAA,CAAK,SAAS,QAAS,EAAA;AACrD,IAAI,IAAA,IAAA,CAAK,UAAU,CAAG,EAAA;AACpB,MAAA,OAAO,KAAK,QAAS,CAAA,aAAA,CAAc,KAAK,CAAC,CAAA,CAAE,IAAI,GAAG,CAAA;AAAA;AAEpD,IAAM,MAAA,IAAI,MAAM,qCAAqC,CAAA;AAAA;AACvD,EAEA,MAAa,cAA8C,GAAA;AACzD,IAAA,MAAM,EAAE,KAAO,EAAA,IAAA,KAAS,MAAM,IAAA,CAAK,SAAS,QAAS,EAAA;AACrD,IAAO,OAAA,EAAE,MAAM,IAAK,CAAA,GAAA,CAAI,CAAC,EAAE,GAAA,EAAU,KAAA,GAAG,CAAE,EAAA;AAAA;AAE9C;;;;"}
|
|
@@ -1,21 +1,17 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
-
var catalogModel = require('@backstage/catalog-model');
|
|
4
|
-
var errors = require('@backstage/errors');
|
|
5
3
|
var jose = require('jose');
|
|
6
|
-
var lodash = require('lodash');
|
|
7
4
|
var luxon = require('luxon');
|
|
8
5
|
var uuid = require('uuid');
|
|
9
|
-
var
|
|
6
|
+
var issueUserToken = require('./issueUserToken.cjs.js');
|
|
10
7
|
|
|
11
|
-
const MS_IN_S = 1e3;
|
|
12
|
-
const MAX_TOKEN_LENGTH = 32768;
|
|
13
8
|
class TokenFactory {
|
|
14
9
|
issuer;
|
|
15
10
|
logger;
|
|
16
11
|
keyStore;
|
|
17
12
|
keyDurationSeconds;
|
|
18
13
|
algorithm;
|
|
14
|
+
omitClaimsFromToken;
|
|
19
15
|
userInfoDatabaseHandler;
|
|
20
16
|
keyExpiry;
|
|
21
17
|
privateKeyPromise;
|
|
@@ -25,62 +21,20 @@ class TokenFactory {
|
|
|
25
21
|
this.keyStore = options.keyStore;
|
|
26
22
|
this.keyDurationSeconds = options.keyDurationSeconds;
|
|
27
23
|
this.algorithm = options.algorithm ?? "ES256";
|
|
24
|
+
this.omitClaimsFromToken = options.omitClaimsFromToken;
|
|
28
25
|
this.userInfoDatabaseHandler = options.userInfoDatabaseHandler;
|
|
29
26
|
}
|
|
30
27
|
async issueToken(params) {
|
|
31
28
|
const key = await this.getKey();
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
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
|
|
29
|
+
return issueUserToken.issueUserToken({
|
|
30
|
+
issuer: this.issuer,
|
|
31
|
+
key,
|
|
32
|
+
keyDurationSeconds: this.keyDurationSeconds,
|
|
33
|
+
logger: this.logger,
|
|
34
|
+
omitClaimsFromToken: this.omitClaimsFromToken,
|
|
35
|
+
params,
|
|
36
|
+
userInfoDatabaseHandler: this.userInfoDatabaseHandler
|
|
57
37
|
});
|
|
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
38
|
}
|
|
85
39
|
// This will be called by other services that want to verify ID tokens.
|
|
86
40
|
// It is important that it returns a list of all public keys that could
|
|
@@ -139,25 +93,6 @@ class TokenFactory {
|
|
|
139
93
|
}
|
|
140
94
|
return promise;
|
|
141
95
|
}
|
|
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
96
|
}
|
|
162
97
|
|
|
163
98
|
exports.TokenFactory = TokenFactory;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"TokenFactory.cjs.js","sources":["../../src/identity/TokenFactory.ts"],"sourcesContent":["/*\n * Copyright 2020 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { parseEntityRef } from '@backstage/catalog-model';\nimport { AuthenticationError } from '@backstage/errors';\nimport {\n exportJWK,\n generateKeyPair,\n importJWK,\n JWK,\n SignJWT,\n GeneralSign,\n KeyLike,\n} from 'jose';\nimport { omit } from 'lodash';\nimport { DateTime } from 'luxon';\nimport { v4 as uuid } from 'uuid';\nimport { LoggerService } from '@backstage/backend-plugin-api';\nimport { TokenParams, tokenTypes } from '@backstage/plugin-auth-node';\nimport { AnyJWK, KeyStore, TokenIssuer } from './types';\nimport { JsonValue } from '@backstage/types';\nimport { UserInfoDatabaseHandler } from './UserInfoDatabaseHandler';\n\nconst MS_IN_S = 1000;\nconst MAX_TOKEN_LENGTH = 32768; // At 64 bytes per entity ref this still leaves room for about 500 entities\n\n/**\n * The payload contents of a valid Backstage JWT token\n */\nexport interface BackstageTokenPayload {\n /**\n * The issuer of the token, currently the discovery URL of the auth backend\n */\n iss: string;\n\n /**\n * The entity ref of the user\n */\n sub: string;\n\n /**\n * The entity refs that the user claims ownership througg\n */\n ent: string[];\n\n /**\n * A hard coded audience string\n */\n aud: typeof tokenTypes.user.audClaim;\n\n /**\n * Standard expiry in epoch seconds\n */\n exp: number;\n\n /**\n * Standard issue time in epoch seconds\n */\n iat: number;\n\n /**\n * A separate user identity proof that the auth service can convert to a limited user token\n */\n uip: string;\n\n /**\n * Any other custom claims that the adopter may have added\n */\n [claim: string]: JsonValue;\n}\n\n/**\n * The payload contents of a valid Backstage user identity claim token\n *\n * @internal\n */\ninterface BackstageUserIdentityProofPayload {\n /**\n * The entity ref of the user\n */\n sub: string;\n\n /**\n * Standard expiry in epoch seconds\n */\n exp: number;\n\n /**\n * Standard issue time in epoch seconds\n */\n iat: number;\n}\n\ntype Options = {\n logger: LoggerService;\n /** Value of the issuer claim in issued tokens */\n issuer: string;\n /** Key store used for storing signing keys */\n keyStore: KeyStore;\n /** Expiration time of signing keys in seconds */\n keyDurationSeconds: number;\n /** JWS \"alg\" (Algorithm) Header Parameter value. Defaults to ES256.\n * Must match one of the algorithms defined for IdentityClient.\n * When setting a different algorithm, check if the `key` field\n * of the `signing_keys` table can fit the length of the generated keys.\n * If not, add a knex migration file in the migrations folder.\n * More info on supported algorithms: https://github.com/panva/jose */\n algorithm?: string;\n userInfoDatabaseHandler: UserInfoDatabaseHandler;\n};\n\n/**\n * A token issuer that is able to issue tokens in a distributed system\n * backed by a single database. Tokens are issued using lazily generated\n * signing keys, where each running instance of the auth service uses its own\n * signing key.\n *\n * The public parts of the keys are all stored in the shared key storage,\n * and any of the instances of the auth service will return the full list\n * of public keys that are currently in storage.\n *\n * Signing keys are automatically rotated at the same interval as the token\n * duration. Expired keys are kept in storage until there are no valid tokens\n * in circulation that could have been signed by that key.\n */\nexport class TokenFactory implements TokenIssuer {\n private readonly issuer: string;\n private readonly logger: LoggerService;\n private readonly keyStore: KeyStore;\n private readonly keyDurationSeconds: number;\n private readonly algorithm: string;\n private readonly userInfoDatabaseHandler: UserInfoDatabaseHandler;\n\n private keyExpiry?: Date;\n private privateKeyPromise?: Promise<JWK>;\n\n constructor(options: Options) {\n this.issuer = options.issuer;\n this.logger = options.logger;\n this.keyStore = options.keyStore;\n this.keyDurationSeconds = options.keyDurationSeconds;\n this.algorithm = options.algorithm ?? 'ES256';\n this.userInfoDatabaseHandler = options.userInfoDatabaseHandler;\n }\n\n async issueToken(params: TokenParams): Promise<string> {\n const key = await this.getKey();\n\n const iss = this.issuer;\n const { sub, ent = [sub], ...additionalClaims } = params.claims;\n const aud = tokenTypes.user.audClaim;\n const iat = Math.floor(Date.now() / MS_IN_S);\n const exp = iat + this.keyDurationSeconds;\n\n try {\n // The subject must be a valid entity ref\n parseEntityRef(sub);\n } catch (error) {\n throw new Error(\n '\"sub\" claim provided by the auth resolver is not a valid EntityRef.',\n );\n }\n\n if (!key.alg) {\n throw new AuthenticationError('No algorithm was provided in the key');\n }\n\n this.logger.info(`Issuing token for ${sub}, with entities ${ent}`);\n\n const signingKey = await importJWK(key);\n\n const uip = await this.createUserIdentityClaim({\n header: {\n typ: tokenTypes.limitedUser.typParam,\n alg: key.alg,\n kid: key.kid,\n },\n payload: { sub, iat, exp },\n key: signingKey,\n });\n\n const claims: BackstageTokenPayload = {\n ...additionalClaims,\n iss,\n sub,\n ent,\n aud,\n iat,\n exp,\n uip,\n };\n\n const token = await new SignJWT(claims)\n .setProtectedHeader({\n typ: tokenTypes.user.typParam,\n alg: key.alg,\n kid: key.kid,\n })\n .sign(signingKey);\n\n if (token.length > MAX_TOKEN_LENGTH) {\n throw new Error(\n `Failed to issue a new user token. The resulting token is excessively large, with either too many ownership claims or too large custom claims. You likely have a bug either in the sign-in resolver or catalog data. The following claims were requested: '${JSON.stringify(\n claims,\n )}'`,\n );\n }\n\n // Store the user info in the database upon successful token\n // issuance so that it can be retrieved later by limited user tokens\n await this.userInfoDatabaseHandler.addUserInfo({\n claims: omit(claims, ['aud', 'iat', 'iss', 'uip']),\n });\n\n return token;\n }\n\n // This will be called by other services that want to verify ID tokens.\n // It is important that it returns a list of all public keys that could\n // have been used to sign tokens that have not yet expired.\n async listPublicKeys(): Promise<{ keys: AnyJWK[] }> {\n const { items: keys } = await this.keyStore.listKeys();\n\n const validKeys = [];\n const expiredKeys = [];\n\n for (const key of keys) {\n // Allow for a grace period of another full key duration before we remove the keys from the database\n const expireAt = DateTime.fromJSDate(key.createdAt).plus({\n seconds: 3 * this.keyDurationSeconds,\n });\n if (expireAt < DateTime.local()) {\n expiredKeys.push(key);\n } else {\n validKeys.push(key);\n }\n }\n\n // Lazily prune expired keys. This may cause duplicate removals if we have concurrent callers, but w/e\n if (expiredKeys.length > 0) {\n const kids = expiredKeys.map(({ key }) => key.kid);\n\n this.logger.info(`Removing expired signing keys, '${kids.join(\"', '\")}'`);\n\n // We don't await this, just let it run in the background\n this.keyStore.removeKeys(kids).catch(error => {\n this.logger.error(`Failed to remove expired keys, ${error}`);\n });\n }\n\n // NOTE: we're currently only storing public keys, but if we start storing private keys we'd have to convert here\n return { keys: validKeys.map(({ key }) => key) };\n }\n\n private async getKey(): Promise<JWK> {\n // Make sure that we only generate one key at a time\n if (this.privateKeyPromise) {\n if (\n this.keyExpiry &&\n DateTime.fromJSDate(this.keyExpiry) > DateTime.local()\n ) {\n return this.privateKeyPromise;\n }\n this.logger.info(`Signing key has expired, generating new key`);\n delete this.privateKeyPromise;\n }\n\n this.keyExpiry = DateTime.utc()\n .plus({\n seconds: this.keyDurationSeconds,\n })\n .toJSDate();\n const promise = (async () => {\n // This generates a new signing key to be used to sign tokens until the next key rotation\n const key = await generateKeyPair(this.algorithm);\n const publicKey = await exportJWK(key.publicKey);\n const privateKey = await exportJWK(key.privateKey);\n publicKey.kid = privateKey.kid = uuid();\n publicKey.alg = privateKey.alg = this.algorithm;\n\n // We're not allowed to use the key until it has been successfully stored\n // TODO: some token verification implementations aggressively cache the list of keys, and\n // don't attempt to fetch new ones even if they encounter an unknown kid. Therefore we\n // may want to keep using the existing key for some period of time until we switch to\n // the new one. This also needs to be implemented cross-service though, meaning new services\n // that boot up need to be able to grab an existing key to use for signing.\n this.logger.info(`Created new signing key ${publicKey.kid}`);\n await this.keyStore.addKey(publicKey as AnyJWK);\n\n // At this point we are allowed to start using the new key\n return privateKey;\n })();\n\n this.privateKeyPromise = promise;\n\n try {\n // If we fail to generate a new key, we need to clear the state so that\n // the next caller will try to generate another key.\n await promise;\n } catch (error) {\n this.logger.error(`Failed to generate new signing key, ${error}`);\n delete this.keyExpiry;\n delete this.privateKeyPromise;\n }\n\n return promise;\n }\n\n // Creates a string claim that can be used as part of reconstructing a limited\n // user token. The output of this function is only the signature part of a\n // JWS.\n private async createUserIdentityClaim(options: {\n header: {\n typ: string;\n alg: string;\n kid?: string;\n };\n payload: BackstageUserIdentityProofPayload;\n key: KeyLike | Uint8Array;\n }): Promise<string> {\n // NOTE: We reconstruct the header and payload structures carefully to\n // perfectly guarantee ordering. The reason for this is that we store only\n // the signature part of these to reduce duplication within the Backstage\n // token. Anyone who wants to make an actual JWT based on all this must be\n // able to do the EXACT reconstruction of the header and payload parts, to\n // then append the signature.\n\n const header = {\n typ: options.header.typ,\n alg: options.header.alg,\n ...(options.header.kid ? { kid: options.header.kid } : {}),\n };\n\n const payload = {\n sub: options.payload.sub,\n iat: options.payload.iat,\n exp: options.payload.exp,\n };\n\n const jws = await new GeneralSign(\n new TextEncoder().encode(JSON.stringify(payload)),\n )\n .addSignature(options.key)\n .setProtectedHeader(header)\n .done()\n .sign();\n\n return jws.signatures[0].signature;\n }\n}\n"],"names":["tokenTypes","parseEntityRef","AuthenticationError","importJWK","SignJWT","omit","DateTime","generateKeyPair","exportJWK","uuid","GeneralSign"],"mappings":";;;;;;;;;;AAoCA,MAAM,OAAU,GAAA,GAAA;AAChB,MAAM,gBAAmB,GAAA,KAAA;AAqGlB,MAAM,YAAoC,CAAA;AAAA,EAC9B,MAAA;AAAA,EACA,MAAA;AAAA,EACA,QAAA;AAAA,EACA,kBAAA;AAAA,EACA,SAAA;AAAA,EACA,uBAAA;AAAA,EAET,SAAA;AAAA,EACA,iBAAA;AAAA,EAER,YAAY,OAAkB,EAAA;AAC5B,IAAA,IAAA,CAAK,SAAS,OAAQ,CAAA,MAAA;AACtB,IAAA,IAAA,CAAK,SAAS,OAAQ,CAAA,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A;AAAA,MACpB,GAAI,OAAQ,CAAA,MAAA,CAAO,GAAM,GAAA,EAAE,KAAK,OAAQ,CAAA,MAAA,CAAO,GAAI,EAAA,GAAI;AAAC,KAC1D;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;AAAA,KACvB;AAEA,IAAM,MAAA,GAAA,GAAM,MAAM,IAAIC,gBAAA;AAAA,MACpB,IAAI,WAAY,EAAA,CAAE,OAAO,IAAK,CAAA,SAAA,CAAU,OAAO,CAAC;AAAA,KAClD,CACG,YAAa,CAAA,OAAA,CAAQ,GAAG,CAAA,CACxB,mBAAmB,MAAM,CAAA,CACzB,IAAK,EAAA,CACL,IAAK,EAAA;AAER,IAAO,OAAA,GAAA,CAAI,UAAW,CAAA,CAAC,CAAE,CAAA,SAAA;AAAA;AAE7B;;;;"}
|
|
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 { exportJWK, generateKeyPair, JWK } from 'jose';\nimport { DateTime } from 'luxon';\nimport { v4 as uuid } from 'uuid';\nimport { LoggerService } from '@backstage/backend-plugin-api';\nimport {\n BackstageSignInResult,\n TokenParams,\n tokenTypes,\n} from '@backstage/plugin-auth-node';\nimport { AnyJWK, KeyStore, TokenIssuer } from './types';\nimport { JsonValue } from '@backstage/types';\nimport { UserInfoDatabaseHandler } from './UserInfoDatabaseHandler';\nimport { issueUserToken } from './issueUserToken';\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 through\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\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 /**\n * A list of claims to omit from issued tokens and only store in the user info database\n */\n omitClaimsFromToken?: 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 omitClaimsFromToken?: 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.omitClaimsFromToken = options.omitClaimsFromToken;\n this.userInfoDatabaseHandler = options.userInfoDatabaseHandler;\n }\n\n async issueToken(params: TokenParams): Promise<BackstageSignInResult> {\n const key = await this.getKey();\n\n return issueUserToken({\n issuer: this.issuer,\n key,\n keyDurationSeconds: this.keyDurationSeconds,\n logger: this.logger,\n omitClaimsFromToken: this.omitClaimsFromToken,\n params,\n userInfoDatabaseHandler: this.userInfoDatabaseHandler,\n });\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"],"names":["issueUserToken","DateTime","generateKeyPair","exportJWK","uuid"],"mappings":";;;;;;;AA+GO,MAAM,YAAoC,CAAA;AAAA,EAC9B,MAAA;AAAA,EACA,MAAA;AAAA,EACA,QAAA;AAAA,EACA,kBAAA;AAAA,EACA,SAAA;AAAA,EACA,mBAAA;AAAA,EACA,uBAAA;AAAA,EAET,SAAA;AAAA,EACA,iBAAA;AAAA,EAER,YAAY,OAAkB,EAAA;AAC5B,IAAA,IAAA,CAAK,SAAS,OAAQ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AAA,MAAMC,cAAU,CAAA,GAAA,CAAI,SAAS,CAAA;AAC/C,MAAA,MAAM,UAAa,GAAA,MAAMA,cAAU,CAAA,GAAA,CAAI,UAAU,CAAA;AACjD,MAAU,SAAA,CAAA,GAAA,GAAM,UAAW,CAAA,GAAA,GAAMC,OAAK,EAAA;AACtC,MAAU,SAAA,CAAA,GAAA,GAAM,UAAW,CAAA,GAAA,GAAM,IAAK,CAAA,SAAA;AAQtC,MAAA,IAAA,CAAK,MAAO,CAAA,IAAA,CAAK,CAA2B,wBAAA,EAAA,SAAA,CAAU,GAAG,CAAE,CAAA,CAAA;AAC3D,MAAM,MAAA,IAAA,CAAK,QAAS,CAAA,MAAA,CAAO,SAAmB,CAAA;AAG9C,MAAO,OAAA,UAAA;AAAA,KACN,GAAA;AAEH,IAAA,IAAA,CAAK,iBAAoB,GAAA,OAAA;AAEzB,IAAI,IAAA;AAGF,MAAM,MAAA,OAAA;AAAA,aACC,KAAO,EAAA;AACd,MAAA,IAAA,CAAK,MAAO,CAAA,KAAA,CAAM,CAAuC,oCAAA,EAAA,KAAK,CAAE,CAAA,CAAA;AAChE,MAAA,OAAO,IAAK,CAAA,SAAA;AACZ,MAAA,OAAO,IAAK,CAAA,iBAAA;AAAA;AAGd,IAAO,OAAA,OAAA;AAAA;AAEX;;;;"}
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
var catalogModel = require('@backstage/catalog-model');
|
|
4
|
+
var errors = require('@backstage/errors');
|
|
5
|
+
var pluginAuthNode = require('@backstage/plugin-auth-node');
|
|
6
|
+
var lodash = require('lodash');
|
|
7
|
+
var jose = require('jose');
|
|
8
|
+
|
|
9
|
+
const MS_IN_S = 1e3;
|
|
10
|
+
const MAX_TOKEN_LENGTH = 32768;
|
|
11
|
+
async function issueUserToken({
|
|
12
|
+
issuer,
|
|
13
|
+
key,
|
|
14
|
+
keyDurationSeconds,
|
|
15
|
+
logger,
|
|
16
|
+
omitClaimsFromToken,
|
|
17
|
+
params,
|
|
18
|
+
userInfoDatabaseHandler
|
|
19
|
+
}) {
|
|
20
|
+
const { sub, ent = [sub], ...additionalClaims } = params.claims;
|
|
21
|
+
const aud = pluginAuthNode.tokenTypes.user.audClaim;
|
|
22
|
+
const iat = Math.floor(Date.now() / MS_IN_S);
|
|
23
|
+
const exp = iat + keyDurationSeconds;
|
|
24
|
+
try {
|
|
25
|
+
catalogModel.parseEntityRef(sub);
|
|
26
|
+
} catch (error) {
|
|
27
|
+
throw new Error(
|
|
28
|
+
'"sub" claim provided by the auth resolver is not a valid EntityRef.'
|
|
29
|
+
);
|
|
30
|
+
}
|
|
31
|
+
if (!key.alg) {
|
|
32
|
+
throw new errors.AuthenticationError("No algorithm was provided in the key");
|
|
33
|
+
}
|
|
34
|
+
logger.info(`Issuing token for ${sub}, with entities ${ent}`);
|
|
35
|
+
const signingKey = await jose.importJWK(key);
|
|
36
|
+
const uip = await createUserIdentityClaim({
|
|
37
|
+
header: {
|
|
38
|
+
typ: pluginAuthNode.tokenTypes.limitedUser.typParam,
|
|
39
|
+
alg: key.alg,
|
|
40
|
+
kid: key.kid
|
|
41
|
+
},
|
|
42
|
+
payload: { sub, iat, exp },
|
|
43
|
+
key: signingKey
|
|
44
|
+
});
|
|
45
|
+
const claims = {
|
|
46
|
+
...additionalClaims,
|
|
47
|
+
iss: issuer,
|
|
48
|
+
sub,
|
|
49
|
+
ent,
|
|
50
|
+
aud,
|
|
51
|
+
iat,
|
|
52
|
+
exp,
|
|
53
|
+
uip
|
|
54
|
+
};
|
|
55
|
+
const tokenClaims = omitClaimsFromToken ? lodash.omit(claims, omitClaimsFromToken) : claims;
|
|
56
|
+
const token = await new jose.SignJWT(tokenClaims).setProtectedHeader({
|
|
57
|
+
typ: pluginAuthNode.tokenTypes.user.typParam,
|
|
58
|
+
alg: key.alg,
|
|
59
|
+
kid: key.kid
|
|
60
|
+
}).sign(signingKey);
|
|
61
|
+
if (token.length > MAX_TOKEN_LENGTH) {
|
|
62
|
+
throw new Error(
|
|
63
|
+
`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(
|
|
64
|
+
tokenClaims
|
|
65
|
+
)}'`
|
|
66
|
+
);
|
|
67
|
+
}
|
|
68
|
+
await userInfoDatabaseHandler.addUserInfo({
|
|
69
|
+
claims: lodash.omit(claims, ["aud", "iat", "iss", "uip"])
|
|
70
|
+
});
|
|
71
|
+
return {
|
|
72
|
+
token,
|
|
73
|
+
identity: {
|
|
74
|
+
type: "user",
|
|
75
|
+
userEntityRef: sub,
|
|
76
|
+
ownershipEntityRefs: ent
|
|
77
|
+
}
|
|
78
|
+
};
|
|
79
|
+
}
|
|
80
|
+
async function createUserIdentityClaim(options) {
|
|
81
|
+
const header = {
|
|
82
|
+
typ: options.header.typ,
|
|
83
|
+
alg: options.header.alg,
|
|
84
|
+
...options.header.kid ? { kid: options.header.kid } : {}
|
|
85
|
+
};
|
|
86
|
+
const payload = {
|
|
87
|
+
sub: options.payload.sub,
|
|
88
|
+
iat: options.payload.iat,
|
|
89
|
+
exp: options.payload.exp
|
|
90
|
+
};
|
|
91
|
+
const jws = await new jose.GeneralSign(
|
|
92
|
+
new TextEncoder().encode(JSON.stringify(payload))
|
|
93
|
+
).addSignature(options.key).setProtectedHeader(header).done().sign();
|
|
94
|
+
return jws.signatures[0].signature;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
exports.issueUserToken = issueUserToken;
|
|
98
|
+
//# sourceMappingURL=issueUserToken.cjs.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"issueUserToken.cjs.js","sources":["../../src/identity/issueUserToken.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 */\n\nimport { parseEntityRef } from '@backstage/catalog-model';\nimport { AuthenticationError } from '@backstage/errors';\nimport {\n BackstageSignInResult,\n TokenParams,\n tokenTypes,\n} from '@backstage/plugin-auth-node';\nimport { omit } from 'lodash';\nimport { UserInfoDatabaseHandler } from './UserInfoDatabaseHandler';\nimport { LoggerService } from '@backstage/backend-plugin-api';\nimport { GeneralSign, importJWK, JWK, KeyLike, SignJWT } from 'jose';\nimport { BackstageTokenPayload } from './TokenFactory';\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\nexport async function issueUserToken({\n issuer,\n key,\n keyDurationSeconds,\n logger,\n omitClaimsFromToken,\n params,\n userInfoDatabaseHandler,\n}: {\n issuer: string;\n key: JWK;\n keyDurationSeconds: number;\n logger: LoggerService;\n omitClaimsFromToken?: string[];\n params: TokenParams;\n userInfoDatabaseHandler: UserInfoDatabaseHandler;\n}): Promise<BackstageSignInResult> {\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 + 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 logger.info(`Issuing token for ${sub}, with entities ${ent}`);\n\n const signingKey = await importJWK(key);\n\n const uip = await 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: issuer,\n sub,\n ent,\n aud,\n iat,\n exp,\n uip,\n };\n\n const tokenClaims = omitClaimsFromToken\n ? omit(claims, omitClaimsFromToken)\n : claims;\n const token = await new SignJWT(tokenClaims)\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 tokenClaims,\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 userInfoDatabaseHandler.addUserInfo({\n claims: omit(claims, ['aud', 'iat', 'iss', 'uip']),\n });\n\n return {\n token,\n identity: {\n type: 'user',\n userEntityRef: sub,\n ownershipEntityRefs: ent,\n },\n };\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\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 JWS.\n */\nasync function 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"],"names":["tokenTypes","parseEntityRef","AuthenticationError","importJWK","omit","SignJWT","GeneralSign"],"mappings":";;;;;;;;AA6BA,MAAM,OAAU,GAAA,GAAA;AAChB,MAAM,gBAAmB,GAAA,KAAA;AAEzB,eAAsB,cAAe,CAAA;AAAA,EACnC,MAAA;AAAA,EACA,GAAA;AAAA,EACA,kBAAA;AAAA,EACA,MAAA;AAAA,EACA,mBAAA;AAAA,EACA,MAAA;AAAA,EACA;AACF,CAQmC,EAAA;AACjC,EAAM,MAAA,EAAE,KAAK,GAAM,GAAA,CAAC,GAAG,CAAG,EAAA,GAAG,gBAAiB,EAAA,GAAI,MAAO,CAAA,MAAA;AACzD,EAAM,MAAA,GAAA,GAAMA,0BAAW,IAAK,CAAA,QAAA;AAC5B,EAAA,MAAM,MAAM,IAAK,CAAA,KAAA,CAAM,IAAK,CAAA,GAAA,KAAQ,OAAO,CAAA;AAC3C,EAAA,MAAM,MAAM,GAAM,GAAA,kBAAA;AAElB,EAAI,IAAA;AAEF,IAAAC,2BAAA,CAAe,GAAG,CAAA;AAAA,WACX,KAAO,EAAA;AACd,IAAA,MAAM,IAAI,KAAA;AAAA,MACR;AAAA,KACF;AAAA;AAGF,EAAI,IAAA,CAAC,IAAI,GAAK,EAAA;AACZ,IAAM,MAAA,IAAIC,2BAAoB,sCAAsC,CAAA;AAAA;AAGtE,EAAA,MAAA,CAAO,IAAK,CAAA,CAAA,kBAAA,EAAqB,GAAG,CAAA,gBAAA,EAAmB,GAAG,CAAE,CAAA,CAAA;AAE5D,EAAM,MAAA,UAAA,GAAa,MAAMC,cAAA,CAAU,GAAG,CAAA;AAEtC,EAAM,MAAA,GAAA,GAAM,MAAM,uBAAwB,CAAA;AAAA,IACxC,MAAQ,EAAA;AAAA,MACN,GA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,eAAe,wBAAwB,OAQnB,EAAA;AAQlB,EAAA,MAAM,MAAS,GAAA;AAAA,IACb,GAAA,EAAK,QAAQ,MAAO,CAAA,GAAA;AAAA,IACpB,GAAA,EAAK,QAAQ,MAAO,CAAA,GAAA;AAAA,IACpB,GAAI,OAAQ,CAAA,MAAA,CAAO,GAAM,GAAA,EAAE,KAAK,OAAQ,CAAA,MAAA,CAAO,GAAI,EAAA,GAAI;AAAC,GAC1D;AAEA,EAAA,MAAM,OAAU,GAAA;AAAA,IACd,GAAA,EAAK,QAAQ,OAAQ,CAAA,GAAA;AAAA,IACrB,GAAA,EAAK,QAAQ,OAAQ,CAAA,GAAA;AAAA,IACrB,GAAA,EAAK,QAAQ,OAAQ,CAAA;AAAA,GACvB;AAEA,EAAM,MAAA,GAAA,GAAM,MAAM,IAAIE,gBAAA;AAAA,IACpB,IAAI,WAAY,EAAA,CAAE,OAAO,IAAK,CAAA,SAAA,CAAU,OAAO,CAAC;AAAA,GAClD,CACG,YAAa,CAAA,OAAA,CAAQ,GAAG,CAAA,CACxB,mBAAmB,MAAM,CAAA,CACzB,IAAK,EAAA,CACL,IAAK,EAAA;AAER,EAAO,OAAA,GAAA,CAAI,UAAW,CAAA,CAAC,CAAE,CAAA,SAAA;AAC3B;;;;"}
|
|
@@ -34,8 +34,7 @@ class CatalogAuthResolverContext {
|
|
|
34
34
|
);
|
|
35
35
|
}
|
|
36
36
|
async issueToken(params) {
|
|
37
|
-
|
|
38
|
-
return { token };
|
|
37
|
+
return await this.tokenIssuer.issueToken(params);
|
|
39
38
|
}
|
|
40
39
|
async findCatalogUser(query) {
|
|
41
40
|
let result = void 0;
|
|
@@ -90,18 +89,35 @@ class CatalogAuthResolverContext {
|
|
|
90
89
|
}
|
|
91
90
|
return { entity: result };
|
|
92
91
|
}
|
|
93
|
-
async signInWithCatalogUser(query) {
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
92
|
+
async signInWithCatalogUser(query, options) {
|
|
93
|
+
try {
|
|
94
|
+
const { entity } = await this.findCatalogUser(query);
|
|
95
|
+
const { ownershipEntityRefs } = await this.resolveOwnershipEntityRefs(
|
|
96
|
+
entity
|
|
97
|
+
);
|
|
98
|
+
return await this.tokenIssuer.issueToken({
|
|
99
|
+
claims: {
|
|
100
|
+
sub: catalogModel.stringifyEntityRef(entity),
|
|
101
|
+
ent: ownershipEntityRefs
|
|
102
|
+
}
|
|
103
|
+
});
|
|
104
|
+
} catch (error) {
|
|
105
|
+
if (error?.name !== "NotFoundError" || !options?.dangerousEntityRefFallback) {
|
|
106
|
+
throw error;
|
|
102
107
|
}
|
|
103
|
-
|
|
104
|
-
|
|
108
|
+
const userEntityRef = catalogModel.stringifyEntityRef(
|
|
109
|
+
catalogModel.parseEntityRef(options.dangerousEntityRefFallback.entityRef, {
|
|
110
|
+
defaultKind: "User",
|
|
111
|
+
defaultNamespace: catalogModel.DEFAULT_NAMESPACE
|
|
112
|
+
})
|
|
113
|
+
);
|
|
114
|
+
return await this.tokenIssuer.issueToken({
|
|
115
|
+
claims: {
|
|
116
|
+
sub: userEntityRef,
|
|
117
|
+
ent: [userEntityRef]
|
|
118
|
+
}
|
|
119
|
+
});
|
|
120
|
+
}
|
|
105
121
|
}
|
|
106
122
|
async resolveOwnershipEntityRefs(entity) {
|
|
107
123
|
if (this.ownershipResolver) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"CatalogAuthResolverContext.cjs.js","sources":["../../../src/lib/resolvers/CatalogAuthResolverContext.ts"],"sourcesContent":["/*\n * Copyright 2022 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n DEFAULT_NAMESPACE,\n Entity,\n parseEntityRef,\n RELATION_MEMBER_OF,\n stringifyEntityRef,\n} from '@backstage/catalog-model';\nimport { ConflictError, InputError, NotFoundError } from '@backstage/errors';\nimport { AuthService, LoggerService } from '@backstage/backend-plugin-api';\nimport { CatalogService } from '@backstage/plugin-catalog-node';\nimport { TokenIssuer } from '../../identity/types';\nimport {\n AuthOwnershipResolver,\n AuthResolverCatalogUserQuery,\n AuthResolverContext,\n TokenParams,\n} from '@backstage/plugin-auth-node';\nimport { CatalogIdentityClient } from '../catalog/CatalogIdentityClient';\n\nfunction getDefaultOwnershipEntityRefs(entity: Entity) {\n const membershipRefs =\n entity.relations\n ?.filter(\n r => r.type === RELATION_MEMBER_OF && r.targetRef.startsWith('group:'),\n )\n .map(r => r.targetRef) ?? [];\n\n return Array.from(new Set([stringifyEntityRef(entity), ...membershipRefs]));\n}\n\nexport class CatalogAuthResolverContext implements AuthResolverContext {\n static create(options: {\n logger: LoggerService;\n catalog: CatalogService;\n tokenIssuer: TokenIssuer;\n auth: AuthService;\n ownershipResolver?: AuthOwnershipResolver;\n }): CatalogAuthResolverContext {\n const catalogIdentityClient = new CatalogIdentityClient({\n catalog: options.catalog,\n auth: options.auth,\n });\n\n return new CatalogAuthResolverContext(\n options.logger,\n options.tokenIssuer,\n catalogIdentityClient,\n options.catalog,\n options.auth,\n options.ownershipResolver,\n );\n }\n\n private constructor(\n public readonly logger: LoggerService,\n public readonly tokenIssuer: TokenIssuer,\n public readonly catalogIdentityClient: CatalogIdentityClient,\n private readonly catalog: CatalogService,\n private readonly auth: AuthService,\n private readonly ownershipResolver?: AuthOwnershipResolver,\n ) {}\n\n async issueToken(params: TokenParams) {\n const token = await this.tokenIssuer.issueToken(params);\n return { token };\n }\n\n async findCatalogUser(query: AuthResolverCatalogUserQuery) {\n let result: Entity[] | Entity | undefined = undefined;\n\n if ('entityRef' in query) {\n const entityRef = parseEntityRef(query.entityRef, {\n defaultKind: 'User',\n defaultNamespace: DEFAULT_NAMESPACE,\n });\n result = await this.catalog.getEntityByRef(entityRef, {\n credentials: await this.auth.getOwnServiceCredentials(),\n });\n } else if ('annotations' in query) {\n const filter: Record<string, string> = {\n kind: 'user',\n };\n for (const [key, value] of Object.entries(query.annotations)) {\n filter[`metadata.annotations.${key}`] = value;\n }\n const res = await this.catalog.getEntities(\n { filter },\n { credentials: await this.auth.getOwnServiceCredentials() },\n );\n result = res.items;\n } else if ('filter' in query) {\n const filter = [query.filter].flat().map(value => {\n if (\n !Object.keys(value).some(\n key => key.toLocaleLowerCase('en-US') === 'kind',\n )\n ) {\n return {\n ...value,\n kind: 'user',\n };\n }\n return value;\n });\n const res = await this.catalog.getEntities(\n { filter: filter },\n { credentials: await this.auth.getOwnServiceCredentials() },\n );\n result = res.items;\n } else {\n throw new InputError('Invalid user lookup query');\n }\n\n if (Array.isArray(result)) {\n if (result.length > 1) {\n throw new ConflictError('User lookup resulted in multiple matches');\n }\n result = result[0];\n }\n if (!result) {\n throw new NotFoundError('User not found');\n }\n\n return { entity: result };\n }\n\n async signInWithCatalogUser(query: AuthResolverCatalogUserQuery) {\n const { entity } = await this.findCatalogUser(query);\n\n const { ownershipEntityRefs } = await this.resolveOwnershipEntityRefs(\n entity,\n );\n\n const token = await this.tokenIssuer.issueToken({\n claims: {\n sub: stringifyEntityRef(entity),\n ent: ownershipEntityRefs,\n },\n });\n return { token };\n }\n\n async resolveOwnershipEntityRefs(\n entity: Entity,\n ): Promise<{ ownershipEntityRefs: string[] }> {\n if (this.ownershipResolver) {\n return this.ownershipResolver.resolveOwnershipEntityRefs(entity);\n }\n return { ownershipEntityRefs: getDefaultOwnershipEntityRefs(entity) };\n }\n}\n"],"names":["RELATION_MEMBER_OF","stringifyEntityRef","CatalogIdentityClient","parseEntityRef","DEFAULT_NAMESPACE","InputError","ConflictError","NotFoundError"],"mappings":";;;;;;AAmCA,SAAS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P,KACD,CAAA;AACD,IAAA,OAAO,EAAE,KAAM,EAAA;AAAA;AACjB,EAEA,MAAM,2BACJ,MAC4C,EAAA;AAC5C,IAAA,IAAI,KAAK,iBAAmB,EAAA;AAC1B,MAAO,OAAA,IAAA,CAAK,iBAAkB,CAAA,0BAAA,CAA2B,MAAM,CAAA;AAAA;AAEjE,IAAA,OAAO,EAAE,mBAAA,EAAqB,6BAA8B,CAAA,MAAM,CAAE,EAAA;AAAA;AAExE;;;;"}
|
|
1
|
+
{"version":3,"file":"CatalogAuthResolverContext.cjs.js","sources":["../../../src/lib/resolvers/CatalogAuthResolverContext.ts"],"sourcesContent":["/*\n * Copyright 2022 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n DEFAULT_NAMESPACE,\n Entity,\n parseEntityRef,\n RELATION_MEMBER_OF,\n stringifyEntityRef,\n} from '@backstage/catalog-model';\nimport { ConflictError, InputError, NotFoundError } from '@backstage/errors';\nimport { AuthService, LoggerService } from '@backstage/backend-plugin-api';\nimport { CatalogService } from '@backstage/plugin-catalog-node';\nimport { TokenIssuer } from '../../identity/types';\nimport {\n AuthOwnershipResolver,\n AuthResolverCatalogUserQuery,\n AuthResolverContext,\n TokenParams,\n} from '@backstage/plugin-auth-node';\nimport { CatalogIdentityClient } from '../catalog/CatalogIdentityClient';\n\nfunction getDefaultOwnershipEntityRefs(entity: Entity) {\n const membershipRefs =\n entity.relations\n ?.filter(\n r => r.type === RELATION_MEMBER_OF && r.targetRef.startsWith('group:'),\n )\n .map(r => r.targetRef) ?? [];\n\n return Array.from(new Set([stringifyEntityRef(entity), ...membershipRefs]));\n}\n\nexport class CatalogAuthResolverContext implements AuthResolverContext {\n static create(options: {\n logger: LoggerService;\n catalog: CatalogService;\n tokenIssuer: TokenIssuer;\n auth: AuthService;\n ownershipResolver?: AuthOwnershipResolver;\n }): CatalogAuthResolverContext {\n const catalogIdentityClient = new CatalogIdentityClient({\n catalog: options.catalog,\n auth: options.auth,\n });\n\n return new CatalogAuthResolverContext(\n options.logger,\n options.tokenIssuer,\n catalogIdentityClient,\n options.catalog,\n options.auth,\n options.ownershipResolver,\n );\n }\n\n private constructor(\n public readonly logger: LoggerService,\n public readonly tokenIssuer: TokenIssuer,\n public readonly catalogIdentityClient: CatalogIdentityClient,\n private readonly catalog: CatalogService,\n private readonly auth: AuthService,\n private readonly ownershipResolver?: AuthOwnershipResolver,\n ) {}\n\n async issueToken(params: TokenParams) {\n return await this.tokenIssuer.issueToken(params);\n }\n\n async findCatalogUser(query: AuthResolverCatalogUserQuery) {\n let result: Entity[] | Entity | undefined = undefined;\n\n if ('entityRef' in query) {\n const entityRef = parseEntityRef(query.entityRef, {\n defaultKind: 'User',\n defaultNamespace: DEFAULT_NAMESPACE,\n });\n result = await this.catalog.getEntityByRef(entityRef, {\n credentials: await this.auth.getOwnServiceCredentials(),\n });\n } else if ('annotations' in query) {\n const filter: Record<string, string> = {\n kind: 'user',\n };\n for (const [key, value] of Object.entries(query.annotations)) {\n filter[`metadata.annotations.${key}`] = value;\n }\n const res = await this.catalog.getEntities(\n { filter },\n { credentials: await this.auth.getOwnServiceCredentials() },\n );\n result = res.items;\n } else if ('filter' in query) {\n const filter = [query.filter].flat().map(value => {\n if (\n !Object.keys(value).some(\n key => key.toLocaleLowerCase('en-US') === 'kind',\n )\n ) {\n return {\n ...value,\n kind: 'user',\n };\n }\n return value;\n });\n const res = await this.catalog.getEntities(\n { filter: filter },\n { credentials: await this.auth.getOwnServiceCredentials() },\n );\n result = res.items;\n } else {\n throw new InputError('Invalid user lookup query');\n }\n\n if (Array.isArray(result)) {\n if (result.length > 1) {\n throw new ConflictError('User lookup resulted in multiple matches');\n }\n result = result[0];\n }\n if (!result) {\n throw new NotFoundError('User not found');\n }\n\n return { entity: result };\n }\n\n async signInWithCatalogUser(\n query: AuthResolverCatalogUserQuery,\n options?: {\n dangerousEntityRefFallback?: {\n entityRef:\n | string\n | {\n kind?: string;\n namespace?: string;\n name: string;\n };\n };\n },\n ) {\n try {\n const { entity } = await this.findCatalogUser(query);\n\n const { ownershipEntityRefs } = await this.resolveOwnershipEntityRefs(\n entity,\n );\n\n return await this.tokenIssuer.issueToken({\n claims: {\n sub: stringifyEntityRef(entity),\n ent: ownershipEntityRefs,\n },\n });\n } catch (error) {\n if (\n error?.name !== 'NotFoundError' ||\n !options?.dangerousEntityRefFallback\n ) {\n throw error;\n }\n const userEntityRef = stringifyEntityRef(\n parseEntityRef(options.dangerousEntityRefFallback.entityRef, {\n defaultKind: 'User',\n defaultNamespace: DEFAULT_NAMESPACE,\n }),\n );\n\n return await this.tokenIssuer.issueToken({\n claims: {\n sub: userEntityRef,\n ent: [userEntityRef],\n },\n });\n }\n }\n\n async resolveOwnershipEntityRefs(\n entity: Entity,\n ): Promise<{ ownershipEntityRefs: string[] }> {\n if (this.ownershipResolver) {\n return this.ownershipResolver.resolveOwnershipEntityRefs(entity);\n }\n return { ownershipEntityRefs: getDefaultOwnershipEntityRefs(entity) };\n }\n}\n"],"names":["RELATION_MEMBER_OF","stringifyEntityRef","CatalogIdentityClient","parseEntityRef","DEFAULT_NAMESPACE","InputError","ConflictError","NotFoundError"],"mappings":";;;;;;AAmCA,SAAS,8BAA8B,MAAgB,EAAA;AACrD,EAAM,MAAA,cAAA,GACJ,OAAO,SACH,EAAA,MAAA;AAAA,IACA,OAAK,CAAE,CAAA,IAAA,KAASA,mCAAsB,CAAE,CAAA,SAAA,CAAU,WAAW,QAAQ;AAAA,IAEtE,GAAI,CAAA,CAAA,CAAA,KAAK,CAAE,CAAA,SAAS,KAAK,EAAC;AAE/B,EAAO,OAAA,KAAA,C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AkB,EAAAC;AAAA,SACnB;AAAA,OACH;AAEA,MAAO,OAAA,MAAM,IAAK,CAAA,WAAA,CAAY,UAAW,CAAA;AAAA,QACvC,MAAQ,EAAA;AAAA,UACN,GAAK,EAAA,aAAA;AAAA,UACL,GAAA,EAAK,CAAC,aAAa;AAAA;AACrB,OACD,CAAA;AAAA;AACH;AACF,EAEA,MAAM,2BACJ,MAC4C,EAAA;AAC5C,IAAA,IAAI,KAAK,iBAAmB,EAAA;AAC1B,MAAO,OAAA,IAAA,CAAK,iBAAkB,CAAA,0BAAA,CAA2B,MAAM,CAAA;AAAA;AAEjE,IAAA,OAAO,EAAE,mBAAA,EAAqB,6BAA8B,CAAA,MAAM,CAAE,EAAA;AAAA;AAExE;;;;"}
|
|
@@ -47,13 +47,18 @@ async function createRouter(options) {
|
|
|
47
47
|
const userInfoDatabaseHandler = new UserInfoDatabaseHandler.UserInfoDatabaseHandler(
|
|
48
48
|
await authDb.get()
|
|
49
49
|
);
|
|
50
|
+
const omitClaimsFromToken = config.getOptionalBoolean(
|
|
51
|
+
"auth.omitIdentityTokenOwnershipClaim"
|
|
52
|
+
) ? ["ent"] : [];
|
|
50
53
|
let tokenIssuer;
|
|
51
54
|
if (keyStore instanceof StaticKeyStore.StaticKeyStore) {
|
|
52
55
|
tokenIssuer = new StaticTokenIssuer.StaticTokenIssuer(
|
|
53
56
|
{
|
|
54
57
|
logger: logger.child({ component: "token-factory" }),
|
|
55
58
|
issuer: authUrl,
|
|
56
|
-
sessionExpirationSeconds: backstageTokenExpiration
|
|
59
|
+
sessionExpirationSeconds: backstageTokenExpiration,
|
|
60
|
+
userInfoDatabaseHandler,
|
|
61
|
+
omitClaimsFromToken
|
|
57
62
|
},
|
|
58
63
|
keyStore
|
|
59
64
|
);
|
|
@@ -64,7 +69,8 @@ async function createRouter(options) {
|
|
|
64
69
|
keyDurationSeconds: backstageTokenExpiration,
|
|
65
70
|
logger: logger.child({ component: "token-factory" }),
|
|
66
71
|
algorithm: tokenFactoryAlgorithm ?? config.getOptionalString("auth.identityTokenAlgorithm"),
|
|
67
|
-
userInfoDatabaseHandler
|
|
72
|
+
userInfoDatabaseHandler,
|
|
73
|
+
omitClaimsFromToken
|
|
68
74
|
});
|
|
69
75
|
}
|
|
70
76
|
const secret = config.getOptionalString("auth.session.secret");
|
|
@@ -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 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 { bindOidcRouter } from '../identity/router';\nimport { KeyStores } from '../identity/KeyStores';\nimport { TokenFactory } from '../identity/TokenFactory';\nimport { UserInfoDatabaseHandler } from '../identity/UserInfoDatabaseHandler';\nimport session from 'express-session';\nimport connectSessionKnex from 'connect-session-knex';\nimport passport from 'passport';\nimport { AuthDatabase } from '../database/AuthDatabase';\nimport { readBackstageTokenExpiration } from './readBackstageTokenExpiration';\nimport { TokenIssuer } from '../identity/types';\nimport { StaticTokenIssuer } from '../identity/StaticTokenIssuer';\nimport { StaticKeyStore } from '../identity/StaticKeyStore';\nimport { bindProviderRouters, ProviderFactories } from '../providers/router';\n\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}\n\nexport async function createRouter(\n options: RouterOptions,\n): Promise<express.Router> {\n const {\n logger,\n config,\n discovery,\n database,\n tokenFactoryAlgorithm,\n providerFactories = {},\n } = options;\n\n const router = Router();\n\n const appUrl = config.getString('app.baseUrl');\n const authUrl = await discovery.getExternalBaseUrl('auth');\n const backstageTokenExpiration = readBackstageTokenExpiration(config);\n const authDb = AuthDatabase.create(database);\n\n const keyStore = await KeyStores.fromConfig(config, {\n logger,\n database: authDb,\n });\n\n const userInfoDatabaseHandler = new UserInfoDatabaseHandler(\n await authDb.get(),\n );\n\n let tokenIssuer: TokenIssuer;\n if (keyStore instanceof StaticKeyStore) {\n tokenIssuer = new StaticTokenIssuer(\n {\n logger: logger.child({ component: 'token-factory' }),\n issuer: authUrl,\n sessionExpirationSeconds: backstageTokenExpiration,\n },\n keyStore as StaticKeyStore,\n );\n } else {\n tokenIssuer = new TokenFactory({\n issuer: authUrl,\n keyStore,\n keyDurationSeconds: backstageTokenExpiration,\n logger: logger.child({ component: 'token-factory' }),\n algorithm:\n tokenFactoryAlgorithm ??\n config.getOptionalString('auth.identityTokenAlgorithm'),\n userInfoDatabaseHandler,\n });\n }\n\n const secret = config.getOptionalString('auth.session.secret');\n if (secret) {\n router.use(cookieParser(secret));\n const enforceCookieSSL = authUrl.startsWith('https');\n const KnexSessionStore = connectSessionKnex(session);\n router.use(\n session({\n secret,\n saveUninitialized: false,\n resave: false,\n cookie: { secure: enforceCookieSSL ? 'auto' : false },\n store: new KnexSessionStore({\n createtable: false,\n knex: await authDb.get(),\n }),\n }),\n );\n router.use(passport.initialize());\n router.use(passport.session());\n } else {\n router.use(cookieParser());\n }\n\n router.use(express.urlencoded({ extended: false }));\n router.use(express.json());\n\n bindProviderRouters(router, {\n providers: providerFactories,\n appUrl,\n baseUrl: authUrl,\n tokenIssuer,\n ...options,\n auth: options.auth,\n });\n\n bindOidcRouter(router, {\n auth: options.auth,\n tokenIssuer,\n baseUrl: authUrl,\n userInfoDatabaseHandler,\n });\n\n // Gives a more helpful error message than a plain 404\n router.use('/:provider/', req => {\n const { provider } = req.params;\n throw new NotFoundError(`Unknown auth provider '${provider}'`);\n });\n\n return router;\n}\n"],"names":["router","Router","readBackstageTokenExpiration","AuthDatabase","KeyStores","UserInfoDatabaseHandler","StaticKeyStore","StaticTokenIssuer","TokenFactory","cookieParser","connectSessionKnex","session","passport","express","bindProviderRouters","bindOidcRouter","NotFoundError"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuDA,eAAsB,aACpB,OACyB,EAAA;AACzB,EAAM,MAAA;AAAA,IACJ,MAAA;AAAA,IACA,MAAA;AAAA,IACA,SAAA;AAAA,IACA,QAAA;AAAA,IACA,qBAAA;AAAA,IACA,oBAAoB;AAAC,GACnB,GAAA,OAAA;AAEJ,EAAA,MAAMA,WAASC,uBAAO,EAAA;AAEtB,EAAM,MAAA,MAAA,GAAS,MAAO,CAAA,SAAA,CAAU,aAAa,CAAA;AAC7C,EAAA,MAAM,OAAU,GAAA,MAAM,SAAU,CAAA,kBAAA,CAAmB,MAAM,CAAA;AACzD,EAAM,MAAA,wBAAA,GAA2BC,0DAA6B,MAAM,CAAA;AACpE,EAAM,MAAA,MAAA,GAASC,yBAAa,CAAA,MAAA,CAAO,QAAQ,CAAA;AAE3C,EAAA,MAAM,QAAW,GAAA,MAAMC,mBAAU,CAAA,UAAA,CAAW,MAAQ,EAAA;AAAA,IAClD,MAAA;AAAA,IACA,QAAU,EAAA;AAAA,GACX,CAAA;AAED,EAAA,MAAM,0BAA0B,IAAIC,+CAAA;AAAA,IAClC,MAAM,OAAO,GAAI;AAAA,GACnB;AAEA,EAAI,IAAA,WAAA;AACJ,EAAA,IAAI,oBAAoBC,6BAAgB,EAAA;AACtC,IAAA,WAAA,GAAc,IAAIC,mCAAA;AAAA,MAChB;AAAA,QACE,QAAQ,MAAO,CAAA,KAAA,CAAM,EAAE,SAAA,EAAW,iBAAiB,CAAA;AAAA,QACnD,MAAQ,EAAA,OAAA;AAAA,QACR,wBAA0B,EAAA;AAAA,
|
|
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 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 { bindOidcRouter } from '../identity/router';\nimport { KeyStores } from '../identity/KeyStores';\nimport { TokenFactory } from '../identity/TokenFactory';\nimport { UserInfoDatabaseHandler } from '../identity/UserInfoDatabaseHandler';\nimport session from 'express-session';\nimport connectSessionKnex from 'connect-session-knex';\nimport passport from 'passport';\nimport { AuthDatabase } from '../database/AuthDatabase';\nimport { readBackstageTokenExpiration } from './readBackstageTokenExpiration';\nimport { TokenIssuer } from '../identity/types';\nimport { StaticTokenIssuer } from '../identity/StaticTokenIssuer';\nimport { StaticKeyStore } from '../identity/StaticKeyStore';\nimport { bindProviderRouters, ProviderFactories } from '../providers/router';\n\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}\n\nexport async function createRouter(\n options: RouterOptions,\n): Promise<express.Router> {\n const {\n logger,\n config,\n discovery,\n database,\n tokenFactoryAlgorithm,\n providerFactories = {},\n } = options;\n\n const router = Router();\n\n const appUrl = config.getString('app.baseUrl');\n const authUrl = await discovery.getExternalBaseUrl('auth');\n const backstageTokenExpiration = readBackstageTokenExpiration(config);\n const authDb = AuthDatabase.create(database);\n\n const keyStore = await KeyStores.fromConfig(config, {\n logger,\n database: authDb,\n });\n\n const userInfoDatabaseHandler = new UserInfoDatabaseHandler(\n await authDb.get(),\n );\n\n const omitClaimsFromToken = config.getOptionalBoolean(\n 'auth.omitIdentityTokenOwnershipClaim',\n )\n ? ['ent']\n : [];\n\n let tokenIssuer: TokenIssuer;\n if (keyStore instanceof StaticKeyStore) {\n tokenIssuer = new StaticTokenIssuer(\n {\n logger: logger.child({ component: 'token-factory' }),\n issuer: authUrl,\n sessionExpirationSeconds: backstageTokenExpiration,\n userInfoDatabaseHandler,\n omitClaimsFromToken,\n },\n keyStore as StaticKeyStore,\n );\n } else {\n tokenIssuer = new TokenFactory({\n issuer: authUrl,\n keyStore,\n keyDurationSeconds: backstageTokenExpiration,\n logger: logger.child({ component: 'token-factory' }),\n algorithm:\n tokenFactoryAlgorithm ??\n config.getOptionalString('auth.identityTokenAlgorithm'),\n userInfoDatabaseHandler,\n omitClaimsFromToken,\n });\n }\n\n const secret = config.getOptionalString('auth.session.secret');\n if (secret) {\n router.use(cookieParser(secret));\n const enforceCookieSSL = authUrl.startsWith('https');\n const KnexSessionStore = connectSessionKnex(session);\n router.use(\n session({\n secret,\n saveUninitialized: false,\n resave: false,\n cookie: { secure: enforceCookieSSL ? 'auto' : false },\n store: new KnexSessionStore({\n createtable: false,\n knex: await authDb.get(),\n }),\n }),\n );\n router.use(passport.initialize());\n router.use(passport.session());\n } else {\n router.use(cookieParser());\n }\n\n router.use(express.urlencoded({ extended: false }));\n router.use(express.json());\n\n bindProviderRouters(router, {\n providers: providerFactories,\n appUrl,\n baseUrl: authUrl,\n tokenIssuer,\n ...options,\n auth: options.auth,\n });\n\n bindOidcRouter(router, {\n auth: options.auth,\n tokenIssuer,\n baseUrl: authUrl,\n userInfoDatabaseHandler,\n });\n\n // Gives a more helpful error message than a plain 404\n router.use('/:provider/', req => {\n const { provider } = req.params;\n throw new NotFoundError(`Unknown auth provider '${provider}'`);\n });\n\n return router;\n}\n"],"names":["router","Router","readBackstageTokenExpiration","AuthDatabase","KeyStores","UserInfoDatabaseHandler","StaticKeyStore","StaticTokenIssuer","TokenFactory","cookieParser","connectSessionKnex","session","passport","express","bindProviderRouters","bindOidcRouter","NotFoundError"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuDA,eAAsB,aACpB,OACyB,EAAA;AACzB,EAAM,MAAA;AAAA,IACJ,MAAA;AAAA,IACA,MAAA;AAAA,IACA,SAAA;AAAA,IACA,QAAA;AAAA,IACA,qBAAA;AAAA,IACA,oBAAoB;AAAC,GACnB,GAAA,OAAA;AAEJ,EAAA,MAAMA,WAASC,uBAAO,EAAA;AAEtB,EAAM,MAAA,MAAA,GAAS,MAAO,CAAA,SAAA,CAAU,aAAa,CAAA;AAC7C,EAAA,MAAM,OAAU,GAAA,MAAM,SAAU,CAAA,kBAAA,CAAmB,MAAM,CAAA;AACzD,EAAM,MAAA,wBAAA,GAA2BC,0DAA6B,MAAM,CAAA;AACpE,EAAM,MAAA,MAAA,GAASC,yBAAa,CAAA,MAAA,CAAO,QAAQ,CAAA;AAE3C,EAAA,MAAM,QAAW,GAAA,MAAMC,mBAAU,CAAA,UAAA,CAAW,MAAQ,EAAA;AAAA,IAClD,MAAA;AAAA,IACA,QAAU,EAAA;AAAA,GACX,CAAA;AAED,EAAA,MAAM,0BAA0B,IAAIC,+CAAA;AAAA,IAClC,MAAM,OAAO,GAAI;AAAA,GACnB;AAEA,EAAA,MAAM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,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@backstage/plugin-auth-backend",
|
|
3
|
-
"version": "0.25.0-next.
|
|
3
|
+
"version": "0.25.0-next.2",
|
|
4
4
|
"description": "A Backstage backend plugin that handles authentication",
|
|
5
5
|
"backstage": {
|
|
6
6
|
"role": "backend-plugin",
|
|
@@ -46,12 +46,12 @@
|
|
|
46
46
|
"test": "backstage-cli package test"
|
|
47
47
|
},
|
|
48
48
|
"dependencies": {
|
|
49
|
-
"@backstage/backend-plugin-api": "1.3.1-next.
|
|
49
|
+
"@backstage/backend-plugin-api": "1.3.1-next.2",
|
|
50
50
|
"@backstage/catalog-model": "1.7.3",
|
|
51
51
|
"@backstage/config": "1.3.2",
|
|
52
52
|
"@backstage/errors": "1.2.7",
|
|
53
|
-
"@backstage/plugin-auth-node": "0.6.3-next.
|
|
54
|
-
"@backstage/plugin-catalog-node": "1.17.0-next.
|
|
53
|
+
"@backstage/plugin-auth-node": "0.6.3-next.2",
|
|
54
|
+
"@backstage/plugin-catalog-node": "1.17.0-next.2",
|
|
55
55
|
"@backstage/types": "1.2.1",
|
|
56
56
|
"@google-cloud/firestore": "^7.0.0",
|
|
57
57
|
"connect-session-knex": "^4.0.0",
|
|
@@ -68,10 +68,11 @@
|
|
|
68
68
|
"uuid": "^11.0.0"
|
|
69
69
|
},
|
|
70
70
|
"devDependencies": {
|
|
71
|
-
"@backstage/backend-defaults": "0.
|
|
72
|
-
"@backstage/backend-test-utils": "1.5.0-next.
|
|
73
|
-
"@backstage/cli": "0.32.1-next.
|
|
74
|
-
"@backstage/plugin-auth-backend-module-google-provider": "0.3.3-next.
|
|
71
|
+
"@backstage/backend-defaults": "0.10.0-next.3",
|
|
72
|
+
"@backstage/backend-test-utils": "1.5.0-next.3",
|
|
73
|
+
"@backstage/cli": "0.32.1-next.3",
|
|
74
|
+
"@backstage/plugin-auth-backend-module-google-provider": "0.3.3-next.2",
|
|
75
|
+
"@backstage/plugin-auth-backend-module-guest-provider": "0.2.8-next.2",
|
|
75
76
|
"@types/cookie-parser": "^1.4.2",
|
|
76
77
|
"@types/express": "^4.17.6",
|
|
77
78
|
"@types/express-session": "^1.17.2",
|