@coffre/core 0.15.0 → 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-CgQTlUMz.js → access-CF8UG59J.js} +70 -95
- package/dist/{access-DqLJjnLM.d.ts → access-ERdGGHG7.d.ts} +45 -64
- 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 +3 -1018
- package/dist/identity.js +885 -623
- 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 +27 -4
- package/dist/mcp.js +31 -10
- 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 -12
- package/dist/schemas.js +16 -14
- package/dist/{types-Cp3lB_-W.js → types-DwTO_b4H.js} +17 -5
- package/dist/vault.d.ts +1771 -1419
- package/dist/vault.js +96 -302
- package/dist/{workloads-D049JH0M.d.ts → workloads-CW2dK4AW.d.ts} +1 -9
- package/dist/workloads.d.ts +2 -2
- package/dist/workloads.js +1 -9
- package/package.json +7 -7
- package/src/access.ts +63 -95
- 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 -2
- package/src/identity/{profile-rules.ts → profiles.ts} +1 -9
- 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/identity/workloads.ts +0 -11
- 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/{audit → log}/tiles.ts +18 -49
- package/src/{audit → log}/tree.ts +2 -2
- package/src/mcp.ts +36 -9
- package/src/schemas.ts +15 -12
- package/src/vault.ts +251 -1150
- package/dist/merkle.d.ts +0 -456
- package/dist/merkle.js +0 -964
- package/src/answers.ts +0 -209
- package/src/audit/leaf.ts +0 -81
- package/src/audit/merkle.ts +0 -13
- package/src/audit/note.ts +0 -187
- package/src/audit/pair.ts +0 -86
- package/src/audit/verify.ts +0 -393
- package/src/audit/witness.ts +0 -50
- package/src/checkpoint.ts +0 -22
- package/src/identity/run-proof.ts +0 -159
|
@@ -0,0 +1,306 @@
|
|
|
1
|
+
import { compactVerify, createLocalJWKSet, errors, type JSONWebKeySet } from 'jose';
|
|
2
|
+
|
|
3
|
+
import { expectedAudiences, PROFILE_RULES } from './profiles.ts';
|
|
4
|
+
import { CLOCK_TOLERANCE_SECONDS, decodeWorkloadToken, issuedRefusal, MAX_TOKEN_AGE_SECONDS, WORKLOAD_ALGORITHMS, WorkloadTokenRefused, type DecodedToken } from './workload-token.ts';
|
|
5
|
+
import {
|
|
6
|
+
addressWithin, BEARER_PROFILES, claimAt, differingClaims, OIDC_PROFILES, POLICY_DEFAULTS, POLICY_FIELDS, REPEATING_PROFILES,
|
|
7
|
+
type BindingClaims, type BindingPolicy, type WorkloadProfile,
|
|
8
|
+
} from './workloads.ts';
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* A platform's proof held to a service's bindings (docs/design/0.16.md, "A
|
|
12
|
+
* workload signing in"). The app verifies a token's signature, or asks AWS,
|
|
13
|
+
* since only it reaches the platform; everything else read the binding's
|
|
14
|
+
* row, which only the vault can trust. So the vault decides it, on its own
|
|
15
|
+
* rows and its own clock, with these functions: rows and claims in, a
|
|
16
|
+
* binding or a refusal's word out. No I/O, and no clock but the one passed
|
|
17
|
+
* in, in milliseconds.
|
|
18
|
+
*
|
|
19
|
+
* Example: Ada's `deploy` service has two GitHub bindings on
|
|
20
|
+
* `token.actions.githubusercontent.com`, one for `main` made in March and
|
|
21
|
+
* one for every branch made in May. A run on `main` matches both; the
|
|
22
|
+
* March one, the oldest, issues its credential, with the scope its maker
|
|
23
|
+
* gave it. A run on `feature/x` matches May's alone.
|
|
24
|
+
*/
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* Why a proof is refused, in the vault's words. `no_match`: no binding of
|
|
28
|
+
* the service takes it. `audience`, `expired`, `too_old`, `malformed`: the
|
|
29
|
+
* token is not for this instance or this key, is past its time, or breaks
|
|
30
|
+
* its profile's rule. `unknown_signer`: a binding carries its keys, and they
|
|
31
|
+
* lack the one the token names.
|
|
32
|
+
*/
|
|
33
|
+
export type ExchangeRefusal = 'no_match' | 'audience' | 'expired' | 'too_old' | 'malformed' | 'unknown_signer';
|
|
34
|
+
export type ExchangeRefused = { refused: ExchangeRefusal };
|
|
35
|
+
|
|
36
|
+
/** A trust binding as a decision reads it: the columns of its row that say what it takes. */
|
|
37
|
+
export type ProofBinding = {
|
|
38
|
+
id: string;
|
|
39
|
+
profile: string;
|
|
40
|
+
issuer: string;
|
|
41
|
+
/** Where its issuer's keys are fetched from, or `sha256:<hex>` of those it carries (`CARRIED`). */
|
|
42
|
+
jwksUri: string;
|
|
43
|
+
/** The keys it carries, a JWKS as JSON: null when they are fetched. */
|
|
44
|
+
jwks: string | null;
|
|
45
|
+
/** JSON, sorted by claim name (`canonicalClaims`). */
|
|
46
|
+
claims: string;
|
|
47
|
+
/** Canonical JSON (`policyText`): null on a binding that issues a CI run's token, which no session is made from. */
|
|
48
|
+
policy: string | null;
|
|
49
|
+
createdAt: Date;
|
|
50
|
+
};
|
|
51
|
+
|
|
52
|
+
/** 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. */
|
|
53
|
+
export const CARRIED = 'sha256:';
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* The keys a token was verified under, as the app says: its issuer, and
|
|
57
|
+
* their address, the URL it fetched them from. For a binding that carries
|
|
58
|
+
* its keys the address is theirs, `sha256:<hex>`, and the vault verifies the
|
|
59
|
+
* signature itself (`signatureRefusal`).
|
|
60
|
+
*/
|
|
61
|
+
export type VerifiedUnder = { issuer: string; jwksUri: string };
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* What a proof is traded for: a CI run's five-minute token (`run`), from a
|
|
65
|
+
* binding with no policy, or a workload's session bound to a key
|
|
66
|
+
* (`session`), from one with a policy.
|
|
67
|
+
*/
|
|
68
|
+
export type ProofFor = { kind: 'run' } | { kind: 'session'; jkt: string };
|
|
69
|
+
|
|
70
|
+
/** A token's claims and the hash of what was signed, or `malformed`. */
|
|
71
|
+
export function readIdToken(token: string): DecodedToken | ExchangeRefused {
|
|
72
|
+
try {
|
|
73
|
+
return decodeWorkloadToken(token);
|
|
74
|
+
} catch (error) {
|
|
75
|
+
if (error instanceof WorkloadTokenRefused) return { refused: 'malformed' };
|
|
76
|
+
throw error;
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** 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. */
|
|
81
|
+
export function policyOf(binding: Pick<ProofBinding, 'policy'>): BindingPolicy | null | undefined {
|
|
82
|
+
if (binding.policy === null) return null;
|
|
83
|
+
try {
|
|
84
|
+
const policy: unknown = JSON.parse(binding.policy);
|
|
85
|
+
return typeof policy === 'object' && policy !== null && !Array.isArray(policy) ? (policy as BindingPolicy) : undefined;
|
|
86
|
+
} catch {
|
|
87
|
+
return undefined;
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/** 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. */
|
|
92
|
+
export function issues(binding: Pick<ProofBinding, 'profile' | 'policy'>, wanted: ProofFor['kind']): boolean {
|
|
93
|
+
const profiles: readonly string[] = wanted === 'run' ? BEARER_PROFILES : OIDC_PROFILES;
|
|
94
|
+
return profiles.includes(binding.profile) && (wanted === 'run' ? binding.policy === null : policyOf(binding) != null);
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/** The audience a token names, alone; null for none, or several. */
|
|
98
|
+
export function soleAudience(aud: unknown): string | null {
|
|
99
|
+
if (typeof aud === 'string') return aud;
|
|
100
|
+
return Array.isArray(aud) && aud.length === 1 && typeof aud[0] === 'string' ? aud[0] : null;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* The audiences a binding takes: this instance's URL for a CI run's; for a
|
|
105
|
+
* session's, its policy's, the session's key or its profile's
|
|
106
|
+
* (`expectedAudiences`). None for one whose policy does not read.
|
|
107
|
+
*/
|
|
108
|
+
export function audiencesOf(binding: Pick<ProofBinding, 'profile' | 'policy'>, publicUrl: string, wanted: ProofFor): string[] {
|
|
109
|
+
const policy = policyOf(binding);
|
|
110
|
+
if (wanted.kind === 'run') return policy === null ? [publicUrl] : [];
|
|
111
|
+
return policy == null ? [] : expectedAudiences(binding.profile as WorkloadProfile, policy, { publicUrl, jkt: wanted.jkt });
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* Which audience a token is held to, and the bindings that take it: the
|
|
116
|
+
* token's own if some binding takes it, otherwise the instance's, 0.14's
|
|
117
|
+
* rule. A token none takes is refused `audience` once its times are checked.
|
|
118
|
+
*/
|
|
119
|
+
export function audienceTried<B extends ProofBinding>(aud: unknown, bindings: readonly B[], publicUrl: string, wanted: ProofFor): { audience: string; taking: B[] } {
|
|
120
|
+
const named = soleAudience(aud);
|
|
121
|
+
const audience = named !== null && bindings.some((binding) => audiencesOf(binding, publicUrl, wanted).includes(named)) ? named : publicUrl;
|
|
122
|
+
return { audience, taking: bindings.filter((binding) => audiencesOf(binding, publicUrl, wanted).includes(audience)) };
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/**
|
|
126
|
+
* A token's times on the vault's clock, `now` in milliseconds, each within
|
|
127
|
+
* the clock tolerance, as 0.14 held them: not before its `nbf`, to jose's
|
|
128
|
+
* whole second; before its `exp`, to the millisecond, as 0.14's exchange
|
|
129
|
+
* checked it again; issued `maxAge` seconds ago at most (an hour,
|
|
130
|
+
* or any age for a token its platform hands out again), and, where a binding
|
|
131
|
+
* carries its keys, living `maxLifetime` seconds at most.
|
|
132
|
+
*/
|
|
133
|
+
export function timesRefusal(claims: DecodedToken['claims'], now: number, { maxAge = MAX_TOKEN_AGE_SECONDS, maxLifetime = null }: { maxAge?: number | null; maxLifetime?: number | null } = {}): ExchangeRefusal | null {
|
|
134
|
+
const seconds = Math.floor(now / 1000);
|
|
135
|
+
// 0.14's `not_yet_valid` and `too_long` are `too_old` here, as a token issued in the future already was: past its time.
|
|
136
|
+
if (typeof claims.nbf === 'number' && claims.nbf > seconds + CLOCK_TOLERANCE_SECONDS) return 'too_old';
|
|
137
|
+
if (claims.exp <= now / 1000 - CLOCK_TOLERANCE_SECONDS) return 'expired';
|
|
138
|
+
if (issuedRefusal(claims.iat, now / 1000, maxAge ?? Infinity) !== null) return 'too_old';
|
|
139
|
+
if (maxLifetime !== null && claims.exp - claims.iat > maxLifetime) return 'too_old';
|
|
140
|
+
return null;
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/** The oldest of `bindings` whose every claim the token carries (`differingClaims`), in the order the bindings' index reads them. */
|
|
144
|
+
export function oldestMatching<B extends Pick<ProofBinding, 'id' | 'profile' | 'claims' | 'createdAt'>>(bindings: readonly B[], claims: Record<string, unknown>): B | null {
|
|
145
|
+
const ordered = [...bindings].sort((a, b) => a.createdAt.getTime() - b.createdAt.getTime() || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0));
|
|
146
|
+
return ordered.find((binding) => {
|
|
147
|
+
let expected: unknown;
|
|
148
|
+
try {
|
|
149
|
+
expected = JSON.parse(binding.claims);
|
|
150
|
+
} catch {
|
|
151
|
+
return false;
|
|
152
|
+
}
|
|
153
|
+
return typeof expected === 'object' && expected !== null && !Array.isArray(expected) && differingClaims(binding.profile as WorkloadProfile, expected as BindingClaims, claims).length === 0;
|
|
154
|
+
}) ?? null;
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/** Why a token its binding matched still breaks its profile's own rule (`PROFILE_RULES`: Azure's version, Kubernetes' subject), or null. */
|
|
158
|
+
export function profileRefusal(binding: Pick<ProofBinding, 'profile' | 'issuer' | 'claims'>, policy: BindingPolicy, claims: Record<string, unknown>): 'malformed' | null {
|
|
159
|
+
const rule = PROFILE_RULES[binding.profile as WorkloadProfile];
|
|
160
|
+
if (rule === undefined) return null;
|
|
161
|
+
return rule.token(claims, { issuer: binding.issuer, claims: JSON.parse(binding.claims) as BindingClaims, policy }) === null ? null : 'malformed';
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/**
|
|
165
|
+
* Whether a proof is spent once it is traded, by the SHA-256 of what was
|
|
166
|
+
* signed: a CI run's token always; a session's token unless it names the
|
|
167
|
+
* session's key, which works for no other, or its platform hands the same
|
|
168
|
+
* one out again (`REPEATING_PROFILES`), which spending would refuse.
|
|
169
|
+
*/
|
|
170
|
+
export function spends(binding: Pick<ProofBinding, 'profile'>, policy: BindingPolicy | null, wanted: ProofFor['kind']): boolean {
|
|
171
|
+
if (wanted === 'run') return true;
|
|
172
|
+
return policy?.keyAudience !== true && !REPEATING_PROFILES.includes(binding.profile as WorkloadProfile);
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/**
|
|
176
|
+
* A session's hard end, in milliseconds: the earliest of its binding's
|
|
177
|
+
* `sessionHours` after `at`, where its profile has them (24 unless said),
|
|
178
|
+
* and, unless the token names the session's key, the token's own `exp`, so
|
|
179
|
+
* that a copy of it buys no more than the platform's lifetime. `exp` is in
|
|
180
|
+
* seconds, null for a proof that is no token. A session whose end is not
|
|
181
|
+
* after `at` is refused `expired`.
|
|
182
|
+
*/
|
|
183
|
+
export function hardEnd(binding: Pick<ProofBinding, 'profile'>, policy: BindingPolicy, at: number, exp: number | null): number {
|
|
184
|
+
const fields = POLICY_FIELDS[binding.profile as WorkloadProfile] ?? [];
|
|
185
|
+
const hours = fields.includes('sessionHours') ? (policy.sessionHours ?? POLICY_DEFAULTS.sessionHours) : null;
|
|
186
|
+
const ends = [hours === null ? null : at + hours * 3_600_000, policy.keyAudience === true || exp === null ? null : exp * 1000].filter((end): end is number => end !== null);
|
|
187
|
+
return Math.min(...(ends.length === 0 ? [at + POLICY_DEFAULTS.sessionHours * 3_600_000] : ends));
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
/**
|
|
191
|
+
* Why a session is refused at its sign-in, from its binding's policy and the
|
|
192
|
+
* request's address: the deployment lets no binding list reads (`noReads`)
|
|
193
|
+
* and this one does, or it names its sources and the request came from
|
|
194
|
+
* outside them, or from nowhere the app could tell. Both are `no_match`, as
|
|
195
|
+
* the design's refusals have it; 0.14 answered the second `source`.
|
|
196
|
+
*/
|
|
197
|
+
export function sessionRefusal(policy: BindingPolicy, ip: string | null, { noReads }: { noReads: boolean }): 'no_match' | null {
|
|
198
|
+
if (noReads && policy.reads !== undefined) return 'no_match';
|
|
199
|
+
if (policy.sources !== undefined && (ip === null || !addressWithin(ip, policy.sources))) return 'no_match';
|
|
200
|
+
return null;
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
/** An ID token held to a service's bindings: the binding it is traded at, its claims and policy, and the hash it spends, if any. */
|
|
204
|
+
export type IdTokenMatch<B extends ProofBinding> = { binding: B; policy: BindingPolicy | null; claims: DecodedToken['claims']; spends: Buffer | null };
|
|
205
|
+
|
|
206
|
+
/**
|
|
207
|
+
* An ID token whose signature verified under `under`, held to the
|
|
208
|
+
* service's live bindings, in 0.14's order:
|
|
209
|
+
*
|
|
210
|
+
* 1. of the bindings that issue what it is traded for (`issues`), those
|
|
211
|
+
* on its issuer under the keys it was verified under;
|
|
212
|
+
* 2. the audience tried, and the bindings that take it (`audienceTried`);
|
|
213
|
+
* 3. its times (`timesRefusal`): any age for a token its platform hands
|
|
214
|
+
* out again, where a binding that takes it is of such a platform, and
|
|
215
|
+
* an hour's lifetime at most under keys a binding carries;
|
|
216
|
+
* 4. that audience, the token's own, alone;
|
|
217
|
+
* 5. the oldest whose claims match (`oldestMatching`);
|
|
218
|
+
* 6. an hour's age after all, if the binding that matched is of a
|
|
219
|
+
* platform that hands out no token twice;
|
|
220
|
+
* 7. its profile's own rule (`profileRefusal`).
|
|
221
|
+
*
|
|
222
|
+
* `bindings` are the sealed rows the read found: a decision that picks the
|
|
223
|
+
* oldest of several refuses before this if any row it read is not the
|
|
224
|
+
* vault's, since one passed over would let a later one answer.
|
|
225
|
+
*/
|
|
226
|
+
export function matchIdToken<B extends ProofBinding>(token: DecodedToken, bindings: readonly B[], { under, publicUrl, wanted, now }: { under: VerifiedUnder; publicUrl: string; wanted: ProofFor; now: number }): IdTokenMatch<B> | ExchangeRefused {
|
|
227
|
+
const { claims } = token;
|
|
228
|
+
const candidates = bindings.filter((binding) => issues(binding, wanted.kind) && binding.issuer === under.issuer && binding.jwksUri === under.jwksUri && claims.iss === under.issuer);
|
|
229
|
+
if (candidates.length === 0) return { refused: 'no_match' };
|
|
230
|
+
const { audience, taking } = audienceTried(claims.aud, candidates, publicUrl, wanted);
|
|
231
|
+
const repeats = taking.some((binding) => REPEATING_PROFILES.includes(binding.profile as WorkloadProfile));
|
|
232
|
+
// Keys a binding carries: no issuer to ask whether a token still stands, so none lives past the hour.
|
|
233
|
+
const times = timesRefusal(claims, now, { maxAge: repeats ? null : MAX_TOKEN_AGE_SECONDS, maxLifetime: under.jwksUri.startsWith(CARRIED) ? MAX_TOKEN_AGE_SECONDS : null });
|
|
234
|
+
if (times !== null) return { refused: times };
|
|
235
|
+
if (soleAudience(claims.aud) !== audience || taking.length === 0) return { refused: 'audience' };
|
|
236
|
+
const binding = oldestMatching(taking, claims);
|
|
237
|
+
if (binding === null) return { refused: 'no_match' };
|
|
238
|
+
const policy = policyOf(binding)!;
|
|
239
|
+
// A token its platform hands out again is as old as the platform's cache; one of another platform beside it is an hour old at most.
|
|
240
|
+
if (repeats && !REPEATING_PROFILES.includes(binding.profile as WorkloadProfile) && issuedRefusal(claims.iat, now / 1000) !== null) return { refused: 'too_old' };
|
|
241
|
+
if (policy !== null && profileRefusal(binding, policy, claims) !== null) return { refused: 'malformed' };
|
|
242
|
+
return { binding, policy, claims, spends: spends(binding, policy, wanted.kind) ? token.signingInputHash : null };
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
/**
|
|
246
|
+
* Whether a token's signature verifies under keys a binding carries, a JWKS
|
|
247
|
+
* as its row holds it: null if it does, `unknown_signer` when the set lacks
|
|
248
|
+
* the key the token names, and `malformed` for any other failure, a
|
|
249
|
+
* signature that does not verify under it included. The algorithms are
|
|
250
|
+
* fixed, and nothing is taken from the header but `alg` and `kid`; a set
|
|
251
|
+
* with several keys the header could name tries each. A token that does
|
|
252
|
+
* not read as one (`readIdToken`), an unencoded payload's included, is
|
|
253
|
+
* `malformed` before any key is tried. It checks no claim: the times and
|
|
254
|
+
* the audience are `matchIdToken`'s.
|
|
255
|
+
*/
|
|
256
|
+
export async function signatureRefusal(token: string, jwks: string): Promise<'unknown_signer' | 'malformed' | null> {
|
|
257
|
+
if ('refused' in readIdToken(token)) return 'malformed';
|
|
258
|
+
let keys: JSONWebKeySet;
|
|
259
|
+
try {
|
|
260
|
+
keys = JSON.parse(jwks) as JSONWebKeySet;
|
|
261
|
+
} catch {
|
|
262
|
+
return 'malformed';
|
|
263
|
+
}
|
|
264
|
+
const options = { algorithms: [...WORKLOAD_ALGORITHMS] };
|
|
265
|
+
try {
|
|
266
|
+
await compactVerify(token, createLocalJWKSet(keys), options);
|
|
267
|
+
return null;
|
|
268
|
+
} catch (error) {
|
|
269
|
+
if (error instanceof errors.JWKSNoMatchingKey) return 'unknown_signer';
|
|
270
|
+
if (!(error instanceof errors.JWKSMultipleMatchingKeys)) return 'malformed';
|
|
271
|
+
for await (const key of error) {
|
|
272
|
+
try {
|
|
273
|
+
await compactVerify(token, key, options);
|
|
274
|
+
return null;
|
|
275
|
+
} catch {
|
|
276
|
+
// The next key the header could name.
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
return 'malformed';
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
/**
|
|
284
|
+
* The claims of the run a credential was issued for, as its issuer stated
|
|
285
|
+
* them: those that say which run, each bounded, in the exchange's entry and
|
|
286
|
+
* the credential's row, so that a read leads back to its run. What the
|
|
287
|
+
* issuer says, not proof of which run sent the request.
|
|
288
|
+
*/
|
|
289
|
+
export const RUN_CLAIMS = [
|
|
290
|
+
'sub', 'jti', 'actor', 'event_name', 'ref', 'base_ref', 'head_ref', 'sha', 'repository', 'repository_id', 'run_id', 'run_attempt',
|
|
291
|
+
'workflow_ref', 'job_workflow_ref', 'job_workflow_sha', 'environment',
|
|
292
|
+
'project_path', 'project_id', 'namespace_id', 'pipeline_id', 'pipeline_source', 'job_id',
|
|
293
|
+
'kubernetes.io.pod.name',
|
|
294
|
+
] as const;
|
|
295
|
+
export const MAX_RUN_CLAIM = 256;
|
|
296
|
+
|
|
297
|
+
/** The run's claims, as the issuer stated them: each a string of 256 characters at most, or a finite number. */
|
|
298
|
+
export function runClaims(claims: Record<string, unknown>): Record<string, string | number> {
|
|
299
|
+
const run: Record<string, string | number> = {};
|
|
300
|
+
for (const name of RUN_CLAIMS) {
|
|
301
|
+
const value = claimAt(claims, name);
|
|
302
|
+
if (typeof value === 'string') run[name] = value.slice(0, MAX_RUN_CLAIM);
|
|
303
|
+
else if (typeof value === 'number' && Number.isFinite(value)) run[name] = value;
|
|
304
|
+
}
|
|
305
|
+
return run;
|
|
306
|
+
}
|
|
@@ -474,7 +474,7 @@ function checkProvider(provider: SigninProvider): void {
|
|
|
474
474
|
}
|
|
475
475
|
}
|
|
476
476
|
|
|
477
|
-
function lifetime(value: number | undefined, name: string, fallback: number, max: number): number {
|
|
477
|
+
export function lifetime(value: number | undefined, name: string, fallback: number, max: number): number {
|
|
478
478
|
if (value === undefined) return fallback;
|
|
479
479
|
if (!Number.isFinite(value) || value <= 0 || value > max) {
|
|
480
480
|
throw new Error(`${name} must be a number above 0 and at most ${max}`);
|
package/src/identity/tokens.ts
CHANGED
|
@@ -21,8 +21,13 @@ import { createHash, randomBytes } from 'node:crypto';
|
|
|
21
21
|
*/
|
|
22
22
|
export type CredentialKind = 'browser' | 'cli' | 'service' | 'personal' | 'handle' | 'workload';
|
|
23
23
|
|
|
24
|
-
/**
|
|
25
|
-
|
|
24
|
+
/**
|
|
25
|
+
* What a token's prefix says it is: a credential, an enrollment code, or
|
|
26
|
+
* an MCP client's tokens: an access token, good at `/mcp` alone, and the
|
|
27
|
+
* refresh token it gets the next one with, good at the token endpoint alone
|
|
28
|
+
* (docs/design/0.16.md, "MCP connections").
|
|
29
|
+
*/
|
|
30
|
+
export type TokenKind = CredentialKind | 'enrollment' | 'mcp' | 'mcp-refresh';
|
|
26
31
|
|
|
27
32
|
const PREFIX: Record<TokenKind, string> = {
|
|
28
33
|
browser: 'coffre_web_',
|
|
@@ -32,9 +37,11 @@ const PREFIX: Record<TokenKind, string> = {
|
|
|
32
37
|
handle: 'coffre_use_',
|
|
33
38
|
workload: 'coffre_wl_',
|
|
34
39
|
enrollment: 'coffre_enr_',
|
|
40
|
+
mcp: 'coffre_mcp_',
|
|
41
|
+
'mcp-refresh': 'coffre_mcr_',
|
|
35
42
|
};
|
|
36
43
|
|
|
37
|
-
const TOKEN = /^coffre_(web|cli|svc|pat|use|wl|enr)_[A-Za-z0-9_-]{43}$/;
|
|
44
|
+
const TOKEN = /^coffre_(web|cli|svc|pat|use|wl|enr|mcp|mcr)_[A-Za-z0-9_-]{43}$/;
|
|
38
45
|
|
|
39
46
|
export function generateToken(kind: TokenKind): string {
|
|
40
47
|
return PREFIX[kind] + randomBytes(32).toString('base64url');
|
package/src/identity/verifier.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { createLocalJWKSet, decodeProtectedHeader, errors, jwtVerify, type JSONWebKeySet, type JWTPayload } from 'jose';
|
|
2
2
|
import type { AccessVerifierConfig, IdentityVerifier, Principal } from './types.ts';
|
|
3
3
|
|
|
4
4
|
export type { AccessVerifierConfig };
|
|
@@ -12,6 +12,10 @@ export type { AccessVerifierConfig };
|
|
|
12
12
|
*/
|
|
13
13
|
const ALLOWED_ALGORITHMS = ['RS256', 'ES256'] as const;
|
|
14
14
|
|
|
15
|
+
/** How long a key set is used before it is fetched again, and the least time between two fetches an unknown key asks for. */
|
|
16
|
+
const KEYS_MAX_AGE_MS = 10 * 60_000;
|
|
17
|
+
const REFETCH_COOLDOWN_MS = 30_000;
|
|
18
|
+
|
|
15
19
|
type AccessClaims = JWTPayload & {
|
|
16
20
|
email?: unknown;
|
|
17
21
|
common_name?: unknown;
|
|
@@ -21,39 +25,94 @@ function asNonEmptyString(value: unknown): string | null {
|
|
|
21
25
|
return typeof value === 'string' && value.length > 0 ? value : null;
|
|
22
26
|
}
|
|
23
27
|
|
|
28
|
+
/** 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. */
|
|
29
|
+
export class AccessKeysUnavailable extends Error {
|
|
30
|
+
constructor(message: string, options?: { cause?: unknown }) {
|
|
31
|
+
super(message, options);
|
|
32
|
+
this.name = 'AccessKeysUnavailable';
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** How the verifier fetches the team's key set, and what time it is. */
|
|
37
|
+
export type AccessVerifierIo = {
|
|
38
|
+
/** GET a JSON document; throws when it cannot. The global `fetch` unless given. */
|
|
39
|
+
json?: (url: URL) => Promise<unknown>;
|
|
40
|
+
now?: () => number;
|
|
41
|
+
};
|
|
42
|
+
|
|
43
|
+
async function fetchJson(url: URL): Promise<unknown> {
|
|
44
|
+
const response = await fetch(url, { redirect: 'manual', signal: AbortSignal.timeout(5_000), headers: { accept: 'application/json' } });
|
|
45
|
+
if (response.status !== 200) {
|
|
46
|
+
await response.body?.cancel();
|
|
47
|
+
throw new Error(`${url.href} answered ${response.status}`);
|
|
48
|
+
}
|
|
49
|
+
return response.json();
|
|
50
|
+
}
|
|
51
|
+
|
|
24
52
|
/**
|
|
25
53
|
* Verifies Cloudflare Access JWTs.
|
|
26
54
|
*
|
|
27
55
|
* Signature and claim verification of the token Access sends with each
|
|
28
|
-
* request.
|
|
56
|
+
* request. The team's keys are fetched when first needed, used for ten
|
|
57
|
+
* minutes, and fetched again sooner for a key they lack, at most every 30
|
|
58
|
+
* seconds. The verifier lives as long as its configuration (an isolate's,
|
|
59
|
+
* on Workers) and keeps settled values only, never a fetch in flight
|
|
60
|
+
* (AGENTS.md, "What an isolate keeps"): concurrent requests that find no
|
|
61
|
+
* key set each fetch their own, and the last to land is kept. The 30
|
|
62
|
+
* seconds count from the last refresh started, landed or not, and are
|
|
63
|
+
* taken before it starts: of a burst of assertions naming a key the set
|
|
64
|
+
* lacks, one fetches, and the others are refused as the key unknown.
|
|
29
65
|
*/
|
|
30
66
|
export class AccessIdentityVerifier implements IdentityVerifier {
|
|
31
67
|
readonly #config: AccessVerifierConfig;
|
|
32
|
-
readonly #
|
|
68
|
+
readonly #url: URL;
|
|
69
|
+
readonly #json: (url: URL) => Promise<unknown>;
|
|
70
|
+
readonly #now: () => number;
|
|
71
|
+
#keys: { set: ReturnType<typeof createLocalJWKSet>; at: number } | null = null;
|
|
72
|
+
/** When a refresh for an unknown key last started: a number, settled the moment it starts. */
|
|
73
|
+
#refreshed = Number.NEGATIVE_INFINITY;
|
|
33
74
|
|
|
34
|
-
constructor(config: AccessVerifierConfig) {
|
|
75
|
+
constructor(config: AccessVerifierConfig, io: AccessVerifierIo = {}) {
|
|
35
76
|
this.#config = config;
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
this.#
|
|
39
|
-
cooldownDuration: 30_000,
|
|
40
|
-
cacheMaxAge: 600_000,
|
|
41
|
-
});
|
|
77
|
+
this.#url = new URL(config.jwksUrl);
|
|
78
|
+
this.#json = io.json ?? fetchJson;
|
|
79
|
+
this.#now = io.now ?? Date.now;
|
|
42
80
|
}
|
|
43
81
|
|
|
44
82
|
async verify(token: string): Promise<Principal> {
|
|
45
83
|
if (typeof token !== 'string' || token.length === 0) {
|
|
46
84
|
throw new Error('missing or empty Access token');
|
|
47
85
|
}
|
|
48
|
-
|
|
49
|
-
const {
|
|
86
|
+
// Malformed, or signed with an algorithm we never take: refused before anything is fetched for it.
|
|
87
|
+
const { alg } = decodeProtectedHeader(token);
|
|
88
|
+
if (!(ALLOWED_ALGORITHMS as readonly unknown[]).includes(alg)) throw new errors.JOSEAlgNotAllowed(`"alg" (Algorithm) Header Parameter value not allowed`);
|
|
89
|
+
const options = {
|
|
50
90
|
issuer: this.#config.issuer,
|
|
51
91
|
audience: this.#config.audience,
|
|
52
92
|
algorithms: [...ALLOWED_ALGORITHMS],
|
|
53
93
|
clockTolerance: this.#config.clockToleranceSeconds ?? 0,
|
|
54
|
-
}
|
|
94
|
+
};
|
|
95
|
+
let keys = this.#keys;
|
|
96
|
+
if (keys === null || this.#now() - keys.at >= KEYS_MAX_AGE_MS) keys = await this.#fetch();
|
|
97
|
+
try {
|
|
98
|
+
return toPrincipal((await jwtVerify<AccessClaims>(token, keys.set, options)).payload);
|
|
99
|
+
} catch (error) {
|
|
100
|
+
// A key the set lacks may be one Access rotated in since: asked again, once, past the cooldown.
|
|
101
|
+
const now = this.#now();
|
|
102
|
+
if (!(error instanceof errors.JWKSNoMatchingKey) || now - Math.max(keys.at, this.#refreshed) < REFETCH_COOLDOWN_MS) throw error;
|
|
103
|
+
this.#refreshed = now;
|
|
104
|
+
}
|
|
105
|
+
return toPrincipal((await jwtVerify<AccessClaims>(token, (await this.#fetch()).set, options)).payload);
|
|
106
|
+
}
|
|
55
107
|
|
|
56
|
-
|
|
108
|
+
async #fetch(): Promise<{ set: ReturnType<typeof createLocalJWKSet>; at: number }> {
|
|
109
|
+
let set: ReturnType<typeof createLocalJWKSet>;
|
|
110
|
+
try {
|
|
111
|
+
set = createLocalJWKSet((await this.#json(this.#url)) as JSONWebKeySet);
|
|
112
|
+
} catch (error) {
|
|
113
|
+
throw new AccessKeysUnavailable(`Cloudflare Access's keys could not be fetched from ${this.#url.href}`, { cause: error });
|
|
114
|
+
}
|
|
115
|
+
return (this.#keys = { set, at: this.#now() });
|
|
57
116
|
}
|
|
58
117
|
}
|
|
59
118
|
|
|
@@ -79,8 +79,12 @@ export function decodeWorkloadToken(token: string): DecodedToken {
|
|
|
79
79
|
return value as Record<string, unknown>;
|
|
80
80
|
};
|
|
81
81
|
const [header, claims] = [json(parts[0]!), json(parts[1]!)];
|
|
82
|
+
// An extension the signer requires to be understood, `b64: false`'s unencoded payload above all, is one this reader does not: it reads `alg` and `kid` alone.
|
|
83
|
+
if (header.crit !== undefined) throw malformed('names a critical header extension');
|
|
82
84
|
for (const name of ['iss', 'sub'] as const) {
|
|
83
85
|
if (typeof claims[name] !== 'string' || claims[name] === '') throw malformed(`has no ${name}, as a nonempty string`);
|
|
86
|
+
// A database stores no NUL, and UTF-8 no lone surrogate: a claim with one could match nothing, and is no text.
|
|
87
|
+
if (/[\0\p{Cs}]/u.test(claims[name])) throw malformed(`has an ${name} with a NUL or a lone surrogate`);
|
|
84
88
|
}
|
|
85
89
|
for (const name of ['exp', 'iat'] as const) {
|
|
86
90
|
if (typeof claims[name] !== 'number' || !Number.isFinite(claims[name])) throw malformed(`has no ${name}, as a finite number`);
|
|
@@ -673,17 +673,6 @@ export type BindingPolicy = {
|
|
|
673
673
|
readonly unsignedUploads?: true;
|
|
674
674
|
};
|
|
675
675
|
|
|
676
|
-
/** How long a credential an exchange issues lives: one `coffre run` needs it for seconds. The vault holds a sign-in to it (T149). */
|
|
677
|
-
export const EXCHANGED_CREDENTIAL_MS = 5 * 60 * 1000;
|
|
678
|
-
|
|
679
|
-
/** How long a session lives past each renewal, unless its proof says less: an hour (section 5.4). The vault holds a sign-in to it. */
|
|
680
|
-
export const SESSION_MS = 60 * 60 * 1000;
|
|
681
|
-
|
|
682
|
-
/** A workload's sign-in route, whose URL on the instance its DPoP proof signs: the app's route, and what the vault checks the proof for (PR 3b). */
|
|
683
|
-
export const WORKLOAD_SIGN_IN_PATH = '/api/auth/workload';
|
|
684
|
-
/** How far a sign-in's DPoP proof's `iat` may be from now: it carries no nonce, so its clock bounds it (section 4.1). The app and the vault alike. */
|
|
685
|
-
export const EXCHANGE_SKEW_SECONDS = 60;
|
|
686
|
-
|
|
687
676
|
/** What a field left out of a policy means. */
|
|
688
677
|
export const POLICY_DEFAULTS = {
|
|
689
678
|
keyAudience: false,
|
package/src/kek/aws-kms.ts
CHANGED
|
@@ -5,6 +5,7 @@ import {
|
|
|
5
5
|
DEK_BYTES,
|
|
6
6
|
KekBadClaimError,
|
|
7
7
|
KekCancelledError,
|
|
8
|
+
KekRefusedError,
|
|
8
9
|
KekUnavailableError,
|
|
9
10
|
type KeyOperation,
|
|
10
11
|
type KekProvider,
|
|
@@ -103,11 +104,11 @@ export class AwsKmsKekProvider implements KekProvider {
|
|
|
103
104
|
CiphertextBlob: base64(wrapped.bytes),
|
|
104
105
|
EncryptionContext: encryptionContext(ctx),
|
|
105
106
|
}, operation);
|
|
106
|
-
if (KeyId !== this.keyId) throw new
|
|
107
|
+
if (KeyId !== this.keyId) throw new KekRefusedError(`KMS decrypted under ${KeyId}, not ${this.keyId}`, true);
|
|
107
108
|
const dek = Buffer.from(Plaintext, 'base64');
|
|
108
109
|
if (dek.length !== DEK_BYTES) {
|
|
109
110
|
dek.fill(0);
|
|
110
|
-
throw new
|
|
111
|
+
throw new KekRefusedError('unwrapped DEK has the wrong length', true);
|
|
111
112
|
}
|
|
112
113
|
return dek;
|
|
113
114
|
}
|
|
@@ -116,7 +117,9 @@ export class AwsKmsKekProvider implements KekProvider {
|
|
|
116
117
|
* One KMS call, tried up to three times while KMS throttles, fails on its
|
|
117
118
|
* side or does not answer. Every failure but a ciphertext that does not
|
|
118
119
|
* open is a `KekUnavailableError`, retried or not: a key KMS will not use
|
|
119
|
-
* or credentials it refuses say nothing about the claim either.
|
|
120
|
+
* or credentials it refuses say nothing about the claim either. What KMS
|
|
121
|
+
* answered and will answer again, such as `AccessDeniedException` or
|
|
122
|
+
* `DisabledException`, is a `KekRefusedError`, which only its operator mends.
|
|
120
123
|
*/
|
|
121
124
|
async #call(action: 'Encrypt' | 'Decrypt', request: object, operation?: KeyOperation): Promise<Record<string, string>> {
|
|
122
125
|
const body = JSON.stringify(request);
|
|
@@ -144,7 +147,8 @@ export class AwsKmsKekProvider implements KekProvider {
|
|
|
144
147
|
throw new KekBadClaimError(`KMS ${action}: ${answer.type}`);
|
|
145
148
|
}
|
|
146
149
|
if (!answer.retry || attempt === ATTEMPTS) {
|
|
147
|
-
|
|
150
|
+
const failed = answer.refused ? KekRefusedError : KekUnavailableError;
|
|
151
|
+
throw new failed(`KMS ${action} failed${attempt > 1 ? ` ${attempt} times` : ''}: ${answer.failure}`, uncertain);
|
|
148
152
|
}
|
|
149
153
|
try {
|
|
150
154
|
await delay(100 * 4 ** (attempt - 1) * (1 + Math.random()), signal);
|
|
@@ -162,7 +166,7 @@ export class AwsKmsKekProvider implements KekProvider {
|
|
|
162
166
|
credentials: AwsCredentials,
|
|
163
167
|
signal?: AbortSignal,
|
|
164
168
|
operation?: KeyOperation,
|
|
165
|
-
): Promise<{ data: Record<string, string> } | { type: string; failure: string; retry: boolean; uncertain: boolean }> {
|
|
169
|
+
): Promise<{ data: Record<string, string> } | { type: string; failure: string; retry: boolean; refused: boolean; uncertain: boolean }> {
|
|
166
170
|
const headers = signV4({
|
|
167
171
|
method: 'POST',
|
|
168
172
|
url: this.#url,
|
|
@@ -186,25 +190,22 @@ export class AwsKmsKekProvider implements KekProvider {
|
|
|
186
190
|
});
|
|
187
191
|
text = await response.text();
|
|
188
192
|
} catch (error) {
|
|
189
|
-
return { type: 'network', failure: messageOf(error), retry: sent, uncertain: sent };
|
|
193
|
+
return { type: 'network', failure: messageOf(error), retry: sent, refused: false, uncertain: sent };
|
|
190
194
|
}
|
|
191
195
|
const parsed = parse(text);
|
|
192
196
|
if (response.ok) {
|
|
193
197
|
const complete =
|
|
194
198
|
parsed !== null && (action === 'Encrypt' ? typeof parsed.CiphertextBlob === 'string' : typeof parsed.Plaintext === 'string');
|
|
195
199
|
if (complete) return { data: parsed as Record<string, string> };
|
|
196
|
-
return { type: 'malformed', failure: `KMS answered ${response.status} without a result`, retry: true, uncertain: true };
|
|
200
|
+
return { type: 'malformed', failure: `KMS answered ${response.status} without a result`, retry: true, refused: false, uncertain: true };
|
|
197
201
|
}
|
|
198
202
|
// `__type` may carry a namespace (`com.amazonaws.kms#…`), the header a URL after `:`.
|
|
199
203
|
const raw = response.headers.get('x-amzn-errortype') ?? (typeof parsed?.__type === 'string' ? parsed.__type : '');
|
|
200
204
|
const type = raw.split(':')[0]!.split('#').pop() || `HTTP ${response.status}`;
|
|
201
205
|
const message = parsed?.message ?? parsed?.Message;
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
uncertain: false,
|
|
206
|
-
retry: response.status >= 500 || response.status === 429 || type === 'ThrottlingException',
|
|
207
|
-
};
|
|
206
|
+
const retry = response.status >= 500 || response.status === 429 || type === 'ThrottlingException';
|
|
207
|
+
// Any other answer is KMS's word on coffre's request itself, which it gives again: refused.
|
|
208
|
+
return { type, failure: `${type}${typeof message === 'string' ? `, ${message}` : ''}`, uncertain: false, retry, refused: !retry };
|
|
208
209
|
}
|
|
209
210
|
}
|
|
210
211
|
|
|
@@ -222,6 +223,10 @@ function encryptionContext(ctx: SecretContext): Record<string, string> {
|
|
|
222
223
|
...(ctx.owner === undefined ? {} : { 'coffre:owner': ctx.owner }),
|
|
223
224
|
// A sensitive value's: KMS refuses to decrypt it as anything else.
|
|
224
225
|
...(ctx.sensitive === true ? { 'coffre:sensitive': 'true' } : {}),
|
|
226
|
+
// A plain value's, from envelope version 2: KMS refuses to decrypt a secret as one.
|
|
227
|
+
...(ctx.plain === true ? { 'coffre:plain': 'true' } : {}),
|
|
228
|
+
// The version's number, from envelope version 2: KMS refuses to decrypt one version's key as another's.
|
|
229
|
+
...(ctx.version === undefined ? {} : { 'coffre:version': String(ctx.version) }),
|
|
225
230
|
};
|
|
226
231
|
}
|
|
227
232
|
|