@coffre/client 0.10.2 → 0.11.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.
@@ -0,0 +1,365 @@
1
+ /**
2
+ * How a workload proves who it is, once per session (docs/design/workload-access.md,
3
+ * section 4): each platform's own proof, asked for afresh at each exchange,
4
+ * and bound to the session's key wherever the platform lets the caller say
5
+ * so. `workload({ proof })` takes one of these:
6
+ *
7
+ * kubernetes() the projected service account token, read from its file
8
+ * aws() a GetCallerIdentity signed with the role's own credentials
9
+ * gcp() the metadata server's ID token, its audience naming the key
10
+ * azure({ audience }) the managed identity's token for coffre's Entra application
11
+ * fly() the machine's OIDC token, its audience naming the key
12
+ * vercel() the function's OIDC token, exchanged for one naming the key
13
+ * github() the Actions runner's ID token, its audience naming the key
14
+ * oidc(token) any other ID token: GitLab's `id_tokens`, a custom issuer's
15
+ * enrollment(code) a code CI minted for this deploy, on a platform that signs nothing
16
+ *
17
+ * A proof reads only its platform's own variables and endpoints (AWS's,
18
+ * GitHub's runner's, Azure's identity endpoint), never one of coffre's, and
19
+ * nothing here writes anything anywhere. No dependency: `fetch`, WebCrypto,
20
+ * and Node's `fs` and `http` loaded only by the proofs that read a file or
21
+ * a socket.
22
+ */
23
+
24
+ /** What the exchange is sent as `proof`: an ID token, a signed `GetCallerIdentity`, or an enrollment code. */
25
+ export type PlatformProof = { oidc: string } | { aws: { url: string; headers: Record<string, string>; body: string } } | { enrollment: string };
26
+
27
+ type Fetch = (input: string, init?: RequestInit) => Promise<Response>;
28
+
29
+ /** What a proof is given at each exchange: the instance and the key to name, and how to reach its platform. */
30
+ export type ProofContext = {
31
+ /** The instance's URL as its audience: `https://secrets.acme.example`. */
32
+ audience: string;
33
+ /** The session key's thumbprint, which a key-naming audience carries: `<audience>#jkt=<jkt>`. */
34
+ jkt: string;
35
+ fetch: Fetch;
36
+ /** Where the SDK says what it waits for: stderr unless the app said otherwise. */
37
+ log: (line: string) => void;
38
+ /** Aborted when the session closes: a proof that waits (a spent token's next) stops waiting, and one that asks a socket (Fly's) stops asking. `fetch` ends with it already. */
39
+ signal?: AbortSignal;
40
+ };
41
+
42
+ export interface Proof {
43
+ /** Which platform, as messages name it. */
44
+ readonly name: string;
45
+ /** An enrollment session's expiry is its liveness: it renews every 30 seconds, and can never re-prove past its code's end. */
46
+ readonly kind: 'oidc' | 'aws' | 'enrollment';
47
+ /** A fresh proof, for this key at this instance. */
48
+ prove(context: ProofContext): Promise<PlatformProof>;
49
+ /**
50
+ * After the exchange said the proof was spent (`replayed`): wait until a
51
+ * fresh one exists, as the kubelet writes a projected token's next, and
52
+ * say whether one does. Only a proof whose platform hands out new ones
53
+ * has it.
54
+ */
55
+ spent?(context: ProofContext): Promise<boolean>;
56
+ }
57
+
58
+ /** `<audience>#jkt=<thumbprint>`: an audience only this key can use (section 4.2). */
59
+ export function keyAudience(context: ProofContext): string {
60
+ return `${context.audience}#jkt=${context.jkt}`;
61
+ }
62
+
63
+ type Env = Record<string, string | undefined>;
64
+ const env = (): Env => (globalThis as { process?: { env: Env } }).process?.env ?? {};
65
+
66
+ async function json(response: Response, what: string): Promise<Record<string, unknown>> {
67
+ const body = (await response.json().catch(() => null)) as Record<string, unknown> | null;
68
+ if (!response.ok || body === null || typeof body !== 'object') throw new Error(`${what} answered ${response.status}`);
69
+ return body;
70
+ }
71
+
72
+ /** The token a platform answered, or why not. */
73
+ function tokenOf(body: Record<string, unknown>, field: string, what: string): string {
74
+ const token = body[field];
75
+ if (typeof token !== 'string' || token === '') throw new Error(`${what} gave no token`);
76
+ return token;
77
+ }
78
+
79
+ /** The default projected token's path, as docs/workloads.md mounts it. */
80
+ export const KUBERNETES_TOKEN = '/var/run/secrets/coffre/token';
81
+
82
+ /**
83
+ * A Kubernetes projected service account token, read from its file before
84
+ * each exchange: the pod spec's `serviceAccountToken` with coffre's URL as
85
+ * its `audience`. Such a token is spent once used. If the exchange finds it
86
+ * spent (a restarted process reading the file again), this waits for the
87
+ * kubelet's next, which it writes at 80% of the token's life, watching the
88
+ * file for up to 10 minutes.
89
+ */
90
+ export function kubernetes(path: string = KUBERNETES_TOKEN): Proof {
91
+ let last: string | null = null;
92
+ const read = async () => (await (await import('node:fs/promises')).readFile(path, 'utf8')).trim();
93
+ return {
94
+ name: 'kubernetes',
95
+ kind: 'oidc',
96
+ prove: async () => {
97
+ last = await read().catch((error: Error & { code?: string }) => {
98
+ throw new Error(`no projected service account token at ${path} (${error.code ?? error.message}): mount one whose audience is coffre's URL`);
99
+ });
100
+ return { oidc: last };
101
+ },
102
+ spent: async ({ log, signal }) => {
103
+ log(`coffre: the projected token at ${path} was spent already, by an earlier start; waiting for the kubelet to write its next, up to 10 minutes`);
104
+ for (const end = Date.now() + 10 * 60_000; Date.now() < end; ) {
105
+ await sleep(1000);
106
+ signal?.throwIfAborted();
107
+ const now = await read().catch(() => last);
108
+ if (now !== last) return true;
109
+ }
110
+ return false;
111
+ },
112
+ };
113
+ }
114
+
115
+ /** AWS credentials, as the AWS SDK's providers give them. */
116
+ export type AwsCredentials = { accessKeyId: string; secretAccessKey: string; sessionToken?: string };
117
+
118
+ /** A region as STS's regional hosts name one, in the commercial partition: the exchange takes no other. */
119
+ const REGION = /^[a-z]{2}(-[a-z]+)+-\d$/;
120
+
121
+ /**
122
+ * A `GetCallerIdentity` request, signed with the workload's own role
123
+ * credentials, for coffre to send STS (section 4.3). The credentials never
124
+ * leave: coffre gets the URL, the headers and the body, and the signature
125
+ * covers `x-coffre-key`, so the proof works with this session's key only.
126
+ *
127
+ * The credentials are the given ones, an AWS SDK provider's
128
+ * (`aws({ credentials: fromNodeProviderChain() })`), or else, in order, the
129
+ * environment's, the ECS container endpoint's, or EC2's instance metadata
130
+ * (IMDSv2). The region is `AWS_REGION`'s, for its regional STS host, unless
131
+ * given; without one, the global host.
132
+ */
133
+ export function aws(options: { credentials?: AwsCredentials | (() => Promise<AwsCredentials>); region?: string } = {}): Proof {
134
+ return {
135
+ name: 'aws',
136
+ kind: 'aws',
137
+ prove: async (context) => {
138
+ const given = options.credentials;
139
+ const credentials = given === undefined ? await awsCredentials(context.fetch) : typeof given === 'function' ? await given() : given;
140
+ const region = options.region ?? env().AWS_REGION ?? env().AWS_DEFAULT_REGION;
141
+ if (region !== undefined && (!REGION.test(region) || region.includes('-gov-'))) throw new Error(`aws(): ${region} is no commercial AWS region`);
142
+ const url = region === undefined ? 'https://sts.amazonaws.com/' : `https://sts.${region}.amazonaws.com/`;
143
+ const body = 'Action=GetCallerIdentity&Version=2011-06-15';
144
+ const headers: Record<string, string> = {
145
+ 'content-type': 'application/x-www-form-urlencoded; charset=utf-8',
146
+ host: new URL(url).host,
147
+ 'x-amz-date': amzDate(new Date()),
148
+ 'x-coffre-audience': context.audience,
149
+ 'x-coffre-key': context.jkt,
150
+ };
151
+ if (credentials.sessionToken) headers['x-amz-security-token'] = credentials.sessionToken;
152
+ headers.authorization = await sigv4({ method: 'POST', url, headers, body, region: region ?? 'us-east-1', service: 'sts', credentials });
153
+ return { aws: { url, headers, body } };
154
+ },
155
+ };
156
+ }
157
+
158
+ /** The environment's, the ECS container endpoint's, or IMDSv2's role credentials, as the AWS SDK's default chain finds them. */
159
+ async function awsCredentials(fetchImpl: Fetch): Promise<AwsCredentials> {
160
+ const vars = env();
161
+ if (vars.AWS_ACCESS_KEY_ID && vars.AWS_SECRET_ACCESS_KEY) {
162
+ return { accessKeyId: vars.AWS_ACCESS_KEY_ID, secretAccessKey: vars.AWS_SECRET_ACCESS_KEY, sessionToken: vars.AWS_SESSION_TOKEN || undefined };
163
+ }
164
+ const container = vars.AWS_CONTAINER_CREDENTIALS_FULL_URI ?? (vars.AWS_CONTAINER_CREDENTIALS_RELATIVE_URI ? `http://169.254.170.2${vars.AWS_CONTAINER_CREDENTIALS_RELATIVE_URI}` : undefined);
165
+ if (container !== undefined) {
166
+ // As the AWS SDKs allow: https, or this machine, or the ECS and EKS agents' own addresses.
167
+ const at = new URL(container);
168
+ if (at.protocol !== 'https:' && !/^(127(\.\d{1,3}){3}|localhost|\[::1\]|169\.254\.170\.(2|23)|\[fd00:ec2::23\])$/.test(at.hostname)) {
169
+ throw new Error(`aws(): AWS_CONTAINER_CREDENTIALS_FULL_URI names ${at.host}, which is neither https nor this machine nor the container agent's`);
170
+ }
171
+ const file = vars.AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE;
172
+ const authorization = file ? (await (await import('node:fs/promises')).readFile(file, 'utf8')).trim() : vars.AWS_CONTAINER_AUTHORIZATION_TOKEN;
173
+ const body = await json(await fetchImpl(container, { headers: authorization ? { authorization } : {} }), 'the ECS credentials endpoint');
174
+ return { accessKeyId: tokenOf(body, 'AccessKeyId', 'ECS'), secretAccessKey: tokenOf(body, 'SecretAccessKey', 'ECS'), sessionToken: body.Token as string | undefined };
175
+ }
176
+ const imds = 'http://169.254.169.254/latest';
177
+ const session = await fetchImpl(`${imds}/api/token`, { method: 'PUT', headers: { 'x-aws-ec2-metadata-token-ttl-seconds': '300' }, signal: AbortSignal.timeout(2000) }).catch(() => null);
178
+ if (session === null || !session.ok) {
179
+ throw new Error('aws(): no role credentials here: none in the environment, no ECS credentials endpoint, and no EC2 instance metadata');
180
+ }
181
+ const headers = { 'x-aws-ec2-metadata-token': await session.text() };
182
+ const role = (await (await fetchImpl(`${imds}/meta-data/iam/security-credentials/`, { headers })).text()).trim().split('\n')[0];
183
+ if (!role) throw new Error('aws(): this instance has no instance profile: give it a role');
184
+ const body = await json(await fetchImpl(`${imds}/meta-data/iam/security-credentials/${role}`, { headers }), 'EC2 instance metadata');
185
+ return { accessKeyId: tokenOf(body, 'AccessKeyId', 'IMDS'), secretAccessKey: tokenOf(body, 'SecretAccessKey', 'IMDS'), sessionToken: body.Token as string | undefined };
186
+ }
187
+
188
+ /** `20261024T013000Z`, SigV4's time. */
189
+ function amzDate(date: Date): string {
190
+ return date.toISOString().replace(/[-:]/g, '').replace(/\.\d{3}/, '');
191
+ }
192
+
193
+ const ENCODER = new TextEncoder();
194
+
195
+ async function hmac(key: Uint8Array, data: string): Promise<Uint8Array> {
196
+ const imported = await crypto.subtle.importKey('raw', key as Uint8Array<ArrayBuffer>, { name: 'HMAC', hash: 'SHA-256' }, false, ['sign']);
197
+ return new Uint8Array(await crypto.subtle.sign('HMAC', imported, ENCODER.encode(data)));
198
+ }
199
+
200
+ async function sha256Hex(data: string): Promise<string> {
201
+ return hex(new Uint8Array(await crypto.subtle.digest('SHA-256', ENCODER.encode(data))));
202
+ }
203
+
204
+ function hex(bytes: Uint8Array): string {
205
+ return Array.from(bytes, (byte) => byte.toString(16).padStart(2, '0')).join('');
206
+ }
207
+
208
+ /** RFC 3986's encoding, as SigV4 writes a query: everything but the unreserved characters escaped. */
209
+ const awsEncode = (text: string) => encodeURIComponent(text).replace(/[!'()*]/g, (char) => `%${char.charCodeAt(0).toString(16).toUpperCase()}`);
210
+
211
+ /**
212
+ * The `authorization` header AWS Signature Version 4 gives a request, every
213
+ * header given signed (`host` and `x-amz-date` among them). Exported for its
214
+ * test, against AWS's own documented example.
215
+ */
216
+ export async function sigv4(request: {
217
+ method: string;
218
+ url: string;
219
+ headers: Record<string, string>;
220
+ body: string;
221
+ region: string;
222
+ service: string;
223
+ credentials: AwsCredentials;
224
+ }): Promise<string> {
225
+ const url = new URL(request.url);
226
+ const names = Object.keys(request.headers).map((name) => name.toLowerCase()).sort();
227
+ const value = (name: string) => Object.entries(request.headers).find(([given]) => given.toLowerCase() === name)![1].trim().replace(/\s+/g, ' ');
228
+ const query = [...url.searchParams].map(([name, v]) => `${awsEncode(name)}=${awsEncode(v)}`).sort().join('&');
229
+ const canonical = [request.method, url.pathname, query, ...names.map((name) => `${name}:${value(name)}`), '', names.join(';'), await sha256Hex(request.body)].join('\n');
230
+ const time = value('x-amz-date');
231
+ const scope = `${time.slice(0, 8)}/${request.region}/${request.service}/aws4_request`;
232
+ const toSign = ['AWS4-HMAC-SHA256', time, scope, await sha256Hex(canonical)].join('\n');
233
+ let key: Uint8Array = ENCODER.encode(`AWS4${request.credentials.secretAccessKey}`);
234
+ for (const part of [time.slice(0, 8), request.region, request.service, 'aws4_request']) key = await hmac(key, part);
235
+ return `AWS4-HMAC-SHA256 Credential=${request.credentials.accessKeyId}/${scope}, SignedHeaders=${names.join(';')}, Signature=${hex(await hmac(key, toSign))}`;
236
+ }
237
+
238
+ /** Google Cloud's metadata server's ID token for the default service account, its audience naming the key: Cloud Run, GKE, GCE. */
239
+ export function gcp(): Proof {
240
+ return {
241
+ name: 'gcp',
242
+ kind: 'oidc',
243
+ prove: async (context) => {
244
+ const url = new URL('http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/identity');
245
+ url.searchParams.set('audience', keyAudience(context));
246
+ url.searchParams.set('format', 'full');
247
+ const response = await context.fetch(url.href, { headers: { 'metadata-flavor': 'Google' } });
248
+ if (!response.ok) throw new Error(`Google's metadata server gave no ID token (status ${response.status})`);
249
+ return { oidc: (await response.text()).trim() };
250
+ },
251
+ };
252
+ }
253
+
254
+ /**
255
+ * An Azure managed identity's token for coffre's Entra application, its
256
+ * `audience` (`api://coffre-acme`): from App Service's and Functions'
257
+ * identity endpoint, or else IMDS. `clientId` picks a user-assigned
258
+ * identity. Entra mints only for a registered audience, so the token cannot
259
+ * name the key, and repeats until it expires (section 4.2).
260
+ */
261
+ export function azure(options: { audience: string; clientId?: string }): Proof {
262
+ return {
263
+ name: 'azure',
264
+ kind: 'oidc',
265
+ prove: async ({ fetch: fetchImpl }) => {
266
+ const vars = env();
267
+ const service = vars.IDENTITY_ENDPOINT && vars.IDENTITY_HEADER;
268
+ const url = new URL(service ? vars.IDENTITY_ENDPOINT! : 'http://169.254.169.254/metadata/identity/oauth2/token');
269
+ url.searchParams.set('api-version', service ? '2019-08-01' : '2018-02-01');
270
+ url.searchParams.set('resource', options.audience);
271
+ if (options.clientId !== undefined) url.searchParams.set('client_id', options.clientId);
272
+ const headers: Record<string, string> = service ? { 'x-identity-header': vars.IDENTITY_HEADER! } : { metadata: 'true' };
273
+ return { oidc: tokenOf(await json(await fetchImpl(url.href, { headers }), 'Azure\'s identity endpoint'), 'access_token', 'Azure') };
274
+ },
275
+ };
276
+ }
277
+
278
+ /** A Fly Machine's OIDC token, from its `/.fly/api` socket, its audience naming the key. */
279
+ export function fly(socketPath = '/.fly/api'): Proof {
280
+ return {
281
+ name: 'fly',
282
+ kind: 'oidc',
283
+ prove: async (context) => {
284
+ const { request } = await import('node:http');
285
+ const body = JSON.stringify({ aud: keyAudience(context) });
286
+ const token = await new Promise<string>((resolve, reject) => {
287
+ const asked = request({ socketPath, path: '/v1/tokens/oidc', method: 'POST', signal: context.signal, headers: { 'content-type': 'application/json', 'content-length': ENCODER.encode(body).length } }, (answer) => {
288
+ let text = '';
289
+ answer.setEncoding('utf8');
290
+ answer.on('data', (chunk: string) => (text += chunk));
291
+ answer.on('end', () => (answer.statusCode === 200 ? resolve(text.trim()) : reject(new Error(`Fly's API gave no OIDC token (status ${answer.statusCode})`))));
292
+ });
293
+ asked.on('error', (error) => reject(new Error(`no Fly API at ${socketPath}: ${error.message}`)));
294
+ asked.end(body);
295
+ });
296
+ return { oidc: token };
297
+ },
298
+ };
299
+ }
300
+
301
+ /**
302
+ * A Vercel function's OIDC token, exchanged at Vercel for one whose audience
303
+ * names the key, as `@vercel/oidc` does, asked afresh for each proof. The
304
+ * function's own token is the file `VERCEL_OIDC_TOKEN_FILE` names, or else
305
+ * `VERCEL_OIDC_TOKEN`, unless given: per request, from the
306
+ * `x-vercel-oidc-token` header, as `vercel(() => headers.get(…))`.
307
+ */
308
+ export function vercel(token?: string | (() => string | Promise<string>)): Proof {
309
+ return {
310
+ name: 'vercel',
311
+ kind: 'oidc',
312
+ prove: async (context) => {
313
+ const file = env().VERCEL_OIDC_TOKEN_FILE;
314
+ const own = typeof token === 'function' ? await token() : (token ?? (file ? (await (await import('node:fs/promises')).readFile(file, 'utf8')).trim() : env().VERCEL_OIDC_TOKEN));
315
+ if (!own) throw new Error('vercel(): no OIDC token: turn on OIDC federation for the project, or pass the request\'s x-vercel-oidc-token');
316
+ const response = await context.fetch('https://oidc.vercel.com/~token', {
317
+ method: 'POST',
318
+ headers: { 'content-type': 'application/json', accept: 'application/json' },
319
+ body: JSON.stringify({ token: own, aud: keyAudience(context) }),
320
+ });
321
+ return { oidc: tokenOf(await json(response, 'Vercel\'s token exchange'), 'token', 'Vercel') };
322
+ },
323
+ };
324
+ }
325
+
326
+ /** A GitHub Actions job's ID token, from its runner, its audience naming the key: the job needs `permissions: id-token: write`. */
327
+ export function github(): Proof {
328
+ return {
329
+ name: 'github',
330
+ kind: 'oidc',
331
+ prove: async (context) => {
332
+ const vars = env();
333
+ const [url, bearer] = [vars.ACTIONS_ID_TOKEN_REQUEST_URL?.trim(), vars.ACTIONS_ID_TOKEN_REQUEST_TOKEN?.trim()];
334
+ if (!url || !bearer) throw new Error('github(): this job has no ID token: give it `permissions: id-token: write`');
335
+ const request = new URL(url);
336
+ request.searchParams.set('audience', keyAudience(context));
337
+ const response = await context.fetch(request.href, { headers: { authorization: `bearer ${bearer}`, accept: 'application/json' } });
338
+ return { oidc: tokenOf(await json(response, 'GitHub\'s runner'), 'value', 'GitHub') };
339
+ },
340
+ };
341
+ }
342
+
343
+ /**
344
+ * Any other ID token, as given, or asked for at each exchange: GitLab's
345
+ * `id_tokens` entry, whose `aud` is coffre's URL, or a custom issuer's. A
346
+ * token is spent once used, so a given string proves one session.
347
+ */
348
+ export function oidc(token: string | (() => string | Promise<string>), name = 'oidc'): Proof {
349
+ return { name, kind: 'oidc', prove: async () => ({ oidc: typeof token === 'function' ? await token() : token }) };
350
+ }
351
+
352
+ /**
353
+ * An enrollment code (section 4.4), on a platform that signs nothing:
354
+ * Railway, Render, a VM. Once given, the code leaves `process.env`, under
355
+ * whatever name held it, so the app's own dumps of its environment no
356
+ * longer show it; the platform's store still holds it.
357
+ */
358
+ export function enrollment(code: string | undefined): Proof {
359
+ if (code === undefined || !code.startsWith('coffre_enr_')) throw new Error('enrollment(): no enrollment code: CI sets one each deploy, from `coffre enroll <service>`');
360
+ const vars = (globalThis as { process?: { env: Env } }).process?.env;
361
+ for (const [name, value] of Object.entries(vars ?? {})) if (value === code) delete vars![name];
362
+ return { name: 'enrollment', kind: 'enrollment', prove: async () => ({ enrollment: code }) };
363
+ }
364
+
365
+ const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));