@coffre/core 0.14.7 → 0.16.0
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/README.md +1 -1
- package/dist/{access-BrdZKp1d.js → access-CF8UG59J.js} +70 -8
- package/dist/{access-qkMZa-6Z.d.ts → access-ERdGGHG7.d.ts} +45 -3
- package/dist/access.d.ts +2 -2
- package/dist/access.js +2 -2
- package/dist/envelope.d.ts +28 -9
- package/dist/envelope.js +25 -8
- package/dist/identity.d.ts +2 -917
- package/dist/identity.js +1036 -525
- package/dist/index-DuG9p3GH.d.ts +1233 -0
- package/dist/kek.d.ts +10 -16
- package/dist/kek.js +26 -41
- package/dist/log.d.ts +114 -0
- package/dist/log.js +291 -0
- package/dist/mcp.d.ts +25 -1
- package/dist/mcp.js +29 -4
- package/dist/recipe-BgJpmJum.d.ts +128 -0
- package/dist/recipe.d.ts +2 -127
- package/dist/{registry-D7X-x202.d.ts → registry-B7_LUDsJ.d.ts} +30 -5
- package/dist/schemas.d.ts +14 -4
- package/dist/schemas.js +16 -4
- package/dist/{types-Cp3lB_-W.js → types-DwTO_b4H.js} +17 -5
- package/dist/vault.d.ts +1800 -299
- package/dist/vault.js +99 -32
- package/package.json +8 -3
- package/src/access.ts +63 -8
- package/src/changes/access.ts +140 -0
- package/src/changes/freezes.ts +40 -0
- package/src/changes/mcp.ts +150 -0
- package/src/changes/places.ts +219 -0
- package/src/changes/secrets.ts +235 -0
- package/src/changes/signin.ts +197 -0
- package/src/changes/workloads.ts +166 -0
- package/src/context.ts +18 -2
- package/src/envelope.ts +35 -12
- package/src/identity/auth.ts +11 -3
- package/src/identity/aws.ts +62 -0
- package/src/identity/github-app.ts +45 -24
- package/src/identity/index.ts +3 -0
- package/src/identity/profiles.ts +139 -0
- package/src/identity/proofs.ts +306 -0
- package/src/identity/signin/config.ts +1 -1
- package/src/identity/tokens.ts +10 -3
- package/src/identity/verifier.ts +73 -14
- package/src/identity/workload-token.ts +4 -0
- package/src/kek/aws-kms.ts +18 -13
- package/src/kek/check.ts +16 -46
- package/src/kek/index.ts +2 -2
- package/src/kek/types.ts +15 -3
- package/src/log/index.ts +7 -0
- package/src/log/tiles.ts +166 -0
- package/src/log/tree.ts +163 -0
- package/src/mcp.ts +34 -3
- package/src/schemas.ts +16 -2
- package/src/vault.ts +308 -276
- package/src/checkpoint.ts +0 -22
package/dist/identity.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { BEARER_PROFILES, BindingInvalid, CREDENTIAL_NAME, EVENT_EXPOSURE, GITHUB_EVENTS, GITHUB_ISSUER, GITLAB_ISSUER, GITLAB_PIPELINE_SOURCES, GOOGLE_ISSUER, KEY_NAMING_PROFILES, MAX_BINDINGS, MAX_CLAIMS, MAX_CLAIM_BYTES, MAX_ISSUER_BYTES, MAX_READ_KEYS, MAX_READ_PLACES, MAX_SOURCES, OIDC_PROFILES, POLICY_DEFAULTS, POLICY_FIELDS, PROFILE_URNS, REPEATING_PROFILES, REQUIRED_CLAIMS, WORKLOAD_PROFILES, addressWithin, canonicalClaims, checkBinding, checkFetchUrl, checkPolicy, claimAt, claimValues, defaultIssuer, differingClaims, freezeTarget, fullRef, githubEventsAt, githubReusable, githubWorkflow, gitlabProject, isBearerProfile, parseAddress, parseCidr, policyText, workflowRef } from "./workloads.js";
|
|
2
2
|
import { createCipheriv, createDecipheriv, createHash, hkdfSync, randomBytes } from "node:crypto";
|
|
3
3
|
import * as oauth from "oauth4webapi";
|
|
4
|
+
import { compactVerify, createLocalJWKSet, decodeProtectedHeader, errors, importJWK, jwtVerify } from "jose";
|
|
4
5
|
import { MAX_PROOF_LENGTH, MAX_PROOF_LENGTH as MAX_PROOF_LENGTH$1, MAX_SIGNED_HEADERS, MAX_SIGNED_HEADERS as MAX_SIGNED_HEADERS$1, METHOD_TOKEN, UNSIGNED_HEADERS, canonicalHtu, canonicalHtu as canonicalHtu$1, canonicalRequest, fetchMethod, fetchMethod as fetchMethod$1, fromBase64url, requestDigest, sentTarget, sentTarget as sentTarget$1, thumbprint, thumbprint as thumbprint$1, tokenDigest } from "@coffre/client/dpop";
|
|
5
|
-
import { createLocalJWKSet, createRemoteJWKSet, errors, importJWK, jwtVerify } from "jose";
|
|
6
6
|
//#region src/identity/github-app.ts
|
|
7
7
|
/** GitHub could not be asked, or refused the app: the message says which, for a person, and carries no credential. */
|
|
8
8
|
var GitHubAppUnavailable = class extends Error {
|
|
@@ -49,18 +49,28 @@ var GitHubApp = class {
|
|
|
49
49
|
clientSecret: this.#clientSecret
|
|
50
50
|
};
|
|
51
51
|
}
|
|
52
|
-
/**
|
|
53
|
-
|
|
52
|
+
/**
|
|
53
|
+
* Every repository of every account the app is installed on, as many as
|
|
54
|
+
* `MAX_LISTING_REQUESTS` reach. `signal` ends every request still going
|
|
55
|
+
* when it aborts, and the listing with `GitHubAppUnavailable`: the caller's
|
|
56
|
+
* deadline for the whole of it, beside each request's own.
|
|
57
|
+
*/
|
|
58
|
+
async repositories(options = {}) {
|
|
59
|
+
const failed = new AbortController();
|
|
60
|
+
const signal = options.signal === void 0 ? failed.signal : AbortSignal.any([options.signal, failed.signal]);
|
|
54
61
|
const budget = { left: 40 };
|
|
55
|
-
this.#app ??= await this.#appInfo(budget);
|
|
56
|
-
const { installations, more } = await this.#installations(budget);
|
|
62
|
+
this.#app ??= await this.#appInfo(budget, signal);
|
|
63
|
+
const { installations, more } = await this.#installations(budget, signal);
|
|
57
64
|
let truncated = more;
|
|
58
65
|
/** An installation's repositories, its first page paid from `own`, and the rest from what the listing has left. */
|
|
59
66
|
const list = async (installation, own) => {
|
|
60
67
|
const repositories = [];
|
|
61
68
|
try {
|
|
62
69
|
for (let page = 1;; page++) {
|
|
63
|
-
const body = record(await this.#asInstallation(installation.id, `/installation/repositories?per_page=${PAGE}&page=${page}`, {
|
|
70
|
+
const body = record(await this.#asInstallation(installation.id, `/installation/repositories?per_page=${PAGE}&page=${page}`, {
|
|
71
|
+
budget: own,
|
|
72
|
+
signal
|
|
73
|
+
}));
|
|
64
74
|
const items = Array.isArray(body.repositories) ? body.repositories : [];
|
|
65
75
|
repositories.push(...items.flatMap((item) => repository(item) ?? []));
|
|
66
76
|
const total = typeof body.total_count === "number" ? body.total_count : 0;
|
|
@@ -92,7 +102,14 @@ var GitHubApp = class {
|
|
|
92
102
|
break;
|
|
93
103
|
}
|
|
94
104
|
rest = rest.slice(wave.length);
|
|
95
|
-
|
|
105
|
+
const failures = [];
|
|
106
|
+
const pages = await Promise.all(wave.map(({ installation, own }) => list(installation, own).catch((error) => {
|
|
107
|
+
failures.push(error);
|
|
108
|
+
failed.abort();
|
|
109
|
+
return [];
|
|
110
|
+
})));
|
|
111
|
+
if (failures.length > 0) throw failures[0];
|
|
112
|
+
listed.push(...pages);
|
|
96
113
|
for (const { own } of wave) budget.left += own.left;
|
|
97
114
|
}
|
|
98
115
|
const byId = new Map(listed.flat().map((each) => [each.repositoryId, each]));
|
|
@@ -103,14 +120,24 @@ var GitHubApp = class {
|
|
|
103
120
|
truncated
|
|
104
121
|
};
|
|
105
122
|
}
|
|
106
|
-
/** `owner/name`'s IDs, when the app is installed on it; null when it is not, its installation is suspended, or GitHub knows no such repository. */
|
|
107
|
-
async repository(fullName) {
|
|
108
|
-
const {
|
|
123
|
+
/** `owner/name`'s IDs, when the app is installed on it; null when it is not, its installation is suspended, or GitHub knows no such repository. `signal` as for `repositories`. */
|
|
124
|
+
async repository(fullName, options = {}) {
|
|
125
|
+
const { signal } = options;
|
|
126
|
+
const { id, suspended_at: suspended } = record(await this.#asApp(`/repos/${fullName}/installation`, {
|
|
127
|
+
missing: true,
|
|
128
|
+
signal
|
|
129
|
+
}));
|
|
109
130
|
if (typeof id !== "number" || suspended !== null && suspended !== void 0) return null;
|
|
110
|
-
return repository(await this.#asInstallation(id, `/repos/${fullName}`, {
|
|
131
|
+
return repository(await this.#asInstallation(id, `/repos/${fullName}`, {
|
|
132
|
+
missing: true,
|
|
133
|
+
signal
|
|
134
|
+
}));
|
|
111
135
|
}
|
|
112
|
-
async #appInfo(budget) {
|
|
113
|
-
const app = record(await this.#asApp("/app", {
|
|
136
|
+
async #appInfo(budget, signal) {
|
|
137
|
+
const app = record(await this.#asApp("/app", {
|
|
138
|
+
budget,
|
|
139
|
+
signal
|
|
140
|
+
}));
|
|
114
141
|
if (typeof app.name !== "string" || typeof app.html_url !== "string") throw new GitHubAppUnavailable("GitHub answered /app without the app");
|
|
115
142
|
return {
|
|
116
143
|
name: app.name,
|
|
@@ -118,8 +145,11 @@ var GitHubApp = class {
|
|
|
118
145
|
};
|
|
119
146
|
}
|
|
120
147
|
/** The installations not suspended, of the first page: `more` when there may be others. */
|
|
121
|
-
async #installations(budget) {
|
|
122
|
-
const answer = await this.#asApp(`/app/installations?per_page=${PAGE}`, {
|
|
148
|
+
async #installations(budget, signal) {
|
|
149
|
+
const answer = await this.#asApp(`/app/installations?per_page=${PAGE}`, {
|
|
150
|
+
budget,
|
|
151
|
+
signal
|
|
152
|
+
});
|
|
123
153
|
const items = Array.isArray(answer) ? answer : [];
|
|
124
154
|
return {
|
|
125
155
|
installations: items.flatMap((item) => {
|
|
@@ -144,7 +174,7 @@ var GitHubApp = class {
|
|
|
144
174
|
async #asInstallation(id, path, options = {}) {
|
|
145
175
|
const kept = this.#kept(id);
|
|
146
176
|
const fresh = kept === null;
|
|
147
|
-
const token = kept ?? await this.#issueToken(id, options
|
|
177
|
+
const token = kept ?? await this.#issueToken(id, options);
|
|
148
178
|
const answer = await this.#call(path, {
|
|
149
179
|
method: "GET",
|
|
150
180
|
token,
|
|
@@ -154,7 +184,7 @@ var GitHubApp = class {
|
|
|
154
184
|
if (answer !== REFUSED) return answer;
|
|
155
185
|
return this.#call(path, {
|
|
156
186
|
method: "GET",
|
|
157
|
-
token: await this.#issueToken(id, options
|
|
187
|
+
token: await this.#issueToken(id, options),
|
|
158
188
|
...options
|
|
159
189
|
});
|
|
160
190
|
}
|
|
@@ -164,12 +194,13 @@ var GitHubApp = class {
|
|
|
164
194
|
return kept !== void 0 && kept.expiresAt - 3e5 > this.#now() ? kept.token : null;
|
|
165
195
|
}
|
|
166
196
|
/** https://docs.github.com/en/rest/apps/apps#create-an-installation-access-token-for-an-app */
|
|
167
|
-
async #issueToken(id, budget) {
|
|
197
|
+
async #issueToken(id, { budget, signal }) {
|
|
168
198
|
this.#tokens.delete(id);
|
|
169
199
|
const answer = record(await this.#call(`/app/installations/${id}/access_tokens`, {
|
|
170
200
|
method: "POST",
|
|
171
201
|
token: await this.#jwt(),
|
|
172
|
-
budget
|
|
202
|
+
budget,
|
|
203
|
+
signal
|
|
173
204
|
}));
|
|
174
205
|
const expiresAt = typeof answer.expires_at === "string" ? Date.parse(answer.expires_at) : NaN;
|
|
175
206
|
if (typeof answer.token !== "string" || !Number.isFinite(expiresAt)) throw new GitHubAppUnavailable("GitHub issued no installation token");
|
|
@@ -203,7 +234,8 @@ var GitHubApp = class {
|
|
|
203
234
|
* `SPENT` when none is left. A 404 is null where `missing` allows it; a
|
|
204
235
|
* 401 is `REFUSED` where `refused` asks, for a token to be issued again;
|
|
205
236
|
* any other answer than a 2xx says GitHub's status and the path, and a
|
|
206
|
-
* redirect is never followed.
|
|
237
|
+
* redirect is never followed. It ends at its own deadline, or at the
|
|
238
|
+
* caller's `signal`, whichever comes first.
|
|
207
239
|
*/
|
|
208
240
|
async #call(path, request) {
|
|
209
241
|
if (request.budget !== void 0 && !spend(request.budget)) throw SPENT;
|
|
@@ -212,7 +244,7 @@ var GitHubApp = class {
|
|
|
212
244
|
response = await this.#fetch(`${this.apiUrl}${path}`, {
|
|
213
245
|
method: request.method,
|
|
214
246
|
redirect: "manual",
|
|
215
|
-
signal: AbortSignal.timeout(DEADLINE_MS),
|
|
247
|
+
signal: request.signal === void 0 ? AbortSignal.timeout(DEADLINE_MS) : AbortSignal.any([AbortSignal.timeout(DEADLINE_MS), request.signal]),
|
|
216
248
|
headers: {
|
|
217
249
|
accept: "application/vnd.github+json",
|
|
218
250
|
authorization: `Bearer ${request.token}`,
|
|
@@ -221,7 +253,7 @@ var GitHubApp = class {
|
|
|
221
253
|
}
|
|
222
254
|
});
|
|
223
255
|
} catch (cause) {
|
|
224
|
-
throw new GitHubAppUnavailable("GitHub could not be reached", { cause });
|
|
256
|
+
throw new GitHubAppUnavailable(request.signal?.aborted === true ? "GitHub did not answer in time" : "GitHub could not be reached", { cause });
|
|
225
257
|
}
|
|
226
258
|
if (response.ok) try {
|
|
227
259
|
return await response.json();
|
|
@@ -892,9 +924,14 @@ function checkAudience(audience) {
|
|
|
892
924
|
/**
|
|
893
925
|
* Cloudflare Access in front of coffre: every request carries Access's
|
|
894
926
|
* signed assertion, checked against the team's keys and the application's
|
|
895
|
-
* AUD tag.
|
|
927
|
+
* AUD tag. A browser's first request signs its person in to a session of
|
|
928
|
+
* coffre's, which every later one shows beside the assertion; the CLI and
|
|
929
|
+
* machines are not served behind Access yet.
|
|
896
930
|
*
|
|
897
931
|
* cloudflareAccess({ teamDomain: 'acme.cloudflareaccess.com', audience: env.ACCESS_AUD })
|
|
932
|
+
*
|
|
933
|
+
* `browserSessionHours`: the longest that session lasts, 12 hours unless
|
|
934
|
+
* set, at most a week. Access's own session is the one people see.
|
|
898
935
|
*/
|
|
899
936
|
function cloudflareAccess(options) {
|
|
900
937
|
const domain = options.teamDomain.trim();
|
|
@@ -907,7 +944,8 @@ function cloudflareAccess(options) {
|
|
|
907
944
|
issuer,
|
|
908
945
|
jwksUrl: `${issuer}/cdn-cgi/access/certs`,
|
|
909
946
|
audience: checkAudience(options.audience.trim())
|
|
910
|
-
}
|
|
947
|
+
},
|
|
948
|
+
browserSessionHours: lifetime(options.browserSessionHours, "browserSessionHours", 12, 168)
|
|
911
949
|
};
|
|
912
950
|
return { resolve: () => config };
|
|
913
951
|
}
|
|
@@ -943,171 +981,844 @@ function toSignin(options) {
|
|
|
943
981
|
};
|
|
944
982
|
}
|
|
945
983
|
//#endregion
|
|
946
|
-
//#region src/identity/
|
|
984
|
+
//#region src/identity/profiles.ts
|
|
985
|
+
const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
|
|
986
|
+
/** A Kubernetes namespace (a DNS label) and service account (a DNS subdomain), as its tokens' `sub` names them. */
|
|
987
|
+
const SERVICE_ACCOUNT_SUB = /^system:serviceaccount:([a-z0-9]([-a-z0-9]{0,61}[a-z0-9])?):([a-z0-9]([-a-z0-9.]{0,251}[a-z0-9])?)$/;
|
|
988
|
+
/** A Google service account's unique ID: digits, 21 of them today. */
|
|
989
|
+
const GOOGLE_ID = /^[1-9]\d{0,31}$/;
|
|
990
|
+
const AZURE_V1 = /^https:\/\/sts\.windows\.net\/([0-9a-f-]{36})\/$/;
|
|
991
|
+
const AZURE_V2 = /^https:\/\/login\.microsoftonline\.com\/([0-9a-f-]{36})\/v2\.0$/;
|
|
992
|
+
const FLY_ISSUER = /^https:\/\/oidc\.fly\.io\/[a-z0-9][a-z0-9-]{0,62}$/;
|
|
947
993
|
/**
|
|
948
|
-
*
|
|
949
|
-
*
|
|
950
|
-
*
|
|
951
|
-
* it asked and what its parent holds, computed when it is made and stored
|
|
952
|
-
* under its row's MAC, and every operation it asks for is checked against
|
|
953
|
-
* them by `constraintsAllow`, on the URL the proxy is about to send.
|
|
954
|
-
*
|
|
955
|
-
* parent { credentials: ['stripe', 'openai'] } child asks { credentials: ['stripe'], paths: ['/v1/refunds'] }
|
|
956
|
-
* child { credentials: ['stripe'], paths: ['/v1/refunds'] }
|
|
957
|
-
* POST https://api.stripe.com/v1/refunds/re_1 allowed
|
|
958
|
-
* POST https://api.stripe.com/v1/refunds/%2e%2e/charges refused: it is /v1/charges once parsed
|
|
959
|
-
* POST https://api.stripe.com/v1/refundsX refused: a prefix matches whole segments
|
|
994
|
+
* Fly's IDs are digits in its documentation's tokens, unchecked live: kept
|
|
995
|
+
* loose, which fails closed, since a token's `org_id` and `app_id` are IDs
|
|
996
|
+
* and a binding naming a name matches none.
|
|
960
997
|
*/
|
|
961
|
-
|
|
962
|
-
const
|
|
963
|
-
|
|
964
|
-
|
|
965
|
-
|
|
966
|
-
|
|
967
|
-
|
|
998
|
+
const FLY_ID = /^[A-Za-z0-9_-]{1,64}$/;
|
|
999
|
+
const VERCEL_ISSUER = /^https:\/\/oidc\.vercel\.com(\/[a-z0-9][a-z0-9-]{0,62})?$/;
|
|
1000
|
+
const VERCEL_OWNER = /^(team_)?[A-Za-z0-9]{8,64}$/;
|
|
1001
|
+
const VERCEL_PROJECT = /^prj_[A-Za-z0-9]{8,64}$/;
|
|
1002
|
+
/** `production`, `preview`, `development`, or a custom environment's slug. */
|
|
1003
|
+
const VERCEL_ENVIRONMENT = /^[a-z0-9][a-z0-9-]{0,63}$/;
|
|
1004
|
+
const AWS_ACCOUNT = /^\d{12}$/;
|
|
1005
|
+
/** A role's unique ID: `AROA`, then its own characters. */
|
|
1006
|
+
const AWS_ROLE_ID = /^AROA[A-Z0-9]{8,124}$/;
|
|
1007
|
+
function shaped(claims, name, pattern, what) {
|
|
1008
|
+
if (!pattern.test(claims[name])) throw new BindingInvalid(`${name} is ${what}`);
|
|
1009
|
+
}
|
|
1010
|
+
const none = () => null;
|
|
1011
|
+
const PROFILE_RULES = {
|
|
1012
|
+
kubernetes: {
|
|
1013
|
+
binding({ claims }) {
|
|
1014
|
+
const sub = SERVICE_ACCOUNT_SUB.exec(claims.sub);
|
|
1015
|
+
if (sub === null) throw new BindingInvalid("sub is the service account's, system:serviceaccount:<namespace>:<name>");
|
|
1016
|
+
shaped(claims, "kubernetes.io.serviceaccount.uid", UUID, "the service account's UID, which a service account made again under the same name does not keep: kubectl get serviceaccount <name> -o jsonpath='{.metadata.uid}'");
|
|
1017
|
+
for (const [name, value] of [["kubernetes.io.namespace", sub[1]], ["kubernetes.io.serviceaccount.name", sub[3]]]) if (claims[name] !== void 0 && claims[name] !== value) throw new BindingInvalid(`${name} is ${value}, as its sub says`);
|
|
1018
|
+
},
|
|
1019
|
+
token(claims) {
|
|
1020
|
+
const sub = SERVICE_ACCOUNT_SUB.exec(String(claims.sub));
|
|
1021
|
+
if (sub === null) return "the token's sub is no service account's";
|
|
1022
|
+
const namespace = claimAt(claims, "kubernetes.io.namespace");
|
|
1023
|
+
const name = claimAt(claims, "kubernetes.io.serviceaccount.name");
|
|
1024
|
+
return namespace === sub[1] && name === sub[3] ? null : "the token names another service account under kubernetes.io than its sub";
|
|
1025
|
+
}
|
|
1026
|
+
},
|
|
1027
|
+
gcp: {
|
|
1028
|
+
binding({ claims }) {
|
|
1029
|
+
shaped(claims, "sub", GOOGLE_ID, "the service account's unique ID, its digits, which a service account made again under the same email does not keep: gcloud iam service-accounts describe <email> --format='value(uniqueId)'");
|
|
1030
|
+
},
|
|
1031
|
+
token: none
|
|
1032
|
+
},
|
|
1033
|
+
azure: {
|
|
1034
|
+
binding({ issuer, claims }, policy) {
|
|
1035
|
+
const tenant = AZURE_V1.exec(issuer)?.[1] ?? AZURE_V2.exec(issuer)?.[1];
|
|
1036
|
+
if (tenant === void 0 || !UUID.test(tenant)) throw new BindingInvalid("an azure binding's issuer is https://sts.windows.net/<tenant>/ (v1 tokens) or https://login.microsoftonline.com/<tenant>/v2.0 (v2), by the tenant's ID");
|
|
1037
|
+
shaped(claims, "tid", UUID, "the tenant's ID");
|
|
1038
|
+
if (claims.tid !== tenant) throw new BindingInvalid("tid is the tenant its issuer names");
|
|
1039
|
+
shaped(claims, "oid", UUID, "the managed identity's object ID (its principal ID): az identity show --query principalId");
|
|
1040
|
+
if (AZURE_V2.test(issuer) && !UUID.test(policy.audience ?? "")) throw new BindingInvalid("a v2 token's audience is the API's application (client) ID, a GUID, never its App ID URI: Entra puts no other in a v2 token");
|
|
1041
|
+
},
|
|
1042
|
+
token(claims, binding) {
|
|
1043
|
+
const version = AZURE_V1.test(binding.issuer) ? "1.0" : "2.0";
|
|
1044
|
+
return claims.ver === version ? null : `the token is of version ${JSON.stringify(claims.ver ?? null)}, and its binding's issuer issues ${version}`;
|
|
1045
|
+
}
|
|
1046
|
+
},
|
|
1047
|
+
fly: {
|
|
1048
|
+
binding({ issuer, claims }) {
|
|
1049
|
+
if (!FLY_ISSUER.test(issuer)) throw new BindingInvalid("a fly binding's issuer is https://oidc.fly.io/<organization>, by its slug");
|
|
1050
|
+
shaped(claims, "org_id", FLY_ID, "the organization's ID, as its tokens' org_id says it");
|
|
1051
|
+
shaped(claims, "app_id", FLY_ID, "the app's ID, as its tokens' app_id says it");
|
|
1052
|
+
},
|
|
1053
|
+
token: none
|
|
1054
|
+
},
|
|
1055
|
+
vercel: {
|
|
1056
|
+
binding({ issuer, claims }) {
|
|
1057
|
+
if (!VERCEL_ISSUER.test(issuer)) throw new BindingInvalid("a vercel binding's issuer is https://oidc.vercel.com/<team> (team mode) or https://oidc.vercel.com (global mode)");
|
|
1058
|
+
shaped(claims, "owner_id", VERCEL_OWNER, "the team's ID, team_…, as .vercel/project.json's orgId says it");
|
|
1059
|
+
shaped(claims, "project_id", VERCEL_PROJECT, "the project's ID, prj_…, as .vercel/project.json's projectId says it");
|
|
1060
|
+
shaped(claims, "environment", VERCEL_ENVIRONMENT, "production, preview, development or a custom environment's slug");
|
|
1061
|
+
},
|
|
1062
|
+
token: none
|
|
1063
|
+
},
|
|
1064
|
+
aws: {
|
|
1065
|
+
binding({ claims }) {
|
|
1066
|
+
const extra = Object.keys(claims).filter((name) => name !== "account" && name !== "role_id");
|
|
1067
|
+
if (extra.length > 0) throw new BindingInvalid(`an aws binding names its role's account and role_id alone, not ${extra.join(", ")}`);
|
|
1068
|
+
shaped(claims, "account", AWS_ACCOUNT, "the account's 12 digits");
|
|
1069
|
+
shaped(claims, "role_id", AWS_ROLE_ID, "the role's unique ID, AROA…, which a role made again under the same name does not keep: aws iam get-role --role-name <name> --query Role.RoleId");
|
|
1070
|
+
},
|
|
1071
|
+
token: none
|
|
968
1072
|
}
|
|
969
1073
|
};
|
|
970
|
-
const PLACE = /^[a-z0-9][a-z0-9-]{0,62}\/[a-z0-9][a-z0-9-]{0,62}(@me)?$/;
|
|
971
|
-
/** A path segment as a constraint names one: no escape, no `;`, no dot segment. */
|
|
972
|
-
const SEGMENT = /^[A-Za-z0-9\-_~!$&'()*+,=:@.]+$/;
|
|
973
1074
|
/**
|
|
974
|
-
*
|
|
975
|
-
*
|
|
976
|
-
*
|
|
977
|
-
* (
|
|
978
|
-
*
|
|
1075
|
+
* The audiences a token of a binding may name, the first the one its SDK
|
|
1076
|
+
* asks for: the session's key, `<publicUrl>#jkt=<thumbprint>`, for the
|
|
1077
|
+
* platforms whose caller picks the audience, and `?jkt=` for one that
|
|
1078
|
+
* refuses a `#` in it (section 4.2); the exact audience of a platform that
|
|
1079
|
+
* fixes it; this instance's URL for every other.
|
|
979
1080
|
*/
|
|
980
|
-
|
|
981
|
-
|
|
982
|
-
|
|
983
|
-
if (!Array.isArray(value) || value.length > 32 || value.some((item) => typeof item !== "string" || !valid(item))) throw new ConstraintsInvalid(`${what} lists at most 32 of them`);
|
|
984
|
-
return [...new Set(value)].sort();
|
|
985
|
-
}
|
|
986
|
-
function isPrefix(path) {
|
|
987
|
-
if (path === "/") return true;
|
|
988
|
-
if (!path.startsWith("/") || path.endsWith("/")) return false;
|
|
989
|
-
return path.slice(1).split("/").every((segment) => SEGMENT.test(segment) && segment !== "." && segment !== "..");
|
|
990
|
-
}
|
|
991
|
-
/** Whether `path` is `prefix` or below it, by whole segments. */
|
|
992
|
-
function under(path, prefix) {
|
|
993
|
-
return prefix === "/" || path === prefix || path.startsWith(`${prefix}/`);
|
|
1081
|
+
function expectedAudiences(profile, policy, expected) {
|
|
1082
|
+
if (KEY_NAMING_PROFILES.includes(profile) || policy.keyAudience === true) return [`${expected.publicUrl}#jkt=${expected.jkt}`, `${expected.publicUrl}?jkt=${expected.jkt}`];
|
|
1083
|
+
return [policy.audience ?? expected.publicUrl];
|
|
994
1084
|
}
|
|
1085
|
+
//#endregion
|
|
1086
|
+
//#region src/identity/workload-token.ts
|
|
995
1087
|
/**
|
|
996
|
-
*
|
|
997
|
-
*
|
|
998
|
-
*
|
|
999
|
-
* another, which it would add nothing to. Throws `ConstraintsInvalid`.
|
|
1088
|
+
* An ID token a CI platform signed for a run, as the exchange checks it
|
|
1089
|
+
* (docs/design/oidc.md, section 3). The checks run in this order; each
|
|
1090
|
+
* refusal says which, as a reason a CI user can act on.
|
|
1000
1091
|
*/
|
|
1001
|
-
|
|
1002
|
-
|
|
1003
|
-
|
|
1004
|
-
|
|
1005
|
-
|
|
1006
|
-
|
|
1007
|
-
|
|
1008
|
-
|
|
1009
|
-
|
|
1010
|
-
|
|
1011
|
-
|
|
1012
|
-
|
|
1013
|
-
|
|
1014
|
-
|
|
1015
|
-
}
|
|
1016
|
-
|
|
1017
|
-
|
|
1018
|
-
|
|
1019
|
-
|
|
1020
|
-
|
|
1021
|
-
if (
|
|
1022
|
-
if (
|
|
1023
|
-
|
|
1092
|
+
/** A compact JWS is three base64url parts; the whole token at most this long. */
|
|
1093
|
+
const MAX_TOKEN_BYTES = 8192;
|
|
1094
|
+
/** Each side of every time check. */
|
|
1095
|
+
const CLOCK_TOLERANCE_SECONDS = 30;
|
|
1096
|
+
/** The oldest token accepted, by its `iat`: tokens handed to a job at its start fit, day-old ones do not. */
|
|
1097
|
+
const MAX_TOKEN_AGE_SECONDS = 3600;
|
|
1098
|
+
/** RS256 and ES256 (P-256), as for Access assertions: never `none`, never HS*. */
|
|
1099
|
+
const WORKLOAD_ALGORITHMS = ["RS256", "ES256"];
|
|
1100
|
+
var WorkloadTokenRefused = class extends Error {
|
|
1101
|
+
reason;
|
|
1102
|
+
constructor(reason, message) {
|
|
1103
|
+
super(message);
|
|
1104
|
+
this.name = "WorkloadTokenRefused";
|
|
1105
|
+
this.reason = reason;
|
|
1106
|
+
}
|
|
1107
|
+
};
|
|
1108
|
+
const PART = /^[A-Za-z0-9_-]+$/;
|
|
1109
|
+
/** A token's parts and claims, checked for shape and types only. Throws `WorkloadTokenRefused('malformed')`. */
|
|
1110
|
+
function decodeWorkloadToken(token) {
|
|
1111
|
+
const malformed = (why) => new WorkloadTokenRefused("malformed", `the token ${why}`);
|
|
1112
|
+
if (typeof token !== "string" || token.length === 0) throw malformed("is empty");
|
|
1113
|
+
if (token.length > 8192) throw malformed(`is longer than ${MAX_TOKEN_BYTES} bytes`);
|
|
1114
|
+
const parts = token.split(".");
|
|
1115
|
+
if (parts.length !== 3 || !parts.every((part) => PART.test(part))) throw malformed("is not a compact JWS");
|
|
1116
|
+
const json = (part) => {
|
|
1117
|
+
let value;
|
|
1118
|
+
try {
|
|
1119
|
+
value = JSON.parse(Buffer.from(part, "base64url").toString("utf8"));
|
|
1120
|
+
} catch {
|
|
1121
|
+
throw malformed("has a part that is not JSON");
|
|
1122
|
+
}
|
|
1123
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) throw malformed("has a part that is not an object");
|
|
1124
|
+
return value;
|
|
1125
|
+
};
|
|
1126
|
+
const [header, claims] = [json(parts[0]), json(parts[1])];
|
|
1127
|
+
if (header.crit !== void 0) throw malformed("names a critical header extension");
|
|
1128
|
+
for (const name of ["iss", "sub"]) {
|
|
1129
|
+
if (typeof claims[name] !== "string" || claims[name] === "") throw malformed(`has no ${name}, as a nonempty string`);
|
|
1130
|
+
if (/[\0\p{Cs}]/u.test(claims[name])) throw malformed(`has an ${name} with a NUL or a lone surrogate`);
|
|
1131
|
+
}
|
|
1132
|
+
for (const name of ["exp", "iat"]) if (typeof claims[name] !== "number" || !Number.isFinite(claims[name])) throw malformed(`has no ${name}, as a finite number`);
|
|
1133
|
+
if (claims.nbf !== void 0 && (typeof claims.nbf !== "number" || !Number.isFinite(claims.nbf))) throw malformed("has an nbf that is not a finite number");
|
|
1134
|
+
return {
|
|
1135
|
+
header,
|
|
1136
|
+
claims,
|
|
1137
|
+
signingInputHash: createHash("sha256").update(`${parts[0]}.${parts[1]}`, "ascii").digest()
|
|
1138
|
+
};
|
|
1024
1139
|
}
|
|
1025
1140
|
/**
|
|
1026
|
-
*
|
|
1027
|
-
*
|
|
1028
|
-
*
|
|
1029
|
-
*
|
|
1141
|
+
* Verify a token under an issuer's keys: the signature by jose, with the
|
|
1142
|
+
* algorithms fixed and nothing taken from the header but `alg` and `kid`;
|
|
1143
|
+
* the issuer exactly; `exp`, `nbf` and `iat` within the tolerance, `iat` at
|
|
1144
|
+
* most an hour old; and the audience, this instance's public URL alone.
|
|
1145
|
+
* With `maxLifetime`, in seconds, a token whose `exp` is further than that
|
|
1146
|
+
* from its `iat` is refused too. With `maxAge: null`, its `iat` may be any
|
|
1147
|
+
* age, and its own `exp` alone ends it: a token its platform hands out
|
|
1148
|
+
* again for hours, a managed identity's (docs/design/workload-access.md,
|
|
1149
|
+
* section 4.2). Returns the verified claims.
|
|
1030
1150
|
*/
|
|
1031
|
-
function
|
|
1032
|
-
|
|
1033
|
-
|
|
1034
|
-
|
|
1035
|
-
|
|
1036
|
-
|
|
1037
|
-
|
|
1038
|
-
|
|
1039
|
-
|
|
1040
|
-
|
|
1041
|
-
|
|
1042
|
-
|
|
1043
|
-
}
|
|
1044
|
-
|
|
1045
|
-
|
|
1151
|
+
async function verifyWorkloadToken(token, keys, expected) {
|
|
1152
|
+
const options = {
|
|
1153
|
+
algorithms: [...WORKLOAD_ALGORITHMS],
|
|
1154
|
+
issuer: expected.issuer,
|
|
1155
|
+
clockTolerance: 30,
|
|
1156
|
+
requiredClaims: [
|
|
1157
|
+
"iss",
|
|
1158
|
+
"sub",
|
|
1159
|
+
"exp",
|
|
1160
|
+
"iat"
|
|
1161
|
+
],
|
|
1162
|
+
currentDate: expected.now
|
|
1163
|
+
};
|
|
1164
|
+
let payload;
|
|
1165
|
+
try {
|
|
1166
|
+
({payload} = await jwtVerify(token, createLocalJWKSet(keys), options));
|
|
1167
|
+
} catch (error) {
|
|
1168
|
+
if (!(error instanceof errors.JWKSMultipleMatchingKeys)) throw refusalOf(error);
|
|
1169
|
+
payload = await anyKey(token, error, options);
|
|
1046
1170
|
}
|
|
1047
|
-
|
|
1048
|
-
|
|
1049
|
-
|
|
1050
|
-
|
|
1051
|
-
|
|
1052
|
-
return
|
|
1053
|
-
places,
|
|
1054
|
-
credentials,
|
|
1055
|
-
methods,
|
|
1056
|
-
paths
|
|
1057
|
-
});
|
|
1171
|
+
const issued = issuedRefusal(payload.iat, expected.now.getTime() / 1e3, expected.maxAge === null ? Infinity : MAX_TOKEN_AGE_SECONDS);
|
|
1172
|
+
if (issued !== null) throw issued;
|
|
1173
|
+
if (expected.maxLifetime !== void 0 && payload.exp - payload.iat > expected.maxLifetime) throw new WorkloadTokenRefused("too_long", `the token lives longer than ${expected.maxLifetime / 60} minutes, from its iat to its exp: ask for a shorter one`);
|
|
1174
|
+
const { aud } = payload;
|
|
1175
|
+
if (!(aud === expected.audience || Array.isArray(aud) && aud.length === 1 && aud[0] === expected.audience)) throw new WorkloadTokenRefused("audience", `the token is for ${JSON.stringify(aud ?? null)}, not ${expected.audience} alone`);
|
|
1176
|
+
return payload;
|
|
1058
1177
|
}
|
|
1059
1178
|
/**
|
|
1060
|
-
*
|
|
1061
|
-
*
|
|
1062
|
-
*
|
|
1063
|
-
*
|
|
1064
|
-
* tunnel) is refused wherever methods or paths are limited: a constraint
|
|
1065
|
-
* that cannot be checked refuses.
|
|
1179
|
+
* Why a token issued at `iat` may not be exchanged at `now`, both in
|
|
1180
|
+
* seconds, or null: issued `maxAge` seconds ago at most, an hour unless
|
|
1181
|
+
* said, exactly, and no further ahead than the clock tolerance.
|
|
1182
|
+
* Verification and the exchange's commit both ask it.
|
|
1066
1183
|
*/
|
|
1067
|
-
function
|
|
1068
|
-
if (
|
|
1069
|
-
if (
|
|
1070
|
-
|
|
1071
|
-
if (constraints.methods === void 0 && constraints.paths === void 0) return true;
|
|
1072
|
-
if (operation.request === void 0) return false;
|
|
1073
|
-
if (constraints.methods !== void 0 && !(METHOD_TOKEN.test(operation.request.method) && constraints.methods.includes(fetchMethod$1(operation.request.method)))) return false;
|
|
1074
|
-
if (constraints.paths === void 0) return true;
|
|
1075
|
-
let path;
|
|
1076
|
-
try {
|
|
1077
|
-
path = new URL(String(operation.request.url)).pathname;
|
|
1078
|
-
} catch {
|
|
1079
|
-
return false;
|
|
1080
|
-
}
|
|
1081
|
-
if (AMBIGUOUS.test(path)) return false;
|
|
1082
|
-
return constraints.paths.some((prefix) => under(path, prefix));
|
|
1184
|
+
function issuedRefusal(iat, now, maxAge = MAX_TOKEN_AGE_SECONDS) {
|
|
1185
|
+
if (now - iat > maxAge) return new WorkloadTokenRefused("too_old", `the token was issued more than ${maxAge / 60} minutes ago`);
|
|
1186
|
+
if (iat - now > 30) return new WorkloadTokenRefused("too_old", "the token says it was issued in the future");
|
|
1187
|
+
return null;
|
|
1083
1188
|
}
|
|
1084
|
-
//#endregion
|
|
1085
|
-
//#region src/identity/dpop.ts
|
|
1086
1189
|
/**
|
|
1087
|
-
*
|
|
1088
|
-
*
|
|
1089
|
-
*
|
|
1090
|
-
*
|
|
1091
|
-
* 1. shape at most 2 KiB, `typ` exactly `dpop+jwt`, `alg` exactly `ES256`
|
|
1092
|
-
* 2. the key `jwk` exactly `kty`, `crv`, `x` and `y`, a point on P-256
|
|
1093
|
-
* 3. claims `jti` 16 bytes, `iat` an integer, `hdr` at most 32 names, none unsigned
|
|
1094
|
-
* (`parseProof`, no I/O)
|
|
1095
|
-
* 4. the session row, from the token's hash: the server's, between the two
|
|
1096
|
-
* 5. key and signature the thumbprint is the row's `jkt`, then ES256
|
|
1097
|
-
* 6. what was signed `htm`, `htu`, `ath`, `req`, then `iat` within ±300 s
|
|
1098
|
-
* (`verifyProof`)
|
|
1099
|
-
* 7. the gate's nonce and `jti`: the server's again (`Gate`)
|
|
1100
|
-
*
|
|
1101
|
-
* Each claim the caller expects (`ath` with a token, `hdr` and `req` with a
|
|
1102
|
-
* request's content) must be there, and one it does not expect must not.
|
|
1103
|
-
* Two signatures of one payload, `(r, s)` and `(r, n − s)`, both verify:
|
|
1104
|
-
* they carry one `jti`, which the gate takes once.
|
|
1190
|
+
* A token that names no key, or one several keys share, verified by
|
|
1191
|
+
* whichever of them signed it: a set may hold several, as while its issuer
|
|
1192
|
+
* rotates. At most `MAX_KEYS` tries, each a signature check alone.
|
|
1105
1193
|
*/
|
|
1106
|
-
|
|
1107
|
-
const
|
|
1108
|
-
|
|
1109
|
-
|
|
1110
|
-
|
|
1194
|
+
async function anyKey(token, matching, options) {
|
|
1195
|
+
for await (const key of matching) try {
|
|
1196
|
+
return (await jwtVerify(token, key, options)).payload;
|
|
1197
|
+
} catch (error) {
|
|
1198
|
+
if (!(error instanceof errors.JWSSignatureVerificationFailed)) throw refusalOf(error);
|
|
1199
|
+
}
|
|
1200
|
+
throw new WorkloadTokenRefused("signature", "the token's signature does not verify");
|
|
1201
|
+
}
|
|
1202
|
+
function refusalOf(error) {
|
|
1203
|
+
if (error instanceof errors.JWKSNoMatchingKey) return new WorkloadTokenRefused("unknown_key", "the token's key is not among the issuer's");
|
|
1204
|
+
if (error instanceof errors.JWTExpired) return error.claim === "iat" ? new WorkloadTokenRefused("too_old", `the token was issued more than ${MAX_TOKEN_AGE_SECONDS / 60} minutes ago`) : new WorkloadTokenRefused("expired", "the token has expired");
|
|
1205
|
+
if (error instanceof errors.JWTClaimValidationFailed) {
|
|
1206
|
+
if (error.claim === "nbf") return new WorkloadTokenRefused("not_yet_valid", "the token is not valid yet");
|
|
1207
|
+
if (error.claim === "iat") return new WorkloadTokenRefused("too_old", "the token says it was issued in the future");
|
|
1208
|
+
if (error.claim === "iss") return new WorkloadTokenRefused("signature", "the token is not from the binding's issuer");
|
|
1209
|
+
return new WorkloadTokenRefused("malformed", `the token's ${error.claim} is not as required`);
|
|
1210
|
+
}
|
|
1211
|
+
if (error instanceof errors.JOSEAlgNotAllowed || error instanceof errors.JOSENotSupported) return new WorkloadTokenRefused("signature", "the token is signed with an algorithm coffre does not accept");
|
|
1212
|
+
if (error instanceof errors.JWSSignatureVerificationFailed || error instanceof errors.JWSInvalid || error instanceof errors.JWTInvalid) return new WorkloadTokenRefused("signature", "the token's signature does not verify");
|
|
1213
|
+
if (error instanceof errors.JOSEError) return new WorkloadTokenRefused("signature", `the token does not verify: ${error.code}`);
|
|
1214
|
+
return new WorkloadTokenRefused("signature", "the token does not verify");
|
|
1215
|
+
}
|
|
1216
|
+
/** At most this many keys in a set, fetched or uploaded. */
|
|
1217
|
+
const MAX_KEYS = 32;
|
|
1218
|
+
/** A key set that cannot be uploaded, said so an owner can fix it. */
|
|
1219
|
+
var KeysInvalid = class extends Error {
|
|
1220
|
+
constructor(message) {
|
|
1221
|
+
super(message);
|
|
1222
|
+
this.name = "KeysInvalid";
|
|
1223
|
+
}
|
|
1224
|
+
};
|
|
1225
|
+
/** Members that only a private or a symmetric key has. */
|
|
1226
|
+
const PRIVATE_MEMBERS = [
|
|
1227
|
+
"d",
|
|
1228
|
+
"p",
|
|
1229
|
+
"q",
|
|
1230
|
+
"dp",
|
|
1231
|
+
"dq",
|
|
1232
|
+
"qi",
|
|
1233
|
+
"oth",
|
|
1234
|
+
"k"
|
|
1235
|
+
];
|
|
1236
|
+
/**
|
|
1237
|
+
* An issuer's public keys, as uploaded for a binding: a JWKS, `{ "keys": [
|
|
1238
|
+
* … ] }`, of RSA keys of 2048 bits or more, for RS256, and P-256 keys, for
|
|
1239
|
+
* ES256, each kept with only the members that verify (`kty`, `kid`, `use`,
|
|
1240
|
+
* `alg` and the key), in the order of their thumbprints, so that one set
|
|
1241
|
+
* however listed has one digest. An RSA key's parameters are checked
|
|
1242
|
+
* before jose sees them, since it takes some that verify anything: an
|
|
1243
|
+
* exponent of 1 makes every signature its message. Keys for encryption are
|
|
1244
|
+
* left out, as from a fetched set; a private or a symmetric key refuses the
|
|
1245
|
+
* whole set, since coffre keeps no secret of an issuer's. Throws
|
|
1246
|
+
* `KeysInvalid`.
|
|
1247
|
+
*/
|
|
1248
|
+
async function uploadedKeys(value) {
|
|
1249
|
+
const listed = value?.keys;
|
|
1250
|
+
if (typeof value !== "object" || value === null || !Array.isArray(listed)) throw new KeysInvalid("the keys are a JWKS: { \"keys\": [ … ] }");
|
|
1251
|
+
if (listed.length > 32) throw new KeysInvalid(`a key set holds at most 32 keys`);
|
|
1252
|
+
const keys = [];
|
|
1253
|
+
for (const [i, given] of listed.entries()) {
|
|
1254
|
+
if (typeof given !== "object" || given === null || Array.isArray(given)) throw new KeysInvalid(`key ${i + 1} is not a JWK`);
|
|
1255
|
+
const jwk = given;
|
|
1256
|
+
const named = typeof jwk.kid === "string" ? `key ${jwk.kid}` : `key ${i + 1}`;
|
|
1257
|
+
if (PRIVATE_MEMBERS.some((member) => member in jwk)) throw new KeysInvalid(`${named} is a private or a secret key: upload the issuer's public keys only`);
|
|
1258
|
+
if (jwk.use === "enc") continue;
|
|
1259
|
+
if (jwk.use !== void 0 && jwk.use !== "sig") throw new KeysInvalid(`${named} has use ${JSON.stringify(jwk.use)}: sig, or none`);
|
|
1260
|
+
if (jwk.kid !== void 0 && (typeof jwk.kid !== "string" || jwk.kid === "" || jwk.kid.length > 256)) throw new KeysInvalid(`key ${i + 1}'s kid is not a string`);
|
|
1261
|
+
if (jwk.kid !== void 0 && keys.some((key) => key.kid === jwk.kid)) throw new KeysInvalid(`two keys are ${named}`);
|
|
1262
|
+
let alg;
|
|
1263
|
+
let key;
|
|
1264
|
+
if (jwk.kty === "RSA" && (jwk.alg === void 0 || jwk.alg === "RS256")) {
|
|
1265
|
+
alg = "RS256";
|
|
1266
|
+
const [n, e] = [integer(jwk.n), integer(jwk.e)];
|
|
1267
|
+
if (n === null || e === null) throw new KeysInvalid(`${named} is an RSA key without n and e, each a base64url integer in its fewest bytes`);
|
|
1268
|
+
if (n.toString(2).length < 2048) throw new KeysInvalid(`${named} is an RSA key under 2048 bits`);
|
|
1269
|
+
if (n % 2n === 0n) throw new KeysInvalid(`${named} is not a valid RSA key`);
|
|
1270
|
+
if (e % 2n === 0n || e <= 65536n || e >= 2n ** 256n) throw new KeysInvalid(`${named}'s exponent is not one an RSA key signs with: odd, from 65537`);
|
|
1271
|
+
key = {
|
|
1272
|
+
kty: "RSA",
|
|
1273
|
+
...kidAndUse(jwk),
|
|
1274
|
+
alg,
|
|
1275
|
+
n: jwk.n,
|
|
1276
|
+
e: jwk.e
|
|
1277
|
+
};
|
|
1278
|
+
} else if (jwk.kty === "EC" && jwk.crv === "P-256" && (jwk.alg === void 0 || jwk.alg === "ES256")) {
|
|
1279
|
+
alg = "ES256";
|
|
1280
|
+
if (!coordinate(jwk.x) || !coordinate(jwk.y)) throw new KeysInvalid(`${named} is an EC key without x and y, each 32 bytes in base64url`);
|
|
1281
|
+
key = {
|
|
1282
|
+
kty: "EC",
|
|
1283
|
+
...kidAndUse(jwk),
|
|
1284
|
+
alg,
|
|
1285
|
+
crv: "P-256",
|
|
1286
|
+
x: jwk.x,
|
|
1287
|
+
y: jwk.y
|
|
1288
|
+
};
|
|
1289
|
+
} else throw new KeysInvalid(`${named} is not an RSA key for RS256 or a P-256 key for ES256, the two coffre accepts`);
|
|
1290
|
+
try {
|
|
1291
|
+
await importJWK(key, alg);
|
|
1292
|
+
} catch {
|
|
1293
|
+
throw new KeysInvalid(`${named} is not a valid ${key.kty} key`);
|
|
1294
|
+
}
|
|
1295
|
+
keys.push(key);
|
|
1296
|
+
}
|
|
1297
|
+
if (keys.length === 0) throw new KeysInvalid("the key set holds no key that signs");
|
|
1298
|
+
const sorted = keys.map((key) => [`${thumbprint$2(key)} ${JSON.stringify(key)}`, key]).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0);
|
|
1299
|
+
const jwks = JSON.stringify({ keys: sorted.map(([, key]) => key) });
|
|
1300
|
+
return {
|
|
1301
|
+
jwks,
|
|
1302
|
+
digest: createHash("sha256").update(jwks, "utf8").digest("hex"),
|
|
1303
|
+
keys: keySummaries(jwks)
|
|
1304
|
+
};
|
|
1305
|
+
}
|
|
1306
|
+
/** The keys of a set `uploadedKeys` kept, as an owner sees them. */
|
|
1307
|
+
function keySummaries(jwks) {
|
|
1308
|
+
return JSON.parse(jwks).keys.map((key) => ({
|
|
1309
|
+
kid: key.kid ?? null,
|
|
1310
|
+
alg: key.kty === "RSA" ? "RS256" : "ES256",
|
|
1311
|
+
thumbprint: thumbprint$2(key)
|
|
1312
|
+
}));
|
|
1313
|
+
}
|
|
1314
|
+
/** A key's RFC 7638 thumbprint: the SHA-256 of its required members alone, in lexicographic order. */
|
|
1315
|
+
function thumbprint$2(key) {
|
|
1316
|
+
const required = key.kty === "RSA" ? {
|
|
1317
|
+
e: key.e,
|
|
1318
|
+
kty: key.kty,
|
|
1319
|
+
n: key.n
|
|
1320
|
+
} : {
|
|
1321
|
+
crv: key.crv,
|
|
1322
|
+
kty: key.kty,
|
|
1323
|
+
x: key.x,
|
|
1324
|
+
y: key.y
|
|
1325
|
+
};
|
|
1326
|
+
return createHash("sha256").update(JSON.stringify(required), "utf8").digest("base64url");
|
|
1327
|
+
}
|
|
1328
|
+
const BASE64URL = /^[A-Za-z0-9_-]+$/;
|
|
1329
|
+
/** A P-256 coordinate as JWK writes one: 32 bytes, in base64url exactly, so that one key has one spelling. */
|
|
1330
|
+
function coordinate(value) {
|
|
1331
|
+
if (typeof value !== "string" || !BASE64URL.test(value)) return false;
|
|
1332
|
+
const bytes = Buffer.from(value, "base64url");
|
|
1333
|
+
return bytes.length === 32 && bytes.toString("base64url") === value;
|
|
1334
|
+
}
|
|
1335
|
+
/** An unsigned integer as JWK writes one, base64url in its fewest bytes; null for anything else. */
|
|
1336
|
+
function integer(value) {
|
|
1337
|
+
if (typeof value !== "string" || !BASE64URL.test(value)) return null;
|
|
1338
|
+
const bytes = Buffer.from(value, "base64url");
|
|
1339
|
+
if (bytes.length === 0 || bytes[0] === 0 || bytes.toString("base64url") !== value) return null;
|
|
1340
|
+
return BigInt(`0x${bytes.toString("hex")}`);
|
|
1341
|
+
}
|
|
1342
|
+
function kidAndUse(jwk) {
|
|
1343
|
+
return {
|
|
1344
|
+
...jwk.kid === void 0 ? {} : { kid: jwk.kid },
|
|
1345
|
+
...jwk.use === void 0 ? {} : { use: "sig" }
|
|
1346
|
+
};
|
|
1347
|
+
}
|
|
1348
|
+
//#endregion
|
|
1349
|
+
//#region src/identity/proofs.ts
|
|
1350
|
+
/** A binding's `jwks_uri` when it carries its issuer's keys: the SHA-256 of those keys, where a fetched set's URL would be. */
|
|
1351
|
+
const CARRIED = "sha256:";
|
|
1352
|
+
/** A token's claims and the hash of what was signed, or `malformed`. */
|
|
1353
|
+
function readIdToken(token) {
|
|
1354
|
+
try {
|
|
1355
|
+
return decodeWorkloadToken(token);
|
|
1356
|
+
} catch (error) {
|
|
1357
|
+
if (error instanceof WorkloadTokenRefused) return { refused: "malformed" };
|
|
1358
|
+
throw error;
|
|
1359
|
+
}
|
|
1360
|
+
}
|
|
1361
|
+
/** A binding's policy as its row holds it: null for none, undefined for one that does not read as a policy, which takes nothing. */
|
|
1362
|
+
function policyOf(binding) {
|
|
1363
|
+
if (binding.policy === null) return null;
|
|
1364
|
+
try {
|
|
1365
|
+
const policy = JSON.parse(binding.policy);
|
|
1366
|
+
return typeof policy === "object" && policy !== null && !Array.isArray(policy) ? policy : void 0;
|
|
1367
|
+
} catch {
|
|
1368
|
+
return;
|
|
1369
|
+
}
|
|
1370
|
+
}
|
|
1371
|
+
/** Whether a binding issues what a proof is traded for: a CI run's token from a bearer profile with no policy, a session from an ID-token profile with one. */
|
|
1372
|
+
function issues(binding, wanted) {
|
|
1373
|
+
return (wanted === "run" ? BEARER_PROFILES : OIDC_PROFILES).includes(binding.profile) && (wanted === "run" ? binding.policy === null : policyOf(binding) != null);
|
|
1374
|
+
}
|
|
1375
|
+
/** The audience a token names, alone; null for none, or several. */
|
|
1376
|
+
function soleAudience(aud) {
|
|
1377
|
+
if (typeof aud === "string") return aud;
|
|
1378
|
+
return Array.isArray(aud) && aud.length === 1 && typeof aud[0] === "string" ? aud[0] : null;
|
|
1379
|
+
}
|
|
1380
|
+
/**
|
|
1381
|
+
* The audiences a binding takes: this instance's URL for a CI run's; for a
|
|
1382
|
+
* session's, its policy's, the session's key or its profile's
|
|
1383
|
+
* (`expectedAudiences`). None for one whose policy does not read.
|
|
1384
|
+
*/
|
|
1385
|
+
function audiencesOf(binding, publicUrl, wanted) {
|
|
1386
|
+
const policy = policyOf(binding);
|
|
1387
|
+
if (wanted.kind === "run") return policy === null ? [publicUrl] : [];
|
|
1388
|
+
return policy == null ? [] : expectedAudiences(binding.profile, policy, {
|
|
1389
|
+
publicUrl,
|
|
1390
|
+
jkt: wanted.jkt
|
|
1391
|
+
});
|
|
1392
|
+
}
|
|
1393
|
+
/**
|
|
1394
|
+
* Which audience a token is held to, and the bindings that take it: the
|
|
1395
|
+
* token's own if some binding takes it, otherwise the instance's, 0.14's
|
|
1396
|
+
* rule. A token none takes is refused `audience` once its times are checked.
|
|
1397
|
+
*/
|
|
1398
|
+
function audienceTried(aud, bindings, publicUrl, wanted) {
|
|
1399
|
+
const named = soleAudience(aud);
|
|
1400
|
+
const audience = named !== null && bindings.some((binding) => audiencesOf(binding, publicUrl, wanted).includes(named)) ? named : publicUrl;
|
|
1401
|
+
return {
|
|
1402
|
+
audience,
|
|
1403
|
+
taking: bindings.filter((binding) => audiencesOf(binding, publicUrl, wanted).includes(audience))
|
|
1404
|
+
};
|
|
1405
|
+
}
|
|
1406
|
+
/**
|
|
1407
|
+
* A token's times on the vault's clock, `now` in milliseconds, each within
|
|
1408
|
+
* the clock tolerance, as 0.14 held them: not before its `nbf`, to jose's
|
|
1409
|
+
* whole second; before its `exp`, to the millisecond, as 0.14's exchange
|
|
1410
|
+
* checked it again; issued `maxAge` seconds ago at most (an hour,
|
|
1411
|
+
* or any age for a token its platform hands out again), and, where a binding
|
|
1412
|
+
* carries its keys, living `maxLifetime` seconds at most.
|
|
1413
|
+
*/
|
|
1414
|
+
function timesRefusal(claims, now, { maxAge = MAX_TOKEN_AGE_SECONDS, maxLifetime = null } = {}) {
|
|
1415
|
+
const seconds = Math.floor(now / 1e3);
|
|
1416
|
+
if (typeof claims.nbf === "number" && claims.nbf > seconds + 30) return "too_old";
|
|
1417
|
+
if (claims.exp <= now / 1e3 - 30) return "expired";
|
|
1418
|
+
if (issuedRefusal(claims.iat, now / 1e3, maxAge ?? Infinity) !== null) return "too_old";
|
|
1419
|
+
if (maxLifetime !== null && claims.exp - claims.iat > maxLifetime) return "too_old";
|
|
1420
|
+
return null;
|
|
1421
|
+
}
|
|
1422
|
+
/** The oldest of `bindings` whose every claim the token carries (`differingClaims`), in the order the bindings' index reads them. */
|
|
1423
|
+
function oldestMatching(bindings, claims) {
|
|
1424
|
+
return [...bindings].sort((a, b) => a.createdAt.getTime() - b.createdAt.getTime() || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0)).find((binding) => {
|
|
1425
|
+
let expected;
|
|
1426
|
+
try {
|
|
1427
|
+
expected = JSON.parse(binding.claims);
|
|
1428
|
+
} catch {
|
|
1429
|
+
return false;
|
|
1430
|
+
}
|
|
1431
|
+
return typeof expected === "object" && expected !== null && !Array.isArray(expected) && differingClaims(binding.profile, expected, claims).length === 0;
|
|
1432
|
+
}) ?? null;
|
|
1433
|
+
}
|
|
1434
|
+
/** Why a token its binding matched still breaks its profile's own rule (`PROFILE_RULES`: Azure's version, Kubernetes' subject), or null. */
|
|
1435
|
+
function profileRefusal(binding, policy, claims) {
|
|
1436
|
+
const rule = PROFILE_RULES[binding.profile];
|
|
1437
|
+
if (rule === void 0) return null;
|
|
1438
|
+
return rule.token(claims, {
|
|
1439
|
+
issuer: binding.issuer,
|
|
1440
|
+
claims: JSON.parse(binding.claims),
|
|
1441
|
+
policy
|
|
1442
|
+
}) === null ? null : "malformed";
|
|
1443
|
+
}
|
|
1444
|
+
/**
|
|
1445
|
+
* Whether a proof is spent once it is traded, by the SHA-256 of what was
|
|
1446
|
+
* signed: a CI run's token always; a session's token unless it names the
|
|
1447
|
+
* session's key, which works for no other, or its platform hands the same
|
|
1448
|
+
* one out again (`REPEATING_PROFILES`), which spending would refuse.
|
|
1449
|
+
*/
|
|
1450
|
+
function spends(binding, policy, wanted) {
|
|
1451
|
+
if (wanted === "run") return true;
|
|
1452
|
+
return policy?.keyAudience !== true && !REPEATING_PROFILES.includes(binding.profile);
|
|
1453
|
+
}
|
|
1454
|
+
/**
|
|
1455
|
+
* A session's hard end, in milliseconds: the earliest of its binding's
|
|
1456
|
+
* `sessionHours` after `at`, where its profile has them (24 unless said),
|
|
1457
|
+
* and, unless the token names the session's key, the token's own `exp`, so
|
|
1458
|
+
* that a copy of it buys no more than the platform's lifetime. `exp` is in
|
|
1459
|
+
* seconds, null for a proof that is no token. A session whose end is not
|
|
1460
|
+
* after `at` is refused `expired`.
|
|
1461
|
+
*/
|
|
1462
|
+
function hardEnd(binding, policy, at, exp) {
|
|
1463
|
+
const hours = (POLICY_FIELDS[binding.profile] ?? []).includes("sessionHours") ? policy.sessionHours ?? POLICY_DEFAULTS.sessionHours : null;
|
|
1464
|
+
const ends = [hours === null ? null : at + hours * 36e5, policy.keyAudience === true || exp === null ? null : exp * 1e3].filter((end) => end !== null);
|
|
1465
|
+
return Math.min(...ends.length === 0 ? [at + POLICY_DEFAULTS.sessionHours * 36e5] : ends);
|
|
1466
|
+
}
|
|
1467
|
+
/**
|
|
1468
|
+
* Why a session is refused at its sign-in, from its binding's policy and the
|
|
1469
|
+
* request's address: the deployment lets no binding list reads (`noReads`)
|
|
1470
|
+
* and this one does, or it names its sources and the request came from
|
|
1471
|
+
* outside them, or from nowhere the app could tell. Both are `no_match`, as
|
|
1472
|
+
* the design's refusals have it; 0.14 answered the second `source`.
|
|
1473
|
+
*/
|
|
1474
|
+
function sessionRefusal(policy, ip, { noReads }) {
|
|
1475
|
+
if (noReads && policy.reads !== void 0) return "no_match";
|
|
1476
|
+
if (policy.sources !== void 0 && (ip === null || !addressWithin(ip, policy.sources))) return "no_match";
|
|
1477
|
+
return null;
|
|
1478
|
+
}
|
|
1479
|
+
/**
|
|
1480
|
+
* An ID token whose signature verified under `under`, held to the
|
|
1481
|
+
* service's live bindings, in 0.14's order:
|
|
1482
|
+
*
|
|
1483
|
+
* 1. of the bindings that issue what it is traded for (`issues`), those
|
|
1484
|
+
* on its issuer under the keys it was verified under;
|
|
1485
|
+
* 2. the audience tried, and the bindings that take it (`audienceTried`);
|
|
1486
|
+
* 3. its times (`timesRefusal`): any age for a token its platform hands
|
|
1487
|
+
* out again, where a binding that takes it is of such a platform, and
|
|
1488
|
+
* an hour's lifetime at most under keys a binding carries;
|
|
1489
|
+
* 4. that audience, the token's own, alone;
|
|
1490
|
+
* 5. the oldest whose claims match (`oldestMatching`);
|
|
1491
|
+
* 6. an hour's age after all, if the binding that matched is of a
|
|
1492
|
+
* platform that hands out no token twice;
|
|
1493
|
+
* 7. its profile's own rule (`profileRefusal`).
|
|
1494
|
+
*
|
|
1495
|
+
* `bindings` are the sealed rows the read found: a decision that picks the
|
|
1496
|
+
* oldest of several refuses before this if any row it read is not the
|
|
1497
|
+
* vault's, since one passed over would let a later one answer.
|
|
1498
|
+
*/
|
|
1499
|
+
function matchIdToken(token, bindings, { under, publicUrl, wanted, now }) {
|
|
1500
|
+
const { claims } = token;
|
|
1501
|
+
const candidates = bindings.filter((binding) => issues(binding, wanted.kind) && binding.issuer === under.issuer && binding.jwksUri === under.jwksUri && claims.iss === under.issuer);
|
|
1502
|
+
if (candidates.length === 0) return { refused: "no_match" };
|
|
1503
|
+
const { audience, taking } = audienceTried(claims.aud, candidates, publicUrl, wanted);
|
|
1504
|
+
const repeats = taking.some((binding) => REPEATING_PROFILES.includes(binding.profile));
|
|
1505
|
+
const times = timesRefusal(claims, now, {
|
|
1506
|
+
maxAge: repeats ? null : MAX_TOKEN_AGE_SECONDS,
|
|
1507
|
+
maxLifetime: under.jwksUri.startsWith("sha256:") ? MAX_TOKEN_AGE_SECONDS : null
|
|
1508
|
+
});
|
|
1509
|
+
if (times !== null) return { refused: times };
|
|
1510
|
+
if (soleAudience(claims.aud) !== audience || taking.length === 0) return { refused: "audience" };
|
|
1511
|
+
const binding = oldestMatching(taking, claims);
|
|
1512
|
+
if (binding === null) return { refused: "no_match" };
|
|
1513
|
+
const policy = policyOf(binding);
|
|
1514
|
+
if (repeats && !REPEATING_PROFILES.includes(binding.profile) && issuedRefusal(claims.iat, now / 1e3) !== null) return { refused: "too_old" };
|
|
1515
|
+
if (policy !== null && profileRefusal(binding, policy, claims) !== null) return { refused: "malformed" };
|
|
1516
|
+
return {
|
|
1517
|
+
binding,
|
|
1518
|
+
policy,
|
|
1519
|
+
claims,
|
|
1520
|
+
spends: spends(binding, policy, wanted.kind) ? token.signingInputHash : null
|
|
1521
|
+
};
|
|
1522
|
+
}
|
|
1523
|
+
/**
|
|
1524
|
+
* Whether a token's signature verifies under keys a binding carries, a JWKS
|
|
1525
|
+
* as its row holds it: null if it does, `unknown_signer` when the set lacks
|
|
1526
|
+
* the key the token names, and `malformed` for any other failure, a
|
|
1527
|
+
* signature that does not verify under it included. The algorithms are
|
|
1528
|
+
* fixed, and nothing is taken from the header but `alg` and `kid`; a set
|
|
1529
|
+
* with several keys the header could name tries each. A token that does
|
|
1530
|
+
* not read as one (`readIdToken`), an unencoded payload's included, is
|
|
1531
|
+
* `malformed` before any key is tried. It checks no claim: the times and
|
|
1532
|
+
* the audience are `matchIdToken`'s.
|
|
1533
|
+
*/
|
|
1534
|
+
async function signatureRefusal(token, jwks) {
|
|
1535
|
+
if ("refused" in readIdToken(token)) return "malformed";
|
|
1536
|
+
let keys;
|
|
1537
|
+
try {
|
|
1538
|
+
keys = JSON.parse(jwks);
|
|
1539
|
+
} catch {
|
|
1540
|
+
return "malformed";
|
|
1541
|
+
}
|
|
1542
|
+
const options = { algorithms: [...WORKLOAD_ALGORITHMS] };
|
|
1543
|
+
try {
|
|
1544
|
+
await compactVerify(token, createLocalJWKSet(keys), options);
|
|
1545
|
+
return null;
|
|
1546
|
+
} catch (error) {
|
|
1547
|
+
if (error instanceof errors.JWKSNoMatchingKey) return "unknown_signer";
|
|
1548
|
+
if (!(error instanceof errors.JWKSMultipleMatchingKeys)) return "malformed";
|
|
1549
|
+
for await (const key of error) try {
|
|
1550
|
+
await compactVerify(token, key, options);
|
|
1551
|
+
return null;
|
|
1552
|
+
} catch {}
|
|
1553
|
+
return "malformed";
|
|
1554
|
+
}
|
|
1555
|
+
}
|
|
1556
|
+
/**
|
|
1557
|
+
* The claims of the run a credential was issued for, as its issuer stated
|
|
1558
|
+
* them: those that say which run, each bounded, in the exchange's entry and
|
|
1559
|
+
* the credential's row, so that a read leads back to its run. What the
|
|
1560
|
+
* issuer says, not proof of which run sent the request.
|
|
1561
|
+
*/
|
|
1562
|
+
const RUN_CLAIMS = [
|
|
1563
|
+
"sub",
|
|
1564
|
+
"jti",
|
|
1565
|
+
"actor",
|
|
1566
|
+
"event_name",
|
|
1567
|
+
"ref",
|
|
1568
|
+
"base_ref",
|
|
1569
|
+
"head_ref",
|
|
1570
|
+
"sha",
|
|
1571
|
+
"repository",
|
|
1572
|
+
"repository_id",
|
|
1573
|
+
"run_id",
|
|
1574
|
+
"run_attempt",
|
|
1575
|
+
"workflow_ref",
|
|
1576
|
+
"job_workflow_ref",
|
|
1577
|
+
"job_workflow_sha",
|
|
1578
|
+
"environment",
|
|
1579
|
+
"project_path",
|
|
1580
|
+
"project_id",
|
|
1581
|
+
"namespace_id",
|
|
1582
|
+
"pipeline_id",
|
|
1583
|
+
"pipeline_source",
|
|
1584
|
+
"job_id",
|
|
1585
|
+
"kubernetes.io.pod.name"
|
|
1586
|
+
];
|
|
1587
|
+
const MAX_RUN_CLAIM = 256;
|
|
1588
|
+
/** The run's claims, as the issuer stated them: each a string of 256 characters at most, or a finite number. */
|
|
1589
|
+
function runClaims(claims) {
|
|
1590
|
+
const run = {};
|
|
1591
|
+
for (const name of RUN_CLAIMS) {
|
|
1592
|
+
const value = claimAt(claims, name);
|
|
1593
|
+
if (typeof value === "string") run[name] = value.slice(0, 256);
|
|
1594
|
+
else if (typeof value === "number" && Number.isFinite(value)) run[name] = value;
|
|
1595
|
+
}
|
|
1596
|
+
return run;
|
|
1597
|
+
}
|
|
1598
|
+
//#endregion
|
|
1599
|
+
//#region src/identity/aws.ts
|
|
1600
|
+
const ACCOUNT = /^\d{12}$/;
|
|
1601
|
+
const ASSUMED_ROLE = /^arn:aws:sts::(\d{12}):assumed-role\/([\w+=,.@-]{1,64})\/([\w+=,.@-]{2,64})$/;
|
|
1602
|
+
const ROLE_SESSION = /^(AROA[A-Z0-9]{8,124}):([\w+=,.@-]{2,64})$/;
|
|
1603
|
+
/**
|
|
1604
|
+
* The role a caller's identity is a session of, or why none: an account's
|
|
1605
|
+
* root, a federated user and an IAM user are `no_match`, since each means a
|
|
1606
|
+
* long-lived key on disk, which a workload does not hold, and so is any
|
|
1607
|
+
* other partition than `aws`. An answer whose account, ARN and user ID
|
|
1608
|
+
* disagree is no answer STS gives: `malformed` (0.14's server took it as
|
|
1609
|
+
* STS unavailable).
|
|
1610
|
+
*/
|
|
1611
|
+
function assumedRole(identity) {
|
|
1612
|
+
if (!ACCOUNT.test(identity.account)) return { refused: "malformed" };
|
|
1613
|
+
const role = ASSUMED_ROLE.exec(identity.arn);
|
|
1614
|
+
const session = ROLE_SESSION.exec(identity.userId);
|
|
1615
|
+
if (role === null || session === null) return { refused: "no_match" };
|
|
1616
|
+
if (role[1] !== identity.account || session[2] !== role[3]) return { refused: "malformed" };
|
|
1617
|
+
return {
|
|
1618
|
+
account: identity.account,
|
|
1619
|
+
roleId: session[1],
|
|
1620
|
+
arn: identity.arn,
|
|
1621
|
+
role: role[2],
|
|
1622
|
+
session: role[3]
|
|
1623
|
+
};
|
|
1624
|
+
}
|
|
1625
|
+
/** The claims an `aws` binding matches, as the proof makes them. */
|
|
1626
|
+
function awsClaims(identity) {
|
|
1627
|
+
return {
|
|
1628
|
+
account: identity.account,
|
|
1629
|
+
role_id: identity.roleId
|
|
1630
|
+
};
|
|
1631
|
+
}
|
|
1632
|
+
/**
|
|
1633
|
+
* STS's answer held to a service's bindings: the oldest `aws` binding with
|
|
1634
|
+
* a policy that names its role's account and unique ID, and the claims the
|
|
1635
|
+
* session's entry gives, the role's ARN and session name with them. The
|
|
1636
|
+
* request named the session's key and this instance under its signature,
|
|
1637
|
+
* so nothing is spent, and nothing but its binding's hours ends the
|
|
1638
|
+
* session early.
|
|
1639
|
+
*/
|
|
1640
|
+
function matchAwsAnswer(answer, bindings) {
|
|
1641
|
+
const candidates = bindings.filter((binding) => binding.profile === "aws" && binding.issuer === PROFILE_URNS.aws && policyOf(binding) != null);
|
|
1642
|
+
if (candidates.length === 0) return { refused: "no_match" };
|
|
1643
|
+
const identity = assumedRole(answer);
|
|
1644
|
+
if ("refused" in identity) return identity;
|
|
1645
|
+
const binding = oldestMatching(candidates, awsClaims(identity));
|
|
1646
|
+
if (binding === null) return { refused: "no_match" };
|
|
1647
|
+
return {
|
|
1648
|
+
binding,
|
|
1649
|
+
claims: {
|
|
1650
|
+
...awsClaims(identity),
|
|
1651
|
+
arn: identity.arn,
|
|
1652
|
+
session: identity.session
|
|
1653
|
+
}
|
|
1654
|
+
};
|
|
1655
|
+
}
|
|
1656
|
+
//#endregion
|
|
1657
|
+
//#region src/identity/constraints.ts
|
|
1658
|
+
/**
|
|
1659
|
+
* A `narrow` child's limits (docs/design/workload-access.md, section 8.4):
|
|
1660
|
+
* the places, credentials, methods and path prefixes it may reach, each
|
|
1661
|
+
* left out for no limit of its own. A child holds the intersection of what
|
|
1662
|
+
* it asked and what its parent holds, computed when it is made and stored
|
|
1663
|
+
* under its row's MAC, and every operation it asks for is checked against
|
|
1664
|
+
* them by `constraintsAllow`, on the URL the proxy is about to send.
|
|
1665
|
+
*
|
|
1666
|
+
* parent { credentials: ['stripe', 'openai'] } child asks { credentials: ['stripe'], paths: ['/v1/refunds'] }
|
|
1667
|
+
* child { credentials: ['stripe'], paths: ['/v1/refunds'] }
|
|
1668
|
+
* POST https://api.stripe.com/v1/refunds/re_1 allowed
|
|
1669
|
+
* POST https://api.stripe.com/v1/refunds/%2e%2e/charges refused: it is /v1/charges once parsed
|
|
1670
|
+
* POST https://api.stripe.com/v1/refundsX refused: a prefix matches whole segments
|
|
1671
|
+
*/
|
|
1672
|
+
/** The most entries in each list. */
|
|
1673
|
+
const MAX_CONSTRAINTS = 32;
|
|
1674
|
+
/** A constraint that does not parse, said so the caller can fix it. */
|
|
1675
|
+
var ConstraintsInvalid = class extends Error {
|
|
1676
|
+
constructor(message) {
|
|
1677
|
+
super(message);
|
|
1678
|
+
this.name = "ConstraintsInvalid";
|
|
1679
|
+
}
|
|
1680
|
+
};
|
|
1681
|
+
const PLACE = /^[a-z0-9][a-z0-9-]{0,62}\/[a-z0-9][a-z0-9-]{0,62}(@me)?$/;
|
|
1682
|
+
/** A path segment as a constraint names one: no escape, no `;`, no dot segment. */
|
|
1683
|
+
const SEGMENT = /^[A-Za-z0-9\-_~!$&'()*+,=:@.]+$/;
|
|
1684
|
+
/**
|
|
1685
|
+
* What a path may not hold for a constrained session, since an upstream
|
|
1686
|
+
* might read a segment otherwise than coffre: an escaped `.`, `/` or `\`,
|
|
1687
|
+
* a `%25` (double encoding), or a `;`, raw or escaped
|
|
1688
|
+
* (`/v1/refunds/..;/charges` and `/v1/refunds/..%3b/charges` are
|
|
1689
|
+
* `/v1/charges` to Tomcat).
|
|
1690
|
+
*/
|
|
1691
|
+
const AMBIGUOUS = /%2e|%2f|%5c|%25|%3b|;/i;
|
|
1692
|
+
function list(value, what, valid) {
|
|
1693
|
+
if (value === void 0) return void 0;
|
|
1694
|
+
if (!Array.isArray(value) || value.length > 32 || value.some((item) => typeof item !== "string" || !valid(item))) throw new ConstraintsInvalid(`${what} lists at most 32 of them`);
|
|
1695
|
+
return [...new Set(value)].sort();
|
|
1696
|
+
}
|
|
1697
|
+
function isPrefix(path) {
|
|
1698
|
+
if (path === "/") return true;
|
|
1699
|
+
if (!path.startsWith("/") || path.endsWith("/")) return false;
|
|
1700
|
+
return path.slice(1).split("/").every((segment) => SEGMENT.test(segment) && segment !== "." && segment !== "..");
|
|
1701
|
+
}
|
|
1702
|
+
/** Whether `path` is `prefix` or below it, by whole segments. */
|
|
1703
|
+
function under(path, prefix) {
|
|
1704
|
+
return prefix === "/" || path === prefix || path.startsWith(`${prefix}/`);
|
|
1705
|
+
}
|
|
1706
|
+
/**
|
|
1707
|
+
* Constraints as a child asks for them, checked and canonical: each list
|
|
1708
|
+
* sorted, without duplicates; methods as Fetch sends them; prefixes absolute,
|
|
1709
|
+
* with no trailing slash, escape, `;` or dot segment, and none under
|
|
1710
|
+
* another, which it would add nothing to. Throws `ConstraintsInvalid`.
|
|
1711
|
+
*/
|
|
1712
|
+
function checkConstraints(input) {
|
|
1713
|
+
if (typeof input !== "object" || input === null || Array.isArray(input)) throw new ConstraintsInvalid("constraints are an object");
|
|
1714
|
+
const { places, credentials, methods, paths, ...rest } = input;
|
|
1715
|
+
if (Object.keys(rest).length > 0) throw new ConstraintsInvalid(`constraints hold places, credentials, methods and paths, not ${Object.keys(rest).join(", ")}`);
|
|
1716
|
+
const checked = {};
|
|
1717
|
+
const placeList = list(places, "places", (place) => PLACE.test(place));
|
|
1718
|
+
const credentialList = list(credentials, "credentials", (name) => CREDENTIAL_NAME.test(name));
|
|
1719
|
+
const methodList = list(Array.isArray(methods) ? methods.map((method) => typeof method === "string" && METHOD_TOKEN.test(method) ? fetchMethod$1(method) : method) : methods, "methods", (method) => METHOD_TOKEN.test(method));
|
|
1720
|
+
const pathList = list(paths, "paths", isPrefix);
|
|
1721
|
+
if (placeList !== void 0) checked.places = placeList;
|
|
1722
|
+
if (credentialList !== void 0) checked.credentials = credentialList;
|
|
1723
|
+
if (methodList !== void 0) checked.methods = methodList;
|
|
1724
|
+
if (pathList !== void 0) checked.paths = outermost(pathList);
|
|
1725
|
+
return checked;
|
|
1726
|
+
}
|
|
1727
|
+
/** The prefixes no other one is above. */
|
|
1728
|
+
function outermost(paths) {
|
|
1729
|
+
return paths.filter((path) => !paths.some((other) => other !== path && under(path, other)));
|
|
1730
|
+
}
|
|
1731
|
+
function both(a, b) {
|
|
1732
|
+
if (a === void 0) return b;
|
|
1733
|
+
if (b === void 0) return a;
|
|
1734
|
+
return a.filter((item) => b.includes(item));
|
|
1735
|
+
}
|
|
1736
|
+
/**
|
|
1737
|
+
* What a child holds: what it asked within what its parent holds, list by
|
|
1738
|
+
* list, and for paths each prefix of one side that is under one of the
|
|
1739
|
+
* other's. A parent with none is a root, which only its scope bounds. Never
|
|
1740
|
+
* wider than either: whatever `intersect(a, b)` allows, `a` and `b` allow.
|
|
1741
|
+
*/
|
|
1742
|
+
function intersect(parent, child) {
|
|
1743
|
+
if (parent === null) return child;
|
|
1744
|
+
const result = {};
|
|
1745
|
+
const places = both(parent.places, child.places);
|
|
1746
|
+
const credentials = both(parent.credentials, child.credentials);
|
|
1747
|
+
const methods = both(parent.methods, child.methods);
|
|
1748
|
+
if (places !== void 0) result.places = places;
|
|
1749
|
+
if (credentials !== void 0) result.credentials = credentials;
|
|
1750
|
+
if (methods !== void 0) result.methods = methods;
|
|
1751
|
+
if (parent.paths === void 0 || child.paths === void 0) {
|
|
1752
|
+
const paths = parent.paths ?? child.paths;
|
|
1753
|
+
if (paths !== void 0) result.paths = paths;
|
|
1754
|
+
} else {
|
|
1755
|
+
const kept = [...child.paths.filter((path) => parent.paths.some((prefix) => under(path, prefix))), ...parent.paths.filter((path) => child.paths.some((prefix) => under(path, prefix)))];
|
|
1756
|
+
result.paths = outermost([...new Set(kept)].sort());
|
|
1757
|
+
}
|
|
1758
|
+
return result;
|
|
1759
|
+
}
|
|
1760
|
+
/** The constraints as a row's `constraints` column and its MAC hold them: `checkConstraints`'s keys in order. */
|
|
1761
|
+
function constraintsText(constraints) {
|
|
1762
|
+
const { places, credentials, methods, paths } = constraints;
|
|
1763
|
+
return JSON.stringify({
|
|
1764
|
+
places,
|
|
1765
|
+
credentials,
|
|
1766
|
+
methods,
|
|
1767
|
+
paths
|
|
1768
|
+
});
|
|
1769
|
+
}
|
|
1770
|
+
/**
|
|
1771
|
+
* Whether one operation is within the constraints: its place and credential
|
|
1772
|
+
* named, and, for one that sends a request upstream, its method and the
|
|
1773
|
+
* path of the URL it is about to send, as the WHATWG parser resolved it.
|
|
1774
|
+
* An operation with no request to check (`sign`, `verify`, `mint`, the
|
|
1775
|
+
* tunnel) is refused wherever methods or paths are limited: a constraint
|
|
1776
|
+
* that cannot be checked refuses.
|
|
1777
|
+
*/
|
|
1778
|
+
function constraintsAllow(constraints, operation) {
|
|
1779
|
+
if (constraints === null) return true;
|
|
1780
|
+
if (constraints.places !== void 0 && !constraints.places.includes(operation.place)) return false;
|
|
1781
|
+
if (constraints.credentials !== void 0 && !constraints.credentials.includes(operation.credential)) return false;
|
|
1782
|
+
if (constraints.methods === void 0 && constraints.paths === void 0) return true;
|
|
1783
|
+
if (operation.request === void 0) return false;
|
|
1784
|
+
if (constraints.methods !== void 0 && !(METHOD_TOKEN.test(operation.request.method) && constraints.methods.includes(fetchMethod$1(operation.request.method)))) return false;
|
|
1785
|
+
if (constraints.paths === void 0) return true;
|
|
1786
|
+
let path;
|
|
1787
|
+
try {
|
|
1788
|
+
path = new URL(String(operation.request.url)).pathname;
|
|
1789
|
+
} catch {
|
|
1790
|
+
return false;
|
|
1791
|
+
}
|
|
1792
|
+
if (AMBIGUOUS.test(path)) return false;
|
|
1793
|
+
return constraints.paths.some((prefix) => under(path, prefix));
|
|
1794
|
+
}
|
|
1795
|
+
//#endregion
|
|
1796
|
+
//#region src/identity/dpop.ts
|
|
1797
|
+
/**
|
|
1798
|
+
* Checking a workload's proof (docs/design/workload-access.md, section
|
|
1799
|
+
* 5.1): the verifying half of `@coffre/client/dpop`, whose canonicalization
|
|
1800
|
+
* it runs, so both sides agree on every byte. Cheapest first:
|
|
1801
|
+
*
|
|
1802
|
+
* 1. shape at most 2 KiB, `typ` exactly `dpop+jwt`, `alg` exactly `ES256`
|
|
1803
|
+
* 2. the key `jwk` exactly `kty`, `crv`, `x` and `y`, a point on P-256
|
|
1804
|
+
* 3. claims `jti` 16 bytes, `iat` an integer, `hdr` at most 32 names, none unsigned
|
|
1805
|
+
* (`parseProof`, no I/O)
|
|
1806
|
+
* 4. the session row, from the token's hash: the server's, between the two
|
|
1807
|
+
* 5. key and signature the thumbprint is the row's `jkt`, then ES256
|
|
1808
|
+
* 6. what was signed `htm`, `htu`, `ath`, `req`, then `iat` within ±300 s
|
|
1809
|
+
* (`verifyProof`)
|
|
1810
|
+
* 7. the gate's nonce and `jti`: the server's again (`Gate`)
|
|
1811
|
+
*
|
|
1812
|
+
* Each claim the caller expects (`ath` with a token, `hdr` and `req` with a
|
|
1813
|
+
* request's content) must be there, and one it does not expect must not.
|
|
1814
|
+
* Two signatures of one payload, `(r, s)` and `(r, n − s)`, both verify:
|
|
1815
|
+
* they carry one `jti`, which the gate takes once.
|
|
1816
|
+
*/
|
|
1817
|
+
/** How far a proof's `iat` may be from now: the nonce, not the clock, is what makes a proof fresh. */
|
|
1818
|
+
const PROOF_SKEW_SECONDS = 300;
|
|
1819
|
+
const refuse = (reason, message) => ({
|
|
1820
|
+
ok: false,
|
|
1821
|
+
reason,
|
|
1111
1822
|
message
|
|
1112
1823
|
});
|
|
1113
1824
|
const DECODER = new TextDecoder("utf-8", { fatal: true });
|
|
@@ -1314,375 +2025,175 @@ function unseal(key, sealed, now = Date.now()) {
|
|
|
1314
2025
|
return null;
|
|
1315
2026
|
}
|
|
1316
2027
|
}
|
|
1317
|
-
//#endregion
|
|
1318
|
-
//#region src/identity/tokens.ts
|
|
1319
|
-
const PREFIX = {
|
|
1320
|
-
browser: "coffre_web_",
|
|
1321
|
-
cli: "coffre_cli_",
|
|
1322
|
-
service: "coffre_svc_",
|
|
1323
|
-
personal: "coffre_pat_",
|
|
1324
|
-
handle: "coffre_use_",
|
|
1325
|
-
workload: "coffre_wl_",
|
|
1326
|
-
enrollment: "coffre_enr_"
|
|
1327
|
-
|
|
1328
|
-
|
|
1329
|
-
|
|
1330
|
-
|
|
1331
|
-
|
|
1332
|
-
|
|
1333
|
-
|
|
1334
|
-
|
|
1335
|
-
|
|
1336
|
-
|
|
1337
|
-
|
|
1338
|
-
* prefix, so a token found under its hash is the kind it says.
|
|
1339
|
-
*/
|
|
1340
|
-
function tokenKind(token) {
|
|
1341
|
-
if (!TOKEN.test(token)) return null;
|
|
1342
|
-
return Object.keys(PREFIX).find((kind) => token.startsWith(PREFIX[kind])) ?? null;
|
|
1343
|
-
}
|
|
1344
|
-
function hashToken(token) {
|
|
1345
|
-
return createHash("sha256").update(token, "utf8").digest();
|
|
1346
|
-
}
|
|
1347
|
-
/**
|
|
1348
|
-
* Enough of a token to recognize it in a list, never enough to use it: the
|
|
1349
|
-
* kind prefix and the last four characters. The prefix is matched rather than
|
|
1350
|
-
* cut at the last underscore, because base64url uses `_` too.
|
|
1351
|
-
*/
|
|
1352
|
-
function tokenHint(token) {
|
|
1353
|
-
return `${Object.values(PREFIX).find((candidate) => token.startsWith(candidate)) ?? ""}…${token.slice(-4)}`;
|
|
1354
|
-
}
|
|
1355
|
-
//#endregion
|
|
1356
|
-
//#region src/identity/types.ts
|
|
1357
|
-
/** Access delivers the JWT to the origin in this header. */
|
|
1358
|
-
const ACCESS_JWT_HEADER = "cf-access-jwt-assertion";
|
|
1359
|
-
//#endregion
|
|
1360
|
-
//#region src/identity/verifier.ts
|
|
1361
|
-
/**
|
|
1362
|
-
* Signature algorithms we accept, as an explicit allowlist.
|
|
1363
|
-
*
|
|
1364
|
-
* Without this, the algorithm is taken from the attacker-controlled token
|
|
1365
|
-
* header, which is how `alg: none` and RS256->HS256 confusion work. jose
|
|
1366
|
-
* defaults to permitting whatever the key supports; we do not rely on that.
|
|
1367
|
-
*/
|
|
1368
|
-
const ALLOWED_ALGORITHMS = ["RS256", "ES256"];
|
|
1369
|
-
function asNonEmptyString(value) {
|
|
1370
|
-
return typeof value === "string" && value.length > 0 ? value : null;
|
|
1371
|
-
}
|
|
1372
|
-
/**
|
|
1373
|
-
* Verifies Cloudflare Access JWTs.
|
|
1374
|
-
*
|
|
1375
|
-
* Signature and claim verification of the token Access sends with each
|
|
1376
|
-
* request.
|
|
1377
|
-
*/
|
|
1378
|
-
var AccessIdentityVerifier = class {
|
|
1379
|
-
#config;
|
|
1380
|
-
#jwks;
|
|
1381
|
-
constructor(config) {
|
|
1382
|
-
this.#config = config;
|
|
1383
|
-
this.#jwks = createRemoteJWKSet(new URL(config.jwksUrl), {
|
|
1384
|
-
cooldownDuration: 3e4,
|
|
1385
|
-
cacheMaxAge: 6e5
|
|
1386
|
-
});
|
|
1387
|
-
}
|
|
1388
|
-
async verify(token) {
|
|
1389
|
-
if (typeof token !== "string" || token.length === 0) throw new Error("missing or empty Access token");
|
|
1390
|
-
const { payload } = await jwtVerify(token, this.#jwks, {
|
|
1391
|
-
issuer: this.#config.issuer,
|
|
1392
|
-
audience: this.#config.audience,
|
|
1393
|
-
algorithms: [...ALLOWED_ALGORITHMS],
|
|
1394
|
-
clockTolerance: this.#config.clockToleranceSeconds ?? 0
|
|
1395
|
-
});
|
|
1396
|
-
return toPrincipal(payload);
|
|
1397
|
-
}
|
|
1398
|
-
};
|
|
1399
|
-
/**
|
|
1400
|
-
* Derive the caller from verified claims.
|
|
1401
|
-
*
|
|
1402
|
-
* Order matters. A service token is identified by `common_name` and carries an
|
|
1403
|
-
* empty `sub`; an identity token carries both `sub` and `email`. Anything else
|
|
1404
|
-
* is rejected rather than being allowed through as an authenticated caller
|
|
1405
|
-
* with no name -- an audit row with a null actor answers no question worth
|
|
1406
|
-
* asking.
|
|
1407
|
-
*/
|
|
1408
|
-
function toPrincipal(claims) {
|
|
1409
|
-
const commonName = asNonEmptyString(claims.common_name);
|
|
1410
|
-
if (commonName !== null) return {
|
|
1411
|
-
type: "service",
|
|
1412
|
-
id: commonName,
|
|
1413
|
-
commonName
|
|
1414
|
-
};
|
|
1415
|
-
const email = asNonEmptyString(claims.email);
|
|
1416
|
-
const subject = asNonEmptyString(claims.sub);
|
|
1417
|
-
if (email !== null && subject !== null) {
|
|
1418
|
-
const id = email.toLowerCase();
|
|
1419
|
-
return {
|
|
1420
|
-
type: "user",
|
|
1421
|
-
id,
|
|
1422
|
-
email: id,
|
|
1423
|
-
subject
|
|
1424
|
-
};
|
|
1425
|
-
}
|
|
1426
|
-
throw new Error("token verified but carries no usable identity: expected common_name (service) or sub+email (user)");
|
|
1427
|
-
}
|
|
1428
|
-
//#endregion
|
|
1429
|
-
//#region src/identity/workload-token.ts
|
|
1430
|
-
/**
|
|
1431
|
-
* An ID token a CI platform signed for a run, as the exchange checks it
|
|
1432
|
-
* (docs/design/oidc.md, section 3). The checks run in this order; each
|
|
1433
|
-
* refusal says which, as a reason a CI user can act on.
|
|
1434
|
-
*/
|
|
1435
|
-
/** A compact JWS is three base64url parts; the whole token at most this long. */
|
|
1436
|
-
const MAX_TOKEN_BYTES = 8192;
|
|
1437
|
-
/** Each side of every time check. */
|
|
1438
|
-
const CLOCK_TOLERANCE_SECONDS = 30;
|
|
1439
|
-
/** The oldest token accepted, by its `iat`: tokens handed to a job at its start fit, day-old ones do not. */
|
|
1440
|
-
const MAX_TOKEN_AGE_SECONDS = 3600;
|
|
1441
|
-
/** RS256 and ES256 (P-256), as for Access assertions: never `none`, never HS*. */
|
|
1442
|
-
const WORKLOAD_ALGORITHMS = ["RS256", "ES256"];
|
|
1443
|
-
var WorkloadTokenRefused = class extends Error {
|
|
1444
|
-
reason;
|
|
1445
|
-
constructor(reason, message) {
|
|
1446
|
-
super(message);
|
|
1447
|
-
this.name = "WorkloadTokenRefused";
|
|
1448
|
-
this.reason = reason;
|
|
1449
|
-
}
|
|
1450
|
-
};
|
|
1451
|
-
const PART = /^[A-Za-z0-9_-]+$/;
|
|
1452
|
-
/** A token's parts and claims, checked for shape and types only. Throws `WorkloadTokenRefused('malformed')`. */
|
|
1453
|
-
function decodeWorkloadToken(token) {
|
|
1454
|
-
const malformed = (why) => new WorkloadTokenRefused("malformed", `the token ${why}`);
|
|
1455
|
-
if (typeof token !== "string" || token.length === 0) throw malformed("is empty");
|
|
1456
|
-
if (token.length > 8192) throw malformed(`is longer than ${MAX_TOKEN_BYTES} bytes`);
|
|
1457
|
-
const parts = token.split(".");
|
|
1458
|
-
if (parts.length !== 3 || !parts.every((part) => PART.test(part))) throw malformed("is not a compact JWS");
|
|
1459
|
-
const json = (part) => {
|
|
1460
|
-
let value;
|
|
1461
|
-
try {
|
|
1462
|
-
value = JSON.parse(Buffer.from(part, "base64url").toString("utf8"));
|
|
1463
|
-
} catch {
|
|
1464
|
-
throw malformed("has a part that is not JSON");
|
|
1465
|
-
}
|
|
1466
|
-
if (typeof value !== "object" || value === null || Array.isArray(value)) throw malformed("has a part that is not an object");
|
|
1467
|
-
return value;
|
|
1468
|
-
};
|
|
1469
|
-
const [header, claims] = [json(parts[0]), json(parts[1])];
|
|
1470
|
-
for (const name of ["iss", "sub"]) if (typeof claims[name] !== "string" || claims[name] === "") throw malformed(`has no ${name}, as a nonempty string`);
|
|
1471
|
-
for (const name of ["exp", "iat"]) if (typeof claims[name] !== "number" || !Number.isFinite(claims[name])) throw malformed(`has no ${name}, as a finite number`);
|
|
1472
|
-
if (claims.nbf !== void 0 && (typeof claims.nbf !== "number" || !Number.isFinite(claims.nbf))) throw malformed("has an nbf that is not a finite number");
|
|
1473
|
-
return {
|
|
1474
|
-
header,
|
|
1475
|
-
claims,
|
|
1476
|
-
signingInputHash: createHash("sha256").update(`${parts[0]}.${parts[1]}`, "ascii").digest()
|
|
1477
|
-
};
|
|
1478
|
-
}
|
|
1479
|
-
/**
|
|
1480
|
-
* Verify a token under an issuer's keys: the signature by jose, with the
|
|
1481
|
-
* algorithms fixed and nothing taken from the header but `alg` and `kid`;
|
|
1482
|
-
* the issuer exactly; `exp`, `nbf` and `iat` within the tolerance, `iat` at
|
|
1483
|
-
* most an hour old; and the audience, this instance's public URL alone.
|
|
1484
|
-
* With `maxLifetime`, in seconds, a token whose `exp` is further than that
|
|
1485
|
-
* from its `iat` is refused too. With `maxAge: null`, its `iat` may be any
|
|
1486
|
-
* age, and its own `exp` alone ends it: a token its platform hands out
|
|
1487
|
-
* again for hours, a managed identity's (docs/design/workload-access.md,
|
|
1488
|
-
* section 4.2). Returns the verified claims.
|
|
1489
|
-
*/
|
|
1490
|
-
async function verifyWorkloadToken(token, keys, expected) {
|
|
1491
|
-
const options = {
|
|
1492
|
-
algorithms: [...WORKLOAD_ALGORITHMS],
|
|
1493
|
-
issuer: expected.issuer,
|
|
1494
|
-
clockTolerance: 30,
|
|
1495
|
-
requiredClaims: [
|
|
1496
|
-
"iss",
|
|
1497
|
-
"sub",
|
|
1498
|
-
"exp",
|
|
1499
|
-
"iat"
|
|
1500
|
-
],
|
|
1501
|
-
currentDate: expected.now
|
|
1502
|
-
};
|
|
1503
|
-
let payload;
|
|
1504
|
-
try {
|
|
1505
|
-
({payload} = await jwtVerify(token, createLocalJWKSet(keys), options));
|
|
1506
|
-
} catch (error) {
|
|
1507
|
-
if (!(error instanceof errors.JWKSMultipleMatchingKeys)) throw refusalOf(error);
|
|
1508
|
-
payload = await anyKey(token, error, options);
|
|
1509
|
-
}
|
|
1510
|
-
const issued = issuedRefusal(payload.iat, expected.now.getTime() / 1e3, expected.maxAge === null ? Infinity : MAX_TOKEN_AGE_SECONDS);
|
|
1511
|
-
if (issued !== null) throw issued;
|
|
1512
|
-
if (expected.maxLifetime !== void 0 && payload.exp - payload.iat > expected.maxLifetime) throw new WorkloadTokenRefused("too_long", `the token lives longer than ${expected.maxLifetime / 60} minutes, from its iat to its exp: ask for a shorter one`);
|
|
1513
|
-
const { aud } = payload;
|
|
1514
|
-
if (!(aud === expected.audience || Array.isArray(aud) && aud.length === 1 && aud[0] === expected.audience)) throw new WorkloadTokenRefused("audience", `the token is for ${JSON.stringify(aud ?? null)}, not ${expected.audience} alone`);
|
|
1515
|
-
return payload;
|
|
1516
|
-
}
|
|
2028
|
+
//#endregion
|
|
2029
|
+
//#region src/identity/tokens.ts
|
|
2030
|
+
const PREFIX = {
|
|
2031
|
+
browser: "coffre_web_",
|
|
2032
|
+
cli: "coffre_cli_",
|
|
2033
|
+
service: "coffre_svc_",
|
|
2034
|
+
personal: "coffre_pat_",
|
|
2035
|
+
handle: "coffre_use_",
|
|
2036
|
+
workload: "coffre_wl_",
|
|
2037
|
+
enrollment: "coffre_enr_",
|
|
2038
|
+
mcp: "coffre_mcp_",
|
|
2039
|
+
"mcp-refresh": "coffre_mcr_"
|
|
2040
|
+
};
|
|
2041
|
+
const TOKEN = /^coffre_(web|cli|svc|pat|use|wl|enr|mcp|mcr)_[A-Za-z0-9_-]{43}$/;
|
|
2042
|
+
function generateToken(kind) {
|
|
2043
|
+
return PREFIX[kind] + randomBytes(32).toString("base64url");
|
|
2044
|
+
}
|
|
2045
|
+
/** Whether a string has the shape of a coffre token, before any lookup. */
|
|
2046
|
+
function isCoffreToken(value) {
|
|
2047
|
+
return TOKEN.test(value);
|
|
2048
|
+
}
|
|
1517
2049
|
/**
|
|
1518
|
-
*
|
|
1519
|
-
*
|
|
1520
|
-
* said, exactly, and no further ahead than the clock tolerance.
|
|
1521
|
-
* Verification and the exchange's commit both ask it.
|
|
2050
|
+
* The kind a token's prefix says, before any lookup. Its hash covers the
|
|
2051
|
+
* prefix, so a token found under its hash is the kind it says.
|
|
1522
2052
|
*/
|
|
1523
|
-
function
|
|
1524
|
-
if (
|
|
1525
|
-
|
|
1526
|
-
|
|
2053
|
+
function tokenKind(token) {
|
|
2054
|
+
if (!TOKEN.test(token)) return null;
|
|
2055
|
+
return Object.keys(PREFIX).find((kind) => token.startsWith(PREFIX[kind])) ?? null;
|
|
2056
|
+
}
|
|
2057
|
+
function hashToken(token) {
|
|
2058
|
+
return createHash("sha256").update(token, "utf8").digest();
|
|
1527
2059
|
}
|
|
1528
2060
|
/**
|
|
1529
|
-
*
|
|
1530
|
-
*
|
|
1531
|
-
*
|
|
2061
|
+
* Enough of a token to recognize it in a list, never enough to use it: the
|
|
2062
|
+
* kind prefix and the last four characters. The prefix is matched rather than
|
|
2063
|
+
* cut at the last underscore, because base64url uses `_` too.
|
|
1532
2064
|
*/
|
|
1533
|
-
|
|
1534
|
-
|
|
1535
|
-
return (await jwtVerify(token, key, options)).payload;
|
|
1536
|
-
} catch (error) {
|
|
1537
|
-
if (!(error instanceof errors.JWSSignatureVerificationFailed)) throw refusalOf(error);
|
|
1538
|
-
}
|
|
1539
|
-
throw new WorkloadTokenRefused("signature", "the token's signature does not verify");
|
|
2065
|
+
function tokenHint(token) {
|
|
2066
|
+
return `${Object.values(PREFIX).find((candidate) => token.startsWith(candidate)) ?? ""}…${token.slice(-4)}`;
|
|
1540
2067
|
}
|
|
1541
|
-
|
|
1542
|
-
|
|
1543
|
-
|
|
1544
|
-
|
|
1545
|
-
|
|
1546
|
-
|
|
1547
|
-
|
|
1548
|
-
|
|
1549
|
-
|
|
1550
|
-
|
|
1551
|
-
|
|
1552
|
-
|
|
1553
|
-
|
|
2068
|
+
//#endregion
|
|
2069
|
+
//#region src/identity/types.ts
|
|
2070
|
+
/** Access delivers the JWT to the origin in this header. */
|
|
2071
|
+
const ACCESS_JWT_HEADER = "cf-access-jwt-assertion";
|
|
2072
|
+
//#endregion
|
|
2073
|
+
//#region src/identity/verifier.ts
|
|
2074
|
+
/**
|
|
2075
|
+
* Signature algorithms we accept, as an explicit allowlist.
|
|
2076
|
+
*
|
|
2077
|
+
* Without this, the algorithm is taken from the attacker-controlled token
|
|
2078
|
+
* header, which is how `alg: none` and RS256->HS256 confusion work. jose
|
|
2079
|
+
* defaults to permitting whatever the key supports; we do not rely on that.
|
|
2080
|
+
*/
|
|
2081
|
+
const ALLOWED_ALGORITHMS = ["RS256", "ES256"];
|
|
2082
|
+
/** How long a key set is used before it is fetched again, and the least time between two fetches an unknown key asks for. */
|
|
2083
|
+
const KEYS_MAX_AGE_MS = 6e5;
|
|
2084
|
+
const REFETCH_COOLDOWN_MS = 3e4;
|
|
2085
|
+
function asNonEmptyString(value) {
|
|
2086
|
+
return typeof value === "string" && value.length > 0 ? value : null;
|
|
1554
2087
|
}
|
|
1555
|
-
/**
|
|
1556
|
-
|
|
1557
|
-
|
|
1558
|
-
|
|
1559
|
-
|
|
1560
|
-
super(message);
|
|
1561
|
-
this.name = "KeysInvalid";
|
|
2088
|
+
/** The team's keys could not be fetched, or are no key set: no assertion can be checked, which is not the caller's fault. */
|
|
2089
|
+
var AccessKeysUnavailable = class extends Error {
|
|
2090
|
+
constructor(message, options) {
|
|
2091
|
+
super(message, options);
|
|
2092
|
+
this.name = "AccessKeysUnavailable";
|
|
1562
2093
|
}
|
|
1563
2094
|
};
|
|
1564
|
-
|
|
1565
|
-
const
|
|
1566
|
-
|
|
1567
|
-
|
|
1568
|
-
|
|
1569
|
-
|
|
1570
|
-
|
|
1571
|
-
|
|
1572
|
-
|
|
1573
|
-
|
|
1574
|
-
|
|
2095
|
+
async function fetchJson(url) {
|
|
2096
|
+
const response = await fetch(url, {
|
|
2097
|
+
redirect: "manual",
|
|
2098
|
+
signal: AbortSignal.timeout(5e3),
|
|
2099
|
+
headers: { accept: "application/json" }
|
|
2100
|
+
});
|
|
2101
|
+
if (response.status !== 200) {
|
|
2102
|
+
await response.body?.cancel();
|
|
2103
|
+
throw new Error(`${url.href} answered ${response.status}`);
|
|
2104
|
+
}
|
|
2105
|
+
return response.json();
|
|
2106
|
+
}
|
|
1575
2107
|
/**
|
|
1576
|
-
*
|
|
1577
|
-
*
|
|
1578
|
-
*
|
|
1579
|
-
*
|
|
1580
|
-
*
|
|
1581
|
-
*
|
|
1582
|
-
*
|
|
1583
|
-
*
|
|
1584
|
-
*
|
|
1585
|
-
*
|
|
2108
|
+
* Verifies Cloudflare Access JWTs.
|
|
2109
|
+
*
|
|
2110
|
+
* Signature and claim verification of the token Access sends with each
|
|
2111
|
+
* request. The team's keys are fetched when first needed, used for ten
|
|
2112
|
+
* minutes, and fetched again sooner for a key they lack, at most every 30
|
|
2113
|
+
* seconds. The verifier lives as long as its configuration (an isolate's,
|
|
2114
|
+
* on Workers) and keeps settled values only, never a fetch in flight
|
|
2115
|
+
* (AGENTS.md, "What an isolate keeps"): concurrent requests that find no
|
|
2116
|
+
* key set each fetch their own, and the last to land is kept. The 30
|
|
2117
|
+
* seconds count from the last refresh started, landed or not, and are
|
|
2118
|
+
* taken before it starts: of a burst of assertions naming a key the set
|
|
2119
|
+
* lacks, one fetches, and the others are refused as the key unknown.
|
|
1586
2120
|
*/
|
|
1587
|
-
|
|
1588
|
-
|
|
1589
|
-
|
|
1590
|
-
|
|
1591
|
-
|
|
1592
|
-
|
|
1593
|
-
|
|
1594
|
-
|
|
1595
|
-
|
|
1596
|
-
|
|
1597
|
-
|
|
1598
|
-
|
|
1599
|
-
|
|
1600
|
-
|
|
1601
|
-
|
|
1602
|
-
|
|
1603
|
-
|
|
1604
|
-
|
|
1605
|
-
|
|
1606
|
-
|
|
1607
|
-
|
|
1608
|
-
|
|
1609
|
-
|
|
1610
|
-
|
|
1611
|
-
|
|
1612
|
-
|
|
1613
|
-
alg,
|
|
1614
|
-
n: jwk.n,
|
|
1615
|
-
e: jwk.e
|
|
1616
|
-
};
|
|
1617
|
-
} else if (jwk.kty === "EC" && jwk.crv === "P-256" && (jwk.alg === void 0 || jwk.alg === "ES256")) {
|
|
1618
|
-
alg = "ES256";
|
|
1619
|
-
if (!coordinate(jwk.x) || !coordinate(jwk.y)) throw new KeysInvalid(`${named} is an EC key without x and y, each 32 bytes in base64url`);
|
|
1620
|
-
key = {
|
|
1621
|
-
kty: "EC",
|
|
1622
|
-
...kidAndUse(jwk),
|
|
1623
|
-
alg,
|
|
1624
|
-
crv: "P-256",
|
|
1625
|
-
x: jwk.x,
|
|
1626
|
-
y: jwk.y
|
|
1627
|
-
};
|
|
1628
|
-
} else throw new KeysInvalid(`${named} is not an RSA key for RS256 or a P-256 key for ES256, the two coffre accepts`);
|
|
2121
|
+
var AccessIdentityVerifier = class {
|
|
2122
|
+
#config;
|
|
2123
|
+
#url;
|
|
2124
|
+
#json;
|
|
2125
|
+
#now;
|
|
2126
|
+
#keys = null;
|
|
2127
|
+
/** When a refresh for an unknown key last started: a number, settled the moment it starts. */
|
|
2128
|
+
#refreshed = Number.NEGATIVE_INFINITY;
|
|
2129
|
+
constructor(config, io = {}) {
|
|
2130
|
+
this.#config = config;
|
|
2131
|
+
this.#url = new URL(config.jwksUrl);
|
|
2132
|
+
this.#json = io.json ?? fetchJson;
|
|
2133
|
+
this.#now = io.now ?? Date.now;
|
|
2134
|
+
}
|
|
2135
|
+
async verify(token) {
|
|
2136
|
+
if (typeof token !== "string" || token.length === 0) throw new Error("missing or empty Access token");
|
|
2137
|
+
const { alg } = decodeProtectedHeader(token);
|
|
2138
|
+
if (!ALLOWED_ALGORITHMS.includes(alg)) throw new errors.JOSEAlgNotAllowed(`"alg" (Algorithm) Header Parameter value not allowed`);
|
|
2139
|
+
const options = {
|
|
2140
|
+
issuer: this.#config.issuer,
|
|
2141
|
+
audience: this.#config.audience,
|
|
2142
|
+
algorithms: [...ALLOWED_ALGORITHMS],
|
|
2143
|
+
clockTolerance: this.#config.clockToleranceSeconds ?? 0
|
|
2144
|
+
};
|
|
2145
|
+
let keys = this.#keys;
|
|
2146
|
+
if (keys === null || this.#now() - keys.at >= KEYS_MAX_AGE_MS) keys = await this.#fetch();
|
|
1629
2147
|
try {
|
|
1630
|
-
await
|
|
1631
|
-
} catch {
|
|
1632
|
-
|
|
2148
|
+
return toPrincipal((await jwtVerify(token, keys.set, options)).payload);
|
|
2149
|
+
} catch (error) {
|
|
2150
|
+
const now = this.#now();
|
|
2151
|
+
if (!(error instanceof errors.JWKSNoMatchingKey) || now - Math.max(keys.at, this.#refreshed) < REFETCH_COOLDOWN_MS) throw error;
|
|
2152
|
+
this.#refreshed = now;
|
|
1633
2153
|
}
|
|
1634
|
-
|
|
2154
|
+
return toPrincipal((await jwtVerify(token, (await this.#fetch()).set, options)).payload);
|
|
1635
2155
|
}
|
|
1636
|
-
|
|
1637
|
-
|
|
1638
|
-
|
|
1639
|
-
|
|
1640
|
-
|
|
1641
|
-
|
|
1642
|
-
|
|
1643
|
-
|
|
1644
|
-
|
|
1645
|
-
|
|
1646
|
-
|
|
1647
|
-
|
|
1648
|
-
|
|
1649
|
-
|
|
1650
|
-
|
|
1651
|
-
|
|
1652
|
-
|
|
1653
|
-
|
|
1654
|
-
|
|
1655
|
-
|
|
1656
|
-
|
|
1657
|
-
|
|
1658
|
-
|
|
1659
|
-
|
|
1660
|
-
|
|
1661
|
-
|
|
1662
|
-
|
|
1663
|
-
|
|
1664
|
-
};
|
|
1665
|
-
return createHash("sha256").update(JSON.stringify(required), "utf8").digest("base64url");
|
|
1666
|
-
}
|
|
1667
|
-
const BASE64URL = /^[A-Za-z0-9_-]+$/;
|
|
1668
|
-
/** A P-256 coordinate as JWK writes one: 32 bytes, in base64url exactly, so that one key has one spelling. */
|
|
1669
|
-
function coordinate(value) {
|
|
1670
|
-
if (typeof value !== "string" || !BASE64URL.test(value)) return false;
|
|
1671
|
-
const bytes = Buffer.from(value, "base64url");
|
|
1672
|
-
return bytes.length === 32 && bytes.toString("base64url") === value;
|
|
1673
|
-
}
|
|
1674
|
-
/** An unsigned integer as JWK writes one, base64url in its fewest bytes; null for anything else. */
|
|
1675
|
-
function integer(value) {
|
|
1676
|
-
if (typeof value !== "string" || !BASE64URL.test(value)) return null;
|
|
1677
|
-
const bytes = Buffer.from(value, "base64url");
|
|
1678
|
-
if (bytes.length === 0 || bytes[0] === 0 || bytes.toString("base64url") !== value) return null;
|
|
1679
|
-
return BigInt(`0x${bytes.toString("hex")}`);
|
|
1680
|
-
}
|
|
1681
|
-
function kidAndUse(jwk) {
|
|
1682
|
-
return {
|
|
1683
|
-
...jwk.kid === void 0 ? {} : { kid: jwk.kid },
|
|
1684
|
-
...jwk.use === void 0 ? {} : { use: "sig" }
|
|
2156
|
+
async #fetch() {
|
|
2157
|
+
let set;
|
|
2158
|
+
try {
|
|
2159
|
+
set = createLocalJWKSet(await this.#json(this.#url));
|
|
2160
|
+
} catch (error) {
|
|
2161
|
+
throw new AccessKeysUnavailable(`Cloudflare Access's keys could not be fetched from ${this.#url.href}`, { cause: error });
|
|
2162
|
+
}
|
|
2163
|
+
return this.#keys = {
|
|
2164
|
+
set,
|
|
2165
|
+
at: this.#now()
|
|
2166
|
+
};
|
|
2167
|
+
}
|
|
2168
|
+
};
|
|
2169
|
+
/**
|
|
2170
|
+
* Derive the caller from verified claims.
|
|
2171
|
+
*
|
|
2172
|
+
* Order matters. A service token is identified by `common_name` and carries an
|
|
2173
|
+
* empty `sub`; an identity token carries both `sub` and `email`. Anything else
|
|
2174
|
+
* is rejected rather than being allowed through as an authenticated caller
|
|
2175
|
+
* with no name -- an audit row with a null actor answers no question worth
|
|
2176
|
+
* asking.
|
|
2177
|
+
*/
|
|
2178
|
+
function toPrincipal(claims) {
|
|
2179
|
+
const commonName = asNonEmptyString(claims.common_name);
|
|
2180
|
+
if (commonName !== null) return {
|
|
2181
|
+
type: "service",
|
|
2182
|
+
id: commonName,
|
|
2183
|
+
commonName
|
|
1685
2184
|
};
|
|
2185
|
+
const email = asNonEmptyString(claims.email);
|
|
2186
|
+
const subject = asNonEmptyString(claims.sub);
|
|
2187
|
+
if (email !== null && subject !== null) {
|
|
2188
|
+
const id = email.toLowerCase();
|
|
2189
|
+
return {
|
|
2190
|
+
type: "user",
|
|
2191
|
+
id,
|
|
2192
|
+
email: id,
|
|
2193
|
+
subject
|
|
2194
|
+
};
|
|
2195
|
+
}
|
|
2196
|
+
throw new Error("token verified but carries no usable identity: expected common_name (service) or sub+email (user)");
|
|
1686
2197
|
}
|
|
1687
2198
|
//#endregion
|
|
1688
|
-
export { ACCESS_JWT_HEADER, AccessIdentityVerifier, BEARER_PROFILES, BindingInvalid, CLOCK_TOLERANCE_SECONDS, CREDENTIAL_NAME, ConstraintsInvalid, EVENT_EXPOSURE, GITHUB_EVENTS, GITHUB_ISSUER, GITLAB_ISSUER, GITLAB_PIPELINE_SOURCES, GOOGLE_ISSUER, GitHubApp, GitHubAppUnavailable, GitHubSigninProvider, KEY_NAMING_PROFILES, KeysInvalid, MAX_BINDINGS, MAX_CLAIMS, MAX_CLAIM_BYTES, MAX_CONSTRAINTS, MAX_ISSUER_BYTES, MAX_KEYS, MAX_LISTING_REQUESTS, MAX_PROOF_LENGTH, MAX_READ_KEYS, MAX_READ_PLACES, MAX_SIGNED_HEADERS, MAX_SOURCES, MAX_TOKEN_AGE_SECONDS, MAX_TOKEN_BYTES, OIDC_PROFILES, OidcSigninProvider, POLICY_DEFAULTS, POLICY_FIELDS, PROFILE_URNS, PROOF_SKEW_SECONDS, REPEATING_PROFILES, REQUIRED_CLAIMS, SigninError, TOKEN_MARGIN_MS, WORKLOAD_ALGORITHMS, WORKLOAD_PROFILES, WorkloadTokenRefused, addressWithin, canonicalClaims, canonicalHtu, canonicalRequest, checkBinding, checkConstraints, checkFetchUrl, checkPolicy, claimAt, claimValues, cloudflareAccess, constraintsAllow, constraintsText, decodeWorkloadToken, defaultIssuer, defineSignin, deriveKey, differingClaims, fetchMethod, freezeTarget, fullRef, generateToken, github, githubApp, githubEventsAt, githubReusable, githubWorkflow, gitlabProject, google, hashToken, intersect, isBearerProfile, isCoffreToken, issuedRefusal, keySummaries, microsoft, oidc, parseAddress, parseCidr, parseProof, pkcs8Of, policyText, publicOrigin, seal, sentTarget, signin, thumbprint, toPrincipal, tokenHint, tokenKind, unseal, uploadedKeys, verifyProof, verifyWorkloadToken, workflowRef };
|
|
2199
|
+
export { ACCESS_JWT_HEADER, AccessIdentityVerifier, AccessKeysUnavailable, BEARER_PROFILES, BindingInvalid, CARRIED, CLOCK_TOLERANCE_SECONDS, CREDENTIAL_NAME, ConstraintsInvalid, EVENT_EXPOSURE, GITHUB_EVENTS, GITHUB_ISSUER, GITLAB_ISSUER, GITLAB_PIPELINE_SOURCES, GOOGLE_ISSUER, GitHubApp, GitHubAppUnavailable, GitHubSigninProvider, KEY_NAMING_PROFILES, KeysInvalid, MAX_BINDINGS, MAX_CLAIMS, MAX_CLAIM_BYTES, MAX_CONSTRAINTS, MAX_ISSUER_BYTES, MAX_KEYS, MAX_LISTING_REQUESTS, MAX_PROOF_LENGTH, MAX_READ_KEYS, MAX_READ_PLACES, MAX_RUN_CLAIM, MAX_SIGNED_HEADERS, MAX_SOURCES, MAX_TOKEN_AGE_SECONDS, MAX_TOKEN_BYTES, OIDC_PROFILES, OidcSigninProvider, POLICY_DEFAULTS, POLICY_FIELDS, PROFILE_RULES, PROFILE_URNS, PROOF_SKEW_SECONDS, REPEATING_PROFILES, REQUIRED_CLAIMS, RUN_CLAIMS, SigninError, TOKEN_MARGIN_MS, WORKLOAD_ALGORITHMS, WORKLOAD_PROFILES, WorkloadTokenRefused, addressWithin, assumedRole, audienceTried, audiencesOf, awsClaims, canonicalClaims, canonicalHtu, canonicalRequest, checkBinding, checkConstraints, checkFetchUrl, checkPolicy, claimAt, claimValues, cloudflareAccess, constraintsAllow, constraintsText, decodeWorkloadToken, defaultIssuer, defineSignin, deriveKey, differingClaims, expectedAudiences, fetchMethod, freezeTarget, fullRef, generateToken, github, githubApp, githubEventsAt, githubReusable, githubWorkflow, gitlabProject, google, hardEnd, hashToken, intersect, isBearerProfile, isCoffreToken, issuedRefusal, issues, keySummaries, lifetime, matchAwsAnswer, matchIdToken, microsoft, oidc, oldestMatching, parseAddress, parseCidr, parseProof, pkcs8Of, policyOf, policyText, profileRefusal, publicOrigin, readIdToken, runClaims, seal, sentTarget, sessionRefusal, signatureRefusal, signin, soleAudience, spends, thumbprint, timesRefusal, toPrincipal, tokenHint, tokenKind, unseal, uploadedKeys, verifyProof, verifyWorkloadToken, workflowRef };
|