@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.
- package/dist/dpop-C5Zyaixy.d.ts +183 -0
- package/dist/dpop.d.ts +2 -0
- package/dist/dpop.js +290 -0
- package/dist/{index-D86fJBDd.d.ts → index--nfmYCFv.d.ts} +222 -13
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -485
- package/dist/routes.d.ts +1 -1
- package/dist/routes.js +13 -0
- package/dist/src-CDyZe9vW.js +490 -0
- package/dist/workload-9LPBYMmN.d.ts +250 -0
- package/dist/workload-postgres.d.ts +54 -0
- package/dist/workload-postgres.js +210 -0
- package/dist/workload-w4QPSyjj.js +1018 -0
- package/dist/workload.d.ts +3 -0
- package/dist/workload.js +3 -0
- package/package.json +16 -1
- package/src/api.ts +178 -10
- package/src/dpop.ts +301 -0
- package/src/index.ts +3 -1
- package/src/routes.ts +10 -0
- package/src/workload-postgres.ts +254 -0
- package/src/workload-proofs.ts +365 -0
- package/src/workload.ts +711 -0
|
@@ -0,0 +1,1018 @@
|
|
|
1
|
+
import { t as CoffreError } from "./src-CDyZe9vW.js";
|
|
2
|
+
import { base64url, bodyDigest, bodyLine, createProof, generateProofKey, thumbprint } from "./dpop.js";
|
|
3
|
+
//#region src/workload-proofs.ts
|
|
4
|
+
/** `<audience>#jkt=<thumbprint>`: an audience only this key can use (section 4.2). */
|
|
5
|
+
function keyAudience(context) {
|
|
6
|
+
return `${context.audience}#jkt=${context.jkt}`;
|
|
7
|
+
}
|
|
8
|
+
const env = () => globalThis.process?.env ?? {};
|
|
9
|
+
async function json(response, what) {
|
|
10
|
+
const body = await response.json().catch(() => null);
|
|
11
|
+
if (!response.ok || body === null || typeof body !== "object") throw new Error(`${what} answered ${response.status}`);
|
|
12
|
+
return body;
|
|
13
|
+
}
|
|
14
|
+
/** The token a platform answered, or why not. */
|
|
15
|
+
function tokenOf(body, field, what) {
|
|
16
|
+
const token = body[field];
|
|
17
|
+
if (typeof token !== "string" || token === "") throw new Error(`${what} gave no token`);
|
|
18
|
+
return token;
|
|
19
|
+
}
|
|
20
|
+
/** The default projected token's path, as docs/workloads.md mounts it. */
|
|
21
|
+
const KUBERNETES_TOKEN = "/var/run/secrets/coffre/token";
|
|
22
|
+
/**
|
|
23
|
+
* A Kubernetes projected service account token, read from its file before
|
|
24
|
+
* each exchange: the pod spec's `serviceAccountToken` with coffre's URL as
|
|
25
|
+
* its `audience`. Such a token is spent once used. If the exchange finds it
|
|
26
|
+
* spent (a restarted process reading the file again), this waits for the
|
|
27
|
+
* kubelet's next, which it writes at 80% of the token's life, watching the
|
|
28
|
+
* file for up to 10 minutes.
|
|
29
|
+
*/
|
|
30
|
+
function kubernetes(path = KUBERNETES_TOKEN) {
|
|
31
|
+
let last = null;
|
|
32
|
+
const read = async () => (await (await import("node:fs/promises")).readFile(path, "utf8")).trim();
|
|
33
|
+
return {
|
|
34
|
+
name: "kubernetes",
|
|
35
|
+
kind: "oidc",
|
|
36
|
+
prove: async () => {
|
|
37
|
+
last = await read().catch((error) => {
|
|
38
|
+
throw new Error(`no projected service account token at ${path} (${error.code ?? error.message}): mount one whose audience is coffre's URL`);
|
|
39
|
+
});
|
|
40
|
+
return { oidc: last };
|
|
41
|
+
},
|
|
42
|
+
spent: async ({ log, signal }) => {
|
|
43
|
+
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`);
|
|
44
|
+
for (const end = Date.now() + 6e5; Date.now() < end;) {
|
|
45
|
+
await sleep$1(1e3);
|
|
46
|
+
signal?.throwIfAborted();
|
|
47
|
+
if (await read().catch(() => last) !== last) return true;
|
|
48
|
+
}
|
|
49
|
+
return false;
|
|
50
|
+
}
|
|
51
|
+
};
|
|
52
|
+
}
|
|
53
|
+
/** A region as STS's regional hosts name one, in the commercial partition: the exchange takes no other. */
|
|
54
|
+
const REGION = /^[a-z]{2}(-[a-z]+)+-\d$/;
|
|
55
|
+
/**
|
|
56
|
+
* A `GetCallerIdentity` request, signed with the workload's own role
|
|
57
|
+
* credentials, for coffre to send STS (section 4.3). The credentials never
|
|
58
|
+
* leave: coffre gets the URL, the headers and the body, and the signature
|
|
59
|
+
* covers `x-coffre-key`, so the proof works with this session's key only.
|
|
60
|
+
*
|
|
61
|
+
* The credentials are the given ones, an AWS SDK provider's
|
|
62
|
+
* (`aws({ credentials: fromNodeProviderChain() })`), or else, in order, the
|
|
63
|
+
* environment's, the ECS container endpoint's, or EC2's instance metadata
|
|
64
|
+
* (IMDSv2). The region is `AWS_REGION`'s, for its regional STS host, unless
|
|
65
|
+
* given; without one, the global host.
|
|
66
|
+
*/
|
|
67
|
+
function aws(options = {}) {
|
|
68
|
+
return {
|
|
69
|
+
name: "aws",
|
|
70
|
+
kind: "aws",
|
|
71
|
+
prove: async (context) => {
|
|
72
|
+
const given = options.credentials;
|
|
73
|
+
const credentials = given === void 0 ? await awsCredentials(context.fetch) : typeof given === "function" ? await given() : given;
|
|
74
|
+
const region = options.region ?? env().AWS_REGION ?? env().AWS_DEFAULT_REGION;
|
|
75
|
+
if (region !== void 0 && (!REGION.test(region) || region.includes("-gov-"))) throw new Error(`aws(): ${region} is no commercial AWS region`);
|
|
76
|
+
const url = region === void 0 ? "https://sts.amazonaws.com/" : `https://sts.${region}.amazonaws.com/`;
|
|
77
|
+
const body = "Action=GetCallerIdentity&Version=2011-06-15";
|
|
78
|
+
const headers = {
|
|
79
|
+
"content-type": "application/x-www-form-urlencoded; charset=utf-8",
|
|
80
|
+
host: new URL(url).host,
|
|
81
|
+
"x-amz-date": amzDate(/* @__PURE__ */ new Date()),
|
|
82
|
+
"x-coffre-audience": context.audience,
|
|
83
|
+
"x-coffre-key": context.jkt
|
|
84
|
+
};
|
|
85
|
+
if (credentials.sessionToken) headers["x-amz-security-token"] = credentials.sessionToken;
|
|
86
|
+
headers.authorization = await sigv4({
|
|
87
|
+
method: "POST",
|
|
88
|
+
url,
|
|
89
|
+
headers,
|
|
90
|
+
body,
|
|
91
|
+
region: region ?? "us-east-1",
|
|
92
|
+
service: "sts",
|
|
93
|
+
credentials
|
|
94
|
+
});
|
|
95
|
+
return { aws: {
|
|
96
|
+
url,
|
|
97
|
+
headers,
|
|
98
|
+
body
|
|
99
|
+
} };
|
|
100
|
+
}
|
|
101
|
+
};
|
|
102
|
+
}
|
|
103
|
+
/** The environment's, the ECS container endpoint's, or IMDSv2's role credentials, as the AWS SDK's default chain finds them. */
|
|
104
|
+
async function awsCredentials(fetchImpl) {
|
|
105
|
+
const vars = env();
|
|
106
|
+
if (vars.AWS_ACCESS_KEY_ID && vars.AWS_SECRET_ACCESS_KEY) return {
|
|
107
|
+
accessKeyId: vars.AWS_ACCESS_KEY_ID,
|
|
108
|
+
secretAccessKey: vars.AWS_SECRET_ACCESS_KEY,
|
|
109
|
+
sessionToken: vars.AWS_SESSION_TOKEN || void 0
|
|
110
|
+
};
|
|
111
|
+
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}` : void 0);
|
|
112
|
+
if (container !== void 0) {
|
|
113
|
+
const at = new URL(container);
|
|
114
|
+
if (at.protocol !== "https:" && !/^(127(\.\d{1,3}){3}|localhost|\[::1\]|169\.254\.170\.(2|23)|\[fd00:ec2::23\])$/.test(at.hostname)) throw new Error(`aws(): AWS_CONTAINER_CREDENTIALS_FULL_URI names ${at.host}, which is neither https nor this machine nor the container agent's`);
|
|
115
|
+
const file = vars.AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE;
|
|
116
|
+
const authorization = file ? (await (await import("node:fs/promises")).readFile(file, "utf8")).trim() : vars.AWS_CONTAINER_AUTHORIZATION_TOKEN;
|
|
117
|
+
const body = await json(await fetchImpl(container, { headers: authorization ? { authorization } : {} }), "the ECS credentials endpoint");
|
|
118
|
+
return {
|
|
119
|
+
accessKeyId: tokenOf(body, "AccessKeyId", "ECS"),
|
|
120
|
+
secretAccessKey: tokenOf(body, "SecretAccessKey", "ECS"),
|
|
121
|
+
sessionToken: body.Token
|
|
122
|
+
};
|
|
123
|
+
}
|
|
124
|
+
const imds = "http://169.254.169.254/latest";
|
|
125
|
+
const session = await fetchImpl(`${imds}/api/token`, {
|
|
126
|
+
method: "PUT",
|
|
127
|
+
headers: { "x-aws-ec2-metadata-token-ttl-seconds": "300" },
|
|
128
|
+
signal: AbortSignal.timeout(2e3)
|
|
129
|
+
}).catch(() => null);
|
|
130
|
+
if (session === null || !session.ok) throw new Error("aws(): no role credentials here: none in the environment, no ECS credentials endpoint, and no EC2 instance metadata");
|
|
131
|
+
const headers = { "x-aws-ec2-metadata-token": await session.text() };
|
|
132
|
+
const role = (await (await fetchImpl(`${imds}/meta-data/iam/security-credentials/`, { headers })).text()).trim().split("\n")[0];
|
|
133
|
+
if (!role) throw new Error("aws(): this instance has no instance profile: give it a role");
|
|
134
|
+
const body = await json(await fetchImpl(`${imds}/meta-data/iam/security-credentials/${role}`, { headers }), "EC2 instance metadata");
|
|
135
|
+
return {
|
|
136
|
+
accessKeyId: tokenOf(body, "AccessKeyId", "IMDS"),
|
|
137
|
+
secretAccessKey: tokenOf(body, "SecretAccessKey", "IMDS"),
|
|
138
|
+
sessionToken: body.Token
|
|
139
|
+
};
|
|
140
|
+
}
|
|
141
|
+
/** `20261024T013000Z`, SigV4's time. */
|
|
142
|
+
function amzDate(date) {
|
|
143
|
+
return date.toISOString().replace(/[-:]/g, "").replace(/\.\d{3}/, "");
|
|
144
|
+
}
|
|
145
|
+
const ENCODER = new TextEncoder();
|
|
146
|
+
async function hmac(key, data) {
|
|
147
|
+
const imported = await crypto.subtle.importKey("raw", key, {
|
|
148
|
+
name: "HMAC",
|
|
149
|
+
hash: "SHA-256"
|
|
150
|
+
}, false, ["sign"]);
|
|
151
|
+
return new Uint8Array(await crypto.subtle.sign("HMAC", imported, ENCODER.encode(data)));
|
|
152
|
+
}
|
|
153
|
+
async function sha256Hex(data) {
|
|
154
|
+
return hex(new Uint8Array(await crypto.subtle.digest("SHA-256", ENCODER.encode(data))));
|
|
155
|
+
}
|
|
156
|
+
function hex(bytes) {
|
|
157
|
+
return Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");
|
|
158
|
+
}
|
|
159
|
+
/** RFC 3986's encoding, as SigV4 writes a query: everything but the unreserved characters escaped. */
|
|
160
|
+
const awsEncode = (text) => encodeURIComponent(text).replace(/[!'()*]/g, (char) => `%${char.charCodeAt(0).toString(16).toUpperCase()}`);
|
|
161
|
+
/**
|
|
162
|
+
* The `authorization` header AWS Signature Version 4 gives a request, every
|
|
163
|
+
* header given signed (`host` and `x-amz-date` among them). Exported for its
|
|
164
|
+
* test, against AWS's own documented example.
|
|
165
|
+
*/
|
|
166
|
+
async function sigv4(request) {
|
|
167
|
+
const url = new URL(request.url);
|
|
168
|
+
const names = Object.keys(request.headers).map((name) => name.toLowerCase()).sort();
|
|
169
|
+
const value = (name) => Object.entries(request.headers).find(([given]) => given.toLowerCase() === name)[1].trim().replace(/\s+/g, " ");
|
|
170
|
+
const query = [...url.searchParams].map(([name, v]) => `${awsEncode(name)}=${awsEncode(v)}`).sort().join("&");
|
|
171
|
+
const canonical = [
|
|
172
|
+
request.method,
|
|
173
|
+
url.pathname,
|
|
174
|
+
query,
|
|
175
|
+
...names.map((name) => `${name}:${value(name)}`),
|
|
176
|
+
"",
|
|
177
|
+
names.join(";"),
|
|
178
|
+
await sha256Hex(request.body)
|
|
179
|
+
].join("\n");
|
|
180
|
+
const time = value("x-amz-date");
|
|
181
|
+
const scope = `${time.slice(0, 8)}/${request.region}/${request.service}/aws4_request`;
|
|
182
|
+
const toSign = [
|
|
183
|
+
"AWS4-HMAC-SHA256",
|
|
184
|
+
time,
|
|
185
|
+
scope,
|
|
186
|
+
await sha256Hex(canonical)
|
|
187
|
+
].join("\n");
|
|
188
|
+
let key = ENCODER.encode(`AWS4${request.credentials.secretAccessKey}`);
|
|
189
|
+
for (const part of [
|
|
190
|
+
time.slice(0, 8),
|
|
191
|
+
request.region,
|
|
192
|
+
request.service,
|
|
193
|
+
"aws4_request"
|
|
194
|
+
]) key = await hmac(key, part);
|
|
195
|
+
return `AWS4-HMAC-SHA256 Credential=${request.credentials.accessKeyId}/${scope}, SignedHeaders=${names.join(";")}, Signature=${hex(await hmac(key, toSign))}`;
|
|
196
|
+
}
|
|
197
|
+
/** Google Cloud's metadata server's ID token for the default service account, its audience naming the key: Cloud Run, GKE, GCE. */
|
|
198
|
+
function gcp() {
|
|
199
|
+
return {
|
|
200
|
+
name: "gcp",
|
|
201
|
+
kind: "oidc",
|
|
202
|
+
prove: async (context) => {
|
|
203
|
+
const url = new URL("http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/identity");
|
|
204
|
+
url.searchParams.set("audience", keyAudience(context));
|
|
205
|
+
url.searchParams.set("format", "full");
|
|
206
|
+
const response = await context.fetch(url.href, { headers: { "metadata-flavor": "Google" } });
|
|
207
|
+
if (!response.ok) throw new Error(`Google's metadata server gave no ID token (status ${response.status})`);
|
|
208
|
+
return { oidc: (await response.text()).trim() };
|
|
209
|
+
}
|
|
210
|
+
};
|
|
211
|
+
}
|
|
212
|
+
/**
|
|
213
|
+
* An Azure managed identity's token for coffre's Entra application, its
|
|
214
|
+
* `audience` (`api://coffre-acme`): from App Service's and Functions'
|
|
215
|
+
* identity endpoint, or else IMDS. `clientId` picks a user-assigned
|
|
216
|
+
* identity. Entra mints only for a registered audience, so the token cannot
|
|
217
|
+
* name the key, and repeats until it expires (section 4.2).
|
|
218
|
+
*/
|
|
219
|
+
function azure(options) {
|
|
220
|
+
return {
|
|
221
|
+
name: "azure",
|
|
222
|
+
kind: "oidc",
|
|
223
|
+
prove: async ({ fetch: fetchImpl }) => {
|
|
224
|
+
const vars = env();
|
|
225
|
+
const service = vars.IDENTITY_ENDPOINT && vars.IDENTITY_HEADER;
|
|
226
|
+
const url = new URL(service ? vars.IDENTITY_ENDPOINT : "http://169.254.169.254/metadata/identity/oauth2/token");
|
|
227
|
+
url.searchParams.set("api-version", service ? "2019-08-01" : "2018-02-01");
|
|
228
|
+
url.searchParams.set("resource", options.audience);
|
|
229
|
+
if (options.clientId !== void 0) url.searchParams.set("client_id", options.clientId);
|
|
230
|
+
const headers = service ? { "x-identity-header": vars.IDENTITY_HEADER } : { metadata: "true" };
|
|
231
|
+
return { oidc: tokenOf(await json(await fetchImpl(url.href, { headers }), "Azure's identity endpoint"), "access_token", "Azure") };
|
|
232
|
+
}
|
|
233
|
+
};
|
|
234
|
+
}
|
|
235
|
+
/** A Fly Machine's OIDC token, from its `/.fly/api` socket, its audience naming the key. */
|
|
236
|
+
function fly(socketPath = "/.fly/api") {
|
|
237
|
+
return {
|
|
238
|
+
name: "fly",
|
|
239
|
+
kind: "oidc",
|
|
240
|
+
prove: async (context) => {
|
|
241
|
+
const { request } = await import("node:http");
|
|
242
|
+
const body = JSON.stringify({ aud: keyAudience(context) });
|
|
243
|
+
return { oidc: await new Promise((resolve, reject) => {
|
|
244
|
+
const asked = request({
|
|
245
|
+
socketPath,
|
|
246
|
+
path: "/v1/tokens/oidc",
|
|
247
|
+
method: "POST",
|
|
248
|
+
signal: context.signal,
|
|
249
|
+
headers: {
|
|
250
|
+
"content-type": "application/json",
|
|
251
|
+
"content-length": ENCODER.encode(body).length
|
|
252
|
+
}
|
|
253
|
+
}, (answer) => {
|
|
254
|
+
let text = "";
|
|
255
|
+
answer.setEncoding("utf8");
|
|
256
|
+
answer.on("data", (chunk) => text += chunk);
|
|
257
|
+
answer.on("end", () => answer.statusCode === 200 ? resolve(text.trim()) : reject(/* @__PURE__ */ new Error(`Fly's API gave no OIDC token (status ${answer.statusCode})`)));
|
|
258
|
+
});
|
|
259
|
+
asked.on("error", (error) => reject(/* @__PURE__ */ new Error(`no Fly API at ${socketPath}: ${error.message}`)));
|
|
260
|
+
asked.end(body);
|
|
261
|
+
}) };
|
|
262
|
+
}
|
|
263
|
+
};
|
|
264
|
+
}
|
|
265
|
+
/**
|
|
266
|
+
* A Vercel function's OIDC token, exchanged at Vercel for one whose audience
|
|
267
|
+
* names the key, as `@vercel/oidc` does, asked afresh for each proof. The
|
|
268
|
+
* function's own token is the file `VERCEL_OIDC_TOKEN_FILE` names, or else
|
|
269
|
+
* `VERCEL_OIDC_TOKEN`, unless given: per request, from the
|
|
270
|
+
* `x-vercel-oidc-token` header, as `vercel(() => headers.get(…))`.
|
|
271
|
+
*/
|
|
272
|
+
function vercel(token) {
|
|
273
|
+
return {
|
|
274
|
+
name: "vercel",
|
|
275
|
+
kind: "oidc",
|
|
276
|
+
prove: async (context) => {
|
|
277
|
+
const file = env().VERCEL_OIDC_TOKEN_FILE;
|
|
278
|
+
const own = typeof token === "function" ? await token() : token ?? (file ? (await (await import("node:fs/promises")).readFile(file, "utf8")).trim() : env().VERCEL_OIDC_TOKEN);
|
|
279
|
+
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");
|
|
280
|
+
return { oidc: tokenOf(await json(await context.fetch("https://oidc.vercel.com/~token", {
|
|
281
|
+
method: "POST",
|
|
282
|
+
headers: {
|
|
283
|
+
"content-type": "application/json",
|
|
284
|
+
accept: "application/json"
|
|
285
|
+
},
|
|
286
|
+
body: JSON.stringify({
|
|
287
|
+
token: own,
|
|
288
|
+
aud: keyAudience(context)
|
|
289
|
+
})
|
|
290
|
+
}), "Vercel's token exchange"), "token", "Vercel") };
|
|
291
|
+
}
|
|
292
|
+
};
|
|
293
|
+
}
|
|
294
|
+
/** A GitHub Actions job's ID token, from its runner, its audience naming the key: the job needs `permissions: id-token: write`. */
|
|
295
|
+
function github() {
|
|
296
|
+
return {
|
|
297
|
+
name: "github",
|
|
298
|
+
kind: "oidc",
|
|
299
|
+
prove: async (context) => {
|
|
300
|
+
const vars = env();
|
|
301
|
+
const [url, bearer] = [vars.ACTIONS_ID_TOKEN_REQUEST_URL?.trim(), vars.ACTIONS_ID_TOKEN_REQUEST_TOKEN?.trim()];
|
|
302
|
+
if (!url || !bearer) throw new Error("github(): this job has no ID token: give it `permissions: id-token: write`");
|
|
303
|
+
const request = new URL(url);
|
|
304
|
+
request.searchParams.set("audience", keyAudience(context));
|
|
305
|
+
return { oidc: tokenOf(await json(await context.fetch(request.href, { headers: {
|
|
306
|
+
authorization: `bearer ${bearer}`,
|
|
307
|
+
accept: "application/json"
|
|
308
|
+
} }), "GitHub's runner"), "value", "GitHub") };
|
|
309
|
+
}
|
|
310
|
+
};
|
|
311
|
+
}
|
|
312
|
+
/**
|
|
313
|
+
* Any other ID token, as given, or asked for at each exchange: GitLab's
|
|
314
|
+
* `id_tokens` entry, whose `aud` is coffre's URL, or a custom issuer's. A
|
|
315
|
+
* token is spent once used, so a given string proves one session.
|
|
316
|
+
*/
|
|
317
|
+
function oidc(token, name = "oidc") {
|
|
318
|
+
return {
|
|
319
|
+
name,
|
|
320
|
+
kind: "oidc",
|
|
321
|
+
prove: async () => ({ oidc: typeof token === "function" ? await token() : token })
|
|
322
|
+
};
|
|
323
|
+
}
|
|
324
|
+
/**
|
|
325
|
+
* An enrollment code (section 4.4), on a platform that signs nothing:
|
|
326
|
+
* Railway, Render, a VM. Once given, the code leaves `process.env`, under
|
|
327
|
+
* whatever name held it, so the app's own dumps of its environment no
|
|
328
|
+
* longer show it; the platform's store still holds it.
|
|
329
|
+
*/
|
|
330
|
+
function enrollment(code) {
|
|
331
|
+
if (code === void 0 || !code.startsWith("coffre_enr_")) throw new Error("enrollment(): no enrollment code: CI sets one each deploy, from `coffre enroll <service>`");
|
|
332
|
+
const vars = globalThis.process?.env;
|
|
333
|
+
for (const [name, value] of Object.entries(vars ?? {})) if (value === code) delete vars[name];
|
|
334
|
+
return {
|
|
335
|
+
name: "enrollment",
|
|
336
|
+
kind: "enrollment",
|
|
337
|
+
prove: async () => ({ enrollment: code })
|
|
338
|
+
};
|
|
339
|
+
}
|
|
340
|
+
const sleep$1 = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
341
|
+
//#endregion
|
|
342
|
+
//#region src/workload.ts
|
|
343
|
+
/**
|
|
344
|
+
* A workload's session with coffre (docs/design/workload-access.md, section
|
|
345
|
+
* 9.1): it proves who it is once, gets a session bound to a key that never
|
|
346
|
+
* leaves this process, and from then on uses its credentials through coffre,
|
|
347
|
+
* every request signed. The app holds no secret that works anywhere else.
|
|
348
|
+
*
|
|
349
|
+
* import { workload, enrollment } from '@coffre/client/workload';
|
|
350
|
+
*
|
|
351
|
+
* const coffre = await workload({ url: 'https://secrets.acme.example', service: 'api-prod', proof: enrollment(process.env.COFFRE_ENROLL) });
|
|
352
|
+
* const openai = new OpenAI({ apiKey: 'coffre', baseURL: coffre.url('openai'), fetch: coffre.fetch });
|
|
353
|
+
* const charge = await coffre.credential('stripe').fetch('/v1/charges', { method: 'POST', body: new URLSearchParams({ amount: '2000' }) });
|
|
354
|
+
*
|
|
355
|
+
* What it does for the app, so the app does nothing:
|
|
356
|
+
*
|
|
357
|
+
* - a P-256 key made here, non-extractable; the key, the session's token
|
|
358
|
+
* and the gate's nonce live in this closure only, never on disk or in
|
|
359
|
+
* the environment;
|
|
360
|
+
* - the exchange, retried while an enrollment code is `full` (5 minutes)
|
|
361
|
+
* or its session awaits approval (10), and after a spent projected token,
|
|
362
|
+
* once the kubelet writes the next;
|
|
363
|
+
* - renewal at half-life, every 30 seconds for an enrollment session, whose
|
|
364
|
+
* expiry is its liveness; a fresh proof, with the same key, before the
|
|
365
|
+
* session's hard end, `notAfter`; and a new session whenever the old one
|
|
366
|
+
* is lost (revoked, frozen, expired while the process slept);
|
|
367
|
+
* - each request under `<url>/use/` signed whole (method, URL, query, the
|
|
368
|
+
* headers it was given, the body), with the newest nonce, and sent again
|
|
369
|
+
* once if the gate asks for a fresh one;
|
|
370
|
+
* - logout on `close()`, and on SIGTERM.
|
|
371
|
+
*/
|
|
372
|
+
const dispatch = (nonces) => ({
|
|
373
|
+
seq: ++nonces.sent,
|
|
374
|
+
at: Date.now()
|
|
375
|
+
});
|
|
376
|
+
/** How long a nonce is taken as fresh, for a request that cannot be sent again (a stream, a WebSocket's upgrade): under the 2 minutes it lasts. */
|
|
377
|
+
const FRESH_NONCE_MS = 1e5;
|
|
378
|
+
/** How long the exchange waits out a full enrollment code, and a session awaiting approval. */
|
|
379
|
+
const FULL_MS = 3e5;
|
|
380
|
+
const PENDING_MS = 6e5;
|
|
381
|
+
/** An enrollment session renews every 30 seconds: its expiry, 90 seconds past its last renewal, is its liveness. */
|
|
382
|
+
const ENROLLMENT_RENEW_MS = 3e4;
|
|
383
|
+
/** Refusals no new proof can change: the code was superseded by a newer deploy's. */
|
|
384
|
+
const FINAL = /* @__PURE__ */ new Set(["superseded"]);
|
|
385
|
+
/** How long a logout may take: a process stopping waits no longer for it. */
|
|
386
|
+
const LOGOUT_MS = 3e3;
|
|
387
|
+
/** The redirects fetch follows, and how many it follows at most. */
|
|
388
|
+
const REDIRECTS = /* @__PURE__ */ new Set([
|
|
389
|
+
301,
|
|
390
|
+
302,
|
|
391
|
+
303,
|
|
392
|
+
307,
|
|
393
|
+
308
|
|
394
|
+
]);
|
|
395
|
+
const MOST_REDIRECTS = 20;
|
|
396
|
+
/** Each session's SIGTERM handler: a process whose every handler is one of these ends on SIGTERM once they have logged out. */
|
|
397
|
+
const TERMINATING = /* @__PURE__ */ new WeakSet();
|
|
398
|
+
/** What `upgradeHeaders` and `upgradeRefused` reach, for each workload: its own, never on the object. */
|
|
399
|
+
const UPGRADES = /* @__PURE__ */ new WeakMap();
|
|
400
|
+
/**
|
|
401
|
+
* Sign in as `service`, with `proof`, and hold the session for as long as
|
|
402
|
+
* the process runs. Rejects if the first exchange is refused.
|
|
403
|
+
*/
|
|
404
|
+
async function workload(options) {
|
|
405
|
+
const url = new URL(options.url);
|
|
406
|
+
if (url.protocol !== "https:" && !(url.protocol === "http:" && /^(localhost|127(\.\d{1,3}){3}|\[::1\])$/.test(url.hostname))) throw new TypeError(`workload() talks to coffre over https, or http on this machine: not ${url.origin}`);
|
|
407
|
+
const origin = url.origin;
|
|
408
|
+
const base = options.fetch ?? ((input, init) => fetch(input, init));
|
|
409
|
+
const log = options.log ?? ((line) => console.error(line));
|
|
410
|
+
const key = await generateProofKey();
|
|
411
|
+
/** Aborted by `close()`: an exchange, its waits and its proof's stop with it. */
|
|
412
|
+
const lifetime = new AbortController();
|
|
413
|
+
const proofFetch = (input, init = {}) => base(input, {
|
|
414
|
+
...init,
|
|
415
|
+
signal: init.signal ? anySignal([init.signal, lifetime.signal]) : lifetime.signal
|
|
416
|
+
});
|
|
417
|
+
const context = {
|
|
418
|
+
audience: origin,
|
|
419
|
+
jkt: await thumbprint(key.jwk),
|
|
420
|
+
fetch: proofFetch,
|
|
421
|
+
log,
|
|
422
|
+
signal: lifetime.signal
|
|
423
|
+
};
|
|
424
|
+
const nonces = {
|
|
425
|
+
value: void 0,
|
|
426
|
+
at: 0,
|
|
427
|
+
seq: 0,
|
|
428
|
+
sent: 0
|
|
429
|
+
};
|
|
430
|
+
const enrolled = options.proof.kind === "enrollment";
|
|
431
|
+
const api = apiOf({
|
|
432
|
+
origin,
|
|
433
|
+
base,
|
|
434
|
+
key,
|
|
435
|
+
nonces
|
|
436
|
+
});
|
|
437
|
+
/** Trade a fresh proof for a session, waiting out what the design says to wait out; throws a refusal, with the server's words. */
|
|
438
|
+
const exchange = async () => {
|
|
439
|
+
const start = Date.now();
|
|
440
|
+
const said = /* @__PURE__ */ new Set();
|
|
441
|
+
const say = (line) => void (said.has(line) || (said.add(line), log(line)));
|
|
442
|
+
for (;;) {
|
|
443
|
+
lifetime.signal.throwIfAborted();
|
|
444
|
+
const proof = await options.proof.prove(context);
|
|
445
|
+
const url = `${origin}/api/auth/workload`;
|
|
446
|
+
const sent = dispatch(nonces);
|
|
447
|
+
const response = await base(url, {
|
|
448
|
+
method: "POST",
|
|
449
|
+
headers: {
|
|
450
|
+
"content-type": "application/json",
|
|
451
|
+
accept: "application/json",
|
|
452
|
+
dpop: await createProof(key, {
|
|
453
|
+
method: "POST",
|
|
454
|
+
url
|
|
455
|
+
})
|
|
456
|
+
},
|
|
457
|
+
body: JSON.stringify({
|
|
458
|
+
service: options.service,
|
|
459
|
+
proof
|
|
460
|
+
}),
|
|
461
|
+
signal: lifetime.signal,
|
|
462
|
+
redirect: "error"
|
|
463
|
+
});
|
|
464
|
+
note(nonces, response, sent);
|
|
465
|
+
const body = await response.json().catch(() => null);
|
|
466
|
+
const [expiresAt, notAfter] = [Date.parse(String(body?.expiresAt)), Date.parse(String(body?.notAfter))];
|
|
467
|
+
if (response.status === 200 && typeof body?.token === "string" && Number.isFinite(expiresAt) && Number.isFinite(notAfter)) {
|
|
468
|
+
const places = Array.isArray(body.places) ? body.places.filter((place) => typeof place === "string") : [];
|
|
469
|
+
return {
|
|
470
|
+
token: body.token,
|
|
471
|
+
expiresAt,
|
|
472
|
+
notAfter,
|
|
473
|
+
places,
|
|
474
|
+
issuedAt: Date.now()
|
|
475
|
+
};
|
|
476
|
+
}
|
|
477
|
+
const reason = typeof body?.reason === "string" ? body.reason : void 0;
|
|
478
|
+
if (response.status === 202 && Date.now() - start < PENDING_MS) {
|
|
479
|
+
say(`coffre: ${options.service}'s session waits for a person to approve it${typeof body?.approve === "string" ? `, at ${body.approve}` : ""}`);
|
|
480
|
+
await sleep(5e3, lifetime.signal);
|
|
481
|
+
continue;
|
|
482
|
+
}
|
|
483
|
+
if (response.status === 429 && reason === "full" && Date.now() - start < FULL_MS) {
|
|
484
|
+
say(`coffre: ${options.service}'s enrollment code holds all the sessions it admits; waiting for one to end, up to 5 minutes`);
|
|
485
|
+
await sleep(retryAfter(response, 3e4), lifetime.signal);
|
|
486
|
+
continue;
|
|
487
|
+
}
|
|
488
|
+
if (reason === "replayed" && options.proof.spent !== void 0 && await options.proof.spent(context)) continue;
|
|
489
|
+
throw refusal(response.status, body, `${origin} would not sign ${options.service} in with its ${options.proof.name} proof`);
|
|
490
|
+
}
|
|
491
|
+
};
|
|
492
|
+
let session = await exchange();
|
|
493
|
+
if (options.place !== void 0 && !session.places.includes(options.place)) throw new Error(`${options.service} reaches ${session.places.join(", ") || "no environment"}, not ${options.place}`);
|
|
494
|
+
/** The environments of the newest session, kept while a lost one is proved again. */
|
|
495
|
+
let places = session.places;
|
|
496
|
+
/**
|
|
497
|
+
* Every session proved and not past its hard end: a new proof leaves the
|
|
498
|
+
* old one to finish its requests, and close() ends them all, their
|
|
499
|
+
* children with them. Not pruned by their expiry, which a renewal answered
|
|
500
|
+
* late may have pushed on: a session already ended answers 401, which is
|
|
501
|
+
* an end too.
|
|
502
|
+
*/
|
|
503
|
+
let roots = [session];
|
|
504
|
+
let closed = false;
|
|
505
|
+
/** The exchange in flight, which requests without a session wait for; and why the last one failed, while none holds. */
|
|
506
|
+
let attempt = null;
|
|
507
|
+
let failure = null;
|
|
508
|
+
/** A refusal no new proof can change (a superseded code, a proof given once and spent), once seen. */
|
|
509
|
+
let final = null;
|
|
510
|
+
let tries = 0;
|
|
511
|
+
/** The renewal in flight for each session: one each, so that an old session's renewal answered late takes no new session's turn. */
|
|
512
|
+
const renewals = /* @__PURE__ */ new WeakMap();
|
|
513
|
+
const timers = {
|
|
514
|
+
renew: void 0,
|
|
515
|
+
prove: void 0,
|
|
516
|
+
retry: void 0
|
|
517
|
+
};
|
|
518
|
+
const at = (which, when, run) => {
|
|
519
|
+
clearTimeout(timers[which]);
|
|
520
|
+
if (closed) return;
|
|
521
|
+
timers[which] = setTimeout(() => void run(), Math.max(0, when - Date.now()));
|
|
522
|
+
timers[which].unref?.();
|
|
523
|
+
};
|
|
524
|
+
/** Renew at half-life, or every 30 seconds for an enrollment; prove again at 90% of the way to `notAfter`. */
|
|
525
|
+
const plan = (held) => {
|
|
526
|
+
const now = Date.now();
|
|
527
|
+
at("renew", enrolled ? now + ENROLLMENT_RENEW_MS : now + Math.max(1e3, (held.expiresAt - now) / 2), renew);
|
|
528
|
+
if (!enrolled) at("prove", held.notAfter - (held.notAfter - held.issuedAt) / 10, () => prove().catch(() => void 0));
|
|
529
|
+
};
|
|
530
|
+
/** A new session, with a fresh proof and the same key: requests in flight finish on the old one. Retried with backoff while it fails, unless it cannot change. */
|
|
531
|
+
const prove = () => {
|
|
532
|
+
if (final !== null) return Promise.reject(final);
|
|
533
|
+
attempt ??= exchange().then((next) => {
|
|
534
|
+
if (closed) {
|
|
535
|
+
logout(api, next.token).catch(() => void 0);
|
|
536
|
+
throw new Error(`${options.service}'s session with coffre is closed`);
|
|
537
|
+
}
|
|
538
|
+
session = next;
|
|
539
|
+
places = next.places;
|
|
540
|
+
roots = [...roots.filter((root) => root.notAfter > Date.now()), next];
|
|
541
|
+
failure = null;
|
|
542
|
+
tries = 0;
|
|
543
|
+
plan(next);
|
|
544
|
+
return next;
|
|
545
|
+
}).catch((error) => {
|
|
546
|
+
failure = error;
|
|
547
|
+
const spent = error instanceof CoffreError && error.reason === "replayed" && options.proof.spent === void 0;
|
|
548
|
+
if (spent) log(`coffre: ${options.service}'s ${options.proof.name} proof was spent, and it gives no fresh one: the session ends at its expiry`);
|
|
549
|
+
if (spent || error instanceof CoffreError && FINAL.has(error.reason ?? "")) final = error;
|
|
550
|
+
else if (!closed) at("retry", Date.now() + backoff(tries++), () => prove().catch(() => void 0));
|
|
551
|
+
throw error;
|
|
552
|
+
}).finally(() => attempt = null);
|
|
553
|
+
return attempt;
|
|
554
|
+
};
|
|
555
|
+
/** Push the session's expiry on; a session coffre no longer renews is lost, and proved again. */
|
|
556
|
+
const renew = () => {
|
|
557
|
+
const held = session;
|
|
558
|
+
if (held === null || closed) return Promise.resolve();
|
|
559
|
+
const running = renewals.get(held);
|
|
560
|
+
if (running !== void 0) return running;
|
|
561
|
+
const renewal = (async () => {
|
|
562
|
+
try {
|
|
563
|
+
const { response, body } = await api("/api/auth/workload/renew", held.token);
|
|
564
|
+
if (response.ok && typeof body?.expiresAt === "string") {
|
|
565
|
+
held.expiresAt = Date.parse(body.expiresAt);
|
|
566
|
+
if (session === held) at("renew", enrolled ? Date.now() + ENROLLMENT_RENEW_MS : Date.now() + Math.max(1e3, (held.expiresAt - Date.now()) / 2), renew);
|
|
567
|
+
return;
|
|
568
|
+
}
|
|
569
|
+
if (response.status !== 401 && response.status !== 403 || askedNonce(response)) throw new Error(`renewal answered ${response.status}`);
|
|
570
|
+
if (session === held) lose();
|
|
571
|
+
} catch {
|
|
572
|
+
if (session !== held) return;
|
|
573
|
+
if (Date.now() >= held.expiresAt) return lose();
|
|
574
|
+
at("renew", Math.min(Date.now() + (enrolled ? 5e3 : 3e4), held.expiresAt), renew);
|
|
575
|
+
}
|
|
576
|
+
})().finally(() => renewals.delete(held));
|
|
577
|
+
renewals.set(held, renewal);
|
|
578
|
+
return renewal;
|
|
579
|
+
};
|
|
580
|
+
const lose = () => {
|
|
581
|
+
if (closed) return;
|
|
582
|
+
session = null;
|
|
583
|
+
clearTimeout(timers.renew);
|
|
584
|
+
clearTimeout(timers.prove);
|
|
585
|
+
prove().catch(() => void 0);
|
|
586
|
+
};
|
|
587
|
+
/** The session to sign with: the one held, the exchange in flight, or, while exchanges fail, why. */
|
|
588
|
+
const current = async () => {
|
|
589
|
+
if (closed) throw new Error(`${options.service}'s session with coffre is closed`);
|
|
590
|
+
if (session !== null && Date.now() < session.expiresAt - 5e3) return session;
|
|
591
|
+
if (attempt !== null) return attempt;
|
|
592
|
+
if (failure !== null) throw failure;
|
|
593
|
+
return prove();
|
|
594
|
+
};
|
|
595
|
+
plan(session);
|
|
596
|
+
const signals = globalThis.process;
|
|
597
|
+
let closing = null;
|
|
598
|
+
const close = () => closing ??= (async () => {
|
|
599
|
+
closed = true;
|
|
600
|
+
lifetime.abort();
|
|
601
|
+
for (const timer of Object.values(timers)) clearTimeout(timer);
|
|
602
|
+
session = null;
|
|
603
|
+
try {
|
|
604
|
+
const failed = (await Promise.allSettled(roots.filter((root) => root.notAfter > Date.now()).map((root) => logout(api, root.token)))).find((each) => each.status === "rejected");
|
|
605
|
+
if (failed !== void 0) throw failed.reason;
|
|
606
|
+
} finally {
|
|
607
|
+
signals?.off?.("SIGTERM", onTerm);
|
|
608
|
+
TERMINATING.delete(onTerm);
|
|
609
|
+
}
|
|
610
|
+
})();
|
|
611
|
+
const onTerm = () => {
|
|
612
|
+
const alone = signals.listeners("SIGTERM").every((listener) => TERMINATING.has(listener));
|
|
613
|
+
close().catch(() => void 0).finally(() => alone && signals.listenerCount("SIGTERM") === 0 && signals.kill(signals.pid, "SIGTERM"));
|
|
614
|
+
};
|
|
615
|
+
if (options.sigterm !== false) {
|
|
616
|
+
TERMINATING.add(onTerm);
|
|
617
|
+
signals?.on?.("SIGTERM", onTerm);
|
|
618
|
+
}
|
|
619
|
+
return surface({
|
|
620
|
+
origin,
|
|
621
|
+
base,
|
|
622
|
+
key,
|
|
623
|
+
nonces,
|
|
624
|
+
api,
|
|
625
|
+
service: options.service,
|
|
626
|
+
place: options.place,
|
|
627
|
+
current,
|
|
628
|
+
places: () => places,
|
|
629
|
+
refresh: renew,
|
|
630
|
+
close
|
|
631
|
+
});
|
|
632
|
+
}
|
|
633
|
+
function surface(core) {
|
|
634
|
+
const { origin, key, nonces } = core;
|
|
635
|
+
const under = (url) => {
|
|
636
|
+
try {
|
|
637
|
+
const parsed = new URL(url);
|
|
638
|
+
return parsed.origin === origin && parsed.pathname.startsWith("/use/");
|
|
639
|
+
} catch {
|
|
640
|
+
return false;
|
|
641
|
+
}
|
|
642
|
+
};
|
|
643
|
+
const fresh = async () => {
|
|
644
|
+
if (Date.now() - nonces.at > FRESH_NONCE_MS) await core.refresh().catch(() => void 0);
|
|
645
|
+
};
|
|
646
|
+
/** A request under `/use/`, signed; or any other, as given. Redirects come back through here, so each hop is signed for itself. */
|
|
647
|
+
const go = async (input, init, hops) => {
|
|
648
|
+
const url = input instanceof Request ? input.url : input instanceof URL ? input.href : String(input);
|
|
649
|
+
if (!under(url)) return core.base(input, init);
|
|
650
|
+
const request = new Request(input, init);
|
|
651
|
+
const declared = request.headers.get("x-amz-content-sha256");
|
|
652
|
+
const streamed = init?.body instanceof ReadableStream || input instanceof Request && init?.body === void 0;
|
|
653
|
+
const stream = declared !== null && request.body !== null && streamed ? request.body : null;
|
|
654
|
+
const bytes = stream === null && request.body !== null ? new Uint8Array(await request.arrayBuffer()) : null;
|
|
655
|
+
const stated = request.headers.get("content-length");
|
|
656
|
+
const length = stream === null ? bytes?.length ?? 0 : stated !== null && /^\d+$/.test(stated) ? Number(stated) : null;
|
|
657
|
+
const line = await bodyLine({
|
|
658
|
+
declared,
|
|
659
|
+
length,
|
|
660
|
+
bytes
|
|
661
|
+
});
|
|
662
|
+
const send = async () => {
|
|
663
|
+
const { token } = await core.current();
|
|
664
|
+
const headers = new Headers(request.headers);
|
|
665
|
+
headers.set("authorization", `DPoP ${token}`);
|
|
666
|
+
headers.set("dpop", await createProof(key, {
|
|
667
|
+
method: request.method,
|
|
668
|
+
url: request.url,
|
|
669
|
+
token,
|
|
670
|
+
nonce: nonces.value,
|
|
671
|
+
content: {
|
|
672
|
+
headers: request.headers,
|
|
673
|
+
body: line
|
|
674
|
+
}
|
|
675
|
+
}));
|
|
676
|
+
const sent = dispatch(nonces);
|
|
677
|
+
const response = await core.base(request.url, {
|
|
678
|
+
method: request.method,
|
|
679
|
+
headers,
|
|
680
|
+
body: stream ?? bytes,
|
|
681
|
+
signal: request.signal,
|
|
682
|
+
redirect: "manual",
|
|
683
|
+
...stream === null ? {} : { duplex: "half" }
|
|
684
|
+
});
|
|
685
|
+
note(nonces, response, sent);
|
|
686
|
+
return response;
|
|
687
|
+
};
|
|
688
|
+
let response;
|
|
689
|
+
if (stream !== null) {
|
|
690
|
+
await fresh();
|
|
691
|
+
response = await send();
|
|
692
|
+
} else {
|
|
693
|
+
response = await send();
|
|
694
|
+
if (askedNonce(response)) {
|
|
695
|
+
await response.body?.cancel();
|
|
696
|
+
response = await send();
|
|
697
|
+
}
|
|
698
|
+
}
|
|
699
|
+
const location = response.headers.get("location");
|
|
700
|
+
if (request.redirect === "manual" || !REDIRECTS.has(response.status) || location === null) return response;
|
|
701
|
+
await response.body?.cancel();
|
|
702
|
+
if (request.redirect === "error") throw new TypeError(`fetch failed: ${request.url} redirects, and redirect is "error"`);
|
|
703
|
+
if (hops >= MOST_REDIRECTS) throw new TypeError(`fetch failed: more than ${MOST_REDIRECTS} redirects`);
|
|
704
|
+
const asGet = response.status === 303 && request.method !== "HEAD" || (response.status === 301 || response.status === 302) && request.method === "POST";
|
|
705
|
+
if (!asGet && stream !== null) throw new TypeError(`fetch failed: ${request.url} redirects a streamed body, which cannot be sent again`);
|
|
706
|
+
const next = new URL(location, request.url);
|
|
707
|
+
const headers = new Headers(request.headers);
|
|
708
|
+
if (asGet) for (const name of [
|
|
709
|
+
"content-type",
|
|
710
|
+
"content-length",
|
|
711
|
+
"content-encoding",
|
|
712
|
+
"content-language",
|
|
713
|
+
"content-location"
|
|
714
|
+
]) headers.delete(name);
|
|
715
|
+
if (next.origin !== new URL(request.url).origin) for (const name of [
|
|
716
|
+
"authorization",
|
|
717
|
+
"cookie",
|
|
718
|
+
"proxy-authorization"
|
|
719
|
+
]) headers.delete(name);
|
|
720
|
+
return go(next, {
|
|
721
|
+
method: asGet ? "GET" : request.method,
|
|
722
|
+
headers,
|
|
723
|
+
body: asGet ? null : bytes,
|
|
724
|
+
signal: request.signal,
|
|
725
|
+
redirect: "follow"
|
|
726
|
+
}, hops + 1);
|
|
727
|
+
};
|
|
728
|
+
const signed = (input, init) => go(input, init, 0);
|
|
729
|
+
const placeOf = () => {
|
|
730
|
+
const places = core.places();
|
|
731
|
+
const place = core.place ?? (places.length === 1 ? places[0] : void 0);
|
|
732
|
+
if (place === void 0) throw new Error(`${core.service} reaches ${places.join(", ") || "no environment"}: name the one to use, workload({ place })`);
|
|
733
|
+
return place;
|
|
734
|
+
};
|
|
735
|
+
const placeUrl = () => `${origin}/use/${placeOf().split("/").map(encodeURIComponent).join("/")}`;
|
|
736
|
+
const url = (name) => core.places().length === 1 ? `${origin}/use/${encodeURIComponent(name)}` : `${placeUrl()}/${encodeURIComponent(name)}`;
|
|
737
|
+
/** What coffre makes with the environment's values, at the environment's URL: a signature, a verdict, a presigned URL, a minted child. */
|
|
738
|
+
const compute = async (asked, what) => {
|
|
739
|
+
const response = await signed(placeUrl(), {
|
|
740
|
+
method: "POST",
|
|
741
|
+
headers: {
|
|
742
|
+
"content-type": "application/json",
|
|
743
|
+
accept: "application/json"
|
|
744
|
+
},
|
|
745
|
+
body: JSON.stringify(asked)
|
|
746
|
+
});
|
|
747
|
+
const body = await response.json().catch(() => null);
|
|
748
|
+
if (!response.ok || body === null) throw refusal(response.status, body, `coffre ${what} nothing`);
|
|
749
|
+
return body;
|
|
750
|
+
};
|
|
751
|
+
const workload = {
|
|
752
|
+
service: core.service,
|
|
753
|
+
get places() {
|
|
754
|
+
return core.places();
|
|
755
|
+
},
|
|
756
|
+
fetch: signed,
|
|
757
|
+
url,
|
|
758
|
+
credential: (name) => ({
|
|
759
|
+
fetch: async (path, init) => {
|
|
760
|
+
const base = url(name);
|
|
761
|
+
const target = new URL(`${base}${path.startsWith("/") ? "" : "/"}${path}`);
|
|
762
|
+
const under = new URL(base).pathname;
|
|
763
|
+
if (target.pathname !== under && !target.pathname.startsWith(`${under}/`)) throw new TypeError(`${JSON.stringify(path)} leaves ${name}'s URL: a credential's fetch reaches its own upstream only`);
|
|
764
|
+
return signed(target.href, init);
|
|
765
|
+
},
|
|
766
|
+
sign: async (message) => {
|
|
767
|
+
const body = await compute({ sign: {
|
|
768
|
+
credential: name,
|
|
769
|
+
message: bytesOf(message)
|
|
770
|
+
} }, "signed");
|
|
771
|
+
if (typeof body.signature !== "string") throw new Error("coffre signed nothing");
|
|
772
|
+
return body.signature;
|
|
773
|
+
},
|
|
774
|
+
verify: async (message, signature) => (await compute({ verify: {
|
|
775
|
+
credential: name,
|
|
776
|
+
message: bytesOf(message),
|
|
777
|
+
signature
|
|
778
|
+
} }, "verified")).valid === true,
|
|
779
|
+
presign: async (path, options = {}) => {
|
|
780
|
+
const body = await compute({ presign: {
|
|
781
|
+
credential: name,
|
|
782
|
+
path,
|
|
783
|
+
...options
|
|
784
|
+
} }, "presigned");
|
|
785
|
+
if (typeof body.url !== "string" || typeof body.expiresAt !== "string") throw new Error("coffre presigned nothing");
|
|
786
|
+
return {
|
|
787
|
+
url: body.url,
|
|
788
|
+
expiresAt: body.expiresAt
|
|
789
|
+
};
|
|
790
|
+
},
|
|
791
|
+
mint: async () => await compute({ mint: { credential: name } }, "minted")
|
|
792
|
+
}),
|
|
793
|
+
read: async (name) => {
|
|
794
|
+
const response = await signed(placeUrl(), { headers: { accept: "application/json" } });
|
|
795
|
+
const body = await response.json().catch(() => null);
|
|
796
|
+
if (!response.ok) throw refusal(response.status, body, `coffre answered no plan for ${placeOf()}`);
|
|
797
|
+
const value = body?.values?.[name];
|
|
798
|
+
if (typeof value === "string") return value;
|
|
799
|
+
throw new CoffreError(403, "forbidden", `${core.service} reads no ${name} in ${placeOf()}: it reads plain values and those its binding lists in reads, and uses every other through coffre`, "use_only");
|
|
800
|
+
},
|
|
801
|
+
narrow: (async (options) => {
|
|
802
|
+
const own = options.key === void 0 ? await generateProofKey() : null;
|
|
803
|
+
const { token } = await core.current();
|
|
804
|
+
const { key: given, expiresIn, label, ...constraints } = options;
|
|
805
|
+
const { response, body } = await core.api("/api/auth/workload/narrow", token, {
|
|
806
|
+
key: given ?? own.jwk,
|
|
807
|
+
label,
|
|
808
|
+
constraints,
|
|
809
|
+
expiresIn
|
|
810
|
+
});
|
|
811
|
+
if (!response.ok || typeof body?.token !== "string" || typeof body.expiresAt !== "string") throw refusal(response.status, body, `coffre narrowed ${core.service} to nothing`);
|
|
812
|
+
if (own === null) return {
|
|
813
|
+
token: body.token,
|
|
814
|
+
expiresAt: body.expiresAt
|
|
815
|
+
};
|
|
816
|
+
return child(core, own, body.token, Date.parse(body.expiresAt), options.places ?? core.places());
|
|
817
|
+
}),
|
|
818
|
+
close: core.close
|
|
819
|
+
};
|
|
820
|
+
UPGRADES.set(workload, {
|
|
821
|
+
sign: async (target) => {
|
|
822
|
+
await fresh();
|
|
823
|
+
const { token } = await core.current();
|
|
824
|
+
const url = target.replace(/^ws/, "http");
|
|
825
|
+
return {
|
|
826
|
+
authorization: `DPoP ${token}`,
|
|
827
|
+
dpop: await createProof(key, {
|
|
828
|
+
method: "GET",
|
|
829
|
+
url,
|
|
830
|
+
token,
|
|
831
|
+
nonce: nonces.value
|
|
832
|
+
})
|
|
833
|
+
};
|
|
834
|
+
},
|
|
835
|
+
refused: () => nonces.at = 0
|
|
836
|
+
});
|
|
837
|
+
return workload;
|
|
838
|
+
}
|
|
839
|
+
/** A narrowed session in this process: its own key, no renewal, and its end its parent's or its own. */
|
|
840
|
+
function child(parent, key, token, expiresAt, places) {
|
|
841
|
+
let closed = false;
|
|
842
|
+
let closing = null;
|
|
843
|
+
const held = {
|
|
844
|
+
token,
|
|
845
|
+
expiresAt,
|
|
846
|
+
notAfter: expiresAt,
|
|
847
|
+
places,
|
|
848
|
+
issuedAt: Date.now()
|
|
849
|
+
};
|
|
850
|
+
const api = apiOf({
|
|
851
|
+
origin: parent.origin,
|
|
852
|
+
base: parent.base,
|
|
853
|
+
key,
|
|
854
|
+
nonces: parent.nonces
|
|
855
|
+
});
|
|
856
|
+
return surface({
|
|
857
|
+
...parent,
|
|
858
|
+
key,
|
|
859
|
+
api,
|
|
860
|
+
places: () => places,
|
|
861
|
+
place: parent.place !== void 0 && places.includes(parent.place) ? parent.place : void 0,
|
|
862
|
+
current: async () => {
|
|
863
|
+
if (closed || Date.now() >= held.expiresAt) throw new Error(`this narrowed session of ${parent.service} has ended`);
|
|
864
|
+
return held;
|
|
865
|
+
},
|
|
866
|
+
refresh: parent.refresh,
|
|
867
|
+
close: () => closing ??= (async () => {
|
|
868
|
+
closed = true;
|
|
869
|
+
await logout(api, token);
|
|
870
|
+
})()
|
|
871
|
+
});
|
|
872
|
+
}
|
|
873
|
+
/**
|
|
874
|
+
* The headers that sign a WebSocket's upgrade to `url` (a tunnel's), made
|
|
875
|
+
* outside `coffre.fetch`: the session, and a proof of a GET at its `https`
|
|
876
|
+
* form with a nonce fresh enough that the gate takes it, since an upgrade
|
|
877
|
+
* refused cannot be told why and sent again.
|
|
878
|
+
*/
|
|
879
|
+
function upgradeHeaders(coffre, url) {
|
|
880
|
+
const upgrade = UPGRADES.get(coffre);
|
|
881
|
+
if (upgrade === void 0) throw new TypeError("upgradeHeaders takes a workload() session");
|
|
882
|
+
return upgrade.sign(url);
|
|
883
|
+
}
|
|
884
|
+
/**
|
|
885
|
+
* Say that coffre refused an upgrade, or that it never opened: its nonce may
|
|
886
|
+
* be the gate's no longer, so the next upgrade, which cannot be sent again
|
|
887
|
+
* either, first asks for the newest.
|
|
888
|
+
*/
|
|
889
|
+
function upgradeRefused(coffre) {
|
|
890
|
+
UPGRADES.get(coffre)?.refused();
|
|
891
|
+
}
|
|
892
|
+
/**
|
|
893
|
+
* An AWS SDK credential provider over delivered minting (section 7.2): a
|
|
894
|
+
* minter's short-lived children, where the binding lists it, each kept
|
|
895
|
+
* until a minute before it expires.
|
|
896
|
+
*
|
|
897
|
+
* const s3 = new S3Client({ region: 'eu-west-3', credentials: fromCoffre(coffre, 'aws') });
|
|
898
|
+
*/
|
|
899
|
+
function fromCoffre(coffre, minter) {
|
|
900
|
+
let held = null;
|
|
901
|
+
return async () => {
|
|
902
|
+
if (held !== null && Date.now() < held.until) return held.value;
|
|
903
|
+
const minted = await coffre.credential(minter).mint();
|
|
904
|
+
if (typeof minted.accessKeyId !== "string" || typeof minted.secretAccessKey !== "string") throw new Error(`${minter} minted no AWS credentials`);
|
|
905
|
+
const expiration = new Date(minted.expiresAt);
|
|
906
|
+
held = {
|
|
907
|
+
value: {
|
|
908
|
+
accessKeyId: minted.accessKeyId,
|
|
909
|
+
secretAccessKey: minted.secretAccessKey,
|
|
910
|
+
sessionToken: minted.sessionToken,
|
|
911
|
+
expiration
|
|
912
|
+
},
|
|
913
|
+
until: expiration.getTime() - 6e4
|
|
914
|
+
};
|
|
915
|
+
return held.value;
|
|
916
|
+
};
|
|
917
|
+
}
|
|
918
|
+
/** Keep the gate's newest nonce: every answer from coffre carries it, and the newest is the one to a request sent last. */
|
|
919
|
+
function note(nonces, response, sent) {
|
|
920
|
+
const nonce = response.headers.get("dpop-nonce");
|
|
921
|
+
if (nonce !== null && nonce !== "" && sent.seq > nonces.seq) {
|
|
922
|
+
nonces.value = nonce;
|
|
923
|
+
nonces.at = sent.at;
|
|
924
|
+
nonces.seq = sent.seq;
|
|
925
|
+
}
|
|
926
|
+
}
|
|
927
|
+
/**
|
|
928
|
+
* Its proof signs the token and the newest nonce, and a body where there is
|
|
929
|
+
* one (`hdr` and `req`: narrow's, the key and the limits it gives a child),
|
|
930
|
+
* so no one who sees the request can make it say anything else; sent again
|
|
931
|
+
* once if the gate asks for a fresh nonce.
|
|
932
|
+
*/
|
|
933
|
+
function apiOf({ origin, base, key, nonces }) {
|
|
934
|
+
return async (path, token, body, signal) => {
|
|
935
|
+
const url = `${origin}${path}`;
|
|
936
|
+
const json = body === void 0 ? void 0 : JSON.stringify(body);
|
|
937
|
+
const headers = {
|
|
938
|
+
accept: "application/json",
|
|
939
|
+
...json === void 0 ? {} : { "content-type": "application/json" }
|
|
940
|
+
};
|
|
941
|
+
const content = json === void 0 ? void 0 : {
|
|
942
|
+
headers,
|
|
943
|
+
body: await bodyDigest(json)
|
|
944
|
+
};
|
|
945
|
+
const send = async () => {
|
|
946
|
+
const sent = dispatch(nonces);
|
|
947
|
+
const response = await base(url, {
|
|
948
|
+
method: "POST",
|
|
949
|
+
headers: {
|
|
950
|
+
...headers,
|
|
951
|
+
authorization: `DPoP ${token}`,
|
|
952
|
+
dpop: await createProof(key, {
|
|
953
|
+
method: "POST",
|
|
954
|
+
url,
|
|
955
|
+
token,
|
|
956
|
+
nonce: nonces.value,
|
|
957
|
+
content
|
|
958
|
+
})
|
|
959
|
+
},
|
|
960
|
+
body: json,
|
|
961
|
+
signal,
|
|
962
|
+
redirect: "error"
|
|
963
|
+
});
|
|
964
|
+
note(nonces, response, sent);
|
|
965
|
+
return response;
|
|
966
|
+
};
|
|
967
|
+
let response = await send();
|
|
968
|
+
if (askedNonce(response)) {
|
|
969
|
+
await response.body?.cancel();
|
|
970
|
+
response = await send();
|
|
971
|
+
}
|
|
972
|
+
return {
|
|
973
|
+
response,
|
|
974
|
+
body: await response.json().catch(() => null)
|
|
975
|
+
};
|
|
976
|
+
};
|
|
977
|
+
}
|
|
978
|
+
/** End a session, waiting 3 seconds at most; rejects unless coffre says it ended, or had already (401). */
|
|
979
|
+
async function logout(api, token) {
|
|
980
|
+
const { response, body } = await api("/api/auth/logout", token, void 0, AbortSignal.timeout(LOGOUT_MS));
|
|
981
|
+
if (!response.ok && (response.status !== 401 || askedNonce(response))) throw refusal(response.status, body, "coffre did not end the session");
|
|
982
|
+
}
|
|
983
|
+
/** Whether coffre refused a proof for its nonce alone (RFC 9449, section 8): sent again once, with the nonce it gave. */
|
|
984
|
+
function askedNonce(response) {
|
|
985
|
+
return response.status === 401 && /error="?use_dpop_nonce/.test(response.headers.get("www-authenticate") ?? "") && response.headers.has("dpop-nonce");
|
|
986
|
+
}
|
|
987
|
+
function refusal(status, body, what) {
|
|
988
|
+
const reason = typeof body?.reason === "string" ? body.reason : void 0;
|
|
989
|
+
const message = typeof body?.message === "string" ? body.message : `status ${status}`;
|
|
990
|
+
return new CoffreError(status, typeof body?.error === "string" ? body.error : "refused", `${what}${reason === void 0 ? "" : ` (${reason})`}: ${message}`, reason);
|
|
991
|
+
}
|
|
992
|
+
/** `Retry-After`, in milliseconds, or `fallback`. */
|
|
993
|
+
function retryAfter(response, fallback) {
|
|
994
|
+
const seconds = Number(response.headers.get("retry-after"));
|
|
995
|
+
return Number.isFinite(seconds) && seconds > 0 ? Math.min(seconds, 300) * 1e3 : fallback;
|
|
996
|
+
}
|
|
997
|
+
/** 1, 2, 4… seconds, at most a minute, a little jittered so that a fleet's replicas spread out. */
|
|
998
|
+
function backoff(tries) {
|
|
999
|
+
return Math.min(6e4, 1e3 * 2 ** tries) * (.75 + Math.random() / 2);
|
|
1000
|
+
}
|
|
1001
|
+
/** A message as coffre's `sign` and `verify` take it: a string's UTF-8, base64url. */
|
|
1002
|
+
const bytesOf = (message) => base64url(typeof message === "string" ? new TextEncoder().encode(message) : message);
|
|
1003
|
+
/** A signal that aborts with the first of `signals`: `AbortSignal.any`, where the runtime has it (Node 20.3 and later). */
|
|
1004
|
+
function anySignal(signals) {
|
|
1005
|
+
if (typeof AbortSignal.any === "function") return AbortSignal.any(signals);
|
|
1006
|
+
const controller = new AbortController();
|
|
1007
|
+
for (const signal of signals) if (signal.aborted) controller.abort(signal.reason);
|
|
1008
|
+
else signal.addEventListener("abort", () => controller.abort(signal.reason), { once: true });
|
|
1009
|
+
return controller.signal;
|
|
1010
|
+
}
|
|
1011
|
+
/** A wait that `signal` ends early, rejecting. */
|
|
1012
|
+
const sleep = (ms, signal) => new Promise((resolve, reject) => {
|
|
1013
|
+
const timer = setTimeout(() => (signal.removeEventListener("abort", stop), resolve()), ms);
|
|
1014
|
+
const stop = () => (clearTimeout(timer), reject(signal.reason));
|
|
1015
|
+
signal.addEventListener("abort", stop, { once: true });
|
|
1016
|
+
});
|
|
1017
|
+
//#endregion
|
|
1018
|
+
export { KUBERNETES_TOKEN as a, enrollment as c, github as d, keyAudience as f, vercel as h, workload as i, fly as l, oidc as m, upgradeHeaders as n, aws as o, kubernetes as p, upgradeRefused as r, azure as s, fromCoffre as t, gcp as u };
|