@fabrika/cli 0.9.0-dev.42 → 0.9.0-dev.44
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/package.json +15 -13
- package/src/control.ts +749 -26
- package/src/data.ts +32 -14
- package/src/index.ts +4 -3
- package/types/src/control.d.ts +68 -5
- package/types/src/data.d.ts +1 -1
package/src/control.ts
CHANGED
|
@@ -10,14 +10,30 @@
|
|
|
10
10
|
// `--json` prints the procedure's result verbatim so a caller never parses a table.
|
|
11
11
|
|
|
12
12
|
import { createRpcClient, type InferRpcClient, RpcError, type RpcFetch } from '@fabrika/app'
|
|
13
|
-
import {
|
|
14
|
-
|
|
13
|
+
import {
|
|
14
|
+
displayNameProblem,
|
|
15
|
+
isCimdClientId,
|
|
16
|
+
isOAuthResourceUri,
|
|
17
|
+
type IssueKeyInput,
|
|
18
|
+
type IssueKeyResult,
|
|
19
|
+
MAX_KEY_LIFETIME_SECONDS,
|
|
20
|
+
sha256Hex,
|
|
21
|
+
} from '@fabrika/auth-core'
|
|
22
|
+
import {
|
|
23
|
+
APP_ENV_KINDS,
|
|
24
|
+
APPROVAL_REQUESTED,
|
|
25
|
+
type ApprovalRequestDto,
|
|
26
|
+
approvalRequestedSchema,
|
|
27
|
+
CONTROL_CLI_PRESETS,
|
|
28
|
+
isFinalApprovalRequestState,
|
|
29
|
+
} from '@fabrika/control-contract'
|
|
15
30
|
import type {
|
|
16
31
|
AppDto,
|
|
17
32
|
AppEnvDto,
|
|
18
33
|
AppEnvKind,
|
|
19
34
|
AppSecretDto,
|
|
20
35
|
ControlRpcContract,
|
|
36
|
+
CreateApprovalRequestResponse,
|
|
21
37
|
DeploymentNamespaceDetailDto,
|
|
22
38
|
DeploymentNamespaceDto,
|
|
23
39
|
JsonValue,
|
|
@@ -30,6 +46,24 @@ import type {
|
|
|
30
46
|
RegisterAppResponse,
|
|
31
47
|
RunDto,
|
|
32
48
|
} from '@fabrika/control-contract'
|
|
49
|
+
import {
|
|
50
|
+
type ExternalAppDto,
|
|
51
|
+
type IamAdminRpcContract,
|
|
52
|
+
isHttpsDocumentUrl,
|
|
53
|
+
isOAuthIdentityAppId,
|
|
54
|
+
isOAuthIdentityRoleKey,
|
|
55
|
+
MAX_EXTERNAL_APP_CLIENTS,
|
|
56
|
+
MAX_OAUTH_IDENTITY_ROLES,
|
|
57
|
+
OAUTH_CLIENT_PROVIDERS,
|
|
58
|
+
OAUTH_REGISTRY_NOT_IMPORTED,
|
|
59
|
+
type OAuthClientDto,
|
|
60
|
+
type PutExternalAppRequest,
|
|
61
|
+
type PutOAuthClientRequest,
|
|
62
|
+
recipientKeyThumbprint,
|
|
63
|
+
type RecipientPublicKey,
|
|
64
|
+
REQUESTED_KEY_JWE,
|
|
65
|
+
} from '@fabrika/iam-contract'
|
|
66
|
+
import { compactDecrypt, exportJWK, generateKeyPair } from 'jose'
|
|
33
67
|
import { z } from 'zod'
|
|
34
68
|
import {
|
|
35
69
|
authorizeDevice,
|
|
@@ -69,15 +103,15 @@ Usage:
|
|
|
69
103
|
fabrika control apps environments list --app=<id>
|
|
70
104
|
fabrika control apps environments put --provider=<name> --app=<id> --env=<name> --manifest=<path>
|
|
71
105
|
[--domain=<host>] [--public-origin=<url>] [--trigger-ref=<ref>] [--namespace=<id>]
|
|
72
|
-
[--cross-origin=<origin> ...] [--kind=standard|dev]
|
|
73
|
-
fabrika control apps environments suspend --app=<id> --env=<name>
|
|
74
|
-
fabrika control apps environments resume --app=<id> --env=<name>
|
|
106
|
+
[--cross-origin=<origin> ...] [--kind=standard|dev] [--wait]
|
|
107
|
+
fabrika control apps environments suspend --app=<id> --env=<name> [--wait]
|
|
108
|
+
fabrika control apps environments resume --app=<id> --env=<name> [--wait]
|
|
75
109
|
fabrika control apps variables list --app=<id>
|
|
76
|
-
fabrika control apps variables put --app=<id> --name=<name> --value=<text> [--env=<name>] [--not-secret]
|
|
77
|
-
fabrika control apps variables delete --app=<id> --name=<name> [--env=<name>]
|
|
110
|
+
fabrika control apps variables put --app=<id> --name=<name> --value=<text> [--env=<name>] [--not-secret] [--request] [--wait]
|
|
111
|
+
fabrika control apps variables delete --app=<id> --name=<name> [--env=<name>] [--request] [--wait]
|
|
78
112
|
fabrika control apps secrets list --app=<id>
|
|
79
|
-
fabrika control apps secrets put --app=<id> --name=<name> [--env=<name>] (the value on stdin)
|
|
80
|
-
fabrika control apps secrets delete --app=<id> --name=<name> [--env=<name>]
|
|
113
|
+
fabrika control apps secrets put --app=<id> --name=<name> [--env=<name>] [--request] [--wait] (the value on stdin)
|
|
114
|
+
fabrika control apps secrets delete --app=<id> --name=<name> [--env=<name>] [--request] [--wait]
|
|
81
115
|
fabrika control register --provider=<name> --app=<id> --repo=<url> --env=<name> --manifest=<path>
|
|
82
116
|
[--domain=<host>] [--public-origin=<url>] [--trigger-ref=<ref>]
|
|
83
117
|
[--namespace=<id>] [--installation-id=<n|none>] [--cross-origin=<origin> ...]
|
|
@@ -89,10 +123,17 @@ Usage:
|
|
|
89
123
|
fabrika control namespaces update --namespace=<id> --proxy-source=current
|
|
90
124
|
fabrika control namespaces remove --namespace=<id>
|
|
91
125
|
fabrika control namespaces release-claims --namespace=<id> --app=<id> --env=<name>
|
|
92
|
-
fabrika control deploy --app=<id> --env=<name> [--ref=<ref>]
|
|
126
|
+
fabrika control deploy --app=<id> --env=<name> [--ref=<ref>] [--wait]
|
|
93
127
|
fabrika control runs list [--app=<id>] [--env=<name>] [--limit=<n>]
|
|
94
128
|
fabrika control runs get --run=<id>
|
|
95
129
|
fabrika control runs log --run=<id>
|
|
130
|
+
fabrika control requests get <id> [--wait]
|
|
131
|
+
fabrika control access request-grant --app=<id> --env=<name> --principal=<id> --role=<role>
|
|
132
|
+
[--scope=<dimension>:<value>] --expires-in=<seconds> [--wait]
|
|
133
|
+
fabrika control access request-key --app=<id> --action=<action> [--action=<action>…] --label=<text>
|
|
134
|
+
--expires-in=<seconds> --wait
|
|
135
|
+
fabrika control external-apps list | get <app> | put --file=<app.json> | delete <app> [--iam-url=<origin>]
|
|
136
|
+
fabrika control oauth-clients list | put --file=<client.json> | delete <client id> [--iam-url=<origin>]
|
|
96
137
|
|
|
97
138
|
\`register\` CREATES an app and refuses a second one with the same id. Re-registering a changed
|
|
98
139
|
manifest — a new import document, or a new \`zerops.yaml\` of an app without a contract — is
|
|
@@ -144,6 +185,50 @@ A full ref is kept as given: \`refs/heads/<branch>\`, \`refs/tags/<tag>\`, or a
|
|
|
144
185
|
environment of an app needs its own trigger ref. Branches named \`fabrika/…\` are reserved for MCP
|
|
145
186
|
workspaces and are never a trigger ref.
|
|
146
187
|
|
|
188
|
+
\`deploy\` of a protected environment with \`FABRIKA_CONTROL_KEY\` or a device grant is a request a person approves:
|
|
189
|
+
\`--ref\` names a 40-character commit SHA, by default one merged into the environment's trigger ref (or the default
|
|
190
|
+
branch), and stderr prints the console link the person opens. \`--wait\` follows the run until it succeeds or
|
|
191
|
+
fails, approval being one step on the way, and prints its final row; a refusal or an expiry says so on stderr.
|
|
192
|
+
|
|
193
|
+
\`requests get\` reads one approval request: a change an agent or a key asked a person to approve, by the id its
|
|
194
|
+
creation answered. stderr prints the console link while it waits, and why it did not run once it failed, went stale or
|
|
195
|
+
expired. \`--wait\` reads it again until it is refused, expired, executed, failed or stale, and prints its final row;
|
|
196
|
+
once a person decided it, it stops with an error after 15 minutes without an outcome.
|
|
197
|
+
|
|
198
|
+
\`--request\` on \`apps secrets put|delete\` and \`apps variables put|delete\` does not make the change: it asks a person
|
|
199
|
+
to approve it. Every other verb refuses it. Control stores the request, inert, and stderr prints the console link the person opens; for a secret it
|
|
200
|
+
also prints the value's fingerprint (the first 8 hex characters of its SHA-256, computed here), which the page shows
|
|
201
|
+
beside the value's length, so the person can tell it is the value you sent; when Control's answer names another
|
|
202
|
+
fingerprint, the command fails and says to refuse the request. Control seals the value and stores only that. stdout
|
|
203
|
+
prints the request's id, state and link; \`--wait\` follows it as \`requests get --wait\` does. Without \`--env\` the request
|
|
204
|
+
is for every environment of the app, and every protected one judges it. A secret the provider keeps (a Zerops
|
|
205
|
+
environment) is requested for one \`--env\`.
|
|
206
|
+
|
|
207
|
+
\`access request-grant\` asks a person to give a principal (this agent's own, or another) one role of an application
|
|
208
|
+
environment. It needs \`access.request\` at the app, the role must be one the environment's approved contract declares,
|
|
209
|
+
a membership role takes \`--scope\` with a value of its dimension, and \`--expires-in\` is at most 30 days. An IAM
|
|
210
|
+
administrator of the application approves it at the console link stderr prints; the grant is then theirs, and where
|
|
211
|
+
the application's grants wait for approval, IAM holds it for a second administrator. An environment that does not gate
|
|
212
|
+
an agent's grants (not protected, or \`agent-grants\` off) refuses it: there is nothing to approve there. stdout prints
|
|
213
|
+
the request's id, state and link; \`--wait\` follows it as \`requests get --wait\` does.
|
|
214
|
+
|
|
215
|
+
Without \`--request\`, a write by \`FABRIKA_CONTROL_KEY\` or a device grant on a protected environment meets that
|
|
216
|
+
environment's approval policy (ADR-0083): \`apps secrets\` and \`apps variables\` are \`secrets\` and \`variables\` writes,
|
|
217
|
+
\`apps environments put\` is a \`registry\` write, and \`apps environments suspend|resume\` are \`data\` writes.
|
|
218
|
+
A category set to \`off\` applies the write; \`refuse\` refuses it; \`person\` does not make the change but stores it as a
|
|
219
|
+
request, exactly as \`--request\` does: stdout prints its id, state and link, stderr the fingerprint of a secret, and the
|
|
220
|
+
command exits 75. Hand the person the link; nothing changes until they approve it. \`--wait\` follows the request
|
|
221
|
+
instead, and succeeds only when it executed.
|
|
222
|
+
|
|
223
|
+
\`access request-key\` asks a person for a key holding exact Control actions at one application (each \`--action\`, no
|
|
224
|
+
wildcard), for someone other than this agent, expiring in at most 30 days. It needs \`access.request\` at the app, and
|
|
225
|
+
the protected environments' \`credentialCeiling\` decides whether the key may hold actions this agent does not. It
|
|
226
|
+
makes a key pair in memory, sends only the public key, and prints on stderr the console link and the public key's
|
|
227
|
+
thumbprint, which the page shows: an IAM installation administrator checks it there and approves with a passkey. IAM
|
|
228
|
+
encrypts the key to that public key, and Control hands it out once. \`--wait\` is required: the private key never leaves
|
|
229
|
+
this process, so the key cannot be fetched later; the command waits for the decision, fetches the key, decrypts it, and
|
|
230
|
+
prints it once on stdout. A request that issues no key (refused, expired, failed) fails with why.
|
|
231
|
+
|
|
147
232
|
Namespace placement options, each defaulting to what the preset would choose:
|
|
148
233
|
|
|
149
234
|
--project=<name> the provider project the namespace owns; on Zerops the default is
|
|
@@ -217,6 +302,32 @@ and \`platform init\` print in their closing block, and the value \`FABRIKA_IAM_
|
|
|
217
302
|
control service. It is NOT the private hostname the services use between themselves: \`http://iam:3000\`
|
|
218
303
|
resolves inside the provider's project and nowhere else, so from here it only ever fails to connect.
|
|
219
304
|
|
|
305
|
+
\`external-apps\` and \`oauth-clients\` manage the OAuth clients IAM serves (ADR-0089). They call IAM's admin API
|
|
306
|
+
with two of the variables \`key issue\` reads, and nothing else: FABRIKA_IAM_RPC_URL (or --iam-url), IAM's PUBLIC origin,
|
|
307
|
+
and FABRIKA_IAM_PROVISIONING_KEY, the bearer. An external application is an application outside this installation that
|
|
308
|
+
signs people in through IAM; \`put\` replaces it whole from a file (record, roles and clients) and is idempotent:
|
|
309
|
+
|
|
310
|
+
{
|
|
311
|
+
"app": "ops-tool",
|
|
312
|
+
"name": "Ops tool",
|
|
313
|
+
"resource": "https://ops.example.com",
|
|
314
|
+
"roles": [{ "key": "viewer", "name": "Viewer" }],
|
|
315
|
+
"clients": [{ "clientId": "https://ops.example.com/oauth/client.json",
|
|
316
|
+
"redirectUris": ["https://ops.example.com/oauth/callback"], "metadataUrl": null }]
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
\`roles\` null or left out: every active user of the installation signs in. \`get\` prints the same file, ready to edit
|
|
320
|
+
and put back. Removing a client, changing the resource or deleting the application revokes the sign-ins through it.
|
|
321
|
+
\`oauth-clients put\` writes an MCP authoring client, whose tokens reach the console's /mcp:
|
|
322
|
+
|
|
323
|
+
{ "clientId": "https://claude.ai/oauth/mcp-oauth-client-metadata", "label": "claude",
|
|
324
|
+
"redirectUris": ["https://claude.ai/api/mcp/auth_callback"] }
|
|
325
|
+
|
|
326
|
+
\`label\` is claude, chatgpt or external. A client of an external application is written only through
|
|
327
|
+
\`external-apps put\`, and \`oauth-clients\` refuses it. \`put\` checks the file before anything is sent. Until a platform
|
|
328
|
+
deploy of this release has imported the installation's client list, IAM refuses both \`put\`s; deploy, then repeat.
|
|
329
|
+
The console registers external applications too, under Access → External applications.
|
|
330
|
+
|
|
220
331
|
Connecting a GitHub source is NOT here and will not be: App creation is a browser flow whose
|
|
221
332
|
authorization requires a human principal (ADR-0029). Use Settings → Source in the console.
|
|
222
333
|
`
|
|
@@ -230,21 +341,37 @@ interface Flags {
|
|
|
230
341
|
readonly json: boolean
|
|
231
342
|
/** `--not-secret`: `apps variables put` stores a value that looks like a credential. */
|
|
232
343
|
readonly notSecret: boolean
|
|
344
|
+
/**
|
|
345
|
+
* `--wait`: `deploy` follows the run until it succeeds or fails; `requests get`, `--request` and a write Control stores as
|
|
346
|
+
* a request follow the request until it settles.
|
|
347
|
+
*/
|
|
348
|
+
readonly wait: boolean
|
|
349
|
+
/** `--request`: a secret or variable write asks a person to approve it instead of making it (ADR-0083 §8). */
|
|
350
|
+
readonly request: boolean
|
|
233
351
|
readonly positional: readonly string[]
|
|
234
352
|
}
|
|
235
353
|
|
|
236
|
-
/**
|
|
354
|
+
/**
|
|
355
|
+
* Split `--key=value` options from positional words; `--json` is the one flag every verb shares, `--not-secret`, `--wait`
|
|
356
|
+
* and `--request` the other bare ones.
|
|
357
|
+
*/
|
|
237
358
|
export const parseControlFlags = (argv: readonly string[]): Flags => {
|
|
238
359
|
const values = new Map<string, string>()
|
|
239
360
|
const repeated = new Map<string, string[]>()
|
|
240
361
|
const positional: string[] = []
|
|
241
362
|
let json = false
|
|
242
363
|
let notSecret = false
|
|
364
|
+
let wait = false
|
|
365
|
+
let request = false
|
|
243
366
|
for (const arg of argv) {
|
|
244
367
|
if (arg === '--json') {
|
|
245
368
|
json = true
|
|
246
369
|
} else if (arg === '--not-secret') {
|
|
247
370
|
notSecret = true
|
|
371
|
+
} else if (arg === '--wait') {
|
|
372
|
+
wait = true
|
|
373
|
+
} else if (arg === '--request') {
|
|
374
|
+
request = true
|
|
248
375
|
} else if (arg.startsWith('--')) {
|
|
249
376
|
const eq = arg.indexOf('=')
|
|
250
377
|
if (eq === -1) {
|
|
@@ -258,7 +385,7 @@ export const parseControlFlags = (argv: readonly string[]): Flags => {
|
|
|
258
385
|
positional.push(arg)
|
|
259
386
|
}
|
|
260
387
|
}
|
|
261
|
-
return { values, repeated, json, notSecret, positional }
|
|
388
|
+
return { values, repeated, json, notSecret, wait, request, positional }
|
|
262
389
|
}
|
|
263
390
|
|
|
264
391
|
const required = (flags: Flags, name: string): string => {
|
|
@@ -339,11 +466,17 @@ const carriesKey = (text: string, key: string): boolean => {
|
|
|
339
466
|
* A JSON answer that carries the key is dropped whole, so no row, `--json` output or error can repeat it. Any other
|
|
340
467
|
* body passes: the RPC client reports a non-JSON answer by its status alone.
|
|
341
468
|
*/
|
|
342
|
-
const withoutEchoedKey = async (
|
|
469
|
+
const withoutEchoedKey = async (
|
|
470
|
+
response: Response,
|
|
471
|
+
key: string,
|
|
472
|
+
source: { readonly service: string; readonly label: string } = { service: 'Control', label: KEY_LABEL },
|
|
473
|
+
): Promise<Response> => {
|
|
343
474
|
if (!(response.headers.get('content-type') ?? '').includes('application/json')) return response
|
|
344
475
|
const text = await response.text()
|
|
345
476
|
if (carriesKey(text, key)) {
|
|
346
|
-
return Response.json({ error: { type: 'transport', message:
|
|
477
|
+
return Response.json({ error: { type: 'transport', message: `${source.service}'s answer carried ${source.label}; it was dropped` } }, {
|
|
478
|
+
status: 502,
|
|
479
|
+
})
|
|
347
480
|
}
|
|
348
481
|
return new Response(text, { status: response.status, statusText: response.statusText, headers: response.headers })
|
|
349
482
|
}
|
|
@@ -442,7 +575,7 @@ const parseJsonText = (text: string, label: string): JsonValue => {
|
|
|
442
575
|
}
|
|
443
576
|
}
|
|
444
577
|
|
|
445
|
-
const emit = (flags: Flags, result: unknown, render: () => string): void => {
|
|
578
|
+
const emit = (flags: Pick<Flags, 'json'>, result: unknown, render: () => string): void => {
|
|
446
579
|
console.info(flags.json ? JSON.stringify(result, null, 2) : render())
|
|
447
580
|
}
|
|
448
581
|
|
|
@@ -737,13 +870,20 @@ const runEnvironments = async (
|
|
|
737
870
|
...(namespaceId === undefined ? {} : { namespaceId }),
|
|
738
871
|
...(kind === undefined ? {} : { kind }),
|
|
739
872
|
}
|
|
740
|
-
const
|
|
873
|
+
const target = { appId: required(flags, 'app'), env: required(flags, 'env') }
|
|
874
|
+
const result = await directWrite(client, flags, () => client.apps.environments.put({ ...target, environment }))
|
|
875
|
+
if (result === null) return
|
|
741
876
|
emit(flags, result, () => `${result.appId}\t${result.env}\t${result.provider}`)
|
|
742
877
|
return
|
|
743
878
|
}
|
|
744
879
|
if (verb === 'suspend' || verb === 'resume') {
|
|
745
880
|
const target = { appId: required(flags, 'app'), env: required(flags, 'env') }
|
|
746
|
-
const result =
|
|
881
|
+
const result = await directWrite(
|
|
882
|
+
client,
|
|
883
|
+
flags,
|
|
884
|
+
() => verb === 'suspend' ? client.apps.environments.suspend(target) : client.apps.environments.resume(target),
|
|
885
|
+
)
|
|
886
|
+
if (result === null) return
|
|
747
887
|
if (result.namespaceId !== null) {
|
|
748
888
|
console.warn(
|
|
749
889
|
`the proxy of namespace ${result.namespaceId} is rebuilding; follow it: fabrika control namespaces get --namespace=${result.namespaceId}`,
|
|
@@ -791,12 +931,23 @@ const runVariables = async (verb: string | undefined, flags: Flags, env: Readonl
|
|
|
791
931
|
...(scope === undefined ? {} : { env: scope }),
|
|
792
932
|
...(flags.notSecret ? { notSecret: true } : {}),
|
|
793
933
|
}
|
|
794
|
-
|
|
934
|
+
if (flags.request) {
|
|
935
|
+
await requestChange(client, flags, 'apps.variables.put', { appId, variable: { ...variable } })
|
|
936
|
+
return
|
|
937
|
+
}
|
|
938
|
+
const result = await directWrite(client, flags, () => client.apps.variables.put({ appId, variable }))
|
|
939
|
+
if (result === null) return
|
|
795
940
|
emit(flags, result, () => `${result.env ?? '*'}\t${result.name}\t${result.value}`)
|
|
796
941
|
return
|
|
797
942
|
}
|
|
798
943
|
if (verb === 'delete') {
|
|
799
|
-
const
|
|
944
|
+
const target = { appId, name: required(flags, 'name'), ...(scope === undefined ? {} : { env: scope }) }
|
|
945
|
+
if (flags.request) {
|
|
946
|
+
await requestChange(client, flags, 'apps.variables.delete', target)
|
|
947
|
+
return
|
|
948
|
+
}
|
|
949
|
+
const result = await directWrite(client, flags, () => client.apps.variables.delete(target))
|
|
950
|
+
if (result === null) return
|
|
800
951
|
emit(flags, result, () => (result.ok ? 'deleted' : 'not deleted'))
|
|
801
952
|
return
|
|
802
953
|
}
|
|
@@ -854,17 +1005,29 @@ const runSecrets = async (
|
|
|
854
1005
|
const name = required(flags, 'name')
|
|
855
1006
|
const value = await readSecretValue(input, appId, name)
|
|
856
1007
|
const secret: PutAppSecretRequest = { name, value, ...(scope === undefined ? {} : { env: scope }) }
|
|
857
|
-
|
|
1008
|
+
if (flags.request) {
|
|
1009
|
+
await requestChange(client, flags, 'apps.secrets.put', { appId, secret: { ...secret } }, value)
|
|
1010
|
+
return
|
|
1011
|
+
}
|
|
1012
|
+
let result: AppSecretDto | null
|
|
858
1013
|
try {
|
|
859
|
-
result = await client.apps.secrets.put({ appId, secret })
|
|
1014
|
+
result = await directWrite(client, flags, () => client.apps.secrets.put({ appId, secret }), value)
|
|
860
1015
|
} catch (error) {
|
|
1016
|
+
if (error instanceof ApprovalPendingError) throw error
|
|
861
1017
|
throw new Error(failureMessage(error, value, 'secret value'))
|
|
862
1018
|
}
|
|
1019
|
+
if (result === null) return
|
|
863
1020
|
emit(flags, result, () => `${result.env ?? '*'}\t${result.name}\tok`)
|
|
864
1021
|
return
|
|
865
1022
|
}
|
|
866
1023
|
if (verb === 'delete') {
|
|
867
|
-
const
|
|
1024
|
+
const target = { appId, name: required(flags, 'name'), ...(scope === undefined ? {} : { env: scope }) }
|
|
1025
|
+
if (flags.request) {
|
|
1026
|
+
await requestChange(client, flags, 'apps.secrets.delete', target)
|
|
1027
|
+
return
|
|
1028
|
+
}
|
|
1029
|
+
const result = await directWrite(client, flags, () => client.apps.secrets.delete(target))
|
|
1030
|
+
if (result === null) return
|
|
868
1031
|
emit(flags, result, () => (result.ok ? 'deleted' : 'not deleted'))
|
|
869
1032
|
return
|
|
870
1033
|
}
|
|
@@ -920,7 +1083,8 @@ const runRuns = async (verb: string | undefined, flags: Flags, env: Readonly<Rec
|
|
|
920
1083
|
}
|
|
921
1084
|
if (verb === 'get') {
|
|
922
1085
|
const result = await client.runs.get({ runId: required(flags, 'run') })
|
|
923
|
-
|
|
1086
|
+
const hint = runHint(result)
|
|
1087
|
+
if (hint !== null) console.warn(hint)
|
|
924
1088
|
emit(flags, result, () => runLine(result))
|
|
925
1089
|
return
|
|
926
1090
|
}
|
|
@@ -1089,20 +1253,561 @@ const runNamespaces = async (verb: string | undefined, flags: Flags, env: Readon
|
|
|
1089
1253
|
throw new Error(`Unknown \`control namespaces\` verb: ${verb ?? '(missing)'}`)
|
|
1090
1254
|
}
|
|
1091
1255
|
|
|
1256
|
+
// ── IAM's client registry (ADR-0089) ─────────────────────────────────────────
|
|
1257
|
+
// `external-apps` and `oauth-clients` call IAM's `/admin/rpc` with the provisioning key as the bearer, the credential
|
|
1258
|
+
// Control's own IAM provisioning client sends. A person's device grant does not reach IAM's admin API.
|
|
1259
|
+
|
|
1260
|
+
const PROVISIONING_KEY_LABEL = '[FABRIKA_IAM_PROVISIONING_KEY]'
|
|
1261
|
+
|
|
1262
|
+
/** `text` with the provisioning key cut out: every diagnostic of the registry verbs passes through it. */
|
|
1263
|
+
const withoutProvisioningKey = (text: string, env: Readonly<Record<string, string | undefined>>): string => {
|
|
1264
|
+
const key = env['FABRIKA_IAM_PROVISIONING_KEY']?.trim()
|
|
1265
|
+
return key === undefined || key === '' ? text : text.replaceAll(key, PROVISIONING_KEY_LABEL)
|
|
1266
|
+
}
|
|
1267
|
+
|
|
1268
|
+
export type IamAdminClient = InferRpcClient<IamAdminRpcContract>
|
|
1269
|
+
|
|
1270
|
+
/** IAM's admin RPC at its public origin, with the provisioning key from the environment only and no redirect followed. */
|
|
1271
|
+
export const iamAdminClient = (
|
|
1272
|
+
url: string | undefined,
|
|
1273
|
+
env: Readonly<Record<string, string | undefined>>,
|
|
1274
|
+
send: RpcFetch = fetch,
|
|
1275
|
+
): IamAdminClient => {
|
|
1276
|
+
const origin = credentialOrigin(url ?? env['FABRIKA_IAM_RPC_URL'], IAM_ORIGIN)
|
|
1277
|
+
const key = secret('FABRIKA_IAM_PROVISIONING_KEY', env)
|
|
1278
|
+
return createRpcClient<IamAdminRpcContract>({
|
|
1279
|
+
baseUrl: `${origin}/admin/rpc`,
|
|
1280
|
+
bounceOnAuth: false,
|
|
1281
|
+
fetch: async (input, init) => {
|
|
1282
|
+
const headers = new Headers(init?.headers)
|
|
1283
|
+
headers.set('authorization', `Bearer ${key}`)
|
|
1284
|
+
let response: Response
|
|
1285
|
+
try {
|
|
1286
|
+
// A followed 307/308 would re-send the provisioning key to wherever it points; the client refuses a 3xx.
|
|
1287
|
+
response = await send(input, { ...init, headers, redirect: 'manual' })
|
|
1288
|
+
} catch (cause) {
|
|
1289
|
+
// The RPC client reads a rejected fetch as "Network request failed"; this answer keeps the reason.
|
|
1290
|
+
return Response.json({ error: { type: 'transport', message: unreachableIam(origin, cause) } }, { status: 502 })
|
|
1291
|
+
}
|
|
1292
|
+
return await withoutEchoedKey(response, key, { service: 'IAM', label: PROVISIONING_KEY_LABEL })
|
|
1293
|
+
},
|
|
1294
|
+
})
|
|
1295
|
+
}
|
|
1296
|
+
|
|
1297
|
+
const roleFileSchema = z.object({ key: z.string(), name: z.string() }).strict()
|
|
1298
|
+
const externalAppClientFileSchema = z.object({
|
|
1299
|
+
clientId: z.string(),
|
|
1300
|
+
redirectUris: z.array(z.string()),
|
|
1301
|
+
metadataUrl: z.string().nullable().optional(),
|
|
1302
|
+
}).strict()
|
|
1303
|
+
const externalAppFileSchema = z.object({
|
|
1304
|
+
app: z.string(),
|
|
1305
|
+
name: z.string(),
|
|
1306
|
+
resource: z.string(),
|
|
1307
|
+
roles: z.array(roleFileSchema).nullable().optional(),
|
|
1308
|
+
clients: z.array(externalAppClientFileSchema),
|
|
1309
|
+
}).strict()
|
|
1310
|
+
const oauthClientFileSchema = z.object({
|
|
1311
|
+
clientId: z.string(),
|
|
1312
|
+
label: z.enum(OAUTH_CLIENT_PROVIDERS),
|
|
1313
|
+
redirectUris: z.array(z.string()),
|
|
1314
|
+
metadataUrl: z.string().nullable().optional(),
|
|
1315
|
+
}).strict()
|
|
1316
|
+
|
|
1317
|
+
/** What IAM refuses of one client's coordinates, checked with the contract's own predicates. */
|
|
1318
|
+
const clientProblems = (at: string, client: { clientId: string; redirectUris: string[]; metadataUrl?: string | null | undefined }): string[] => {
|
|
1319
|
+
const problems: string[] = []
|
|
1320
|
+
if (!isCimdClientId(client.clientId)) problems.push(`${at}.clientId must be the https URL of the client's metadata document, with a path`)
|
|
1321
|
+
const uris = client.redirectUris
|
|
1322
|
+
if (uris.length === 0 || uris.length > 32 || !uris.every((uri) => isOAuthResourceUri(uri)) || new Set(uris).size !== uris.length) {
|
|
1323
|
+
problems.push(`${at}.redirectUris must list 1 to 32 distinct exact https URLs (loopback http locally) without a fragment`)
|
|
1324
|
+
}
|
|
1325
|
+
if (client.metadataUrl != null && !isHttpsDocumentUrl(client.metadataUrl)) {
|
|
1326
|
+
problems.push(`${at}.metadataUrl must be an https URL without credentials or a fragment, or null`)
|
|
1327
|
+
}
|
|
1328
|
+
return problems
|
|
1329
|
+
}
|
|
1330
|
+
|
|
1331
|
+
/** Zod's complaints about a file's shape, each as `<path>: <message>`; never the value it read. */
|
|
1332
|
+
const shapeProblems = (error: z.ZodError): string[] =>
|
|
1333
|
+
error.issues.map((issue) => `${issue.path.length === 0 ? '(file)' : issue.path.join('.')}: ${issue.message}`)
|
|
1334
|
+
|
|
1335
|
+
const refuseFile = (path: string, what: string, problems: readonly string[]): never => {
|
|
1336
|
+
throw new Error(`${path} is not ${what}:\n${problems.map((problem) => ` - ${problem}`).join('\n')}`)
|
|
1337
|
+
}
|
|
1338
|
+
|
|
1339
|
+
/** An `externalApps.put` request from a file, checked against the contract before it is sent; IAM checks it again. */
|
|
1340
|
+
export const parseExternalAppFile = (value: JsonValue, path: string): PutExternalAppRequest => {
|
|
1341
|
+
const shape = externalAppFileSchema.safeParse(value)
|
|
1342
|
+
if (!shape.success) return refuseFile(path, 'an external application', shapeProblems(shape.error))
|
|
1343
|
+
const file = shape.data
|
|
1344
|
+
const problems: string[] = []
|
|
1345
|
+
if (!isOAuthIdentityAppId(file.app)) problems.push('app must be lowercase letters, digits and dashes, without `@`, at most 63 characters')
|
|
1346
|
+
const nameProblem = displayNameProblem(file.name)
|
|
1347
|
+
if (nameProblem !== null) problems.push(`name ${nameProblem}`)
|
|
1348
|
+
if (!isOAuthResourceUri(file.resource) || !file.resource.startsWith('https://')) problems.push('resource must be an https URI without a fragment')
|
|
1349
|
+
const roles = file.roles ?? []
|
|
1350
|
+
if (roles.length > MAX_OAUTH_IDENTITY_ROLES) problems.push(`roles holds at most ${MAX_OAUTH_IDENTITY_ROLES} roles`)
|
|
1351
|
+
for (const [index, role] of roles.entries()) {
|
|
1352
|
+
if (!isOAuthIdentityRoleKey(role.key)) problems.push(`roles.${index}.key must be lowercase like an app id and no built-in role`)
|
|
1353
|
+
else if (roles.findIndex((other) => other.key === role.key) !== index) problems.push(`roles.${index}.key repeats '${role.key}'`)
|
|
1354
|
+
if (role.name === '' || role.name.length > 100) problems.push(`roles.${index}.name must be 1 to 100 characters`)
|
|
1355
|
+
}
|
|
1356
|
+
if (file.clients.length > MAX_EXTERNAL_APP_CLIENTS) problems.push(`clients holds at most ${MAX_EXTERNAL_APP_CLIENTS} clients`)
|
|
1357
|
+
for (const [index, client] of file.clients.entries()) {
|
|
1358
|
+
problems.push(...clientProblems(`clients.${index}`, client))
|
|
1359
|
+
if (file.clients.findIndex((other) => other.clientId === client.clientId) !== index) problems.push(`clients.${index}.clientId repeats a client`)
|
|
1360
|
+
}
|
|
1361
|
+
if (problems.length > 0) return refuseFile(path, 'an external application', problems)
|
|
1362
|
+
return {
|
|
1363
|
+
app: file.app,
|
|
1364
|
+
name: file.name,
|
|
1365
|
+
resource: file.resource,
|
|
1366
|
+
roles: roles.length === 0 ? null : roles,
|
|
1367
|
+
clients: file.clients.map((client) => ({ clientId: client.clientId, redirectUris: client.redirectUris, metadataUrl: client.metadataUrl ?? null })),
|
|
1368
|
+
}
|
|
1369
|
+
}
|
|
1370
|
+
|
|
1371
|
+
/** An `oauthClients.put` request (an MCP authoring client) from a file, checked against the contract before it is sent. */
|
|
1372
|
+
export const parseOAuthClientFile = (value: JsonValue, path: string): PutOAuthClientRequest => {
|
|
1373
|
+
const shape = oauthClientFileSchema.safeParse(value)
|
|
1374
|
+
if (!shape.success) return refuseFile(path, 'an authoring client', shapeProblems(shape.error))
|
|
1375
|
+
const file = shape.data
|
|
1376
|
+
const problems = clientProblems('(file)', file)
|
|
1377
|
+
if (problems.length > 0) return refuseFile(path, 'an authoring client', problems)
|
|
1378
|
+
return { clientId: file.clientId, label: file.label, redirectUris: file.redirectUris, metadataUrl: file.metadataUrl ?? null }
|
|
1379
|
+
}
|
|
1380
|
+
|
|
1381
|
+
/** What `external-apps get` prints: the file `external-apps put` takes back, so a record can be kept and edited as a file. */
|
|
1382
|
+
export const externalAppFile = (app: ExternalAppDto): PutExternalAppRequest => ({
|
|
1383
|
+
app: app.app,
|
|
1384
|
+
name: app.name ?? app.app,
|
|
1385
|
+
resource: app.resource,
|
|
1386
|
+
roles: app.roles,
|
|
1387
|
+
clients: app.clients,
|
|
1388
|
+
})
|
|
1389
|
+
|
|
1390
|
+
const externalAppLine = (app: ExternalAppDto): string =>
|
|
1391
|
+
[app.app, app.name ?? '', app.resource, `${app.roles?.length ?? 0} roles`, `${app.clients.length} clients`].join('\t')
|
|
1392
|
+
|
|
1393
|
+
const oauthClientLine = (client: OAuthClientDto): string =>
|
|
1394
|
+
[client.clientId, client.label, client.externalApp ?? 'authoring', client.redirectUris.join(',')].join('\t')
|
|
1395
|
+
|
|
1396
|
+
const positionalArgument = (flags: Flags, what: string, usage: string): string => {
|
|
1397
|
+
const value = flags.positional[1]
|
|
1398
|
+
if (value === undefined || value === '') throw new Error(`${usage} needs ${what}`)
|
|
1399
|
+
if (flags.positional.length > 2) throw new Error(`${usage} takes only ${what}`)
|
|
1400
|
+
return value
|
|
1401
|
+
}
|
|
1402
|
+
|
|
1403
|
+
const fileArgument = async (flags: Flags): Promise<{ readonly path: string; readonly value: JsonValue }> => {
|
|
1404
|
+
const path = required(flags, 'file')
|
|
1405
|
+
return { path, value: await readJsonFile(path) }
|
|
1406
|
+
}
|
|
1407
|
+
|
|
1408
|
+
/** Every registry verb names the not-imported refusal's way out: deploy the platform first. */
|
|
1409
|
+
const registryCall = async <T>(call: () => Promise<T>): Promise<T> => {
|
|
1410
|
+
try {
|
|
1411
|
+
return await call()
|
|
1412
|
+
} catch (error) {
|
|
1413
|
+
if (error instanceof RpcError && error.httpStatus === 409 && error.message === OAUTH_REGISTRY_NOT_IMPORTED) {
|
|
1414
|
+
throw new Error(
|
|
1415
|
+
'IAM does not take registry writes yet: a platform deploy of this release has not imported the OAuth client list. '
|
|
1416
|
+
+ 'Run the platform deploy, then repeat this command.',
|
|
1417
|
+
)
|
|
1418
|
+
}
|
|
1419
|
+
throw error
|
|
1420
|
+
}
|
|
1421
|
+
}
|
|
1422
|
+
|
|
1423
|
+
const runExternalApps = async (verb: string | undefined, flags: Flags, env: Readonly<Record<string, string | undefined>>): Promise<void> => {
|
|
1424
|
+
if (verb === 'put') {
|
|
1425
|
+
const { path, value } = await fileArgument(flags)
|
|
1426
|
+
const request = parseExternalAppFile(value, path)
|
|
1427
|
+
const result = await registryCall(() => iamAdminClient(flags.values.get('iam-url'), env).externalApps.put(request))
|
|
1428
|
+
emit(flags, result, () => externalAppLine(result))
|
|
1429
|
+
return
|
|
1430
|
+
}
|
|
1431
|
+
if (verb === 'list') {
|
|
1432
|
+
if (flags.positional.length > 1) throw new Error('`control external-apps list` takes no argument')
|
|
1433
|
+
const result = await iamAdminClient(flags.values.get('iam-url'), env).externalApps.list()
|
|
1434
|
+
emitList(flags, result, externalAppLine, 'no external applications registered')
|
|
1435
|
+
return
|
|
1436
|
+
}
|
|
1437
|
+
if (verb === 'get') {
|
|
1438
|
+
const app = positionalArgument(flags, 'an app id', '`control external-apps get`')
|
|
1439
|
+
const result = await iamAdminClient(flags.values.get('iam-url'), env).externalApps.get({ app })
|
|
1440
|
+
console.info(JSON.stringify(flags.json ? result : externalAppFile(result), null, 2))
|
|
1441
|
+
return
|
|
1442
|
+
}
|
|
1443
|
+
if (verb === 'delete') {
|
|
1444
|
+
const app = positionalArgument(flags, 'an app id', '`control external-apps delete`')
|
|
1445
|
+
const result = await iamAdminClient(flags.values.get('iam-url'), env).externalApps.delete({ app })
|
|
1446
|
+
emit(flags, result, () => 'deleted')
|
|
1447
|
+
return
|
|
1448
|
+
}
|
|
1449
|
+
throw new Error(`Unknown \`control external-apps\` verb: ${verb ?? '(missing)'}`)
|
|
1450
|
+
}
|
|
1451
|
+
|
|
1452
|
+
const runOAuthClients = async (verb: string | undefined, flags: Flags, env: Readonly<Record<string, string | undefined>>): Promise<void> => {
|
|
1453
|
+
if (verb === 'put') {
|
|
1454
|
+
const { path, value } = await fileArgument(flags)
|
|
1455
|
+
const request = parseOAuthClientFile(value, path)
|
|
1456
|
+
const result = await registryCall(() => iamAdminClient(flags.values.get('iam-url'), env).oauthClients.put(request))
|
|
1457
|
+
emit(flags, result, () => oauthClientLine(result))
|
|
1458
|
+
return
|
|
1459
|
+
}
|
|
1460
|
+
if (verb === 'list') {
|
|
1461
|
+
if (flags.positional.length > 1) throw new Error('`control oauth-clients list` takes no argument')
|
|
1462
|
+
const result = await iamAdminClient(flags.values.get('iam-url'), env).oauthClients.list()
|
|
1463
|
+
emitList(flags, result, oauthClientLine, 'no OAuth clients registered')
|
|
1464
|
+
return
|
|
1465
|
+
}
|
|
1466
|
+
if (verb === 'delete') {
|
|
1467
|
+
const clientId = positionalArgument(flags, 'a client id', '`control oauth-clients delete`')
|
|
1468
|
+
const result = await iamAdminClient(flags.values.get('iam-url'), env).oauthClients.delete({ clientId })
|
|
1469
|
+
emit(flags, result, () => 'deleted')
|
|
1470
|
+
return
|
|
1471
|
+
}
|
|
1472
|
+
throw new Error(`Unknown \`control oauth-clients\` verb: ${verb ?? '(missing)'}`)
|
|
1473
|
+
}
|
|
1474
|
+
|
|
1092
1475
|
const runDeploy = async (flags: Flags, env: Readonly<Record<string, string | undefined>>): Promise<void> => {
|
|
1093
1476
|
const ref = optional(flags, 'ref')
|
|
1094
|
-
const
|
|
1477
|
+
const client = controlClient(flags, env)
|
|
1478
|
+
const created = await client.deploy({
|
|
1095
1479
|
appId: required(flags, 'app'),
|
|
1096
1480
|
env: required(flags, 'env'),
|
|
1097
1481
|
...(ref === undefined ? {} : { ref }),
|
|
1098
1482
|
})
|
|
1483
|
+
const result = flags.wait ? await followRun((runId) => client.runs.get({ runId }), created, { intervalMs: WAIT_INTERVAL_MS }) : created
|
|
1484
|
+
const hint = runHint(result)
|
|
1485
|
+
if (hint !== null && !flags.wait) console.warn(hint)
|
|
1099
1486
|
emit(flags, result, () => runLine(result))
|
|
1100
1487
|
}
|
|
1101
1488
|
|
|
1489
|
+
/** How often `deploy --wait` reads the run, and `requests get --wait` the request, again. */
|
|
1490
|
+
const WAIT_INTERVAL_MS = 5000
|
|
1491
|
+
|
|
1492
|
+
/**
|
|
1493
|
+
* What stderr says about a run beside its row: the link a person approves it at, or why it failed. A non-person's
|
|
1494
|
+
* deploy of a protected environment carries the link from its creation (ADR-0050 §4).
|
|
1495
|
+
*/
|
|
1496
|
+
export const runHint = (run: RunDto): string | null => {
|
|
1497
|
+
if (run.status === 'failed') {
|
|
1498
|
+
if (run.failureCause === 'rejected') return 'a person refused this deploy; nothing was deployed'
|
|
1499
|
+
if (run.failureCause === 'expired') return 'nobody approved or refused this deploy before its deadline, so it expired; nothing was deployed'
|
|
1500
|
+
return `why it failed: fabrika control runs log --run=${run.id}`
|
|
1501
|
+
}
|
|
1502
|
+
if (run.approvalUrl !== undefined) return `a person approves or refuses this deploy at ${run.approvalUrl}`
|
|
1503
|
+
return null
|
|
1504
|
+
}
|
|
1505
|
+
|
|
1102
1506
|
/**
|
|
1103
|
-
*
|
|
1507
|
+
* Follow a run until it succeeds or fails, saying on stderr when it starts to wait for a person and where. Approval is
|
|
1508
|
+
* only a step: an approved run deploys, and its outcome is what this answers.
|
|
1509
|
+
*/
|
|
1510
|
+
export const followRun = async (
|
|
1511
|
+
read: (runId: string) => Promise<RunDto>,
|
|
1512
|
+
created: RunDto,
|
|
1513
|
+
options: { readonly intervalMs: number },
|
|
1514
|
+
): Promise<RunDto> => {
|
|
1515
|
+
let run = created
|
|
1516
|
+
let said: string | null = null
|
|
1517
|
+
while (run.status !== 'succeeded' && run.status !== 'failed') {
|
|
1518
|
+
const hint = runHint(run)
|
|
1519
|
+
const line = hint === null ? `the run is ${run.status.replace('_', ' ')}` : hint
|
|
1520
|
+
if (line !== said) console.warn(line)
|
|
1521
|
+
said = line
|
|
1522
|
+
await Bun.sleep(options.intervalMs)
|
|
1523
|
+
run = await read(run.id)
|
|
1524
|
+
}
|
|
1525
|
+
const hint = runHint(run)
|
|
1526
|
+
if (hint !== null) console.warn(hint)
|
|
1527
|
+
return run
|
|
1528
|
+
}
|
|
1529
|
+
|
|
1530
|
+
/**
|
|
1531
|
+
* Ask a person to approve a write instead of making it (ADR-0083 §8): stderr says where they decide it and, for a
|
|
1532
|
+
* secret, the value's fingerprint, computed here and compared with Control's; stdout prints the request. `secretValue`
|
|
1533
|
+
* is cut out of any failure that quotes it.
|
|
1534
|
+
*/
|
|
1535
|
+
const requestChange = async (client: ControlClient, flags: Flags, kind: string, input: JsonValue, secretValue?: string): Promise<void> => {
|
|
1536
|
+
let created: CreateApprovalRequestResponse
|
|
1537
|
+
try {
|
|
1538
|
+
created = await client.approvals.requests.create({ kind, input })
|
|
1539
|
+
} catch (error) {
|
|
1540
|
+
if (secretValue === undefined) throw error
|
|
1541
|
+
throw new Error(failureMessage(error, secretValue, 'secret value'))
|
|
1542
|
+
}
|
|
1543
|
+
await handRequest(client, flags, created, { routed: false, ...(secretValue === undefined ? {} : { secretValue }) })
|
|
1544
|
+
}
|
|
1545
|
+
|
|
1546
|
+
/**
|
|
1547
|
+
* The exit code of a write that did not apply because it waits for a person (ADR-0083 §3): neither done nor failed.
|
|
1548
|
+
* sysexits' EX_TEMPFAIL, "not done now; it may be later".
|
|
1549
|
+
*/
|
|
1550
|
+
export const APPROVAL_PENDING_EXIT_CODE = 75
|
|
1551
|
+
|
|
1552
|
+
/** A write Control stored as a request for a person instead of making it; the process exits with `APPROVAL_PENDING_EXIT_CODE`. */
|
|
1553
|
+
export class ApprovalPendingError extends Error {
|
|
1554
|
+
readonly exitCode = APPROVAL_PENDING_EXIT_CODE
|
|
1555
|
+
}
|
|
1556
|
+
|
|
1557
|
+
/** What printing and following a request takes from a command's flags. */
|
|
1558
|
+
export interface RequestOutput {
|
|
1559
|
+
readonly json: boolean
|
|
1560
|
+
readonly wait: boolean
|
|
1561
|
+
}
|
|
1562
|
+
|
|
1563
|
+
/**
|
|
1564
|
+
* The request Control stored a write as (`approval_requested`), or null for any other answer. An answer whose data does
|
|
1565
|
+
* not read as a request is left as Control's refusal, whose message names the link.
|
|
1566
|
+
*/
|
|
1567
|
+
const routedRequest = (error: unknown): CreateApprovalRequestResponse | null => {
|
|
1568
|
+
if (!(error instanceof RpcError) || error.type !== APPROVAL_REQUESTED) return null
|
|
1569
|
+
const parsed = approvalRequestedSchema.safeParse(error.data)
|
|
1570
|
+
return parsed.success ? parsed.data : null
|
|
1571
|
+
}
|
|
1572
|
+
|
|
1573
|
+
/**
|
|
1574
|
+
* Make a write; when Control stores it as a request for a person instead (D8, a protected environment), print the
|
|
1575
|
+
* request as `--request` does and, without `--wait`, fail with `ApprovalPendingError`. With `--wait` the request is
|
|
1576
|
+
* followed: an executed one answers null, anything else fails. `secretValue` is the value a secret write sent, whose
|
|
1577
|
+
* fingerprint is computed here.
|
|
1578
|
+
*/
|
|
1579
|
+
export const directWrite = async <T>(
|
|
1580
|
+
client: ControlClient,
|
|
1581
|
+
output: RequestOutput,
|
|
1582
|
+
write: () => Promise<T>,
|
|
1583
|
+
secretValue?: string,
|
|
1584
|
+
): Promise<T | null> => {
|
|
1585
|
+
try {
|
|
1586
|
+
return await write()
|
|
1587
|
+
} catch (error) {
|
|
1588
|
+
const created = routedRequest(error)
|
|
1589
|
+
if (created === null) throw error
|
|
1590
|
+
await handRequest(client, output, created, { routed: true, ...(secretValue === undefined ? {} : { secretValue }) })
|
|
1591
|
+
return null
|
|
1592
|
+
}
|
|
1593
|
+
}
|
|
1594
|
+
|
|
1595
|
+
/**
|
|
1596
|
+
* Print a request a person decides: for a secret, the value's fingerprint, computed here and compared with Control's;
|
|
1597
|
+
* then follow it with `--wait`, or print it. A routed write that did not execute fails.
|
|
1598
|
+
*/
|
|
1599
|
+
const handRequest = async (
|
|
1600
|
+
client: ControlClient,
|
|
1601
|
+
output: RequestOutput,
|
|
1602
|
+
created: CreateApprovalRequestResponse,
|
|
1603
|
+
options: { readonly routed: boolean; readonly secretValue?: string },
|
|
1604
|
+
): Promise<void> => {
|
|
1605
|
+
if (options.secretValue !== undefined) {
|
|
1606
|
+
// The first 8 hex characters of the value's SHA-256, as the page shows them: the CLI's own, not an echo of Control's.
|
|
1607
|
+
const fingerprint = sha256Hex(options.secretValue).slice(0, 8)
|
|
1608
|
+
if (created.fingerprint !== fingerprint) {
|
|
1609
|
+
throw new Error(
|
|
1610
|
+
`Control answered the fingerprint ${created.fingerprint ?? '(none)'}, but the value sent has ${fingerprint}: `
|
|
1611
|
+
+ `refuse the request at ${created.url}, since what it holds is not the value you sent`,
|
|
1612
|
+
)
|
|
1613
|
+
}
|
|
1614
|
+
console.warn(`the value's fingerprint is ${fingerprint}: the person sees the same one beside the value's length on the page`)
|
|
1615
|
+
}
|
|
1616
|
+
if (output.wait) {
|
|
1617
|
+
const read = (id: string) => client.approvals.requests.get({ id })
|
|
1618
|
+
const result = await followRequest(read, await read(created.id), { intervalMs: WAIT_INTERVAL_MS, settleTimeoutMs: REQUEST_SETTLE_TIMEOUT_MS })
|
|
1619
|
+
emit(output, result, () => requestLine(result))
|
|
1620
|
+
if (options.routed && result.state !== 'executed') {
|
|
1621
|
+
throw new Error(requestHint(result) ?? `the request is ${result.state}`)
|
|
1622
|
+
}
|
|
1623
|
+
return
|
|
1624
|
+
}
|
|
1625
|
+
if (!options.routed) console.warn(`a person approves or refuses this request at ${created.url}`)
|
|
1626
|
+
emit(output, created, () => `${created.id}\t${created.state}\t${created.url}`)
|
|
1627
|
+
if (options.routed) {
|
|
1628
|
+
throw new ApprovalPendingError(
|
|
1629
|
+
`the change was not made: it waits for a person, who approves or refuses it at ${created.url}; `
|
|
1630
|
+
+ `hand them the link, and follow it with \`fabrika control requests get ${created.id} --wait\``,
|
|
1631
|
+
)
|
|
1632
|
+
}
|
|
1633
|
+
}
|
|
1634
|
+
|
|
1635
|
+
const runRequests = async (verb: string | undefined, flags: Flags, env: Readonly<Record<string, string | undefined>>): Promise<void> => {
|
|
1636
|
+
if (verb !== 'get') throw new Error(`Unknown \`control requests\` verb: ${verb ?? '(missing)'}`)
|
|
1637
|
+
const id = flags.positional[1]
|
|
1638
|
+
if (id === undefined) throw new Error('`control requests get` needs the request id: fabrika control requests get <id>')
|
|
1639
|
+
const client = controlClient(flags, env)
|
|
1640
|
+
const read = (requestId: string) => client.approvals.requests.get({ id: requestId })
|
|
1641
|
+
const request = await read(id)
|
|
1642
|
+
const result = flags.wait
|
|
1643
|
+
? await followRequest(read, request, { intervalMs: WAIT_INTERVAL_MS, settleTimeoutMs: REQUEST_SETTLE_TIMEOUT_MS })
|
|
1644
|
+
: request
|
|
1645
|
+
const hint = requestHint(result)
|
|
1646
|
+
if (hint !== null && !flags.wait) console.warn(hint)
|
|
1647
|
+
emit(flags, result, () => requestLine(result))
|
|
1648
|
+
}
|
|
1649
|
+
|
|
1650
|
+
/**
|
|
1651
|
+
* `access request-grant`: ask a person to give a principal one role of an application environment; `access request-key`:
|
|
1652
|
+
* ask a person for a key (ADR-0083 §8).
|
|
1653
|
+
*/
|
|
1654
|
+
const runAccess = async (verb: string | undefined, flags: Flags, env: Readonly<Record<string, string | undefined>>): Promise<void> => {
|
|
1655
|
+
if (verb === 'request-key') return requestKey(flags, env)
|
|
1656
|
+
if (verb !== 'request-grant') throw new Error(`Unknown \`control access\` verb: ${verb ?? '(missing)'}`)
|
|
1657
|
+
const expiresIn = Number(required(flags, 'expires-in'))
|
|
1658
|
+
if (!Number.isSafeInteger(expiresIn) || expiresIn <= 0) throw new Error('--expires-in must be a positive whole number of seconds')
|
|
1659
|
+
const scope = optional(flags, 'scope')
|
|
1660
|
+
const separator = scope?.indexOf(':') ?? -1
|
|
1661
|
+
if (scope !== undefined && (separator <= 0 || separator === scope.length - 1)) {
|
|
1662
|
+
throw new Error("--scope names a value of the role's dimension: --scope=<dimension>:<value>")
|
|
1663
|
+
}
|
|
1664
|
+
const input: JsonValue = {
|
|
1665
|
+
appId: required(flags, 'app'),
|
|
1666
|
+
env: required(flags, 'env'),
|
|
1667
|
+
principalId: required(flags, 'principal'),
|
|
1668
|
+
role: required(flags, 'role'),
|
|
1669
|
+
scope: scope === undefined ? null : { type: scope.slice(0, separator), value: scope.slice(separator + 1) },
|
|
1670
|
+
expiresAt: Math.floor(Date.now() / 1000) + expiresIn,
|
|
1671
|
+
}
|
|
1672
|
+
await requestChange(controlClient(flags, env), flags, 'iam.grants.create', input)
|
|
1673
|
+
}
|
|
1674
|
+
|
|
1675
|
+
/**
|
|
1676
|
+
* `access request-key`: a key pair made in memory, whose public half goes with the request and whose private half opens
|
|
1677
|
+
* the key IAM encrypted to it. The private key is never exported or written, so the key is fetched in this run or never.
|
|
1678
|
+
*/
|
|
1679
|
+
const requestKey = async (flags: Flags, env: Readonly<Record<string, string | undefined>>): Promise<void> => {
|
|
1680
|
+
const actions = flags.repeated.get('action') ?? []
|
|
1681
|
+
if (actions.length === 0) throw new Error('--action is required: each action the key holds, e.g. --action=deploy.trigger --action=deploy.read')
|
|
1682
|
+
const expiresIn = Number(required(flags, 'expires-in'))
|
|
1683
|
+
if (!Number.isSafeInteger(expiresIn) || expiresIn <= 0) throw new Error('--expires-in must be a positive whole number of seconds')
|
|
1684
|
+
const appId = required(flags, 'app')
|
|
1685
|
+
const label = required(flags, 'label')
|
|
1686
|
+
if (!flags.wait) {
|
|
1687
|
+
throw new Error(
|
|
1688
|
+
'`control access request-key` needs --wait: the private key that opens the issued key lives only in this process, so the key cannot be fetched later',
|
|
1689
|
+
)
|
|
1690
|
+
}
|
|
1691
|
+
const pair = await generateKeyPair(REQUESTED_KEY_JWE.alg, { crv: 'P-256' })
|
|
1692
|
+
const exported = await exportJWK(pair.publicKey)
|
|
1693
|
+
if (typeof exported.x !== 'string' || typeof exported.y !== 'string') throw new Error('could not export the public key')
|
|
1694
|
+
const publicKey: RecipientPublicKey = { kty: 'EC', crv: 'P-256', x: exported.x, y: exported.y }
|
|
1695
|
+
const client = controlClient(flags, env)
|
|
1696
|
+
const created = await client.approvals.requests.create({
|
|
1697
|
+
kind: 'iam.apiKeys.provision',
|
|
1698
|
+
input: { appId, label, actions: [...actions], expiresAt: Math.floor(Date.now() / 1000) + expiresIn, publicKey },
|
|
1699
|
+
})
|
|
1700
|
+
console.warn(`a person approves or refuses this request at ${created.url}`)
|
|
1701
|
+
console.warn(`the public key's thumbprint is ${recipientKeyThumbprint(publicKey)}: the person sees the same one on the page`)
|
|
1702
|
+
const read = (id: string) => client.approvals.requests.get({ id })
|
|
1703
|
+
const settled = await followRequest(read, await read(created.id), {
|
|
1704
|
+
intervalMs: WAIT_INTERVAL_MS,
|
|
1705
|
+
settleTimeoutMs: REQUEST_SETTLE_TIMEOUT_MS,
|
|
1706
|
+
unsettled: (request, minutes) =>
|
|
1707
|
+
`the request is still ${request.state} after ${minutes} minutes, and this process stops waiting: no other process can fetch the key, `
|
|
1708
|
+
+ 'since the private key that opens it lived only here; a key nobody fetched is revoked at its delivery deadline, so ask again',
|
|
1709
|
+
})
|
|
1710
|
+
if (settled.state !== 'executed') throw new Error(requestHint(settled) ?? `the request is ${settled.state}`)
|
|
1711
|
+
const { jwe } = await client.approvals.requests.fetchKey({ id: created.id })
|
|
1712
|
+
const { plaintext } = await compactDecrypt(jwe, pair.privateKey, {
|
|
1713
|
+
keyManagementAlgorithms: [REQUESTED_KEY_JWE.alg],
|
|
1714
|
+
contentEncryptionAlgorithms: [REQUESTED_KEY_JWE.enc],
|
|
1715
|
+
})
|
|
1716
|
+
const key = new TextDecoder().decode(plaintext)
|
|
1717
|
+
emit(flags, { requestId: created.id, key }, () => key)
|
|
1718
|
+
}
|
|
1719
|
+
|
|
1720
|
+
const requestLine = (request: ApprovalRequestDto): string => `${request.id}\t${request.kind}\t${request.appId}\t${request.env}\t${request.state}`
|
|
1721
|
+
|
|
1722
|
+
/** What stderr says about a request beside its row: where a person decides it, or why it did not run. */
|
|
1723
|
+
export const requestHint = (request: ApprovalRequestDto): string | null => {
|
|
1724
|
+
switch (request.state) {
|
|
1725
|
+
case 'pending':
|
|
1726
|
+
return request.url === undefined ? 'the request waits for a person' : `a person approves or refuses this request at ${request.url}`
|
|
1727
|
+
case 'rejected':
|
|
1728
|
+
return 'a person refused this request; nothing changed'
|
|
1729
|
+
case 'expired':
|
|
1730
|
+
return 'nobody approved or refused this request before its deadline, so it expired; nothing changed'
|
|
1731
|
+
case 'failed':
|
|
1732
|
+
case 'stale':
|
|
1733
|
+
case 'unknown':
|
|
1734
|
+
return request.error === undefined ? `the request is ${request.state}` : `the request is ${request.state}: ${request.error}`
|
|
1735
|
+
case 'approved':
|
|
1736
|
+
case 'executing':
|
|
1737
|
+
return `the request is ${request.state}`
|
|
1738
|
+
case 'executed':
|
|
1739
|
+
return null
|
|
1740
|
+
}
|
|
1741
|
+
}
|
|
1742
|
+
|
|
1743
|
+
/**
|
|
1744
|
+
* How long `requests get --wait` follows a request once a person decided it. Waiting is bounded by the request's deadline,
|
|
1745
|
+
* but an `unknown` outcome lasts until Control settles it, which a Control without the request's kind never does.
|
|
1746
|
+
*/
|
|
1747
|
+
const REQUEST_SETTLE_TIMEOUT_MS = 15 * 60_000
|
|
1748
|
+
|
|
1749
|
+
/** A failed read worth repeating: the request never arrived, or Control or a hop before it failed (5xx). */
|
|
1750
|
+
const transientFailure = (error: unknown): string | null => {
|
|
1751
|
+
if (!(error instanceof RpcError) || error.httpStatus === undefined) return null
|
|
1752
|
+
if (error.httpStatus === 0) return 'a network error'
|
|
1753
|
+
return error.httpStatus >= 500 ? `HTTP ${error.httpStatus}` : null
|
|
1754
|
+
}
|
|
1755
|
+
|
|
1756
|
+
/**
|
|
1757
|
+
* Follow a request until it settles, saying each stage once on stderr; what it ended as is what this answers. Once it is
|
|
1758
|
+
* no longer pending, it stops with an error after `settleTimeoutMs`, which `unsettled` words. A read that fails on the way
|
|
1759
|
+
* or with a 5xx is repeated at the next interval while the wait lasts: until the deadline of a pending request, and
|
|
1760
|
+
* until `settleTimeoutMs` of a decided one.
|
|
1761
|
+
*/
|
|
1762
|
+
export const followRequest = async (
|
|
1763
|
+
read: (id: string) => Promise<ApprovalRequestDto>,
|
|
1764
|
+
first: ApprovalRequestDto,
|
|
1765
|
+
options: {
|
|
1766
|
+
readonly intervalMs: number
|
|
1767
|
+
readonly settleTimeoutMs: number
|
|
1768
|
+
readonly unsettled?: (request: ApprovalRequestDto, minutes: number) => string
|
|
1769
|
+
},
|
|
1770
|
+
): Promise<ApprovalRequestDto> => {
|
|
1771
|
+
let request = first
|
|
1772
|
+
let said: string | null = null
|
|
1773
|
+
let decidedAt: number | null = null
|
|
1774
|
+
while (!isFinalApprovalRequestState(request.state)) {
|
|
1775
|
+
if (request.state !== 'pending') {
|
|
1776
|
+
decidedAt ??= Date.now()
|
|
1777
|
+
if (Date.now() - decidedAt >= options.settleTimeoutMs) {
|
|
1778
|
+
const minutes = Math.round(options.settleTimeoutMs / 60_000)
|
|
1779
|
+
throw new Error(
|
|
1780
|
+
options.unsettled?.(request, minutes)
|
|
1781
|
+
?? `the request is still ${request.state} after ${minutes} minutes; Control keeps following it: fabrika control requests get ${request.id}`,
|
|
1782
|
+
)
|
|
1783
|
+
}
|
|
1784
|
+
}
|
|
1785
|
+
const line = requestHint(request) ?? `the request is ${request.state}`
|
|
1786
|
+
if (line !== said) console.warn(line)
|
|
1787
|
+
said = line
|
|
1788
|
+
await Bun.sleep(options.intervalMs)
|
|
1789
|
+
try {
|
|
1790
|
+
request = await read(request.id)
|
|
1791
|
+
} catch (error) {
|
|
1792
|
+
const transient = transientFailure(error)
|
|
1793
|
+
const waitEndsAt = decidedAt === null ? request.deadline * 1000 : decidedAt + options.settleTimeoutMs
|
|
1794
|
+
if (transient === null || Date.now() >= waitEndsAt) throw error
|
|
1795
|
+
console.warn(`could not read the request (${transient}); reading it again`)
|
|
1796
|
+
}
|
|
1797
|
+
}
|
|
1798
|
+
const hint = requestHint(request)
|
|
1799
|
+
if (hint !== null) console.warn(hint)
|
|
1800
|
+
return request
|
|
1801
|
+
}
|
|
1802
|
+
|
|
1803
|
+
/**
|
|
1804
|
+
* `command` is the group (`key`, `apps`, `runs`, `requests`, `register`, `deploy`); the verb, where a group has
|
|
1104
1805
|
* one, is the first positional word after it. `provider` reaches here only to label an envelope.
|
|
1105
1806
|
*/
|
|
1807
|
+
/** Whether a command takes `--request`: only the writes it routes through an approval request. */
|
|
1808
|
+
const takesRequest = (command: string | undefined, positional: readonly string[]): boolean =>
|
|
1809
|
+
command === 'apps' && (positional[0] === 'secrets' || positional[0] === 'variables') && (positional[1] === 'put' || positional[1] === 'delete')
|
|
1810
|
+
|
|
1106
1811
|
export const runControlCli = async (
|
|
1107
1812
|
command: string | undefined,
|
|
1108
1813
|
argv: readonly string[],
|
|
@@ -1113,6 +1818,11 @@ export const runControlCli = async (
|
|
|
1113
1818
|
try {
|
|
1114
1819
|
const flags = parseControlFlags(argv)
|
|
1115
1820
|
const verb = flags.positional[0]
|
|
1821
|
+
if (flags.request && !takesRequest(command, flags.positional)) {
|
|
1822
|
+
throw new Error(
|
|
1823
|
+
'--request is taken only by apps secrets put|delete and apps variables put|delete; anywhere else it would be ignored and the write made directly',
|
|
1824
|
+
)
|
|
1825
|
+
}
|
|
1116
1826
|
switch (command) {
|
|
1117
1827
|
case undefined:
|
|
1118
1828
|
console.info(USAGE)
|
|
@@ -1134,20 +1844,33 @@ export const runControlCli = async (
|
|
|
1134
1844
|
case 'namespaces':
|
|
1135
1845
|
await runNamespaces(verb, flags, env)
|
|
1136
1846
|
return
|
|
1847
|
+
case 'requests':
|
|
1848
|
+
await runRequests(verb, flags, env)
|
|
1849
|
+
return
|
|
1850
|
+
case 'access':
|
|
1851
|
+
await runAccess(verb, flags, env)
|
|
1852
|
+
return
|
|
1137
1853
|
case 'register':
|
|
1138
1854
|
await runRegister(flags, provider, env)
|
|
1139
1855
|
return
|
|
1140
1856
|
case 'deploy':
|
|
1141
1857
|
await runDeploy(flags, env)
|
|
1142
1858
|
return
|
|
1859
|
+
case 'external-apps':
|
|
1860
|
+
await runExternalApps(verb, flags, env)
|
|
1861
|
+
return
|
|
1862
|
+
case 'oauth-clients':
|
|
1863
|
+
await runOAuthClients(verb, flags, env)
|
|
1864
|
+
return
|
|
1143
1865
|
default:
|
|
1144
1866
|
throw new Error(`Unknown control command: ${command}\n\n${USAGE}`)
|
|
1145
1867
|
}
|
|
1146
1868
|
} catch (error) {
|
|
1869
|
+
if (error instanceof ApprovalPendingError) throw error
|
|
1147
1870
|
// An RPC denial is an ANSWER, not a transport fault; keep its type so a caller can tell "the
|
|
1148
1871
|
// control plane said no" from "the control plane was unreachable".
|
|
1149
1872
|
const message = error instanceof RpcError ? `${error.type}: ${error.message}` : error instanceof Error ? error.message : String(error)
|
|
1150
|
-
throw new Error(withoutControlKey(message, env))
|
|
1873
|
+
throw new Error(withoutProvisioningKey(withoutControlKey(message, env), env))
|
|
1151
1874
|
}
|
|
1152
1875
|
}
|
|
1153
1876
|
|