@coffre/client 0.15.0 → 0.16.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/credential-DyAuH0om.d.ts +57 -0
- package/dist/credential.d.ts +2 -54
- package/dist/credential.js +68 -2
- package/dist/{dpop-CYJtAnvD.d.ts → dpop-C9EOdNCi.d.ts} +3 -1
- package/dist/dpop.d.ts +2 -2
- package/dist/dpop.js +3 -1
- package/dist/{index-B2UlVqL3.d.ts → index-DZZ3DRTO.d.ts} +997 -1187
- package/dist/index.d.ts +2 -2
- package/dist/index.js +2 -2
- package/dist/routes.d.ts +1 -1
- package/dist/routes.js +1 -11
- package/dist/{src-Dwhw_Cc4.js → src-JtgcfCXD.js} +38 -79
- package/dist/{workload-DwWrQQg1.d.ts → workload-3gHR2coV.d.ts} +22 -10
- package/dist/{workload-BsyIQcko.js → workload-CizRrO4x.js} +66 -58
- package/dist/workload-postgres.d.ts +2 -2
- package/dist/workload-postgres.js +6 -8
- package/dist/workload.d.ts +4 -3
- package/dist/workload.js +2 -2
- package/package.json +1 -1
- package/src/api.ts +852 -989
- package/src/credential.ts +43 -3
- package/src/dpop.ts +3 -0
- package/src/index.ts +21 -66
- package/src/proofs.ts +42 -0
- package/src/routes.ts +0 -7
- package/src/workload-postgres.ts +5 -7
- package/src/workload-proofs.ts +21 -11
- package/src/workload.ts +39 -16
- package/src/audit.ts +0 -16
package/src/credential.ts
CHANGED
|
@@ -12,6 +12,11 @@
|
|
|
12
12
|
* `COFFRE_HANDLE`, the handle that stands in for the environment's values;
|
|
13
13
|
* the proxy injects the key, and the app never holds it.
|
|
14
14
|
*/
|
|
15
|
+
import { fromBase64url, JSON_MESSAGE_BYTES } from './dpop.ts';
|
|
16
|
+
|
|
17
|
+
/** What a cipher's encrypt gives: the IV coffre drew, 12 bytes, the ciphertext, and the 16-byte tag, which the app stores in its own format. */
|
|
18
|
+
export type Sealed = { iv: Uint8Array; ciphertext: Uint8Array; tag: Uint8Array };
|
|
19
|
+
|
|
15
20
|
export type ProxiedCredential = {
|
|
16
21
|
/** The credential's URL on the proxy: `<url>/<path>` is `<upstream>/<path>`. */
|
|
17
22
|
url: string;
|
|
@@ -29,7 +34,10 @@ export type ProxiedCredential = {
|
|
|
29
34
|
* A signature of `message` (a string signs as its UTF-8) by a signer's
|
|
30
35
|
* key, which stays in coffre: a private key's, what Node's
|
|
31
36
|
* `crypto.sign(undefined, message, key)` gives, base64url, each one use
|
|
32
|
-
* in coffre's log; an HMAC secret's, as its `hmac()` writes it.
|
|
37
|
+
* in coffre's log; an HMAC secret's, as its `hmac()` writes it. A message
|
|
38
|
+
* past 1 MiB goes raw, its bytes as the request's body, which coffre
|
|
39
|
+
* signs as they come, never held: an `hmac()` signer's whose `maxBytes`
|
|
40
|
+
* takes it, SumSub's document upload say.
|
|
33
41
|
*/
|
|
34
42
|
sign(message: Uint8Array | string): Promise<string>;
|
|
35
43
|
/**
|
|
@@ -39,6 +47,13 @@ export type ProxiedCredential = {
|
|
|
39
47
|
* in coffre, which compares in constant time and says only yes or no.
|
|
40
48
|
*/
|
|
41
49
|
verify(message: Uint8Array | string, signature: string): Promise<boolean>;
|
|
50
|
+
/**
|
|
51
|
+
* `plaintext` (a string as its UTF-8) encrypted with a cipher's AES-256-GCM key, which stays in coffre, under `aad`
|
|
52
|
+
* if given: under an IV coffre draws for each, never the app's.
|
|
53
|
+
*/
|
|
54
|
+
encrypt(plaintext: Uint8Array | string, aad?: Uint8Array | string): Promise<Sealed>;
|
|
55
|
+
/** The plaintext `sealed` holds under the cipher's key and `aad`, or null when it does not decrypt: whatever part is wrong, coffre says no more. */
|
|
56
|
+
decrypt(sealed: Sealed, aad?: Uint8Array | string): Promise<Uint8Array | null>;
|
|
42
57
|
};
|
|
43
58
|
|
|
44
59
|
type Env = Record<string, string | undefined>;
|
|
@@ -67,7 +82,17 @@ export function credential(
|
|
|
67
82
|
headers: { authorization: `Bearer ${handle}`, 'content-type': 'application/json' },
|
|
68
83
|
body: JSON.stringify(asked),
|
|
69
84
|
});
|
|
70
|
-
return { answer, body: (await answer.json()) as { url?: string; expiresAt?: string; signature?: string; valid?: boolean; message?: string } };
|
|
85
|
+
return { answer, body: (await answer.json()) as { url?: string; expiresAt?: string; signature?: string; valid?: boolean; iv?: string; ciphertext?: string; tag?: string; plaintext?: string | null; message?: string } };
|
|
86
|
+
};
|
|
87
|
+
/** A message past what JSON takes, signed raw: its bytes as the body, with the SHA-256 that `coffre serve` streams it by, and coffre checks. */
|
|
88
|
+
const raw = async (bytes: Uint8Array) => {
|
|
89
|
+
const digest = new Uint8Array(await crypto.subtle.digest('SHA-256', bytes as Uint8Array<ArrayBuffer>));
|
|
90
|
+
const answer = await fetcher(`${url.slice(0, url.lastIndexOf('/'))}?sign=${encodeURIComponent(name)}`, {
|
|
91
|
+
method: 'POST',
|
|
92
|
+
headers: { authorization: `Bearer ${handle}`, 'content-type': 'application/octet-stream', 'content-length': String(bytes.length), 'content-digest': `sha-256=:${btoa(String.fromCharCode(...digest))}:` },
|
|
93
|
+
body: bytes as Uint8Array<ArrayBuffer>,
|
|
94
|
+
});
|
|
95
|
+
return { answer, body: (await answer.json()) as { signature?: string; message?: string } };
|
|
71
96
|
};
|
|
72
97
|
const bytesOf = (message: Uint8Array | string) => {
|
|
73
98
|
const bytes = typeof message === 'string' ? new TextEncoder().encode(message) : message;
|
|
@@ -88,7 +113,8 @@ export function credential(
|
|
|
88
113
|
return { url: body.url, expiresAt: body.expiresAt! };
|
|
89
114
|
},
|
|
90
115
|
sign: async (message) => {
|
|
91
|
-
const
|
|
116
|
+
const bytes = typeof message === 'string' ? new TextEncoder().encode(message) : message;
|
|
117
|
+
const { answer, body } = bytes.length > JSON_MESSAGE_BYTES ? await raw(bytes) : await compute({ sign: { credential: name, message: bytesOf(bytes) } });
|
|
92
118
|
if (!answer.ok || body.signature === undefined) throw new Error(`coffre signed nothing: ${body.message ?? answer.status}`);
|
|
93
119
|
return body.signature;
|
|
94
120
|
},
|
|
@@ -97,5 +123,19 @@ export function credential(
|
|
|
97
123
|
if (!answer.ok || typeof body.valid !== 'boolean') throw new Error(`coffre verified nothing: ${body.message ?? answer.status}`);
|
|
98
124
|
return body.valid;
|
|
99
125
|
},
|
|
126
|
+
encrypt: async (plaintext, aad) => {
|
|
127
|
+
const { answer, body } = await compute({ encrypt: { credential: name, plaintext: bytesOf(plaintext), ...(aad === undefined ? {} : { aad: bytesOf(aad) }) } });
|
|
128
|
+
const [iv, ciphertext, tag] = [body.iv, body.ciphertext, body.tag].map((part) => (typeof part === 'string' ? fromBase64url(part) : null));
|
|
129
|
+
if (!answer.ok || !iv || !ciphertext || !tag) throw new Error(`coffre encrypted nothing: ${body.message ?? answer.status}`);
|
|
130
|
+
return { iv, ciphertext, tag };
|
|
131
|
+
},
|
|
132
|
+
decrypt: async ({ iv, ciphertext, tag }, aad) => {
|
|
133
|
+
const { answer, body } = await compute({ decrypt: { credential: name, iv: bytesOf(iv), ciphertext: bytesOf(ciphertext), tag: bytesOf(tag), ...(aad === undefined ? {} : { aad: bytesOf(aad) }) } });
|
|
134
|
+
if (!answer.ok || (body.plaintext !== null && typeof body.plaintext !== 'string')) throw new Error(`coffre decrypted nothing: ${body.message ?? answer.status}`);
|
|
135
|
+
if (body.plaintext === null) return null;
|
|
136
|
+
const plaintext = fromBase64url(body.plaintext);
|
|
137
|
+
if (plaintext === null) throw new Error('coffre decrypted nothing: its answer is no base64url');
|
|
138
|
+
return plaintext;
|
|
139
|
+
},
|
|
100
140
|
};
|
|
101
141
|
}
|
package/src/dpop.ts
CHANGED
|
@@ -183,6 +183,9 @@ export async function bodyDigest(body: Uint8Array | string): Promise<string> {
|
|
|
183
183
|
*/
|
|
184
184
|
export const MAX_DIGESTED_BODY = 95 * 1024 * 1024;
|
|
185
185
|
|
|
186
|
+
/** The longest message `sign` sends as JSON, base64url: what coffre reads whole. A longer one goes raw, the body itself. */
|
|
187
|
+
export const JSON_MESSAGE_BYTES = 1024 * 1024;
|
|
188
|
+
|
|
186
189
|
/** A body's `Content-Digest` (RFC 9530) from its SHA-256 in hex, as the SDK and `coffre serve` send it: `sha-256=:<base64>:`. */
|
|
187
190
|
export function contentDigest(sha256: string): string {
|
|
188
191
|
if (!SHA256_HEX.test(sha256)) throw new TypeError('a Content-Digest is made from a SHA-256 in hex');
|
package/src/index.ts
CHANGED
|
@@ -10,7 +10,7 @@
|
|
|
10
10
|
* its own handling of Cloudflare Access redirects. A request that never
|
|
11
11
|
* reaches the instance throws `Unreachable`, which says why.
|
|
12
12
|
*/
|
|
13
|
-
import type { Api, AuthInfo, BindingPlan,
|
|
13
|
+
import type { Api, AuthInfo, BindingPlan, DeletionResult, DryRunOutcome, DryRunResult, KeysPlan, RoleImpact, SetResult, TokenPlan } from './api.ts';
|
|
14
14
|
import { Unreachable } from './reach.ts';
|
|
15
15
|
|
|
16
16
|
export type {
|
|
@@ -57,9 +57,9 @@ export type {
|
|
|
57
57
|
} from './api.ts';
|
|
58
58
|
|
|
59
59
|
export { ageInDays, olderThan } from './age.ts';
|
|
60
|
-
export { runLabel } from './audit.ts';
|
|
61
60
|
export { byFolder, foldersOf } from './folders.ts';
|
|
62
61
|
export { apiMember, serviceName, shownMember } from './members.ts';
|
|
62
|
+
export { judgeProofs, type ProofJudgment } from './proofs.ts';
|
|
63
63
|
export { unreachable, Unreachable } from './reach.ts';
|
|
64
64
|
|
|
65
65
|
export type RouteKey = keyof Api;
|
|
@@ -93,16 +93,13 @@ export class CoffreError extends Error {
|
|
|
93
93
|
readonly code: string;
|
|
94
94
|
/** The vault's own code when it refused: `no_grant`, `removed`, `bulk_limit`, ... */
|
|
95
95
|
readonly reason: string | undefined;
|
|
96
|
-
/** When to ask again, in seconds, when the answer says (`Retry-After`): a 503's, a 429's. */
|
|
97
|
-
readonly retryAfter: string | undefined;
|
|
98
96
|
|
|
99
|
-
constructor(status: number, code: string, message: string, reason?: string
|
|
97
|
+
constructor(status: number, code: string, message: string, reason?: string) {
|
|
100
98
|
super(message);
|
|
101
99
|
this.name = 'CoffreError';
|
|
102
100
|
this.status = status;
|
|
103
101
|
this.code = code;
|
|
104
102
|
this.reason = reason;
|
|
105
|
-
this.retryAfter = retryAfter;
|
|
106
103
|
}
|
|
107
104
|
}
|
|
108
105
|
|
|
@@ -161,7 +158,6 @@ export function createClient(options: ClientOptions) {
|
|
|
161
158
|
typeof error?.error === 'string' ? error.error : 'http_error',
|
|
162
159
|
typeof error?.message === 'string' ? error.message : `request failed with status ${response.status}`,
|
|
163
160
|
typeof error?.reason === 'string' ? error.reason : undefined,
|
|
164
|
-
response.headers.get('retry-after') ?? undefined,
|
|
165
161
|
);
|
|
166
162
|
}
|
|
167
163
|
return payload;
|
|
@@ -269,10 +265,10 @@ export function createClient(options: ClientOptions) {
|
|
|
269
265
|
call('PATCH /secrets/:project/:environment/:key', place(path), patch),
|
|
270
266
|
/**
|
|
271
267
|
* In a fork, a key back to its parent's value (`true`), its own kept,
|
|
272
|
-
* or its own served again (`false`);
|
|
268
|
+
* or its own served again (`false`); the answer says which, `inherit`.
|
|
273
269
|
*/
|
|
274
270
|
inherit: (path: string, inherit: boolean) =>
|
|
275
|
-
call('PATCH /secrets/:project/:environment/:key', place(path), { inherit })
|
|
271
|
+
call('PATCH /secrets/:project/:environment/:key', place(path), { inherit }),
|
|
276
272
|
},
|
|
277
273
|
|
|
278
274
|
/**
|
|
@@ -336,15 +332,15 @@ export function createClient(options: ClientOptions) {
|
|
|
336
332
|
return send(method, `${route}?dryRun=1`, input) as Promise<BindingPlan>;
|
|
337
333
|
},
|
|
338
334
|
create: (member: string, input: RouteInput<'POST /members/:member/bindings'>) =>
|
|
339
|
-
call('POST /members/:member/bindings', { member }, input) as Promise<{ binding:
|
|
340
|
-
/** The service's bindings on an issuer that new keys would replace,
|
|
335
|
+
call('POST /members/:member/bindings', { member }, input) as Promise<Extract<RouteOutput<'POST /members/:member/bindings'>, { binding: unknown }>>,
|
|
336
|
+
/** The service's bindings on an issuer that new keys would replace, the keys as checked, and the places they would withhold; writes nothing. */
|
|
341
337
|
previewKeys: (member: string, input: RouteInput<'POST /members/:member/bindings/keys'>) => {
|
|
342
338
|
const [method, route] = address('POST /members/:member/bindings/keys', { member });
|
|
343
339
|
return send(method, `${route}?dryRun=1`, input) as Promise<KeysPlan>;
|
|
344
340
|
},
|
|
345
341
|
/** New keys, uploaded, for every binding of the service on the issuer: each replaced by one the same but for them. */
|
|
346
342
|
replaceKeys: (member: string, input: RouteInput<'POST /members/:member/bindings/keys'>) =>
|
|
347
|
-
call('POST /members/:member/bindings/keys', { member }, input) as Promise<
|
|
343
|
+
call('POST /members/:member/bindings/keys', { member }, input) as Promise<Extract<RouteOutput<'POST /members/:member/bindings/keys'>, { bindings: unknown }>>,
|
|
348
344
|
remove: (member: string, id: string) => call('DELETE /members/:member/bindings/:id', { member, id }),
|
|
349
345
|
/** A GitHub repository's or GitLab project's IDs, which bindings name: a public one's, or one the deployment's GitHub App is installed on. */
|
|
350
346
|
lookup: (input: RouteInput<'GET /workloads/lookup'>) => call('GET /workloads/lookup', {}, input),
|
|
@@ -352,6 +348,19 @@ export function createClient(options: ClientOptions) {
|
|
|
352
348
|
repositories: () => call('GET /workloads/repositories', {}),
|
|
353
349
|
},
|
|
354
350
|
|
|
351
|
+
/**
|
|
352
|
+
* Freezes: every use under a target refused from its next request, its
|
|
353
|
+
* sessions kept, until lifted. A target is `instance`, `service:<name>`,
|
|
354
|
+
* `binding:<id>` or `session:<id>`.
|
|
355
|
+
*/
|
|
356
|
+
freezes: {
|
|
357
|
+
/** The freezes standing that you may know of: the instance's, and those of the service accounts you manage. */
|
|
358
|
+
list: () => call('GET /freezes', {}),
|
|
359
|
+
freeze: (target: string, reason: string) => call('POST /freezes', {}, { target, reason }),
|
|
360
|
+
/** Lifts it; a target that is not frozen stays so. */
|
|
361
|
+
unfreeze: (target: string) => call('DELETE /freezes/:target', { target }),
|
|
362
|
+
},
|
|
363
|
+
|
|
355
364
|
access: {
|
|
356
365
|
/** What they should hold at each place; the server applies the difference. `null` revokes. */
|
|
357
366
|
set: (member: string, access: RouteInput<'PATCH /access/:member'>) =>
|
|
@@ -463,62 +472,8 @@ export function createClient(options: ClientOptions) {
|
|
|
463
472
|
|
|
464
473
|
audit: {
|
|
465
474
|
list: (query: RouteInput<'GET /audit'> = {}) => call('GET /audit', {}, query),
|
|
466
|
-
/**
|
|
467
|
-
* Whether the log holds, from the newest checkpoint; or, with `from`, a
|
|
468
|
-
* stretch of the walk from the first entry: `start`, then each `next`
|
|
469
|
-
* until it is null (`verifyWhole`).
|
|
470
|
-
*/
|
|
471
|
-
verify: (query: RouteInput<'GET /audit/verification'> = {}) => call('GET /audit/verification', {}, query),
|
|
472
|
-
/**
|
|
473
|
-
* The walk from the first entry to the head, a stretch a request, each
|
|
474
|
-
* as long as the server walks in one: the first stretch that fails, or
|
|
475
|
-
* the last. `onStretch` sees each verdict as it comes.
|
|
476
|
-
*/
|
|
477
|
-
verifyWhole: async (onStretch: (verdict: RouteOutput<'GET /audit/verification'>) => void = () => {}) => {
|
|
478
|
-
for (let from = 'start'; ;) {
|
|
479
|
-
const verdict: RouteOutput<'GET /audit/verification'> = await call('GET /audit/verification', {}, { from });
|
|
480
|
-
onStretch(verdict);
|
|
481
|
-
if (!verdict.ok || verdict.next === undefined || verdict.next === null) return verdict;
|
|
482
|
-
from = verdict.next;
|
|
483
|
-
}
|
|
484
|
-
},
|
|
485
|
-
/**
|
|
486
|
-
* Whether 0.15's log holds (the vault's `verifyTrees`): its newest signed
|
|
487
|
-
* checkpoint and every entry since. `kept` false where the instance
|
|
488
|
-
* keeps 0.14's log alone, a server older than 0.15 (no such route)
|
|
489
|
-
* included.
|
|
490
|
-
*/
|
|
491
|
-
verifyTrees: (): Promise<RouteOutput<'GET /audit/trees'>> =>
|
|
492
|
-
call('GET /audit/trees', {}).catch((error: unknown) => {
|
|
493
|
-
if (error instanceof CoffreError && error.status === 404) return { kept: false as const };
|
|
494
|
-
throw error;
|
|
495
|
-
}),
|
|
496
|
-
/**
|
|
497
|
-
* The reads the audit pages list held to the uses 0.15's log sealed, a
|
|
498
|
-
* stretch a request, from the first to as far as the projector has
|
|
499
|
-
* listed: the first stretch that fails, or the last. `kept` false where
|
|
500
|
-
* the instance keeps 0.14's log alone, a server older than 0.15 (no
|
|
501
|
-
* such route) included.
|
|
502
|
-
*/
|
|
503
|
-
verifyReads: async (onStretch: (verdict: RouteOutput<'GET /audit/reads'>) => void = () => {}): Promise<RouteOutput<'GET /audit/reads'>> => {
|
|
504
|
-
for (let from = 'start'; ;) {
|
|
505
|
-
const verdict: RouteOutput<'GET /audit/reads'> = await call('GET /audit/reads', {}, { from }).catch((error: unknown) => {
|
|
506
|
-
if (error instanceof CoffreError && error.status === 404) return { kept: false as const };
|
|
507
|
-
throw error;
|
|
508
|
-
});
|
|
509
|
-
onStretch(verdict);
|
|
510
|
-
if (!verdict.kept || !verdict.ok || verdict.next === null) return verdict;
|
|
511
|
-
from = verdict.next;
|
|
512
|
-
}
|
|
513
|
-
},
|
|
514
475
|
/** What an escrowed key is checked against: public material, for admins and owners of the whole instance. */
|
|
515
476
|
keys: () => call('GET /audit/keys', {}),
|
|
516
|
-
/**
|
|
517
|
-
* Accept that entries `from` to `to` are lost for good, as an Owner of
|
|
518
|
-
* the whole instance: the audit watch's finding, inside the range, stays
|
|
519
|
-
* in the log, and its anchor goes on past them.
|
|
520
|
-
*/
|
|
521
|
-
acceptLoss: (range: RouteInput<'POST /audit/loss'>) => call('POST /audit/loss', {}, range),
|
|
522
477
|
},
|
|
523
478
|
};
|
|
524
479
|
}
|
package/src/proofs.ts
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
// What a page of `GET /audit` says of its own proofs, judged once for every
|
|
2
|
+
// caller: `coffre verify instance` and conformance each read a page, wait
|
|
3
|
+
// out the signing race and word what they find, and both hold it to this.
|
|
4
|
+
import type { Api, AuditEntryView } from './api.ts';
|
|
5
|
+
|
|
6
|
+
type Page = Api['GET /audit']['output'];
|
|
7
|
+
|
|
8
|
+
export type ProofJudgment = {
|
|
9
|
+
/** The vault's head the page was proven against; none stands before the signer's first batch. */
|
|
10
|
+
head: Page['head'];
|
|
11
|
+
/** Entries the head numbers, which a page waits for: a batch signed between the head's read and the log's can put every one past it. */
|
|
12
|
+
numbered: number;
|
|
13
|
+
proven: number;
|
|
14
|
+
/** Within the head and not what it signed. */
|
|
15
|
+
failed: AuditEntryView[];
|
|
16
|
+
/** Neither failed nor as the head places it: unproven though the head numbers it, or proven past it. The signer signs in order, so the head numbers the log's first `size` entries. */
|
|
17
|
+
misplaced: AuditEntryView[];
|
|
18
|
+
/** What the page's stretch lacks, by the trees' counts: null when it cannot say, on a page that is not of the whole log, or with no head. */
|
|
19
|
+
missing: Page['holes'];
|
|
20
|
+
/**
|
|
21
|
+
* A page to ask again before judging it, as a race between the head's read and the log's can leave it, honestly:
|
|
22
|
+
* a batch signed in between puts every listed entry past the head, and a pruning committed in between leaves the
|
|
23
|
+
* older head counting uses it removed, a stretch lacking aging entries alone. A fresh page past the race says neither.
|
|
24
|
+
*/
|
|
25
|
+
racing: boolean;
|
|
26
|
+
};
|
|
27
|
+
|
|
28
|
+
export function judgeProofs(page: Page): ProofJudgment {
|
|
29
|
+
const { head, entries } = page;
|
|
30
|
+
const within = (entry: AuditEntryView) => head !== null && entry.seq < head.size;
|
|
31
|
+
const numbered = entries.filter(within).length;
|
|
32
|
+
const pruned = page.holes !== null && page.holes.length > 0 && page.holes.every((hole) => hole.kept === 0);
|
|
33
|
+
return {
|
|
34
|
+
head,
|
|
35
|
+
numbered,
|
|
36
|
+
proven: entries.filter((entry) => entry.proof === 'proven').length,
|
|
37
|
+
failed: entries.filter((entry) => entry.proof === 'failed'),
|
|
38
|
+
misplaced: entries.filter((entry) => entry.proof !== 'failed' && within(entry) !== (entry.proof === 'proven')),
|
|
39
|
+
missing: page.holes,
|
|
40
|
+
racing: numbered === 0 || pruned,
|
|
41
|
+
};
|
|
42
|
+
}
|
package/src/routes.ts
CHANGED
|
@@ -55,9 +55,6 @@ export function getCalls({ places, secrets, members, services }: Subjects): GetC
|
|
|
55
55
|
'GET /approvals/:id': [{ params: { id: '00000000-0000-4000-8000-000000000000' } }],
|
|
56
56
|
'GET /apps': [{ params: {} }],
|
|
57
57
|
'GET /audit': [{ params: {}, input: { limit: 500 } }, { params: {}, input: { limit: 500, detail: '1' } }],
|
|
58
|
-
'GET /audit/verification': [{ params: {} }],
|
|
59
|
-
'GET /audit/trees': [{ params: {} }],
|
|
60
|
-
'GET /audit/reads': [{ params: {}, input: { from: 'start' } }],
|
|
61
58
|
'GET /audit/keys': [{ params: {} }],
|
|
62
59
|
};
|
|
63
60
|
}
|
|
@@ -141,11 +138,7 @@ const EVERY_ROUTE: { [K in RouteKey]: true } = {
|
|
|
141
138
|
'GET /apps': true,
|
|
142
139
|
'DELETE /apps/:id': true,
|
|
143
140
|
'GET /audit': true,
|
|
144
|
-
'GET /audit/verification': true,
|
|
145
|
-
'GET /audit/trees': true,
|
|
146
|
-
'GET /audit/reads': true,
|
|
147
141
|
'GET /audit/keys': true,
|
|
148
|
-
'POST /audit/loss': true,
|
|
149
142
|
};
|
|
150
143
|
|
|
151
144
|
/**
|
package/src/workload-postgres.ts
CHANGED
|
@@ -1,15 +1,13 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Postgres from a workload, through coffre's tunnel (docs/design/workload-access.md,
|
|
3
|
-
* section 9.1): a stream
|
|
4
|
-
*
|
|
3
|
+
* section 9.1): a stream node-postgres takes as its socket, carried over the
|
|
4
|
+
* tunnel's WebSocket and signed by the session. No listener, no password,
|
|
5
5
|
* and no database URL in the app: coffre logs in to the database.
|
|
6
6
|
*
|
|
7
|
-
* import
|
|
7
|
+
* import pg from 'pg';
|
|
8
8
|
* import { connect } from '@coffre/client/workload/postgres';
|
|
9
9
|
*
|
|
10
|
-
* const
|
|
11
|
-
*
|
|
12
|
-
* node-postgres takes it as its stream: `new pg.Pool({ stream: () => connect(coffre, 'db') })`.
|
|
10
|
+
* const pool = new pg.Pool({ stream: () => connect(coffre, 'db') });
|
|
13
11
|
*
|
|
14
12
|
* The WebSocket is the runtime's own (`globalThis.WebSocket`: Node 22 and
|
|
15
13
|
* later, Deno, Bun), which takes the upgrade's headers; on Node 20, pass the
|
|
@@ -61,7 +59,7 @@ const FRAME = 64 * 1024;
|
|
|
61
59
|
const KEEPALIVE_MS = 30_000;
|
|
62
60
|
|
|
63
61
|
/**
|
|
64
|
-
* A stream to the database behind the tunnel `name`, which
|
|
62
|
+
* A stream to the database behind the tunnel `name`, which node-postgres
|
|
65
63
|
* connects, writes and ends as it would a socket.
|
|
66
64
|
*/
|
|
67
65
|
export function connect(coffre: Workload, name: string, options: { WebSocket?: WebSocketClass } = {}): TunnelStream {
|
package/src/workload-proofs.ts
CHANGED
|
@@ -53,6 +53,8 @@ export interface Proof {
|
|
|
53
53
|
* has it.
|
|
54
54
|
*/
|
|
55
55
|
spent?(context: ProofContext): Promise<boolean>;
|
|
56
|
+
/** After the exchange took the proof (200): one whose platform's tokens are each taken once sends it no more. */
|
|
57
|
+
accepted?(): void;
|
|
56
58
|
}
|
|
57
59
|
|
|
58
60
|
/** `<audience>#jkt=<thumbprint>`: an audience only this key can use (section 4.2). */
|
|
@@ -82,17 +84,21 @@ export const KUBERNETES_TOKEN = '/var/run/secrets/coffre/token';
|
|
|
82
84
|
/**
|
|
83
85
|
* A Kubernetes projected service account token, read from its file before
|
|
84
86
|
* each exchange: the pod spec's `serviceAccountToken` with coffre's URL as
|
|
85
|
-
* its `audience`. Such a token is spent once
|
|
86
|
-
* the token
|
|
87
|
-
* waits for the kubelet's next, which it writes at 80% of
|
|
88
|
-
* watching the file for up to 10 minutes. That is the
|
|
89
|
-
* long-running pod (the session re-proves at 90% of its
|
|
90
|
-
* kubelet's next volume sync can land after that), and so is
|
|
91
|
-
* case: a restarted process finds the token an earlier one used,
|
|
92
|
-
* exchange says (`replayed`), and `spent()` waits the same way.
|
|
87
|
+
* its `audience`. Such a token is spent once coffre took it, so a file
|
|
88
|
+
* still holding the token coffre took last (`accepted()`) is never sent
|
|
89
|
+
* again: the proof waits for the kubelet's next, which it writes at 80% of
|
|
90
|
+
* the token's life, watching the file for up to 10 minutes. That is the
|
|
91
|
+
* normal renewal in a long-running pod (the session re-proves at 90% of its
|
|
92
|
+
* life, and the kubelet's next volume sync can land after that), and so is
|
|
93
|
+
* the other case: a restarted process finds the token an earlier one used,
|
|
94
|
+
* which the exchange says (`replayed`), and `spent()` waits the same way.
|
|
95
|
+
* A token coffre did not take (503 while its database is out, a network
|
|
96
|
+
* failure) is not spent: the next try sends it again.
|
|
93
97
|
*/
|
|
94
98
|
export function kubernetes(path: string = KUBERNETES_TOKEN): Proof {
|
|
95
99
|
/** The token this process sent last. */
|
|
100
|
+
let sent: string | null = null;
|
|
101
|
+
/** The last token coffre took, or said was spent: never sent again. */
|
|
96
102
|
let last: string | null = null;
|
|
97
103
|
const read = async () => (await (await import('node:fs/promises')).readFile(path, 'utf8')).trim();
|
|
98
104
|
/** The file's next token once it differs from `last`, polled every second, or null after 10 minutes. */
|
|
@@ -115,9 +121,13 @@ export function kubernetes(path: string = KUBERNETES_TOKEN): Proof {
|
|
|
115
121
|
});
|
|
116
122
|
const fresh = token === last || token === '' ? await next(context) : token;
|
|
117
123
|
if (fresh === null) throw new Error(`the kubelet wrote no new token at ${path} in 10 minutes: check the projected volume and its expirationSeconds`);
|
|
118
|
-
return { oidc: (
|
|
124
|
+
return { oidc: (sent = fresh) };
|
|
125
|
+
},
|
|
126
|
+
accepted: () => void (last = sent),
|
|
127
|
+
spent: async (context) => {
|
|
128
|
+
last = sent;
|
|
129
|
+
return (await next(context)) !== null;
|
|
119
130
|
},
|
|
120
|
-
spent: async (context) => (await next(context)) !== null,
|
|
121
131
|
};
|
|
122
132
|
}
|
|
123
133
|
|
|
@@ -365,7 +375,7 @@ export function oidc(token: string | (() => string | Promise<string>), name = 'o
|
|
|
365
375
|
* longer show it; the platform's store still holds it.
|
|
366
376
|
*/
|
|
367
377
|
export function enrollment(code: string | undefined): Proof {
|
|
368
|
-
if (code === undefined || !code.startsWith('coffre_enr_')) throw new Error('enrollment(): no enrollment code:
|
|
378
|
+
if (code === undefined || !code.startsWith('coffre_enr_')) throw new Error('enrollment(): no enrollment code: no release issues one yet (docs/workloads.md)');
|
|
369
379
|
const vars = (globalThis as { process?: { env: Env } }).process?.env;
|
|
370
380
|
for (const [name, value] of Object.entries(vars ?? {})) if (value === code) delete vars![name];
|
|
371
381
|
return { name: 'enrollment', kind: 'enrollment', prove: async () => ({ enrollment: code }) };
|
package/src/workload.ts
CHANGED
|
@@ -19,8 +19,7 @@
|
|
|
19
19
|
* or its session awaits approval (10), and after a spent projected token,
|
|
20
20
|
* once the kubelet writes the next;
|
|
21
21
|
* - renewal at half-life, every 30 seconds for an enrollment session, whose
|
|
22
|
-
* expiry is its liveness
|
|
23
|
-
* (a projected token's), which only a new proof outlives; a fresh proof, with the same key, before the
|
|
22
|
+
* expiry is its liveness; a fresh proof, with the same key, before the
|
|
24
23
|
* session's hard end, `notAfter`; and a new session whenever the old one
|
|
25
24
|
* is lost (revoked, frozen, expired while the process slept);
|
|
26
25
|
* - each request under `<url>/use/` signed whole (method, URL, query, the
|
|
@@ -28,7 +27,10 @@
|
|
|
28
27
|
* once if the gate asks for a fresh one;
|
|
29
28
|
* - logout on `close()`, and on SIGTERM.
|
|
30
29
|
*/
|
|
31
|
-
import
|
|
30
|
+
import type { Sealed } from './credential.ts';
|
|
31
|
+
|
|
32
|
+
export type { Sealed };
|
|
33
|
+
import { base64url, bodyDigest, bodyLine, contentDigest, createProof, declaredDigest, fromBase64url, generateProofKey, JSON_MESSAGE_BYTES, thumbprint, type ProofKey, type PublicJwk } from './dpop.ts';
|
|
32
34
|
import { CoffreError } from './index.ts';
|
|
33
35
|
import type { Proof, ProofContext } from './workload-proofs.ts';
|
|
34
36
|
|
|
@@ -95,10 +97,17 @@ export interface Workload {
|
|
|
95
97
|
export interface UsedCredential {
|
|
96
98
|
/** `<credential's URL>/<path>`, signed: the proxy forwards it to the upstream with the real key. */
|
|
97
99
|
fetch(path: string, init?: RequestInit): Promise<Response>;
|
|
98
|
-
/**
|
|
100
|
+
/**
|
|
101
|
+
* A signature by a signer's key, which stays in coffre: a private key's base64url, an HMAC secret's as its `hmac()` writes it.
|
|
102
|
+
* A message past 1 MiB goes raw, its bytes as the body, signed as they come and never held: an `hmac()` signer's whose `maxBytes` takes it.
|
|
103
|
+
*/
|
|
99
104
|
sign(message: string | Uint8Array): Promise<string>;
|
|
100
105
|
/** Whether `signature`, as its header carried it, is a verifier's HMAC of `message`, an inbound webhook's body as it came: checked without reading its secret. */
|
|
101
106
|
verify(message: string | Uint8Array, signature: string): Promise<boolean>;
|
|
107
|
+
/** `plaintext` encrypted with a cipher's AES-256-GCM key, which stays in coffre, under `aad` if given and an IV coffre draws. */
|
|
108
|
+
encrypt(plaintext: string | Uint8Array, aad?: string | Uint8Array): Promise<Sealed>;
|
|
109
|
+
/** The plaintext `sealed` holds under the cipher's key and `aad`, or null when it does not decrypt. */
|
|
110
|
+
decrypt(sealed: Sealed, aad?: string | Uint8Array): Promise<Uint8Array | null>;
|
|
102
111
|
/** A presigned GET or HEAD of `path` under an AWS-signed credential's upstream: the upstream's own URL, for anyone until `expiresAt`. */
|
|
103
112
|
presign(path: string, options?: { expiresIn?: number; method?: 'GET' | 'HEAD'; query?: Record<string, string> }): Promise<{ url: string; expiresAt: string }>;
|
|
104
113
|
/** A short-lived child of a minter (an AWS session, a GitHub installation token), where the binding lists it. */
|
|
@@ -191,6 +200,7 @@ export async function workload(options: WorkloadOptions): Promise<Workload> {
|
|
|
191
200
|
const body = (await response.json().catch(() => null)) as Record<string, unknown> | null;
|
|
192
201
|
const [expiresAt, notAfter] = [Date.parse(String(body?.expiresAt)), Date.parse(String(body?.notAfter))];
|
|
193
202
|
if (response.status === 200 && typeof body?.token === 'string' && Number.isFinite(expiresAt) && Number.isFinite(notAfter)) {
|
|
203
|
+
options.proof.accepted?.();
|
|
194
204
|
const places = Array.isArray(body.places) ? body.places.filter((place): place is string => typeof place === 'string') : [];
|
|
195
205
|
return { token: body.token, expiresAt, notAfter, places, issuedAt: Date.now() };
|
|
196
206
|
}
|
|
@@ -242,16 +252,10 @@ export async function workload(options: WorkloadOptions): Promise<Workload> {
|
|
|
242
252
|
(timers[which] as { unref?: () => void }).unref?.();
|
|
243
253
|
};
|
|
244
254
|
|
|
245
|
-
/** Renew at half-life, or every 30 seconds for an enrollment
|
|
246
|
-
const
|
|
247
|
-
if (held.expiresAt >= held.notAfter) return clearTimeout(timers.renew);
|
|
255
|
+
/** Renew at half-life, or every 30 seconds for an enrollment; prove again at 90% of the way to `notAfter`. */
|
|
256
|
+
const plan = (held: Session) => {
|
|
248
257
|
const now = Date.now();
|
|
249
258
|
at('renew', enrolled ? now + ENROLLMENT_RENEW_MS : now + Math.max(1000, (held.expiresAt - now) / 2), renew);
|
|
250
|
-
};
|
|
251
|
-
|
|
252
|
-
/** Renew as `planRenewal` says; prove again at 90% of the way to `notAfter`. */
|
|
253
|
-
const plan = (held: Session) => {
|
|
254
|
-
planRenewal(held);
|
|
255
259
|
// An enrollment's `notAfter` is its code's end, which no new proof passes. A projected token's next is written at 80% of its life.
|
|
256
260
|
if (!enrolled) at('prove', held.notAfter - (held.notAfter - held.issuedAt) / 10, () => prove().catch(() => undefined));
|
|
257
261
|
};
|
|
@@ -300,7 +304,7 @@ export async function workload(options: WorkloadOptions): Promise<Workload> {
|
|
|
300
304
|
const { response, body } = await api('/api/auth/workload/renew', held.token);
|
|
301
305
|
if (response.ok && typeof body?.expiresAt === 'string') {
|
|
302
306
|
held.expiresAt = Date.parse(body.expiresAt);
|
|
303
|
-
if (session === held)
|
|
307
|
+
if (session === held) at('renew', enrolled ? Date.now() + ENROLLMENT_RENEW_MS : Date.now() + Math.max(1000, (held.expiresAt - Date.now()) / 2), renew);
|
|
304
308
|
return;
|
|
305
309
|
}
|
|
306
310
|
// Asked for a nonce once more, it says nothing of the session: tried again soon, as when coffre is out of reach.
|
|
@@ -498,8 +502,9 @@ function surface(core: Core): Workload {
|
|
|
498
502
|
const url = (name: string) => (core.places().length === 1 ? `${origin}/use/${encodeURIComponent(name)}` : `${placeUrl()}/${encodeURIComponent(name)}`);
|
|
499
503
|
|
|
500
504
|
/** What coffre makes with the environment's values, at the environment's URL: a signature, a verdict, a presigned URL, a minted child. */
|
|
501
|
-
const compute =
|
|
502
|
-
|
|
505
|
+
const compute = (asked: Record<string, unknown>, what: string) => computed(placeUrl(), { 'content-type': 'application/json' }, JSON.stringify(asked), what);
|
|
506
|
+
const computed = async (at: string, headers: Record<string, string>, sent: BodyInit, what: string): Promise<Record<string, unknown>> => {
|
|
507
|
+
const response = await signed(at, { method: 'POST', headers: { ...headers, accept: 'application/json' }, body: sent });
|
|
503
508
|
const body = (await response.json().catch(() => null)) as Record<string, unknown> | null;
|
|
504
509
|
if (!response.ok || body === null) throw refusal(response.status, body, `coffre ${what} nothing`);
|
|
505
510
|
return body;
|
|
@@ -522,11 +527,29 @@ function surface(core: Core): Workload {
|
|
|
522
527
|
return signed(target.href, init);
|
|
523
528
|
},
|
|
524
529
|
sign: async (message) => {
|
|
525
|
-
const
|
|
530
|
+
const bytes = typeof message === 'string' ? new TextEncoder().encode(message) : message;
|
|
531
|
+
// Past what JSON takes, raw: its bytes as the body, which the proof binds by the Content-Digest `signed` declares.
|
|
532
|
+
const body = await (bytes.length > JSON_MESSAGE_BYTES
|
|
533
|
+
? computed(`${placeUrl()}?sign=${encodeURIComponent(name)}`, { 'content-type': 'application/octet-stream' }, bytes as Uint8Array<ArrayBuffer>, 'signed')
|
|
534
|
+
: compute({ sign: { credential: name, message: bytesOf(bytes) } }, 'signed'));
|
|
526
535
|
if (typeof body.signature !== 'string') throw new Error('coffre signed nothing');
|
|
527
536
|
return body.signature;
|
|
528
537
|
},
|
|
529
538
|
verify: async (message, signature) => (await compute({ verify: { credential: name, message: bytesOf(message), signature } }, 'verified')).valid === true,
|
|
539
|
+
encrypt: async (plaintext, aad) => {
|
|
540
|
+
const body = await compute({ encrypt: { credential: name, plaintext: bytesOf(plaintext), ...(aad === undefined ? {} : { aad: bytesOf(aad) }) } }, 'encrypted');
|
|
541
|
+
const [iv, ciphertext, tag] = [body.iv, body.ciphertext, body.tag].map((part) => (typeof part === 'string' ? fromBase64url(part) : null));
|
|
542
|
+
if (!iv || !ciphertext || !tag) throw new Error('coffre encrypted nothing');
|
|
543
|
+
return { iv, ciphertext, tag };
|
|
544
|
+
},
|
|
545
|
+
decrypt: async ({ iv, ciphertext, tag }, aad) => {
|
|
546
|
+
const body = await compute({ decrypt: { credential: name, iv: bytesOf(iv), ciphertext: bytesOf(ciphertext), tag: bytesOf(tag), ...(aad === undefined ? {} : { aad: bytesOf(aad) }) } }, 'decrypted');
|
|
547
|
+
if (body.plaintext !== null && typeof body.plaintext !== 'string') throw new Error('coffre decrypted nothing');
|
|
548
|
+
if (body.plaintext === null) return null;
|
|
549
|
+
const plaintext = fromBase64url(body.plaintext);
|
|
550
|
+
if (plaintext === null) throw new Error('coffre decrypted nothing: its answer is no base64url');
|
|
551
|
+
return plaintext;
|
|
552
|
+
},
|
|
530
553
|
presign: async (path, options = {}) => {
|
|
531
554
|
const body = await compute({ presign: { credential: name, path, ...options } }, 'presigned');
|
|
532
555
|
if (typeof body.url !== 'string' || typeof body.expiresAt !== 'string') throw new Error('coffre presigned nothing');
|
package/src/audit.ts
DELETED
|
@@ -1,16 +0,0 @@
|
|
|
1
|
-
/** How the audit log's entries are said, to people: by the pages and the CLI alike. */
|
|
2
|
-
|
|
3
|
-
/**
|
|
4
|
-
* The CI run an entry was written for, as its issuer stated it at the
|
|
5
|
-
* exchange: `acme/api run 7001 at 3f2a9c1`, a GitLab pipeline, or the
|
|
6
|
-
* token's subject. Null for an entry no trust binding's credential wrote.
|
|
7
|
-
*/
|
|
8
|
-
export function runLabel(run: { claims: Record<string, string | number> } | null): string | null {
|
|
9
|
-
if (run === null) return null;
|
|
10
|
-
const { claims } = run;
|
|
11
|
-
const text = (name: string) => (typeof claims[name] === 'string' || typeof claims[name] === 'number' ? String(claims[name]) : null);
|
|
12
|
-
const at = text('sha') === null ? '' : ` at ${text('sha')!.slice(0, 7)}`;
|
|
13
|
-
if (text('repository') !== null && text('run_id') !== null) return `${text('repository')} run ${text('run_id')}${at}`;
|
|
14
|
-
if (text('project_path') !== null && text('pipeline_id') !== null) return `${text('project_path')} pipeline ${text('pipeline_id')}${at}`;
|
|
15
|
-
return text('sub') === null ? 'a CI run' : `CI run ${text('sub')}`;
|
|
16
|
-
}
|