@wtfalch/keys 0.8.0 → 0.12.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +248 -8
- package/dist/held/index.d.ts +116 -6
- package/dist/held/index.js +247 -25
- package/dist/held/schema.d.ts +17 -0
- package/dist/held/schema.js +12 -0
- package/dist/held/shred.d.ts +6 -0
- package/dist/held/shred.js +6 -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 +55 -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/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/testing/index.d.ts +3 -0
- package/dist/testing/index.js +3 -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 -3
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { ServiceError, type ServiceErrorCode } from '@wtfalch/contracts';
|
|
2
|
+
import { type HeldKeysErrorCode } from '../held/index.js';
|
|
3
|
+
import type { IssueRefusalReason, RevokeForCompanyResult, RotateRefusalReason } from '../issued/index.js';
|
|
4
|
+
type RevokeRefusal = Extract<RevokeForCompanyResult, {
|
|
5
|
+
ok: false;
|
|
6
|
+
}>['reason'];
|
|
7
|
+
/** Every refusal name the library can hand `toServiceError`. */
|
|
8
|
+
export type Refusal = IssueRefusalReason | RotateRefusalReason | RevokeRefusal | HeldKeysErrorCode;
|
|
9
|
+
/**
|
|
10
|
+
* The closed table. A new member in any refusal union is a type error here until it has a row,
|
|
11
|
+
* and `service.test.ts` fails the same way at run time. The refusals that stay with the caller are
|
|
12
|
+
* `invalid_request`, `not_found`, `conflict`, `forbidden` and `rate_limited`. Everything the
|
|
13
|
+
* caller cannot fix, and anything about the Worker, is `unavailable`.
|
|
14
|
+
*/
|
|
15
|
+
export declare const REFUSAL_CODES: Readonly<Record<Refusal, ServiceErrorCode>>;
|
|
16
|
+
/**
|
|
17
|
+
* The one place a library refusal or a thrown value becomes a `ServiceError`. `message` is the
|
|
18
|
+
* refusal's name and nothing else, and `reason` repeats it where the refusal has one, so the
|
|
19
|
+
* caller can tell two `conflict`s apart. An unknown refusal, or any throw that is not a
|
|
20
|
+
* `ServiceError` or a `HeldKeysError`, is `unavailable` with one fixed log line that names the
|
|
21
|
+
* class and never the message.
|
|
22
|
+
*/
|
|
23
|
+
export declare function toServiceError(failure: unknown, retryAfterMs?: number): ServiceError;
|
|
24
|
+
export {};
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
import { ServiceError } from '@wtfalch/contracts';
|
|
2
|
+
import { HeldKeysError } from '../held/index.js';
|
|
3
|
+
/**
|
|
4
|
+
* The closed table. A new member in any refusal union is a type error here until it has a row,
|
|
5
|
+
* and `service.test.ts` fails the same way at run time. The refusals that stay with the caller are
|
|
6
|
+
* `invalid_request`, `not_found`, `conflict`, `forbidden` and `rate_limited`. Everything the
|
|
7
|
+
* caller cannot fix, and anything about the Worker, is `unavailable`.
|
|
8
|
+
*/
|
|
9
|
+
export const REFUSAL_CODES = {
|
|
10
|
+
// issue
|
|
11
|
+
expires_at_required: 'invalid_request',
|
|
12
|
+
expires_at_past: 'invalid_request',
|
|
13
|
+
minter_not_found: 'not_found',
|
|
14
|
+
minter_revoked: 'forbidden',
|
|
15
|
+
minter_expired: 'forbidden',
|
|
16
|
+
expires_after_minter: 'invalid_request',
|
|
17
|
+
purpose_not_allowed: 'invalid_request',
|
|
18
|
+
organisation_mismatch: 'invalid_request',
|
|
19
|
+
idempotency_conflict: 'conflict',
|
|
20
|
+
idempotent_row_revoked: 'conflict',
|
|
21
|
+
idempotent_row_expired: 'conflict',
|
|
22
|
+
environment_mismatch: 'invalid_request',
|
|
23
|
+
bad_worker_signature: 'unavailable',
|
|
24
|
+
// rotate
|
|
25
|
+
signature_invalid: 'unavailable',
|
|
26
|
+
conflict: 'conflict',
|
|
27
|
+
not_found: 'not_found',
|
|
28
|
+
revoked: 'conflict',
|
|
29
|
+
// revoke
|
|
30
|
+
protected_credential: 'conflict',
|
|
31
|
+
purpose_unknown: 'conflict',
|
|
32
|
+
// held
|
|
33
|
+
unseal_failed: 'unavailable',
|
|
34
|
+
disposed: 'unavailable',
|
|
35
|
+
invalidated: 'unavailable',
|
|
36
|
+
forbidden: 'forbidden',
|
|
37
|
+
// the Worker
|
|
38
|
+
credential_invalid: 'unavailable',
|
|
39
|
+
credential_expired: 'unavailable',
|
|
40
|
+
credential_revoked: 'unavailable',
|
|
41
|
+
grant_missing: 'unavailable',
|
|
42
|
+
rate_limited: 'rate_limited',
|
|
43
|
+
bad_request: 'invalid_request',
|
|
44
|
+
aad_mismatch: 'unavailable',
|
|
45
|
+
unknown_generation: 'unavailable',
|
|
46
|
+
bad_minter_signature: 'unavailable',
|
|
47
|
+
minter_exceeded: 'forbidden',
|
|
48
|
+
lineage_mismatch: 'unavailable',
|
|
49
|
+
bad_old_signature: 'unavailable',
|
|
50
|
+
unlogged_row: 'unavailable',
|
|
51
|
+
not_in_lineage: 'unavailable',
|
|
52
|
+
unreachable: 'unavailable',
|
|
53
|
+
};
|
|
54
|
+
const CLASS_NAME = /^[A-Za-z][A-Za-z0-9_$]{0,63}$/;
|
|
55
|
+
/** The class of a thrown value, never its message or any field of it. */
|
|
56
|
+
function className(error) {
|
|
57
|
+
const name = error?.constructor?.name;
|
|
58
|
+
return typeof name === 'string' && CLASS_NAME.test(name) ? name : 'non-error';
|
|
59
|
+
}
|
|
60
|
+
function unavailable(detail) {
|
|
61
|
+
console.error(`keys-service: unavailable (${detail})`);
|
|
62
|
+
return new ServiceError('unavailable', 'unavailable');
|
|
63
|
+
}
|
|
64
|
+
function isRefusal(value) {
|
|
65
|
+
return typeof value === 'string' && Object.hasOwn(REFUSAL_CODES, value);
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
68
|
+
* The one place a library refusal or a thrown value becomes a `ServiceError`. `message` is the
|
|
69
|
+
* refusal's name and nothing else, and `reason` repeats it where the refusal has one, so the
|
|
70
|
+
* caller can tell two `conflict`s apart. An unknown refusal, or any throw that is not a
|
|
71
|
+
* `ServiceError` or a `HeldKeysError`, is `unavailable` with one fixed log line that names the
|
|
72
|
+
* class and never the message.
|
|
73
|
+
*/
|
|
74
|
+
export function toServiceError(failure, retryAfterMs) {
|
|
75
|
+
if (failure instanceof ServiceError)
|
|
76
|
+
return failure;
|
|
77
|
+
if (failure instanceof HeldKeysError)
|
|
78
|
+
return toServiceError(failure.code, failure.retryAfterMs);
|
|
79
|
+
if (isRefusal(failure)) {
|
|
80
|
+
const code = REFUSAL_CODES[failure];
|
|
81
|
+
if (code === 'unavailable')
|
|
82
|
+
return unavailable(failure);
|
|
83
|
+
const seconds = code === 'rate_limited' && retryAfterMs !== undefined && Number.isFinite(retryAfterMs)
|
|
84
|
+
? Math.max(1, Math.ceil(retryAfterMs / 1000))
|
|
85
|
+
: undefined;
|
|
86
|
+
return new ServiceError(code, failure, seconds, failure === code ? undefined : failure);
|
|
87
|
+
}
|
|
88
|
+
return unavailable(className(failure));
|
|
89
|
+
}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import type { ResourceAccess } from '@wtfalch/authz';
|
|
2
|
+
import { type Db, type RateLimiter, type SerializedCredential, type VerifyKeys, type WorkerClient } from '../issued/index.js';
|
|
3
|
+
export declare const DEFAULT_WORKER_TIMEOUT_MS = 5000;
|
|
4
|
+
/** What the host's token check yields. The handler never reads a token. */
|
|
5
|
+
export interface Principal {
|
|
6
|
+
readonly applicationId: string;
|
|
7
|
+
readonly platformId: string;
|
|
8
|
+
readonly access: Pick<ResourceAccess, 'allows'>;
|
|
9
|
+
}
|
|
10
|
+
export interface CreateKeysHandlerOptions<TGrant> {
|
|
11
|
+
/** The runtime role's connection. */
|
|
12
|
+
readonly db: Db;
|
|
13
|
+
/** The caller, or `null` for 401. A throw is `unavailable`. */
|
|
14
|
+
readonly principal: (request: Request) => Promise<Principal | null> | Principal | null;
|
|
15
|
+
readonly worker: Pick<WorkerClient<TGrant>, 'wrap' | 'unwrap' | 'rewrap' | 'signRow'>;
|
|
16
|
+
readonly credential: SerializedCredential;
|
|
17
|
+
readonly verifyKeys: VerifyKeys;
|
|
18
|
+
/** This host's split-secret prefix, e.g. `ai_live_`. */
|
|
19
|
+
readonly prefix: string;
|
|
20
|
+
/** Bearer token for `GET /v1/keys/audit`. Unset or short, the route answers 503. */
|
|
21
|
+
readonly auditToken: string | undefined;
|
|
22
|
+
/** The mount path, e.g. `/keys`. Default empty. */
|
|
23
|
+
readonly basePath?: string;
|
|
24
|
+
readonly rateLimiter?: RateLimiter;
|
|
25
|
+
readonly now?: () => number;
|
|
26
|
+
/** Bound on every Worker call. Default 5 seconds. */
|
|
27
|
+
readonly workerTimeoutMs?: number;
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* `createKeysHandler(...)` returns `(request) => Promise<Response>` for the keys routes of C7
|
|
31
|
+
* (docs/contracts.md). Every route runs in one order: principal, a bounded body, authorization on
|
|
32
|
+
* the scoping id alone, the other fields, then the library. A refusal at any step is the error
|
|
33
|
+
* envelope of `@wtfalch/contracts`. Nothing escapes as a raw 500.
|
|
34
|
+
*/
|
|
35
|
+
export declare function createKeysHandler<TGrant = unknown>(options: CreateKeysHandlerOptions<TGrant>): (request: Request) => Promise<Response>;
|
|
@@ -0,0 +1,328 @@
|
|
|
1
|
+
import { ServiceError, serviceErrorResponse } from '@wtfalch/contracts';
|
|
2
|
+
import { createHeldKeys, shredExpired } from '../held/index.js';
|
|
3
|
+
import { auditEndpoint, recordEvent, recordEventInTransaction } from '../host/index.js';
|
|
4
|
+
import { createCredentialIssuer, } from '../issued/index.js';
|
|
5
|
+
import { graceField, grantsField, idField, numberField, onlyFields, optionalBooleanField, optionalEnvironmentField, optionalIdField, optionalKeyField, queryFields, readObjectBody, secretField, textField, } from './body.js';
|
|
6
|
+
import { toServiceError } from './errors.js';
|
|
7
|
+
import { withWorkerTimeout } from './timeout.js';
|
|
8
|
+
export const DEFAULT_WORKER_TIMEOUT_MS = 5_000;
|
|
9
|
+
function json(data, status = 200) {
|
|
10
|
+
return Response.json(data, { status, headers: { 'cache-control': 'no-store' } });
|
|
11
|
+
}
|
|
12
|
+
/** A route states its parse and its run once each; the table keeps one shape. */
|
|
13
|
+
function defineRoute(route) {
|
|
14
|
+
return {
|
|
15
|
+
...route,
|
|
16
|
+
run: (ctx, scopeId, input, id) => {
|
|
17
|
+
onlyFields(input, route.fields);
|
|
18
|
+
return route.run(ctx, scopeId, route.parse(input, id), id);
|
|
19
|
+
},
|
|
20
|
+
};
|
|
21
|
+
}
|
|
22
|
+
/** The `:id` of a path, held to the same shape as every other id. */
|
|
23
|
+
function pathIdOf(id) {
|
|
24
|
+
return idField({ id }, 'id');
|
|
25
|
+
}
|
|
26
|
+
function routeTable() {
|
|
27
|
+
return [
|
|
28
|
+
defineRoute({
|
|
29
|
+
method: 'POST',
|
|
30
|
+
path: '/v1/issued/issue',
|
|
31
|
+
permission: 'keys:issue',
|
|
32
|
+
resource: 'keys.credential',
|
|
33
|
+
scope: 'organisationId',
|
|
34
|
+
input: 'body',
|
|
35
|
+
fields: ['organisationId', 'grants', 'minter', 'expiresAt', 'idempotencyKey', 'environment'],
|
|
36
|
+
parse: (input) => ({
|
|
37
|
+
grants: grantsField(input, 'grants'),
|
|
38
|
+
minter: optionalIdField(input, 'minter'),
|
|
39
|
+
expiresAt: numberField(input, 'expiresAt'),
|
|
40
|
+
idempotencyKey: optionalKeyField(input, 'idempotencyKey'),
|
|
41
|
+
environment: optionalEnvironmentField(input, 'environment'),
|
|
42
|
+
}),
|
|
43
|
+
async run(ctx, organisationId, p) {
|
|
44
|
+
// A minter of another organisation is a missing minter.
|
|
45
|
+
if (p.minter !== null && !(await ctx.chainOf(p.minter, organisationId))) {
|
|
46
|
+
throw toServiceError('minter_not_found');
|
|
47
|
+
}
|
|
48
|
+
const result = await ctx.issuer.issue({
|
|
49
|
+
grants: p.grants,
|
|
50
|
+
minter: p.minter,
|
|
51
|
+
expiresAt: p.expiresAt,
|
|
52
|
+
// A root's key is unique across the table, so another organisation's key must not meet it.
|
|
53
|
+
idempotencyKey: p.idempotencyKey === undefined ? undefined : `${organisationId}:${p.idempotencyKey}`,
|
|
54
|
+
environment: p.environment,
|
|
55
|
+
organisationId,
|
|
56
|
+
purpose: 'ordinary',
|
|
57
|
+
});
|
|
58
|
+
if (!result.ok)
|
|
59
|
+
throw toServiceError(result.reason, result.retryAfterMs);
|
|
60
|
+
const row = (await ctx.chainOf(result.id, organisationId))?.[0];
|
|
61
|
+
if (!row)
|
|
62
|
+
throw toServiceError('not_found');
|
|
63
|
+
return json({ id: result.id, secret: result.secret, expiresAt: row.expiresAt }, result.secret === null ? 200 : 201);
|
|
64
|
+
},
|
|
65
|
+
}),
|
|
66
|
+
defineRoute({
|
|
67
|
+
method: 'POST',
|
|
68
|
+
path: '/v1/issued/verify',
|
|
69
|
+
permission: 'keys:verify',
|
|
70
|
+
resource: 'keys.credential',
|
|
71
|
+
scope: 'organisationId',
|
|
72
|
+
input: 'body',
|
|
73
|
+
fields: ['organisationId', 'secret'],
|
|
74
|
+
parse: (input) => secretField(input, 'secret'),
|
|
75
|
+
async run(ctx, organisationId, secret) {
|
|
76
|
+
const result = await ctx.issuer.check(secret, { organisationId });
|
|
77
|
+
if (!result.ok) {
|
|
78
|
+
if (result.reason === 'rate_limited') {
|
|
79
|
+
throw toServiceError('rate_limited', result.retryAfterMs);
|
|
80
|
+
}
|
|
81
|
+
return json({ valid: false, reason: result.reason });
|
|
82
|
+
}
|
|
83
|
+
const row = (await ctx.chainOf(result.id, organisationId))?.[0];
|
|
84
|
+
if (!row)
|
|
85
|
+
return json({ valid: false, reason: 'not_found' });
|
|
86
|
+
return json({
|
|
87
|
+
valid: true,
|
|
88
|
+
id: result.id,
|
|
89
|
+
grants: result.grants,
|
|
90
|
+
expiresAt: row.expiresAt,
|
|
91
|
+
});
|
|
92
|
+
},
|
|
93
|
+
}),
|
|
94
|
+
defineRoute({
|
|
95
|
+
method: 'POST',
|
|
96
|
+
path: '/v1/issued/:id/rotate',
|
|
97
|
+
permission: 'keys:rotate',
|
|
98
|
+
resource: 'keys.credential',
|
|
99
|
+
scope: 'organisationId',
|
|
100
|
+
input: 'body',
|
|
101
|
+
fields: ['organisationId', 'graceMs'],
|
|
102
|
+
parse: (input, id) => {
|
|
103
|
+
pathIdOf(id);
|
|
104
|
+
return graceField(input, 'graceMs');
|
|
105
|
+
},
|
|
106
|
+
async run(ctx, organisationId, graceMs, id) {
|
|
107
|
+
const chain = await ctx.chainOf(id, organisationId);
|
|
108
|
+
// A platform master is the platform's, whatever organisation its row carries.
|
|
109
|
+
if (!chain || chain[0]?.purpose === 'platform_master')
|
|
110
|
+
throw toServiceError('not_found');
|
|
111
|
+
const result = await ctx.issuer.rotate(id, { graceMs });
|
|
112
|
+
if (!result.ok)
|
|
113
|
+
throw toServiceError(result.reason, result.retryAfterMs);
|
|
114
|
+
return json({ id, secret: result.secret });
|
|
115
|
+
},
|
|
116
|
+
}),
|
|
117
|
+
defineRoute({
|
|
118
|
+
method: 'POST',
|
|
119
|
+
path: '/v1/issued/:id/revoke',
|
|
120
|
+
permission: 'keys:revoke',
|
|
121
|
+
resource: 'keys.credential',
|
|
122
|
+
scope: 'organisationId',
|
|
123
|
+
input: 'body',
|
|
124
|
+
fields: ['organisationId', 'cascade'],
|
|
125
|
+
parse: (input, id) => {
|
|
126
|
+
pathIdOf(id);
|
|
127
|
+
return optionalBooleanField(input, 'cascade');
|
|
128
|
+
},
|
|
129
|
+
async run(ctx, organisationId, cascade, id) {
|
|
130
|
+
if (!(await ctx.chainOf(id, organisationId)))
|
|
131
|
+
throw toServiceError('not_found');
|
|
132
|
+
// Never `revoke`: that one reaches protected roots.
|
|
133
|
+
const result = await ctx.issuer.revokeForCompany(id, cascade === undefined ? { organisationId } : { cascade, organisationId });
|
|
134
|
+
if (!result.ok)
|
|
135
|
+
throw toServiceError(result.reason);
|
|
136
|
+
return json({ revoked: result.revoked });
|
|
137
|
+
},
|
|
138
|
+
}),
|
|
139
|
+
defineRoute({
|
|
140
|
+
method: 'GET',
|
|
141
|
+
path: '/v1/issued/:id/lineage',
|
|
142
|
+
permission: 'keys:lineage',
|
|
143
|
+
resource: 'keys.credential',
|
|
144
|
+
scope: 'organisationId',
|
|
145
|
+
input: 'query',
|
|
146
|
+
fields: ['organisationId'],
|
|
147
|
+
parse: (_input, id) => pathIdOf(id),
|
|
148
|
+
async run(ctx, organisationId, id) {
|
|
149
|
+
const chain = await ctx.chainOf(id, organisationId);
|
|
150
|
+
if (!chain)
|
|
151
|
+
throw toServiceError('not_found');
|
|
152
|
+
// The wire carries the fields of `LineageLink` in `@wtfalch/keys-client`, not `purpose`.
|
|
153
|
+
return json({
|
|
154
|
+
chain: chain.map((l) => ({
|
|
155
|
+
id: l.id,
|
|
156
|
+
issuedById: l.issuedById,
|
|
157
|
+
grants: l.grants,
|
|
158
|
+
expiresAt: l.expiresAt,
|
|
159
|
+
revokedAt: l.revokedAt,
|
|
160
|
+
environment: l.environment,
|
|
161
|
+
})),
|
|
162
|
+
});
|
|
163
|
+
},
|
|
164
|
+
}),
|
|
165
|
+
defineRoute({
|
|
166
|
+
method: 'POST',
|
|
167
|
+
path: '/v1/held/put',
|
|
168
|
+
permission: 'keys:put',
|
|
169
|
+
resource: 'keys.held',
|
|
170
|
+
scope: 'tenantId',
|
|
171
|
+
input: 'body',
|
|
172
|
+
fields: ['tenantId', 'entryId', 'value'],
|
|
173
|
+
parse: (input) => ({
|
|
174
|
+
entryId: idField(input, 'entryId'),
|
|
175
|
+
value: textField(input, 'value'),
|
|
176
|
+
}),
|
|
177
|
+
async run(ctx, tenantId, p) {
|
|
178
|
+
const { version } = await ctx.held.put({ tenantId, entryId: p.entryId }, p.value);
|
|
179
|
+
return json({ version }, 201);
|
|
180
|
+
},
|
|
181
|
+
}),
|
|
182
|
+
defineRoute({
|
|
183
|
+
method: 'POST',
|
|
184
|
+
path: '/v1/held/revoke',
|
|
185
|
+
permission: 'keys:held-revoke',
|
|
186
|
+
resource: 'keys.held',
|
|
187
|
+
scope: 'tenantId',
|
|
188
|
+
input: 'body',
|
|
189
|
+
fields: ['tenantId', 'entryId'],
|
|
190
|
+
parse: (input) => idField(input, 'entryId'),
|
|
191
|
+
async run(ctx, tenantId, entryId) {
|
|
192
|
+
await ctx.held.revokeEntry({ tenantId, entryId });
|
|
193
|
+
return json({ revoked: true });
|
|
194
|
+
},
|
|
195
|
+
}),
|
|
196
|
+
defineRoute({
|
|
197
|
+
method: 'POST',
|
|
198
|
+
path: '/v1/held/shred',
|
|
199
|
+
permission: 'keys:shred',
|
|
200
|
+
resource: 'keys.held',
|
|
201
|
+
scope: null,
|
|
202
|
+
input: 'none',
|
|
203
|
+
fields: [],
|
|
204
|
+
parse: () => null,
|
|
205
|
+
async run(ctx) {
|
|
206
|
+
return json({ shredded: await ctx.shred() });
|
|
207
|
+
},
|
|
208
|
+
}),
|
|
209
|
+
];
|
|
210
|
+
}
|
|
211
|
+
function normaliseBasePath(basePath) {
|
|
212
|
+
const path = basePath ?? '';
|
|
213
|
+
if (!/^(\/[A-Za-z0-9._~-]+)*$/.test(path)) {
|
|
214
|
+
throw new RangeError('basePath must be empty, or start with / and have no trailing /');
|
|
215
|
+
}
|
|
216
|
+
return path;
|
|
217
|
+
}
|
|
218
|
+
/** Matches `/v1/issued/:id/rotate` against a path: the `:id` segment ('' when the pattern has none), or `undefined` for a different path. */
|
|
219
|
+
function matchPath(pattern, pathname) {
|
|
220
|
+
const want = pattern.split('/');
|
|
221
|
+
const have = pathname.split('/');
|
|
222
|
+
if (want.length !== have.length)
|
|
223
|
+
return undefined;
|
|
224
|
+
let id = '';
|
|
225
|
+
for (let i = 0; i < want.length; i++) {
|
|
226
|
+
if (want[i] === ':id')
|
|
227
|
+
id = have[i];
|
|
228
|
+
else if (want[i] !== have[i])
|
|
229
|
+
return undefined;
|
|
230
|
+
}
|
|
231
|
+
return id;
|
|
232
|
+
}
|
|
233
|
+
function resourceFor(caller, route, scopeId, id) {
|
|
234
|
+
return {
|
|
235
|
+
id: id !== '' ? id : scopeId !== '' ? scopeId : 'keys-held',
|
|
236
|
+
type: route.resource,
|
|
237
|
+
applicationId: caller.applicationId,
|
|
238
|
+
platformId: caller.platformId,
|
|
239
|
+
organisationId: route.scope === null ? null : scopeId,
|
|
240
|
+
teamId: null,
|
|
241
|
+
};
|
|
242
|
+
}
|
|
243
|
+
/**
|
|
244
|
+
* `createKeysHandler(...)` returns `(request) => Promise<Response>` for the keys routes of C7
|
|
245
|
+
* (docs/contracts.md). Every route runs in one order: principal, a bounded body, authorization on
|
|
246
|
+
* the scoping id alone, the other fields, then the library. A refusal at any step is the error
|
|
247
|
+
* envelope of `@wtfalch/contracts`. Nothing escapes as a raw 500.
|
|
248
|
+
*/
|
|
249
|
+
export function createKeysHandler(options) {
|
|
250
|
+
const basePath = normaliseBasePath(options.basePath);
|
|
251
|
+
const worker = withWorkerTimeout(options.worker, options.workerTimeoutMs ?? DEFAULT_WORKER_TIMEOUT_MS);
|
|
252
|
+
const issuer = createCredentialIssuer({
|
|
253
|
+
db: options.db,
|
|
254
|
+
worker,
|
|
255
|
+
credential: options.credential,
|
|
256
|
+
verifyKeys: options.verifyKeys,
|
|
257
|
+
prefix: options.prefix,
|
|
258
|
+
auditInTransaction: recordEventInTransaction,
|
|
259
|
+
rateLimiter: options.rateLimiter,
|
|
260
|
+
now: options.now,
|
|
261
|
+
});
|
|
262
|
+
const now = options.now ?? Date.now;
|
|
263
|
+
const held = createHeldKeys({
|
|
264
|
+
db: options.db,
|
|
265
|
+
worker,
|
|
266
|
+
credential: options.credential,
|
|
267
|
+
// No route opens a value, so `key.used` is never emitted here.
|
|
268
|
+
audit: (event) => recordEvent(options.db, event),
|
|
269
|
+
auditInTransaction: (tx, event) => recordEvent(tx, event),
|
|
270
|
+
now,
|
|
271
|
+
});
|
|
272
|
+
const ctx = {
|
|
273
|
+
issuer,
|
|
274
|
+
held,
|
|
275
|
+
shred: () => options.db.transaction(async (tx) => {
|
|
276
|
+
const shredded = await shredExpired(tx);
|
|
277
|
+
await recordEvent(tx, { name: 'held.shredded', at: now() });
|
|
278
|
+
return shredded;
|
|
279
|
+
}),
|
|
280
|
+
async chainOf(id, organisationId) {
|
|
281
|
+
const chain = [];
|
|
282
|
+
for (const link of await issuer.lineageOf(id)) {
|
|
283
|
+
if (link.organisationId !== organisationId)
|
|
284
|
+
break;
|
|
285
|
+
chain.push(link);
|
|
286
|
+
}
|
|
287
|
+
return chain[0]?.id === id ? chain : undefined;
|
|
288
|
+
},
|
|
289
|
+
};
|
|
290
|
+
const routes = routeTable();
|
|
291
|
+
const audit = auditEndpoint({ db: options.db, token: options.auditToken, now: options.now });
|
|
292
|
+
const auditPath = `${basePath}/v1/keys/audit`;
|
|
293
|
+
return async (request) => {
|
|
294
|
+
try {
|
|
295
|
+
const url = new URL(request.url);
|
|
296
|
+
if (url.pathname === auditPath)
|
|
297
|
+
return await audit(request);
|
|
298
|
+
const caller = await options.principal(request);
|
|
299
|
+
if (caller === null)
|
|
300
|
+
throw new ServiceError('unauthorized', 'unauthorized');
|
|
301
|
+
let route;
|
|
302
|
+
let id = '';
|
|
303
|
+
for (const candidate of routes) {
|
|
304
|
+
const matched = matchPath(`${basePath}${candidate.path}`, url.pathname);
|
|
305
|
+
if (matched !== undefined && candidate.method === request.method) {
|
|
306
|
+
route = candidate;
|
|
307
|
+
id = matched;
|
|
308
|
+
break;
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
if (!route)
|
|
312
|
+
throw toServiceError('not_found');
|
|
313
|
+
const input = route.input === 'body'
|
|
314
|
+
? await readObjectBody(request)
|
|
315
|
+
: route.input === 'query'
|
|
316
|
+
? queryFields(url)
|
|
317
|
+
: {};
|
|
318
|
+
const scopeId = route.scope === null ? '' : idField(input, route.scope);
|
|
319
|
+
if (!caller.access.allows(route.permission, resourceFor(caller, route, scopeId, id))) {
|
|
320
|
+
throw new ServiceError('forbidden', 'forbidden');
|
|
321
|
+
}
|
|
322
|
+
return await route.run(ctx, scopeId, input, id);
|
|
323
|
+
}
|
|
324
|
+
catch (error) {
|
|
325
|
+
return serviceErrorResponse(toServiceError(error));
|
|
326
|
+
}
|
|
327
|
+
};
|
|
328
|
+
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `./service`: the HTTP half of the keys tables, for a company data service to mount. See the
|
|
3
|
+
* package README's "Adopting ./service" and C7 in docs/contracts.md.
|
|
4
|
+
*/
|
|
5
|
+
export { createKeysHandler, DEFAULT_WORKER_TIMEOUT_MS, type CreateKeysHandlerOptions, type Principal, } from './handler.js';
|
|
6
|
+
export { policyModule, type Permission } from './policy.js';
|
|
7
|
+
export { REFUSAL_CODES, toServiceError, type Refusal } from './errors.js';
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `./service`: the HTTP half of the keys tables, for a company data service to mount. See the
|
|
3
|
+
* package README's "Adopting ./service" and C7 in docs/contracts.md.
|
|
4
|
+
*/
|
|
5
|
+
export { createKeysHandler, DEFAULT_WORKER_TIMEOUT_MS, } from './handler.js';
|
|
6
|
+
export { policyModule } from './policy.js';
|
|
7
|
+
export { REFUSAL_CODES, toServiceError } from './errors.js';
|
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The eight permissions `./service` checks. `keys:put` and `keys:held-revoke` name the tenant in
|
|
3
|
+
* `./held`'s sense, which plays the part an organisation plays for the issued routes.
|
|
4
|
+
* `keys:shred` is a sweep over every tenant, so it is platform-wide and never offered to a company.
|
|
5
|
+
*/
|
|
6
|
+
export declare const policyModule: {
|
|
7
|
+
readonly namespace: "keys";
|
|
8
|
+
readonly permissions: readonly [{
|
|
9
|
+
readonly id: "keys:issue";
|
|
10
|
+
readonly label: "Issue a credential";
|
|
11
|
+
readonly description: "Mint a new issued credential, optionally as a child of another.";
|
|
12
|
+
readonly resourceType: "keys.credential";
|
|
13
|
+
readonly effect: "write";
|
|
14
|
+
readonly boundaries: readonly ["organisation"];
|
|
15
|
+
readonly offered: true;
|
|
16
|
+
readonly sensitive: true;
|
|
17
|
+
readonly survives: readonly [];
|
|
18
|
+
readonly support: "never";
|
|
19
|
+
readonly scopes: readonly ["organisation"];
|
|
20
|
+
readonly relations: readonly ["any"];
|
|
21
|
+
readonly tenantKinds: readonly ["customer", "operator"];
|
|
22
|
+
readonly assignable: true;
|
|
23
|
+
}, {
|
|
24
|
+
readonly id: "keys:verify";
|
|
25
|
+
readonly label: "Verify a credential";
|
|
26
|
+
readonly description: "Check a presented bearer secret against an issued credential.";
|
|
27
|
+
readonly resourceType: "keys.credential";
|
|
28
|
+
readonly effect: "read";
|
|
29
|
+
readonly boundaries: readonly ["organisation"];
|
|
30
|
+
readonly offered: true;
|
|
31
|
+
readonly sensitive: false;
|
|
32
|
+
readonly survives: readonly ["read_only"];
|
|
33
|
+
readonly support: "read";
|
|
34
|
+
readonly scopes: readonly ["organisation"];
|
|
35
|
+
readonly relations: readonly ["any"];
|
|
36
|
+
readonly tenantKinds: readonly ["customer", "operator"];
|
|
37
|
+
readonly assignable: true;
|
|
38
|
+
}, {
|
|
39
|
+
readonly id: "keys:rotate";
|
|
40
|
+
readonly label: "Rotate a credential";
|
|
41
|
+
readonly description: "Replace an issued credential's secret, keeping the old one for a grace period.";
|
|
42
|
+
readonly resourceType: "keys.credential";
|
|
43
|
+
readonly effect: "write";
|
|
44
|
+
readonly boundaries: readonly ["organisation"];
|
|
45
|
+
readonly offered: true;
|
|
46
|
+
readonly sensitive: true;
|
|
47
|
+
readonly survives: readonly [];
|
|
48
|
+
readonly support: "never";
|
|
49
|
+
readonly scopes: readonly ["organisation"];
|
|
50
|
+
readonly relations: readonly ["any"];
|
|
51
|
+
readonly tenantKinds: readonly ["customer", "operator"];
|
|
52
|
+
readonly assignable: true;
|
|
53
|
+
}, {
|
|
54
|
+
readonly id: "keys:revoke";
|
|
55
|
+
readonly label: "Revoke a credential";
|
|
56
|
+
readonly description: "Revoke an ordinary issued credential and, by default, its descendants.";
|
|
57
|
+
readonly resourceType: "keys.credential";
|
|
58
|
+
readonly effect: "write";
|
|
59
|
+
readonly boundaries: readonly ["organisation"];
|
|
60
|
+
readonly offered: true;
|
|
61
|
+
readonly sensitive: true;
|
|
62
|
+
readonly survives: readonly [];
|
|
63
|
+
readonly support: "never";
|
|
64
|
+
readonly scopes: readonly ["organisation"];
|
|
65
|
+
readonly relations: readonly ["any"];
|
|
66
|
+
readonly tenantKinds: readonly ["customer", "operator"];
|
|
67
|
+
readonly assignable: true;
|
|
68
|
+
}, {
|
|
69
|
+
readonly id: "keys:lineage";
|
|
70
|
+
readonly label: "Read a credential lineage";
|
|
71
|
+
readonly description: "Read a credential's chain back to its root.";
|
|
72
|
+
readonly resourceType: "keys.credential";
|
|
73
|
+
readonly effect: "read";
|
|
74
|
+
readonly boundaries: readonly ["organisation"];
|
|
75
|
+
readonly offered: true;
|
|
76
|
+
readonly sensitive: false;
|
|
77
|
+
readonly survives: readonly ["read_only"];
|
|
78
|
+
readonly support: "read";
|
|
79
|
+
readonly scopes: readonly ["organisation"];
|
|
80
|
+
readonly relations: readonly ["any"];
|
|
81
|
+
readonly tenantKinds: readonly ["customer", "operator"];
|
|
82
|
+
readonly assignable: true;
|
|
83
|
+
}, {
|
|
84
|
+
readonly id: "keys:put";
|
|
85
|
+
readonly label: "Put a held key";
|
|
86
|
+
readonly description: "Seal a new version of a held key under one entry.";
|
|
87
|
+
readonly resourceType: "keys.held";
|
|
88
|
+
readonly effect: "write";
|
|
89
|
+
readonly boundaries: readonly ["organisation"];
|
|
90
|
+
readonly offered: true;
|
|
91
|
+
readonly sensitive: true;
|
|
92
|
+
readonly survives: readonly [];
|
|
93
|
+
readonly support: "never";
|
|
94
|
+
readonly scopes: readonly ["organisation"];
|
|
95
|
+
readonly relations: readonly ["any"];
|
|
96
|
+
readonly tenantKinds: readonly ["customer", "operator"];
|
|
97
|
+
readonly assignable: true;
|
|
98
|
+
}, {
|
|
99
|
+
readonly id: "keys:held-revoke";
|
|
100
|
+
readonly label: "Revoke a held key";
|
|
101
|
+
readonly description: "Revoke one held entry so no version of it opens again.";
|
|
102
|
+
readonly resourceType: "keys.held";
|
|
103
|
+
readonly effect: "write";
|
|
104
|
+
readonly boundaries: readonly ["organisation"];
|
|
105
|
+
readonly offered: true;
|
|
106
|
+
readonly sensitive: true;
|
|
107
|
+
readonly survives: readonly [];
|
|
108
|
+
readonly support: "never";
|
|
109
|
+
readonly scopes: readonly ["organisation"];
|
|
110
|
+
readonly relations: readonly ["any"];
|
|
111
|
+
readonly tenantKinds: readonly ["customer", "operator"];
|
|
112
|
+
readonly assignable: true;
|
|
113
|
+
}, {
|
|
114
|
+
readonly id: "keys:shred";
|
|
115
|
+
readonly label: "Shred expired held keys";
|
|
116
|
+
readonly description: "Run the housekeeping sweep that erases eligible held-key versions.";
|
|
117
|
+
readonly resourceType: "keys.held";
|
|
118
|
+
readonly effect: "write";
|
|
119
|
+
readonly tenantKinds: readonly ["operator"];
|
|
120
|
+
readonly boundaries: readonly ["platform"];
|
|
121
|
+
readonly offered: false;
|
|
122
|
+
readonly sensitive: true;
|
|
123
|
+
readonly survives: readonly [];
|
|
124
|
+
readonly support: "never";
|
|
125
|
+
readonly scopes: readonly ["organisation"];
|
|
126
|
+
readonly relations: readonly ["any"];
|
|
127
|
+
readonly assignable: true;
|
|
128
|
+
}];
|
|
129
|
+
};
|
|
130
|
+
export type Permission = (typeof policyModule.permissions)[number]['id'];
|