@wtfalch/keys 0.8.0 → 0.13.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +244 -27
- package/dist/held/index.d.ts +116 -6
- package/dist/held/index.js +259 -37
- package/dist/held/schema.d.ts +17 -0
- package/dist/held/schema.js +12 -0
- package/dist/held/seal.d.ts +1 -1
- package/dist/held/seal.js +1 -1
- package/dist/held/shred.d.ts +6 -0
- package/dist/held/shred.js +6 -0
- package/dist/held/tenant.d.ts +2 -0
- package/dist/held/tenant.js +46 -0
- package/dist/held-edge/index.d.ts +17 -2
- package/dist/held-edge/index.js +51 -9
- package/dist/host/audit-endpoint.js +2 -8
- package/dist/host/company-registrar-keys.d.ts +13 -0
- package/dist/host/company-registrar-keys.js +6 -8
- package/dist/host/events.d.ts +19 -3
- package/dist/host/events.js +56 -20
- package/dist/host/index.d.ts +9 -2
- package/dist/host/index.js +9 -2
- package/dist/host/native-build.d.ts +126 -0
- package/dist/host/native-build.js +322 -0
- package/dist/host/registrar.d.ts +10 -4
- package/dist/host/registrar.js +64 -42
- package/dist/host/rotation-sweep.d.ts +56 -0
- package/dist/host/rotation-sweep.js +89 -0
- package/dist/issued/encoding.d.ts +4 -0
- package/dist/issued/encoding.js +22 -0
- package/dist/issued/index.d.ts +148 -7
- package/dist/issued/index.js +320 -34
- package/dist/issued/resign.d.ts +16 -0
- package/dist/issued/resign.js +55 -2
- package/dist/issued/tables.d.ts +38 -0
- package/dist/issued/tables.js +6 -0
- package/dist/issued/verify.d.ts +14 -3
- package/dist/issued/verify.js +10 -3
- package/dist/migrations/held/0004_keys_archived_publish_guard.sql +46 -0
- package/dist/migrations/held/0005_keys_held_migration_credential.sql +216 -0
- package/dist/migrations/held/0006_keys_held_entries_guard.sql +54 -0
- package/dist/migrations/host/0002_keys_host_held_events.sql +29 -0
- package/dist/migrations/issued/0007_keys_purpose.sql +68 -0
- package/dist/migrations/issued/0008_keys_idempotency_scope.sql +23 -0
- package/dist/migrations/tenant-rows/0001_keys_tenant_rows.sql +63 -0
- package/dist/migrations-dir.d.ts +9 -0
- package/dist/migrations-dir.js +9 -0
- package/dist/service/body.d.ts +21 -0
- package/dist/service/body.js +128 -0
- package/dist/service/errors.d.ts +24 -0
- package/dist/service/errors.js +89 -0
- package/dist/service/handler.d.ts +35 -0
- package/dist/service/handler.js +328 -0
- package/dist/service/index.d.ts +7 -0
- package/dist/service/index.js +7 -0
- package/dist/service/policy.d.ts +130 -0
- package/dist/service/policy.js +123 -0
- package/dist/service/timeout.d.ts +6 -0
- package/dist/service/timeout.js +34 -0
- package/dist/webhooks.d.ts +40 -17
- package/dist/webhooks.js +70 -26
- package/dist/worker-contract.d.ts +43 -6
- package/dist/worker-contract.js +37 -0
- package/dist/worker.d.ts +1 -1
- package/dist/worker.js +7 -28
- package/package.json +21 -7
- package/dist/testing/index.d.ts +0 -9
- package/dist/testing/index.js +0 -9
- package/dist/testing/worker-stub.d.ts +0 -55
- package/dist/testing/worker-stub.js +0 -180
|
@@ -0,0 +1,322 @@
|
|
|
1
|
+
import { createRemoteJWKSet, customFetch, errors, jwtVerify } from 'jose';
|
|
2
|
+
import { HeldKeysError } from '../held/index.js';
|
|
3
|
+
/**
|
|
4
|
+
* S5 of `estate/.plans/2026-10-22-app-shells.md` (decision 5): the one
|
|
5
|
+
* route a `build-app.yml` run may call to trade its own GitHub Actions OIDC
|
|
6
|
+
* token and a `runId` for that run's native build config and the owning
|
|
7
|
+
* company's Apple/Google keys.
|
|
8
|
+
*
|
|
9
|
+
* No table of its own, the same shape `./company-registrar-keys.ts` takes:
|
|
10
|
+
* which company and which `NativeAppConfig` a `runId` names is foundry's
|
|
11
|
+
* row, not this package's, so it arrives through the injected `resolveRun`
|
|
12
|
+
* rather than a query this module writes itself. The four key kinds the
|
|
13
|
+
* plan names each live as one `./held` entry per company (`tenantId` is the
|
|
14
|
+
* organisation id, `entryId` one of `NATIVE_KEY_ENTRY_IDS`); a company that
|
|
15
|
+
* has not entered a kind simply has no entry, read here as "not part of
|
|
16
|
+
* this answer", never a refusal.
|
|
17
|
+
*
|
|
18
|
+
* Authentication is the GitHub Actions OIDC token itself, verified against
|
|
19
|
+
* GitHub's own JWKS -- never a static bearer secret, because the fact that
|
|
20
|
+
* must hold is "this call came from the one workflow file, in the one
|
|
21
|
+
* repo, running on its default branch", which only GitHub's own signed
|
|
22
|
+
* claims can attest to. `repository`, `workflow_ref` and `ref` are each
|
|
23
|
+
* checked by exact match: a token minted for any other repository,
|
|
24
|
+
* workflow file or ref is refused the same as a forged one. The ref is the
|
|
25
|
+
* branch name, not a commit: a run of an older commit of the same file on
|
|
26
|
+
* the default branch carries the same claims and is not told apart.
|
|
27
|
+
*
|
|
28
|
+
* The workflow file is shared by every company, so those checks alone say
|
|
29
|
+
* "some build run", not "this company's run". The token's `run_id` claim is
|
|
30
|
+
* the tie: the exchange answers only when it equals the GitHub run id the
|
|
31
|
+
* `runId` row was bound to (`resolveRun`'s `githubRunId`).
|
|
32
|
+
*/
|
|
33
|
+
/** `ID_PATTERN`-safe entry id per key kind; `held/index.ts`'s `requireId` refuses a dot, so these are not the dotted names the plan uses in prose. */
|
|
34
|
+
const NATIVE_KEY_ENTRY_IDS = {
|
|
35
|
+
appleAscKey: 'apple-asc-key',
|
|
36
|
+
appleDeveloperId: 'apple-developer-id',
|
|
37
|
+
googlePlayServiceAccount: 'google-play-service-account',
|
|
38
|
+
googleUploadKeystore: 'google-upload-keystore',
|
|
39
|
+
};
|
|
40
|
+
/** The `./held` entry id a native key field is stored and read under, for whatever writes it (Boule, through `held.put`). */
|
|
41
|
+
export function nativeKeyEntryId(field) {
|
|
42
|
+
return NATIVE_KEY_ENTRY_IDS[field];
|
|
43
|
+
}
|
|
44
|
+
/** Every member of `NativeBuildRefusalReason`. Adding one is a major change after 1.0.0. */
|
|
45
|
+
export const NATIVE_BUILD_REFUSAL_REASONS = [
|
|
46
|
+
'bad_request',
|
|
47
|
+
'unauthorized',
|
|
48
|
+
'not_found',
|
|
49
|
+
'run_mismatch',
|
|
50
|
+
];
|
|
51
|
+
const GITHUB_OIDC_ISSUER = 'https://token.actions.githubusercontent.com';
|
|
52
|
+
const GITHUB_OIDC_JWKS_URL = 'https://token.actions.githubusercontent.com/.well-known/jwks';
|
|
53
|
+
/** GitHub signs Actions OIDC tokens with RS256 (checked 2026-10-22); no other algorithm is accepted. */
|
|
54
|
+
const ALGORITHMS = ['RS256'];
|
|
55
|
+
/** Generous enough for any id foundry's own build-run table mints; bounded so this field alone cannot grow the request body unreasonably, and excludes whitespace so a run id can never collide with a padded or multi-line value. */
|
|
56
|
+
const RUN_ID_PATTERN = /^\S{1,256}$/;
|
|
57
|
+
/**
|
|
58
|
+
* GitHub's own `workflow_ref` claim is `<owner>/<repo>/.github/workflows/<file>@<ref>`
|
|
59
|
+
* -- the workflow file and the ref it ran at, together. Checking it by exact
|
|
60
|
+
* match is a single check that already covers "the right repo, the right
|
|
61
|
+
* workflow file, and the right ref": a token minted for any other
|
|
62
|
+
* repository, file or ref produces a different string.
|
|
63
|
+
*/
|
|
64
|
+
function expectedWorkflowRef(repository, workflowFile, defaultBranch) {
|
|
65
|
+
return `${repository}/.github/workflows/${workflowFile}@refs/heads/${defaultBranch}`;
|
|
66
|
+
}
|
|
67
|
+
function createGithubActionsVerifier(options) {
|
|
68
|
+
const issuer = options.issuer ?? GITHUB_OIDC_ISSUER;
|
|
69
|
+
const jwksUrl = options.jwksUrl ?? GITHUB_OIDC_JWKS_URL;
|
|
70
|
+
const fetchImpl = options.fetchImpl ?? fetch;
|
|
71
|
+
const resolver = createRemoteJWKSet(new URL(jwksUrl), { [customFetch]: fetchImpl });
|
|
72
|
+
const workflowRef = expectedWorkflowRef(options.repository, options.workflowFile, options.defaultBranch);
|
|
73
|
+
const ref = `refs/heads/${options.defaultBranch}`;
|
|
74
|
+
// A key the JWKS does not hold is the token's own fault (`JWKSNoMatchingKey`/
|
|
75
|
+
// `JWKSMultipleMatchingKeys`); any other failure to fetch or parse the key
|
|
76
|
+
// set (the endpoint down, a non-200, a timeout) is GitHub's, not this
|
|
77
|
+
// token's. Thrown as a plain Error so the outer catch below, which treats
|
|
78
|
+
// only a `JOSEError` as "this token is bad", does not mistake an outage
|
|
79
|
+
// for a forged token -- same split `activity`'s `viewer-bearer.ts` makes.
|
|
80
|
+
const getKey = async (header, input) => {
|
|
81
|
+
try {
|
|
82
|
+
return await resolver(header, input);
|
|
83
|
+
}
|
|
84
|
+
catch (error) {
|
|
85
|
+
if (error instanceof errors.JWKSNoMatchingKey ||
|
|
86
|
+
error instanceof errors.JWKSMultipleMatchingKeys) {
|
|
87
|
+
throw error;
|
|
88
|
+
}
|
|
89
|
+
throw new Error('github oidc jwks fetch failed', { cause: error });
|
|
90
|
+
}
|
|
91
|
+
};
|
|
92
|
+
return async function verify(token) {
|
|
93
|
+
if (!options.audience)
|
|
94
|
+
return null;
|
|
95
|
+
let payload;
|
|
96
|
+
try {
|
|
97
|
+
({ payload } = await jwtVerify(token, getKey, {
|
|
98
|
+
issuer,
|
|
99
|
+
audience: options.audience,
|
|
100
|
+
algorithms: ALGORITHMS,
|
|
101
|
+
requiredClaims: ['exp', 'sub', 'repository', 'workflow_ref', 'ref', 'run_id'],
|
|
102
|
+
clockTolerance: 30,
|
|
103
|
+
}));
|
|
104
|
+
}
|
|
105
|
+
catch (error) {
|
|
106
|
+
if (error instanceof errors.JOSEError)
|
|
107
|
+
return null;
|
|
108
|
+
throw error;
|
|
109
|
+
}
|
|
110
|
+
if (payload.repository !== options.repository)
|
|
111
|
+
return null;
|
|
112
|
+
if (payload.workflow_ref !== workflowRef)
|
|
113
|
+
return null;
|
|
114
|
+
if (payload.ref !== ref)
|
|
115
|
+
return null;
|
|
116
|
+
if (typeof payload.sub !== 'string' || payload.sub.length === 0)
|
|
117
|
+
return null;
|
|
118
|
+
if (typeof payload.run_id !== 'string' || payload.run_id.length === 0)
|
|
119
|
+
return null;
|
|
120
|
+
return { runId: payload.run_id };
|
|
121
|
+
};
|
|
122
|
+
}
|
|
123
|
+
export function createNativeBuildKeyExchange(options) {
|
|
124
|
+
const verify = createGithubActionsVerifier(options);
|
|
125
|
+
const { heldKeys, resolveRun } = options;
|
|
126
|
+
async function readKeys(organisationId) {
|
|
127
|
+
const keys = {};
|
|
128
|
+
for (const field of Object.keys(NATIVE_KEY_ENTRY_IDS)) {
|
|
129
|
+
const entryId = NATIVE_KEY_ENTRY_IDS[field];
|
|
130
|
+
try {
|
|
131
|
+
keys[field] = await heldKeys.openCurrent({ tenantId: organisationId, entryId }, async (raw) => JSON.parse(raw));
|
|
132
|
+
}
|
|
133
|
+
catch (error) {
|
|
134
|
+
// A company simply has not entered this kind: leave it out of the
|
|
135
|
+
// answer rather than refuse the whole exchange over one missing
|
|
136
|
+
// key. Any other code (revoked, disposed, a Worker fault) -- or a
|
|
137
|
+
// stored value that fails to parse -- is a real failure, not "not
|
|
138
|
+
// configured", and propagates to the endpoint's own catch (502).
|
|
139
|
+
if (error instanceof HeldKeysError && error.code === 'not_found')
|
|
140
|
+
continue;
|
|
141
|
+
throw error;
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
return keys;
|
|
145
|
+
}
|
|
146
|
+
return {
|
|
147
|
+
authenticate: verify,
|
|
148
|
+
async exchange({ token, runId }) {
|
|
149
|
+
if (typeof runId !== 'string' || !RUN_ID_PATTERN.test(runId)) {
|
|
150
|
+
return { ok: false, reason: 'bad_request' };
|
|
151
|
+
}
|
|
152
|
+
const claims = await verify(token);
|
|
153
|
+
if (claims === null)
|
|
154
|
+
return { ok: false, reason: 'unauthorized' };
|
|
155
|
+
const run = await resolveRun(runId);
|
|
156
|
+
if (run === null)
|
|
157
|
+
return { ok: false, reason: 'not_found' };
|
|
158
|
+
if (run.githubRunId !== claims.runId)
|
|
159
|
+
return { ok: false, reason: 'run_mismatch' };
|
|
160
|
+
const keys = await readKeys(run.organisationId);
|
|
161
|
+
return { ok: true, config: run.config, keys };
|
|
162
|
+
},
|
|
163
|
+
};
|
|
164
|
+
}
|
|
165
|
+
// ---------------------------------------------------------------------------
|
|
166
|
+
// The HTTP route
|
|
167
|
+
// ---------------------------------------------------------------------------
|
|
168
|
+
const EXCHANGE_PATH = '/v1/keys/native-build';
|
|
169
|
+
const BEARER_PATTERN = /^Bearer ([^\s]+)$/;
|
|
170
|
+
const MAX_BODY_BYTES = 4096;
|
|
171
|
+
/** Only these `.code` values are written to the log; any other string could be a driver's text carrying a value. */
|
|
172
|
+
const LOGGABLE_CODES = new Set([
|
|
173
|
+
'credential_invalid',
|
|
174
|
+
'credential_expired',
|
|
175
|
+
'credential_revoked',
|
|
176
|
+
'grant_missing',
|
|
177
|
+
'rate_limited',
|
|
178
|
+
'bad_request',
|
|
179
|
+
'aad_mismatch',
|
|
180
|
+
'unknown_generation',
|
|
181
|
+
'bad_minter_signature',
|
|
182
|
+
'minter_expired',
|
|
183
|
+
'minter_revoked',
|
|
184
|
+
'minter_exceeded',
|
|
185
|
+
'lineage_mismatch',
|
|
186
|
+
'bad_old_signature',
|
|
187
|
+
'unlogged_row',
|
|
188
|
+
'not_in_lineage',
|
|
189
|
+
'unreachable',
|
|
190
|
+
'not_found',
|
|
191
|
+
'revoked',
|
|
192
|
+
'unseal_failed',
|
|
193
|
+
'disposed',
|
|
194
|
+
'invalidated',
|
|
195
|
+
]);
|
|
196
|
+
/** The body as text, or `null` when it is over `MAX_BODY_BYTES`; stops reading as soon as the cap is passed. */
|
|
197
|
+
async function readCappedText(request) {
|
|
198
|
+
const declared = Number(request.headers.get('content-length'));
|
|
199
|
+
if (Number.isFinite(declared) && declared > MAX_BODY_BYTES)
|
|
200
|
+
return null;
|
|
201
|
+
if (!request.body)
|
|
202
|
+
return '';
|
|
203
|
+
const reader = request.body.getReader();
|
|
204
|
+
const chunks = [];
|
|
205
|
+
let total = 0;
|
|
206
|
+
for (;;) {
|
|
207
|
+
const { done, value } = await reader.read();
|
|
208
|
+
if (done)
|
|
209
|
+
break;
|
|
210
|
+
total += value.byteLength;
|
|
211
|
+
if (total > MAX_BODY_BYTES) {
|
|
212
|
+
await reader.cancel();
|
|
213
|
+
return null;
|
|
214
|
+
}
|
|
215
|
+
chunks.push(value);
|
|
216
|
+
}
|
|
217
|
+
const bytes = new Uint8Array(total);
|
|
218
|
+
let offset = 0;
|
|
219
|
+
for (const chunk of chunks) {
|
|
220
|
+
bytes.set(chunk, offset);
|
|
221
|
+
offset += chunk.byteLength;
|
|
222
|
+
}
|
|
223
|
+
return new TextDecoder().decode(bytes);
|
|
224
|
+
}
|
|
225
|
+
function statusForNativeBuild(reason) {
|
|
226
|
+
switch (reason) {
|
|
227
|
+
case 'bad_request':
|
|
228
|
+
return 400;
|
|
229
|
+
case 'unauthorized':
|
|
230
|
+
return 401;
|
|
231
|
+
case 'not_found':
|
|
232
|
+
return 404;
|
|
233
|
+
case 'run_mismatch':
|
|
234
|
+
return 403;
|
|
235
|
+
default: {
|
|
236
|
+
const unreachable = reason;
|
|
237
|
+
void unreachable;
|
|
238
|
+
return 502;
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
const MESSAGES = {
|
|
243
|
+
bad_request: 'Send { runId } as JSON, with runId a non-empty string of at most 256 characters.',
|
|
244
|
+
unauthorized: 'The bearer token was not accepted as a build-app.yml run on the configured repository, workflow file and default branch.',
|
|
245
|
+
not_found: 'No build run is known by that id.',
|
|
246
|
+
run_mismatch: 'This token belongs to a different build run than the one asked for, so we did not hand over any keys. Start the build again from the app and it will ask for its own run.',
|
|
247
|
+
};
|
|
248
|
+
const UNAVAILABLE_MESSAGE = 'The key service could not complete this request. Try again in a moment, and contact the operator if it keeps happening.';
|
|
249
|
+
/** Every answer, success or not, may carry a secret or tell about one: never cacheable. */
|
|
250
|
+
function jsonHeaders() {
|
|
251
|
+
return new Headers({ 'content-type': 'application/json', 'cache-control': 'no-store' });
|
|
252
|
+
}
|
|
253
|
+
function errorResponse(reason) {
|
|
254
|
+
return new Response(JSON.stringify({ error: reason, message: MESSAGES[reason] }), {
|
|
255
|
+
status: statusForNativeBuild(reason),
|
|
256
|
+
headers: jsonHeaders(),
|
|
257
|
+
});
|
|
258
|
+
}
|
|
259
|
+
function unavailableResponse() {
|
|
260
|
+
return new Response(JSON.stringify({ error: 'unavailable', message: UNAVAILABLE_MESSAGE }), {
|
|
261
|
+
status: 502,
|
|
262
|
+
headers: jsonHeaders(),
|
|
263
|
+
});
|
|
264
|
+
}
|
|
265
|
+
function okResponse(body) {
|
|
266
|
+
return new Response(JSON.stringify(body), { status: 200, headers: jsonHeaders() });
|
|
267
|
+
}
|
|
268
|
+
function plainResponse(status) {
|
|
269
|
+
return new Response(null, { status, headers: { 'cache-control': 'no-store' } });
|
|
270
|
+
}
|
|
271
|
+
/**
|
|
272
|
+
* `nativeBuildKeysEndpoint({ ... })` returns a fetch-shaped handler -- wire
|
|
273
|
+
* it directly as a route, e.g. `export const POST = nativeBuildKeysEndpoint({ ... });`.
|
|
274
|
+
*
|
|
275
|
+
* `POST /v1/keys/native-build` with `{ runId }` and `Authorization: Bearer
|
|
276
|
+
* <GitHub Actions OIDC token>` answers `200 { config, keys }`. Errors answer
|
|
277
|
+
* `{ error, message }`. A dependency failure that throws (GitHub's JWKS,
|
|
278
|
+
* foundry's run store, the held-key Worker) answers 502 `unavailable`,
|
|
279
|
+
* never a refusal such as `unauthorized` -- the same invariant
|
|
280
|
+
* `registrarEndpoint` keeps.
|
|
281
|
+
*/
|
|
282
|
+
export function nativeBuildKeysEndpoint(options) {
|
|
283
|
+
const exchange = createNativeBuildKeyExchange(options);
|
|
284
|
+
return async function handleNativeBuildKeys(request) {
|
|
285
|
+
if (new URL(request.url).pathname !== EXCHANGE_PATH)
|
|
286
|
+
return plainResponse(404);
|
|
287
|
+
if (request.method !== 'POST')
|
|
288
|
+
return plainResponse(405);
|
|
289
|
+
const auth = BEARER_PATTERN.exec(request.headers.get('authorization') ?? '');
|
|
290
|
+
if (!auth?.[1])
|
|
291
|
+
return errorResponse('unauthorized');
|
|
292
|
+
const token = auth[1];
|
|
293
|
+
try {
|
|
294
|
+
if ((await exchange.authenticate(token)) === null)
|
|
295
|
+
return errorResponse('unauthorized');
|
|
296
|
+
const text = await readCappedText(request);
|
|
297
|
+
if (text === null)
|
|
298
|
+
return errorResponse('bad_request');
|
|
299
|
+
let body;
|
|
300
|
+
try {
|
|
301
|
+
body = JSON.parse(text);
|
|
302
|
+
}
|
|
303
|
+
catch {
|
|
304
|
+
return errorResponse('bad_request');
|
|
305
|
+
}
|
|
306
|
+
const runId = body?.runId;
|
|
307
|
+
const result = await exchange.exchange({ token, runId });
|
|
308
|
+
if (!result.ok)
|
|
309
|
+
return errorResponse(result.reason);
|
|
310
|
+
return okResponse({ config: result.config, keys: result.keys });
|
|
311
|
+
}
|
|
312
|
+
catch (error) {
|
|
313
|
+
// Name and code only: a driver or dependency error's message can
|
|
314
|
+
// quote a secret value -- a held key, or the bearer token itself.
|
|
315
|
+
const name = error instanceof Error ? error.name : typeof error;
|
|
316
|
+
const rawCode = error?.code;
|
|
317
|
+
const code = typeof rawCode === 'string' && LOGGABLE_CODES.has(rawCode) ? ` ${rawCode}` : '';
|
|
318
|
+
console.error(`keys native-build: ${request.method} failed (${name}${code})`);
|
|
319
|
+
return unavailableResponse();
|
|
320
|
+
}
|
|
321
|
+
};
|
|
322
|
+
}
|
package/dist/host/registrar.d.ts
CHANGED
|
@@ -26,8 +26,8 @@ import type { CredentialIssuer, Db, IssueRefusalReason } from '../issued/index.j
|
|
|
26
26
|
*/
|
|
27
27
|
export interface RegistrarOptions<TGrant> {
|
|
28
28
|
readonly db: Db;
|
|
29
|
-
/** `check()`, `issue()` and `
|
|
30
|
-
readonly issuer: Pick<CredentialIssuer<TGrant>, 'check' | 'issue' | '
|
|
29
|
+
/** `check()`, `issue()` and `revokeForCompany()` are the only methods this module calls. */
|
|
30
|
+
readonly issuer: Pick<CredentialIssuer<TGrant>, 'check' | 'issue' | 'revokeForCompany'>;
|
|
31
31
|
/** Grants given to every credential minted through this registrar. Fixed by the host; never chosen by a caller. */
|
|
32
32
|
readonly appGrants: readonly TGrant[];
|
|
33
33
|
/** How long a minted app credential lives, in milliseconds from the moment it is registered. */
|
|
@@ -37,7 +37,13 @@ export interface RegistrarOptions<TGrant> {
|
|
|
37
37
|
/** Unix milliseconds. Defaults to `Date.now`; a test passes a fake clock. */
|
|
38
38
|
readonly now?: () => number;
|
|
39
39
|
}
|
|
40
|
-
export type RegistrarRefusalReason = 'bad_app_name' | 'company_key_invalid'
|
|
40
|
+
export type RegistrarRefusalReason = 'bad_app_name' | 'company_key_invalid'
|
|
41
|
+
/** Deprecated, removed at 1.0.0: never returned now. It reads as `company_key_invalid`. */
|
|
42
|
+
| 'company_key_not_a_registrar'
|
|
43
|
+
/** Another live company key of this organisation already holds that app name. */
|
|
44
|
+
| 'app_held_by_another_key' | 'rate_limited';
|
|
45
|
+
/** Every member of `RegistrarRefusalReason`. Adding one is a major change after 1.0.0. */
|
|
46
|
+
export declare const REGISTRAR_REFUSAL_REASONS: readonly ["bad_app_name", "company_key_invalid", "company_key_not_a_registrar", "app_held_by_another_key", "rate_limited"];
|
|
41
47
|
export type RegisterAppResult = {
|
|
42
48
|
readonly ok: true;
|
|
43
49
|
readonly id: string;
|
|
@@ -53,7 +59,7 @@ export type RevokeAppResult = {
|
|
|
53
59
|
readonly revoked: boolean;
|
|
54
60
|
} | {
|
|
55
61
|
readonly ok: false;
|
|
56
|
-
readonly reason: RegistrarRefusalReason | 'app_not_found';
|
|
62
|
+
readonly reason: RegistrarRefusalReason | 'app_not_found' | 'protected_credential' | 'purpose_unknown';
|
|
57
63
|
readonly retryAfterMs?: number;
|
|
58
64
|
};
|
|
59
65
|
export interface Registrar {
|
package/dist/host/registrar.js
CHANGED
|
@@ -1,15 +1,25 @@
|
|
|
1
|
-
import { eq } from 'drizzle-orm';
|
|
1
|
+
import { and, eq, gt, isNull, ne } from 'drizzle-orm';
|
|
2
2
|
import { keysIssuedCredentials } from '../issued/tables.js';
|
|
3
3
|
import { ID_PATTERN } from '../worker-contract.js';
|
|
4
|
+
/** Every member of `RegistrarRefusalReason`. Adding one is a major change after 1.0.0. */
|
|
5
|
+
export const REGISTRAR_REFUSAL_REASONS = [
|
|
6
|
+
'bad_app_name',
|
|
7
|
+
'company_key_invalid',
|
|
8
|
+
'company_key_not_a_registrar',
|
|
9
|
+
'app_held_by_another_key',
|
|
10
|
+
'rate_limited',
|
|
11
|
+
];
|
|
4
12
|
/**
|
|
5
|
-
* `registrar:<
|
|
13
|
+
* `registrar:<organisationId>:<appName>` -- deterministic, so a repeat
|
|
6
14
|
* `registerApp` call is the same `issue()` idempotency key, and `revokeApp`
|
|
7
|
-
* can find the row without a table of its own.
|
|
8
|
-
* `
|
|
9
|
-
*
|
|
15
|
+
* can find the row without a table of its own. A company key with no
|
|
16
|
+
* `organisation_id` (older than 0.10.0) uses its own credential id in that
|
|
17
|
+
* place, as before. Both components are `ID_PATTERN`-checked before this is
|
|
18
|
+
* built, so neither can smuggle a colon in and reach across the boundary
|
|
19
|
+
* between them.
|
|
10
20
|
*/
|
|
11
|
-
function scopeKey(
|
|
12
|
-
return `registrar:${
|
|
21
|
+
function scopeKey(scope, appName) {
|
|
22
|
+
return `registrar:${scope}:${appName}`;
|
|
13
23
|
}
|
|
14
24
|
export function createRegistrar(options) {
|
|
15
25
|
const { db, issuer, appGrants, appTtlMs, isRegistrarGrant } = options;
|
|
@@ -32,41 +42,25 @@ export function createRegistrar(options) {
|
|
|
32
42
|
}
|
|
33
43
|
return { ok: false, reason: 'company_key_invalid' };
|
|
34
44
|
}
|
|
45
|
+
// An app key and a revoked key read alike, so a caller cannot tell them apart.
|
|
35
46
|
if (!checked.grants.some(isRegistrarGrant)) {
|
|
36
|
-
return { ok: false, reason: '
|
|
47
|
+
return { ok: false, reason: 'company_key_invalid' };
|
|
37
48
|
}
|
|
38
|
-
return {
|
|
49
|
+
return {
|
|
50
|
+
ok: true,
|
|
51
|
+
companyCredentialId: checked.id,
|
|
52
|
+
scope: checked.organisationId ?? checked.id,
|
|
53
|
+
environment: checked.environment,
|
|
54
|
+
};
|
|
39
55
|
}
|
|
40
|
-
/**
|
|
41
|
-
|
|
42
|
-
* it does not look at `revokedAt`/`expiresAt` (`../issued/index.ts`), so
|
|
43
|
-
* a revoked or expired app would otherwise keep answering every future
|
|
44
|
-
* `registerApp` with its own dead id and `secret: null` forever, and the
|
|
45
|
-
* company could never get a working credential for that name again.
|
|
46
|
-
* Renaming a stale row's `idempotencyKey` away (an ordinary column,
|
|
47
|
-
* unlike the four `keys_issued_guard` freezes) frees the live key for
|
|
48
|
-
* `issue()` to mint a genuinely new credential under, while leaving the
|
|
49
|
-
* old row itself untouched and still in its lineage.
|
|
50
|
-
*/
|
|
51
|
-
async function freeStaleSlot(companyCredentialId, appName) {
|
|
52
|
-
const key = scopeKey(companyCredentialId, appName);
|
|
56
|
+
/** True when a different, live key of the same organisation already holds this app name. */
|
|
57
|
+
async function heldByAnotherKey(scope, companyCredentialId, appName) {
|
|
53
58
|
const [row] = await db
|
|
54
|
-
.select({
|
|
55
|
-
id: keysIssuedCredentials.id,
|
|
56
|
-
revokedAt: keysIssuedCredentials.revokedAt,
|
|
57
|
-
expiresAt: keysIssuedCredentials.expiresAt,
|
|
58
|
-
})
|
|
59
|
+
.select({ id: keysIssuedCredentials.id })
|
|
59
60
|
.from(keysIssuedCredentials)
|
|
60
|
-
.where(eq(keysIssuedCredentials.idempotencyKey,
|
|
61
|
+
.where(and(eq(keysIssuedCredentials.idempotencyKey, scopeKey(scope, appName)), ne(keysIssuedCredentials.issuedById, companyCredentialId), isNull(keysIssuedCredentials.revokedAt), gt(keysIssuedCredentials.expiresAt, now())))
|
|
61
62
|
.limit(1);
|
|
62
|
-
|
|
63
|
-
return;
|
|
64
|
-
if (row.revokedAt === null && row.expiresAt > now())
|
|
65
|
-
return;
|
|
66
|
-
await db
|
|
67
|
-
.update(keysIssuedCredentials)
|
|
68
|
-
.set({ idempotencyKey: `${key}:superseded:${row.id}` })
|
|
69
|
-
.where(eq(keysIssuedCredentials.id, row.id));
|
|
63
|
+
return row !== undefined;
|
|
70
64
|
}
|
|
71
65
|
async function registerApp(companySecret, appName) {
|
|
72
66
|
if (!ID_PATTERN.test(appName))
|
|
@@ -74,13 +68,23 @@ export function createRegistrar(options) {
|
|
|
74
68
|
const scoped = await checkCompanyKey(companySecret);
|
|
75
69
|
if (!scoped.ok)
|
|
76
70
|
return scoped;
|
|
77
|
-
await
|
|
71
|
+
if (await heldByAnotherKey(scoped.scope, scoped.companyCredentialId, appName)) {
|
|
72
|
+
return { ok: false, reason: 'app_held_by_another_key' };
|
|
73
|
+
}
|
|
74
|
+
// An app cannot outlive its company key (`issue()` refuses it), so a key
|
|
75
|
+
// with less life left than `appTtlMs` gives its apps the rest of its own.
|
|
76
|
+
const [company] = await db
|
|
77
|
+
.select({ expiresAt: keysIssuedCredentials.expiresAt })
|
|
78
|
+
.from(keysIssuedCredentials)
|
|
79
|
+
.where(eq(keysIssuedCredentials.id, scoped.companyCredentialId))
|
|
80
|
+
.limit(1);
|
|
78
81
|
const result = await issuer.issue({
|
|
79
82
|
grants: appGrants,
|
|
80
83
|
minter: scoped.companyCredentialId,
|
|
81
|
-
expiresAt: now() + appTtlMs,
|
|
84
|
+
expiresAt: Math.min(now() + appTtlMs, company?.expiresAt ?? Number.POSITIVE_INFINITY),
|
|
82
85
|
environment: scoped.environment,
|
|
83
|
-
idempotencyKey: scopeKey(scoped.
|
|
86
|
+
idempotencyKey: scopeKey(scoped.scope, appName),
|
|
87
|
+
replaceStale: true,
|
|
84
88
|
});
|
|
85
89
|
if (!result.ok)
|
|
86
90
|
return result;
|
|
@@ -99,7 +103,7 @@ export function createRegistrar(options) {
|
|
|
99
103
|
revokedAt: keysIssuedCredentials.revokedAt,
|
|
100
104
|
})
|
|
101
105
|
.from(keysIssuedCredentials)
|
|
102
|
-
.where(eq(keysIssuedCredentials.idempotencyKey, scopeKey(scoped.
|
|
106
|
+
.where(and(eq(keysIssuedCredentials.idempotencyKey, scopeKey(scoped.scope, appName)), eq(keysIssuedCredentials.issuedById, scoped.companyCredentialId)))
|
|
103
107
|
.limit(1);
|
|
104
108
|
// Scoped twice: by the idempotency key (unique per company+app already)
|
|
105
109
|
// and, belt and suspenders, by `issuedById` -- so a lookup can never
|
|
@@ -112,8 +116,10 @@ export function createRegistrar(options) {
|
|
|
112
116
|
// No app credential this registrar mints is ever a minter of its own --
|
|
113
117
|
// it is always a leaf under the company credential -- so cascading has
|
|
114
118
|
// nothing to reach beyond the row itself.
|
|
115
|
-
await issuer.
|
|
116
|
-
|
|
119
|
+
const revoked = await issuer.revokeForCompany(row.id, { cascade: false });
|
|
120
|
+
if (!revoked.ok)
|
|
121
|
+
return revoked;
|
|
122
|
+
return { ok: true, revoked: revoked.revoked.length > 0 };
|
|
117
123
|
}
|
|
118
124
|
return { registerApp, revokeApp };
|
|
119
125
|
}
|
|
@@ -128,10 +134,15 @@ function statusForRegistrar(reason) {
|
|
|
128
134
|
case 'expires_at_required':
|
|
129
135
|
case 'expires_at_past':
|
|
130
136
|
case 'environment_mismatch':
|
|
137
|
+
case 'expires_after_minter':
|
|
131
138
|
return 400;
|
|
132
139
|
case 'company_key_invalid':
|
|
133
140
|
return 401;
|
|
134
141
|
case 'company_key_not_a_registrar':
|
|
142
|
+
case 'protected_credential':
|
|
143
|
+
case 'purpose_unknown':
|
|
144
|
+
case 'purpose_not_allowed':
|
|
145
|
+
case 'organisation_mismatch':
|
|
135
146
|
case 'minter_not_found':
|
|
136
147
|
case 'minter_revoked':
|
|
137
148
|
case 'minter_expired':
|
|
@@ -140,6 +151,11 @@ function statusForRegistrar(reason) {
|
|
|
140
151
|
return 429;
|
|
141
152
|
case 'app_not_found':
|
|
142
153
|
return 404;
|
|
154
|
+
case 'app_held_by_another_key':
|
|
155
|
+
case 'idempotency_conflict':
|
|
156
|
+
case 'idempotent_row_revoked':
|
|
157
|
+
case 'idempotent_row_expired':
|
|
158
|
+
return 409;
|
|
143
159
|
// Raw Worker codes surfaced by `issue()`: none of them is something the
|
|
144
160
|
// caller can fix by changing the request. They are a fault between this
|
|
145
161
|
// host and its signing Worker, so they answer 502, not a refusal.
|
|
@@ -151,6 +167,8 @@ function statusForRegistrar(reason) {
|
|
|
151
167
|
case 'aad_mismatch':
|
|
152
168
|
case 'unknown_generation':
|
|
153
169
|
case 'bad_minter_signature':
|
|
170
|
+
case 'minter_exceeded':
|
|
171
|
+
case 'bad_worker_signature':
|
|
154
172
|
case 'lineage_mismatch':
|
|
155
173
|
case 'bad_old_signature':
|
|
156
174
|
case 'unlogged_row':
|
|
@@ -170,6 +188,9 @@ const MESSAGES = {
|
|
|
170
188
|
company_key_invalid: 'The company key was not accepted. Check that you are sending the current key as a Bearer token; if it was rotated or revoked, ask for a new one.',
|
|
171
189
|
company_key_not_a_registrar: 'This key belongs to an app, not to a company, so it cannot register apps. Use the company key.',
|
|
172
190
|
rate_limited: 'Too many attempts. Please wait a little and try again.',
|
|
191
|
+
app_held_by_another_key: 'Another key of this company already registered an app with that name. Use a different name, or ask that key to remove it first.',
|
|
192
|
+
protected_credential: 'This key is a company root and cannot be removed here. We can roll it to a new secret for you instead.',
|
|
193
|
+
purpose_unknown: 'We have not yet marked what this key is for, so we left it as it is. Ask the operator to finish setting it up, then try again.',
|
|
173
194
|
app_not_found: 'No app with that name is registered under this company key.',
|
|
174
195
|
expires_at_required: 'The app credential could not be given an expiry. Contact the operator.',
|
|
175
196
|
expires_at_past: 'The app credential could not be given an expiry. Contact the operator.',
|
|
@@ -177,6 +198,7 @@ const MESSAGES = {
|
|
|
177
198
|
minter_not_found: 'The company key is no longer known. Ask for a new company key and register again.',
|
|
178
199
|
minter_revoked: 'The company key has been revoked. Ask for a new company key and register again.',
|
|
179
200
|
minter_expired: 'The company key has expired. Ask for a new company key and register again.',
|
|
201
|
+
minter_exceeded: 'The company key needs to be renewed before it can register this app. Ask the operator for a new company key and register again.',
|
|
180
202
|
};
|
|
181
203
|
const UNAVAILABLE_MESSAGE = 'The key service could not complete this request. Nothing was changed that you need to undo; try again in a moment, and contact the operator if it keeps happening.';
|
|
182
204
|
function messageFor(reason) {
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `runRotationSweep` (docs/contracts.md C3): the sweep a host runs from its
|
|
3
|
+
* migrate container after `rotate-host.mjs start`. It moves every wrapped key
|
|
4
|
+
* onto the new wrap key id and every signed row onto the new signing
|
|
5
|
+
* generation, then counts what is left and reports it. `promote` reads that
|
|
6
|
+
* report.
|
|
7
|
+
*
|
|
8
|
+
* The counts come from the stored labels, not from the ids the sweep was told
|
|
9
|
+
* about, so a version left under an id nobody named still shows up.
|
|
10
|
+
*/
|
|
11
|
+
import { type HeldKeys } from '../held/index.js';
|
|
12
|
+
import type { SigningGenerationMigrator } from '../issued/resign.js';
|
|
13
|
+
export interface RotationSweepOptions {
|
|
14
|
+
readonly hostId: string;
|
|
15
|
+
readonly kekIdNew: string;
|
|
16
|
+
readonly sigIdNew: string;
|
|
17
|
+
/** Built with an operator database handle and a credential holding `rewrap`. Leave out for a host that holds no wrapped keys. */
|
|
18
|
+
readonly held?: Pick<HeldKeys, 'rewrap' | 'countNotUnder' | 'kekIdsInUse'>;
|
|
19
|
+
/** Built with a credential holding `resign`. Leave out for a host that signs nothing, such as an `app-*` host. */
|
|
20
|
+
readonly migrator?: Pick<SigningGenerationMigrator, 'resignBatch' | 'countNotGeneration' | 'generationsInUse'>;
|
|
21
|
+
/** The public key of `sigIdNew`. Required with `migrator`. */
|
|
22
|
+
readonly targetPublicKey?: Uint8Array;
|
|
23
|
+
/** Unix milliseconds. Defaults to `Date.now`. */
|
|
24
|
+
readonly now?: () => number;
|
|
25
|
+
}
|
|
26
|
+
/** What `promote --report` reads. */
|
|
27
|
+
export interface RotationSweepReport {
|
|
28
|
+
readonly version: 1;
|
|
29
|
+
readonly hostId: string;
|
|
30
|
+
readonly kekIdNew: string;
|
|
31
|
+
readonly sigIdNew: string;
|
|
32
|
+
readonly rewrapped: number;
|
|
33
|
+
readonly resigned: number;
|
|
34
|
+
readonly remainingWrapped: number;
|
|
35
|
+
readonly remainingSigned: number;
|
|
36
|
+
/** Whether the held-key sweep ran (`held` was given). When false, `remainingWrapped` is 0 because nothing was counted. */
|
|
37
|
+
readonly heldSwept: boolean;
|
|
38
|
+
/** Whether the signing sweep ran (`migrator` was given). When false, `remainingSigned` is 0 because nothing was counted. */
|
|
39
|
+
readonly signedSwept: boolean;
|
|
40
|
+
/** Unix milliseconds. */
|
|
41
|
+
readonly finishedAt: number;
|
|
42
|
+
}
|
|
43
|
+
export type RotationSweepResult = {
|
|
44
|
+
readonly ok: true;
|
|
45
|
+
readonly report: RotationSweepReport;
|
|
46
|
+
} | {
|
|
47
|
+
readonly ok: false;
|
|
48
|
+
readonly step: 'rewrap' | 'resign' | 'input';
|
|
49
|
+
readonly reason: string;
|
|
50
|
+
/** The key id or generation being moved when it stopped. */
|
|
51
|
+
readonly from?: string;
|
|
52
|
+
/** Moved before it stopped. Nothing here is a report: do not promote. */
|
|
53
|
+
readonly rewrapped: number;
|
|
54
|
+
readonly resigned: number;
|
|
55
|
+
};
|
|
56
|
+
export declare function runRotationSweep(options: RotationSweepOptions): Promise<RotationSweepResult>;
|