@airctrl/cli 0.0.0-stage → 0.4.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 +2080 -2
- package/dist/cli-error.js +29 -0
- package/dist/cli.js +502 -0
- package/dist/config.js +102 -0
- package/dist/deadline.js +13 -0
- package/dist/gateway-commands.js +487 -0
- package/dist/group-commands.js +92 -0
- package/dist/identity-rotation.js +550 -0
- package/dist/index.js +21 -0
- package/dist/migrate.js +232 -0
- package/dist/parser.js +120 -0
- package/dist/pat-expired.js +31 -0
- package/dist/project-commands.js +121 -0
- package/dist/prompt.js +45 -0
- package/dist/record-commands.js +330 -0
- package/dist/resolve-client.js +160 -0
- package/dist/resolve-status-principal.js +69 -0
- package/dist/sa-commands.js +1485 -0
- package/dist/service-account-read-commands.js +38 -0
- package/dist/store/atomic-write.js +344 -0
- package/dist/store/base-url.js +71 -0
- package/dist/store/canonical.js +45 -0
- package/dist/store/durable-delete.js +86 -0
- package/dist/store/errors.js +25 -0
- package/dist/store/fsops.js +94 -0
- package/dist/store/handoff-store.js +183 -0
- package/dist/store/identity-rotation-journal.js +396 -0
- package/dist/store/index.js +20 -0
- package/dist/store/lock.js +294 -0
- package/dist/store/names.js +52 -0
- package/dist/store/paths.js +219 -0
- package/dist/store/profile-store.js +262 -0
- package/dist/store/receipt-store.js +75 -0
- package/dist/store/resolve-principal.js +125 -0
- package/dist/store/rotation-store.js +66 -0
- package/dist/store/schema.js +554 -0
- package/package.json +42 -4
|
@@ -0,0 +1,550 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* U4 Capa 3 · `airctrl sa rotate-identity --operation <uuid> --profile <successor> --holder-profile <holder>`.
|
|
3
|
+
*
|
|
4
|
+
* MACHINE/HOLDER continuation of an ALREADY-authorized identity rotation (authorize/cancel are ADMIN, out of this
|
|
5
|
+
* command). Two MACHINE authorities in one process (D12): the `--holder-profile` (sealed+active, OLD identity —
|
|
6
|
+
* claim + open old wrappers) and the `--profile` successor (its bearer authenticates manifest/stage/commit/status).
|
|
7
|
+
* Crash-safe FSM `identity_prepared → claimed → staging → commit_prepared → active_pending_cleanup → active`, driven
|
|
8
|
+
* under the DEDICATED operation lease held for the WHOLE async execution; profile locks are brief (read/checkpoint
|
|
9
|
+
* only, NEVER during HTTP). The holder is unlocked ONLY for the pre-commit stages; once the successor is
|
|
10
|
+
* committed/active the revoked holder is NEVER unlocked again (cleanup uses the durably-persisted holder binding).
|
|
11
|
+
* stdout is ONE byte-exact JSON line emitted ONLY after the lease released cleanly; zero secrets/paths/env anywhere.
|
|
12
|
+
*/
|
|
13
|
+
import { IdentityRotationContext, AirctrlError, } from '@airctrl/sdk';
|
|
14
|
+
import { acquireIdentityRotationLease, withIdentityRotationLease, journalStart, journalLoad, journalAppend, journalMarkComplete, journalDelete, acquireProfileLock, createProfile, loadProfile, replaceProfile, bumpIdentityRotationClaimAttempts, evidenceSecure, isCanonicalB64, normalizeBaseUrl, StoreError, } from './store/index.js';
|
|
15
|
+
import { resolveHolderProfile } from './resolve-client.js';
|
|
16
|
+
import { CliError } from './cli-error.js';
|
|
17
|
+
import { parseArgv } from './parser.js';
|
|
18
|
+
/** Ratified grammar (C3.3 · T6): three obligatory flags, no positional, no `--account`. */
|
|
19
|
+
export const ROTATE_IDENTITY_SPEC = {
|
|
20
|
+
positionals: [],
|
|
21
|
+
flags: ['operation', 'profile', 'holder-profile'],
|
|
22
|
+
requiredFlags: ['operation', 'profile', 'holder-profile'],
|
|
23
|
+
};
|
|
24
|
+
/** D12 · the SSOT set of authority/config control vars whose PRESENCE (never value) forbids a MACHINE flow (F3). */
|
|
25
|
+
export const IDENTITY_ROTATION_FORBIDDEN_ENV = [
|
|
26
|
+
'AC_TOKEN',
|
|
27
|
+
'AC_SA_CREDENTIAL_ID',
|
|
28
|
+
'AC_SA_CAP_PRIVATE_KEY_B64',
|
|
29
|
+
'AC_SA_SERVICE_ACCOUNT_ID',
|
|
30
|
+
'AC_SA_PRINCIPAL',
|
|
31
|
+
'AC_SA_PROFILE',
|
|
32
|
+
'AC_API_BASE_URL',
|
|
33
|
+
'AC_VAULT_PASSWORD',
|
|
34
|
+
];
|
|
35
|
+
const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
|
|
36
|
+
const UUID_ANY_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
|
|
37
|
+
const isUuid = (v) => typeof v === 'string' && UUID_RE.test(v);
|
|
38
|
+
const isLowerUuid = (v) => typeof v === 'string' && UUID_ANY_RE.test(v);
|
|
39
|
+
const isNeStr = (v) => typeof v === 'string' && v.length > 0;
|
|
40
|
+
const isIntNonNeg = (v) => typeof v === 'number' && Number.isInteger(v) && v >= 0;
|
|
41
|
+
const MAX_MANIFEST_PAGE = 200;
|
|
42
|
+
const EARLY_STAGES = new Set(['identity_prepared', 'claimed', 'staging']);
|
|
43
|
+
/** TOTAL exact-own DATA reader (F2): read EXACTLY `keys` as own DATA props or `null` — never a getter/Proxy/symbol/extra. */
|
|
44
|
+
function readExactOwnData(obj, keys) {
|
|
45
|
+
if (!obj || typeof obj !== 'object')
|
|
46
|
+
return null;
|
|
47
|
+
try {
|
|
48
|
+
if (Reflect.ownKeys(obj).length !== keys.length)
|
|
49
|
+
return null;
|
|
50
|
+
const out = {};
|
|
51
|
+
for (const k of keys) {
|
|
52
|
+
const d = Object.getOwnPropertyDescriptor(obj, k);
|
|
53
|
+
if (!d || typeof d.get === 'function' || typeof d.set === 'function' || !('value' in d))
|
|
54
|
+
return null;
|
|
55
|
+
out[k] = d.value;
|
|
56
|
+
}
|
|
57
|
+
return out;
|
|
58
|
+
}
|
|
59
|
+
catch {
|
|
60
|
+
return null;
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
function str(p, key) {
|
|
64
|
+
const v = p[key];
|
|
65
|
+
if (typeof v !== 'string' || v.length === 0)
|
|
66
|
+
throw new CliError('sa_identity_rotation_profile_conflict');
|
|
67
|
+
return v;
|
|
68
|
+
}
|
|
69
|
+
function num(p, key) {
|
|
70
|
+
const v = p[key];
|
|
71
|
+
if (typeof v !== 'number')
|
|
72
|
+
throw new CliError('sa_identity_rotation_profile_conflict');
|
|
73
|
+
return v;
|
|
74
|
+
}
|
|
75
|
+
/** Brief profile lock (read/checkpoint only, NEVER during HTTP) with falsy-safe release precedence. */
|
|
76
|
+
function withProfileLock(deps, name, fn) {
|
|
77
|
+
const lock = acquireProfileLock(deps.root, name, deps.fs);
|
|
78
|
+
let result;
|
|
79
|
+
let primary;
|
|
80
|
+
let hasPrimary = false;
|
|
81
|
+
try {
|
|
82
|
+
result = fn();
|
|
83
|
+
}
|
|
84
|
+
catch (e) {
|
|
85
|
+
primary = e;
|
|
86
|
+
hasPrimary = true;
|
|
87
|
+
}
|
|
88
|
+
let hasReleaseErr = false;
|
|
89
|
+
try {
|
|
90
|
+
lock.release();
|
|
91
|
+
}
|
|
92
|
+
catch {
|
|
93
|
+
hasReleaseErr = true;
|
|
94
|
+
}
|
|
95
|
+
if (hasPrimary)
|
|
96
|
+
throw primary;
|
|
97
|
+
if (hasReleaseErr)
|
|
98
|
+
throw new StoreError('sa_profile_lock_release_failed');
|
|
99
|
+
return result;
|
|
100
|
+
}
|
|
101
|
+
function assertSecure(deps, ev) {
|
|
102
|
+
if (!evidenceSecure(ev, deps.fs, { requireCleanTemp: true }))
|
|
103
|
+
throw new CliError('sa_identity_rotation_profile_insecure');
|
|
104
|
+
}
|
|
105
|
+
function tryLoadProfile(deps, name) {
|
|
106
|
+
try {
|
|
107
|
+
return loadProfile(deps.root, name, deps.fs);
|
|
108
|
+
}
|
|
109
|
+
catch (e) {
|
|
110
|
+
if (e instanceof StoreError && e.code === 'sa_profile_not_found')
|
|
111
|
+
return null;
|
|
112
|
+
throw e;
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
function loadStrict(deps, name) {
|
|
116
|
+
return loadProfile(deps.root, name, deps.fs);
|
|
117
|
+
}
|
|
118
|
+
// ── entry point ──────────────────────────────────────────────────────────────────────────────────────
|
|
119
|
+
export async function saRotateIdentity(argv, deps) {
|
|
120
|
+
const parsed = parseArgv(argv, ROTATE_IDENTITY_SPEC);
|
|
121
|
+
const operationId = parsed.flags.operation;
|
|
122
|
+
const successorName = parsed.flags.profile;
|
|
123
|
+
const holderName = parsed.flags['holder-profile'];
|
|
124
|
+
if (!isUuid(operationId))
|
|
125
|
+
throw new CliError('sa_identity_rotation_operation_invalid');
|
|
126
|
+
if (successorName === holderName)
|
|
127
|
+
throw new CliError('sa_identity_rotation_profiles_must_differ');
|
|
128
|
+
// D12 (F3): reject authority/config env PRESENCE BEFORE any profile read / client build / HTTP.
|
|
129
|
+
for (const k of IDENTITY_ROTATION_FORBIDDEN_ENV) {
|
|
130
|
+
if (Object.hasOwn(deps.env, k))
|
|
131
|
+
throw new CliError('sa_identity_rotation_env_authority_forbidden');
|
|
132
|
+
}
|
|
133
|
+
// Acquire the operation lease BEFORE reading any profile or building any client (F1). A concurrent loser fails
|
|
134
|
+
// here — before unlock/HTTP. `reclaimStale` lets a RESUME reclaim the op's OWN lease left behind by a crashed
|
|
135
|
+
// (SIGKILL'd) prior run: same host + provably-dead PID only; a live/foreign holder still loses by `busy`.
|
|
136
|
+
const leaseCtx = acquireIdentityRotationLease(deps.root, operationId, deps.fs, { reclaimStale: true });
|
|
137
|
+
const output = await withIdentityRotationLease(leaseCtx, () => driveRotation(deps, { operationId, successorName, holderName, leaseCtx }));
|
|
138
|
+
deps.stdout(`${JSON.stringify(output)}\n`); // ONLY after a clean release
|
|
139
|
+
return 0;
|
|
140
|
+
}
|
|
141
|
+
async function driveRotation(deps, ctx) {
|
|
142
|
+
const { operationId, successorName, holderName } = ctx;
|
|
143
|
+
let profile = withProfileLock(deps, successorName, () => tryLoadProfile(deps, successorName));
|
|
144
|
+
if (profile)
|
|
145
|
+
assertSuccessorOpBinding(profile, operationId);
|
|
146
|
+
const needsHolder = !profile || EARLY_STAGES.has(profile.stage);
|
|
147
|
+
let client;
|
|
148
|
+
if (needsHolder) {
|
|
149
|
+
// EARLY path: resolve + unlock the (still-active) holder for claim + re-seal.
|
|
150
|
+
const holder = resolveHolderProfile({ ...deps.resolve, profileFlag: holderName });
|
|
151
|
+
if (profile)
|
|
152
|
+
assertHolderBinding(profile, holder, holderName);
|
|
153
|
+
const holderSession = await holder.client.unlock();
|
|
154
|
+
const holderIdentityPub = holderSession.serviceIdentityPublicKeyB64();
|
|
155
|
+
if (profile && str(profile, 'holderIdentityPublicKeyB64') !== holderIdentityPub)
|
|
156
|
+
throw new CliError('sa_identity_rotation_holder_mismatch');
|
|
157
|
+
client = holder.client;
|
|
158
|
+
if (!profile) {
|
|
159
|
+
const { material } = await IdentityRotationContext.prepare();
|
|
160
|
+
const prepared = {
|
|
161
|
+
schemaVersion: 1,
|
|
162
|
+
flow: 'standard',
|
|
163
|
+
stage: 'identity_prepared',
|
|
164
|
+
serviceAccountId: holder.serviceAccountId,
|
|
165
|
+
baseUrl: holder.baseUrl,
|
|
166
|
+
principalType: 'service_account',
|
|
167
|
+
mode: 'identity_rotation',
|
|
168
|
+
operationId,
|
|
169
|
+
newIdentityPublicKeyB64: material.newIdentityPublicKeyB64,
|
|
170
|
+
capPublicKeyB64: material.successorCapPublicKeyB64,
|
|
171
|
+
capPrivateKeyB64: material.successorCapPrivateKeyB64,
|
|
172
|
+
seedSealedB64: material.seedSealedB64,
|
|
173
|
+
claimIdempotencyKey: deps.newIdempotencyKey(),
|
|
174
|
+
claimAttempts: 0,
|
|
175
|
+
holderProfileName: holderName,
|
|
176
|
+
holderCredentialId: holder.credentialId,
|
|
177
|
+
holderPatId: holder.patId,
|
|
178
|
+
holderIdentityPublicKeyB64: holderIdentityPub,
|
|
179
|
+
};
|
|
180
|
+
withProfileLock(deps, successorName, () => assertSecure(deps, createProfile(deps.root, successorName, prepared, deps.fs)));
|
|
181
|
+
profile = loadStrict(deps, successorName);
|
|
182
|
+
}
|
|
183
|
+
if (profile.stage === 'identity_prepared')
|
|
184
|
+
profile = await doClaim(deps, ctx, profile, holderSession);
|
|
185
|
+
if (profile.stage === 'claimed')
|
|
186
|
+
profile = advanceStage(deps, successorName, profile, 'claimed', 'staging');
|
|
187
|
+
if (profile.stage === 'staging')
|
|
188
|
+
profile = await doStaging(deps, ctx, profile, holderSession, client);
|
|
189
|
+
}
|
|
190
|
+
else {
|
|
191
|
+
// LATE path: successor at commit_prepared/active_pending_cleanup/active — NO holder resolution/unlock. Build a
|
|
192
|
+
// successor client from the persisted successor bearer for commit/status/replay.
|
|
193
|
+
if (!profile)
|
|
194
|
+
throw new CliError('sa_identity_rotation_profile_conflict'); // unreachable (needsHolder false ⇒ profile set)
|
|
195
|
+
client = deps.makeClient({ baseUrl: str(profile, 'baseUrl'), auth: str(profile, 'bearer') });
|
|
196
|
+
}
|
|
197
|
+
if (!profile)
|
|
198
|
+
throw new CliError('sa_identity_rotation_profile_conflict');
|
|
199
|
+
if (profile.stage === 'commit_prepared')
|
|
200
|
+
profile = await doCommit(deps, ctx, profile, client);
|
|
201
|
+
return finalize(deps, ctx, profile, client);
|
|
202
|
+
}
|
|
203
|
+
/** Every stage: the successor MUST be THIS identity-rotation op, same SA. Holder binding is checked separately. */
|
|
204
|
+
function assertSuccessorOpBinding(profile, operationId) {
|
|
205
|
+
const p = profile;
|
|
206
|
+
if (profile.flow !== 'standard' || p.mode !== 'identity_rotation')
|
|
207
|
+
throw new CliError('sa_identity_rotation_profile_conflict');
|
|
208
|
+
if (profile.stage !== 'terminal' && str(profile, 'operationId') !== operationId)
|
|
209
|
+
throw new CliError('sa_identity_rotation_operation_mismatch');
|
|
210
|
+
}
|
|
211
|
+
/** Early stages only: the loaded successor must be bound to the resolved holder (name/credential/pat + SA/baseUrl). */
|
|
212
|
+
function assertHolderBinding(profile, holder, holderName) {
|
|
213
|
+
if (profile.serviceAccountId !== holder.serviceAccountId)
|
|
214
|
+
throw new CliError('sa_identity_rotation_holder_mismatch');
|
|
215
|
+
try {
|
|
216
|
+
if (normalizeBaseUrl(profile.baseUrl) !== normalizeBaseUrl(holder.baseUrl))
|
|
217
|
+
throw new CliError('sa_identity_rotation_holder_mismatch');
|
|
218
|
+
}
|
|
219
|
+
catch {
|
|
220
|
+
throw new CliError('sa_identity_rotation_holder_mismatch');
|
|
221
|
+
}
|
|
222
|
+
if (str(profile, 'holderProfileName') !== holderName || str(profile, 'holderCredentialId') !== holder.credentialId || str(profile, 'holderPatId') !== holder.patId) {
|
|
223
|
+
throw new CliError('sa_identity_rotation_holder_mismatch');
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
function advanceStage(deps, name, profile, from, to) {
|
|
227
|
+
const next = { ...profile, stage: to };
|
|
228
|
+
assertSecure(deps, replaceProfile(deps.root, name, from, next, deps.fs)); // replaceProfile self-locks
|
|
229
|
+
return loadStrict(deps, name);
|
|
230
|
+
}
|
|
231
|
+
// ── claim (durable budget F4) ──────────────────────────────────────────────────────────────────────────
|
|
232
|
+
async function doClaim(deps, ctx, profile, holderSession) {
|
|
233
|
+
const context = await IdentityRotationContext.restore({
|
|
234
|
+
seedSealedB64: str(profile, 'seedSealedB64'),
|
|
235
|
+
newIdentityPublicKeyB64: str(profile, 'newIdentityPublicKeyB64'),
|
|
236
|
+
successorCapPublicKeyB64: str(profile, 'capPublicKeyB64'),
|
|
237
|
+
successorCapPrivateKeyB64: str(profile, 'capPrivateKeyB64'),
|
|
238
|
+
});
|
|
239
|
+
const claim = await claimWithDurableBudget(deps, ctx, profile, holderSession);
|
|
240
|
+
const oldResp = await holderSession.openIdentityRotationOldChallenge(claim.challenges.oldIdentitySealedB64);
|
|
241
|
+
const commitBody = await context.buildCommitBody({
|
|
242
|
+
successorCredentialId: claim.successorCredentialId,
|
|
243
|
+
successorBearer: claim.bearerPlaintext,
|
|
244
|
+
oldIdentityResponseB64: oldResp,
|
|
245
|
+
newIdentitySealedB64: claim.challenges.newIdentitySealedB64,
|
|
246
|
+
successorCapSealedB64: claim.challenges.successorCapSealedB64,
|
|
247
|
+
});
|
|
248
|
+
const p = profile;
|
|
249
|
+
const next = {
|
|
250
|
+
schemaVersion: 1,
|
|
251
|
+
flow: 'standard',
|
|
252
|
+
stage: 'claimed',
|
|
253
|
+
serviceAccountId: p.serviceAccountId,
|
|
254
|
+
baseUrl: p.baseUrl,
|
|
255
|
+
principalType: 'service_account',
|
|
256
|
+
mode: 'identity_rotation',
|
|
257
|
+
operationId: p.operationId,
|
|
258
|
+
newIdentityPublicKeyB64: p.newIdentityPublicKeyB64,
|
|
259
|
+
capPublicKeyB64: p.capPublicKeyB64,
|
|
260
|
+
capPrivateKeyB64: p.capPrivateKeyB64,
|
|
261
|
+
credentialId: claim.successorCredentialId,
|
|
262
|
+
bearer: claim.bearerPlaintext,
|
|
263
|
+
patId: claim.patId,
|
|
264
|
+
commitBody,
|
|
265
|
+
commitIdempotencyKey: deps.newIdempotencyKey(),
|
|
266
|
+
holderProfileName: p.holderProfileName,
|
|
267
|
+
holderCredentialId: p.holderCredentialId,
|
|
268
|
+
holderPatId: p.holderPatId,
|
|
269
|
+
holderIdentityPublicKeyB64: p.holderIdentityPublicKeyB64,
|
|
270
|
+
}; // seedSealedB64 dropped in this durable transition (F1)
|
|
271
|
+
assertSecure(deps, replaceProfile(deps.root, ctx.successorName, 'identity_prepared', next, deps.fs));
|
|
272
|
+
return loadStrict(deps, ctx.successorName);
|
|
273
|
+
}
|
|
274
|
+
async function claimWithDurableBudget(deps, ctx, profile, holderSession) {
|
|
275
|
+
const saId = str(profile, 'serviceAccountId');
|
|
276
|
+
const newPub = str(profile, 'newIdentityPublicKeyB64');
|
|
277
|
+
const capPub = str(profile, 'capPublicKeyB64');
|
|
278
|
+
const idemKey = str(profile, 'claimIdempotencyKey');
|
|
279
|
+
let attempts = num(profile, 'claimAttempts');
|
|
280
|
+
// eslint-disable-next-line no-constant-condition
|
|
281
|
+
while (true) {
|
|
282
|
+
if (attempts >= 2)
|
|
283
|
+
throw new CliError('sa_identity_rotation_not_resumable'); // budget exhausted, no HTTP
|
|
284
|
+
attempts = bumpIdentityRotationClaimAttempts(deps.root, ctx.successorName, deps.fs).claimAttempts; // persist BEFORE HTTP
|
|
285
|
+
try {
|
|
286
|
+
const claim = await holderSession.saClaimIdentityRotation(saId, ctx.operationId, {
|
|
287
|
+
newIdentityPublicKeyB64: newPub,
|
|
288
|
+
successorCapPublicKeyB64: capPub,
|
|
289
|
+
idempotencyKey: idemKey,
|
|
290
|
+
});
|
|
291
|
+
return validateClaimResult(claim); // F2: exact-own, canonical, bearer present — else not_resumable
|
|
292
|
+
}
|
|
293
|
+
catch (e) {
|
|
294
|
+
if (e instanceof CliError)
|
|
295
|
+
throw e;
|
|
296
|
+
if (e instanceof TypeError)
|
|
297
|
+
continue; // transport loss ONLY → replay with the SAME key/body within budget
|
|
298
|
+
throw new CliError('sa_identity_rotation_not_resumable'); // definitive/unclaimable → not resumable
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
function validateClaimResult(c) {
|
|
303
|
+
const r = readExactOwnData(c, ['successorCredentialId', 'patId', 'bearerPlaintext', 'challenges']);
|
|
304
|
+
// R3: successorCredentialId AND patId must be canonical UUIDs (not merely non-empty), bearer a non-empty string.
|
|
305
|
+
if (!r || !isLowerUuid(r.successorCredentialId) || !isLowerUuid(r.patId) || !isNeStr(r.bearerPlaintext))
|
|
306
|
+
throw new CliError('sa_identity_rotation_not_resumable');
|
|
307
|
+
const ch = readExactOwnData(r.challenges, ['oldIdentitySealedB64', 'newIdentitySealedB64', 'successorCapSealedB64']);
|
|
308
|
+
// R3: the three challenges must be CANONICAL base64 (not any non-empty string) before they feed the SDK crypto.
|
|
309
|
+
if (!ch || !isCanonicalB64(ch.oldIdentitySealedB64) || !isCanonicalB64(ch.newIdentitySealedB64) || !isCanonicalB64(ch.successorCapSealedB64))
|
|
310
|
+
throw new CliError('sa_identity_rotation_not_resumable');
|
|
311
|
+
return c;
|
|
312
|
+
}
|
|
313
|
+
// ── staging (manifest pagination + real re-seal + durable journal) ───────────────────────────────────────
|
|
314
|
+
async function doStaging(deps, ctx, profile, holderSession, client) {
|
|
315
|
+
const saId = str(profile, 'serviceAccountId');
|
|
316
|
+
const bearer = str(profile, 'bearer');
|
|
317
|
+
const newPub = str(profile, 'newIdentityPublicKeyB64');
|
|
318
|
+
journalStart(ctx.leaseCtx, { serviceAccountId: saId, baseUrl: str(profile, 'baseUrl') });
|
|
319
|
+
let journal = journalLoad(ctx.leaseCtx);
|
|
320
|
+
let cursor = journal.batches.length ? journal.batches[journal.batches.length - 1].nextCursor : null;
|
|
321
|
+
// R3 — tie staged/totalStaged to the batch AND to the expected running total. `runningTotal` is the count of
|
|
322
|
+
// DISTINCT manifest rows we have posted (batches are disjoint manifest pages); the server's `totalStaged` MUST
|
|
323
|
+
// equal it exactly, and each `staged` MUST equal the batch size. `lastTotalStaged` is checked before commit.
|
|
324
|
+
let runningTotal = 0;
|
|
325
|
+
let lastTotalStaged = null;
|
|
326
|
+
for (const b of journal.batches) {
|
|
327
|
+
const r = validateStageResult(await client.saStageIdentityRotation(saId, ctx.operationId, { bearer, wrappers: b.body.wrappers, idempotencyKey: b.stageIdempotencyKey }), b.body.wrappers.length);
|
|
328
|
+
runningTotal += b.body.wrappers.length;
|
|
329
|
+
lastTotalStaged = r.totalStaged;
|
|
330
|
+
}
|
|
331
|
+
while (!journal.complete) {
|
|
332
|
+
const page = validateManifestPage(await client.saIdentityRotationManifest(saId, ctx.operationId, { bearer, cursor, limit: MAX_MANIFEST_PAGE }));
|
|
333
|
+
if (page.entries.length === 0) {
|
|
334
|
+
journal = journalMarkComplete(ctx.leaseCtx);
|
|
335
|
+
break;
|
|
336
|
+
}
|
|
337
|
+
const wrappers = [];
|
|
338
|
+
for (const entry of page.entries)
|
|
339
|
+
wrappers.push(await holderSession.resealIdentityRotationWrapper({ entry, newIdentityPublicKeyB64: newPub }));
|
|
340
|
+
const batch = { ordinal: journal.batches.length, entryCursor: cursor, nextCursor: page.nextCursor, stageIdempotencyKey: deps.newIdempotencyKey(), body: { wrappers } };
|
|
341
|
+
journal = journalAppend(ctx.leaseCtx, batch); // DURABLE before the POST
|
|
342
|
+
const r = validateStageResult(await client.saStageIdentityRotation(saId, ctx.operationId, { bearer, wrappers, idempotencyKey: batch.stageIdempotencyKey }), wrappers.length);
|
|
343
|
+
runningTotal += wrappers.length;
|
|
344
|
+
lastTotalStaged = r.totalStaged;
|
|
345
|
+
cursor = page.nextCursor;
|
|
346
|
+
}
|
|
347
|
+
// Before commit: the server's cumulative staged count MUST equal every distinct wrapper we posted. A pure
|
|
348
|
+
// empty-manifest / journal-already-complete resume (no stage call this run) has nothing to re-assert.
|
|
349
|
+
if (lastTotalStaged !== null && lastTotalStaged !== runningTotal)
|
|
350
|
+
throw new CliError('sa_identity_rotation_stage_total_mismatch');
|
|
351
|
+
return advanceStage(deps, ctx.successorName, profile, 'staging', 'commit_prepared');
|
|
352
|
+
}
|
|
353
|
+
function validateManifestPage(page) {
|
|
354
|
+
const r = readExactOwnData(page, ['entries', 'nextCursor']);
|
|
355
|
+
if (!r || !Array.isArray(r.entries) || r.entries.length > MAX_MANIFEST_PAGE)
|
|
356
|
+
throw new CliError('sa_identity_rotation_manifest_invalid');
|
|
357
|
+
if (!(r.nextCursor === null || isNeStr(r.nextCursor)))
|
|
358
|
+
throw new CliError('sa_identity_rotation_manifest_invalid');
|
|
359
|
+
// R3 — an EMPTY page terminates staging and therefore may ONLY carry a null cursor; a non-null next-cursor on
|
|
360
|
+
// an empty page is a contradictory (never-terminating) manifest and is rejected.
|
|
361
|
+
if (r.entries.length === 0 && r.nextCursor !== null)
|
|
362
|
+
throw new CliError('sa_identity_rotation_manifest_invalid');
|
|
363
|
+
return page;
|
|
364
|
+
}
|
|
365
|
+
function validateStageResult(res, expectedStaged) {
|
|
366
|
+
const r = readExactOwnData(res, ['staged', 'totalStaged']);
|
|
367
|
+
if (!r || !isIntNonNeg(r.staged) || !isIntNonNeg(r.totalStaged))
|
|
368
|
+
throw new CliError('sa_identity_rotation_stage_result_invalid');
|
|
369
|
+
// R3 — the backend reports `staged = <this batch's length>`; it MUST equal the batch we posted, and the
|
|
370
|
+
// cumulative `totalStaged` can never be below this batch.
|
|
371
|
+
if (r.staged !== expectedStaged || r.totalStaged < r.staged)
|
|
372
|
+
throw new CliError('sa_identity_rotation_stage_result_invalid');
|
|
373
|
+
return res;
|
|
374
|
+
}
|
|
375
|
+
// ── commit (exactly-once + transport uncertainty F4) ────────────────────────────────────────────────────
|
|
376
|
+
async function doCommit(deps, ctx, profile, client) {
|
|
377
|
+
const saId = str(profile, 'serviceAccountId');
|
|
378
|
+
const bearer = str(profile, 'bearer');
|
|
379
|
+
const commitIdemKey = str(profile, 'commitIdempotencyKey');
|
|
380
|
+
const expectedCred = str(profile, 'credentialId');
|
|
381
|
+
const commitBody = profile.commitBody;
|
|
382
|
+
let result;
|
|
383
|
+
try {
|
|
384
|
+
result = validateCommitResult(await client.saCommitIdentityRotation(saId, ctx.operationId, { bearer, body: commitBody, idempotencyKey: commitIdemKey }), ctx.operationId, expectedCred);
|
|
385
|
+
}
|
|
386
|
+
catch (e) {
|
|
387
|
+
if (e instanceof CliError)
|
|
388
|
+
throw e;
|
|
389
|
+
if (e instanceof TypeError) {
|
|
390
|
+
result = await resolveCommitUncertainty(client, saId, ctx, bearer, commitBody, commitIdemKey, expectedCred);
|
|
391
|
+
}
|
|
392
|
+
else if (e instanceof AirctrlError && e.code) {
|
|
393
|
+
throw new CliError(e.code);
|
|
394
|
+
}
|
|
395
|
+
else {
|
|
396
|
+
throw new CliError('sa_identity_rotation_not_resumable');
|
|
397
|
+
}
|
|
398
|
+
}
|
|
399
|
+
const p = profile;
|
|
400
|
+
const next = {
|
|
401
|
+
schemaVersion: 1,
|
|
402
|
+
flow: 'standard',
|
|
403
|
+
stage: 'active_pending_cleanup',
|
|
404
|
+
serviceAccountId: p.serviceAccountId,
|
|
405
|
+
baseUrl: p.baseUrl,
|
|
406
|
+
principalType: 'service_account',
|
|
407
|
+
mode: 'identity_rotation',
|
|
408
|
+
operationId: p.operationId,
|
|
409
|
+
credentialId: p.credentialId,
|
|
410
|
+
patId: p.patId,
|
|
411
|
+
bearer: p.bearer,
|
|
412
|
+
capPublicKeyB64: p.capPublicKeyB64,
|
|
413
|
+
capPrivateKeyB64: p.capPrivateKeyB64,
|
|
414
|
+
holderProfileName: p.holderProfileName,
|
|
415
|
+
holderCredentialId: p.holderCredentialId,
|
|
416
|
+
holderPatId: p.holderPatId,
|
|
417
|
+
resultResealedRecord: result.resealedRecordWrappers,
|
|
418
|
+
resultResealedProject: result.resealedProjectWrappers,
|
|
419
|
+
resultRevoked: result.revokedCredentials,
|
|
420
|
+
};
|
|
421
|
+
assertSecure(deps, replaceProfile(deps.root, ctx.successorName, 'commit_prepared', next, deps.fs));
|
|
422
|
+
return loadStrict(deps, ctx.successorName);
|
|
423
|
+
}
|
|
424
|
+
/**
|
|
425
|
+
* Resolve a lost-to-transport commit (F4): status FIRST. `committed`+valid → exactly-once success; still committable
|
|
426
|
+
* (`claimed`/`staging`) → ONE bounded replay with the SAME key/body (the single commit); a further transport loss →
|
|
427
|
+
* conserve `commit_prepared` for a later resume (`sa_identity_rotation_commit_uncertain`, no output); terminal →
|
|
428
|
+
* stable code.
|
|
429
|
+
*/
|
|
430
|
+
async function resolveCommitUncertainty(client, saId, ctx, bearer, body, key, expectedCred) {
|
|
431
|
+
let st;
|
|
432
|
+
try {
|
|
433
|
+
st = validateStatus(await client.saGetIdentityRotationStatus(saId, ctx.operationId, { bearer }), ctx.operationId);
|
|
434
|
+
}
|
|
435
|
+
catch (e) {
|
|
436
|
+
if (e instanceof CliError)
|
|
437
|
+
throw e;
|
|
438
|
+
throw new CliError('sa_identity_rotation_commit_uncertain'); // status also lost → resume later
|
|
439
|
+
}
|
|
440
|
+
if (st.status === 'committed') {
|
|
441
|
+
return validateCommitResult(st.result, ctx.operationId, expectedCred); // post-commit loss → exactly-once
|
|
442
|
+
}
|
|
443
|
+
if (st.status === 'claimed' || st.status === 'staging') {
|
|
444
|
+
try {
|
|
445
|
+
return validateCommitResult(await client.saCommitIdentityRotation(saId, ctx.operationId, { bearer, body, idempotencyKey: key }), ctx.operationId, expectedCred);
|
|
446
|
+
}
|
|
447
|
+
catch (e) {
|
|
448
|
+
if (e instanceof CliError)
|
|
449
|
+
throw e;
|
|
450
|
+
if (e instanceof TypeError)
|
|
451
|
+
throw new CliError('sa_identity_rotation_commit_uncertain'); // transport again → resume later
|
|
452
|
+
if (e instanceof AirctrlError && e.code)
|
|
453
|
+
throw new CliError(e.code);
|
|
454
|
+
throw new CliError('sa_identity_rotation_not_resumable');
|
|
455
|
+
}
|
|
456
|
+
}
|
|
457
|
+
throw new CliError(st.status === 'expired' ? 'sa_identity_rotation_expired' : st.status === 'cancelled' ? 'sa_identity_rotation_cancelled' : 'sa_identity_rotation_not_resumable');
|
|
458
|
+
}
|
|
459
|
+
function validateCommitResult(res, operationId, expectedCred) {
|
|
460
|
+
const r = readExactOwnData(res, ['operationId', 'successorCredentialId', 'resealedRecordWrappers', 'resealedProjectWrappers', 'revokedCredentials']);
|
|
461
|
+
if (!r || r.operationId !== operationId || r.successorCredentialId !== expectedCred)
|
|
462
|
+
throw new CliError('sa_identity_rotation_commit_result_invalid');
|
|
463
|
+
if (!isIntNonNeg(r.resealedRecordWrappers) || !isIntNonNeg(r.resealedProjectWrappers) || !isIntNonNeg(r.revokedCredentials))
|
|
464
|
+
throw new CliError('sa_identity_rotation_commit_result_invalid');
|
|
465
|
+
return res;
|
|
466
|
+
}
|
|
467
|
+
function validateStatus(res, operationId) {
|
|
468
|
+
const r = readExactOwnData(res, ['operationId', 'status', 'manifestCount', 'stagedCount', 'result']);
|
|
469
|
+
const STATES = ['authorized', 'claimed', 'staging', 'committed', 'cancelled', 'expired'];
|
|
470
|
+
if (!r || r.operationId !== operationId || typeof r.status !== 'string' || !STATES.includes(r.status))
|
|
471
|
+
throw new CliError('sa_identity_rotation_status_invalid');
|
|
472
|
+
if (!isIntNonNeg(r.manifestCount) || !isIntNonNeg(r.stagedCount))
|
|
473
|
+
throw new CliError('sa_identity_rotation_status_invalid');
|
|
474
|
+
if (r.status === 'committed') {
|
|
475
|
+
if (!r.result || typeof r.result !== 'object')
|
|
476
|
+
throw new CliError('sa_identity_rotation_status_invalid');
|
|
477
|
+
}
|
|
478
|
+
else if (r.result !== null) {
|
|
479
|
+
throw new CliError('sa_identity_rotation_status_invalid');
|
|
480
|
+
}
|
|
481
|
+
return res;
|
|
482
|
+
}
|
|
483
|
+
// ── finalize (post-commit crash-safe order) ─────────────────────────────────────────────────────────────
|
|
484
|
+
async function finalize(deps, ctx, profile, client) {
|
|
485
|
+
if (profile.stage === 'active_pending_cleanup') {
|
|
486
|
+
const result = { resealedRecordWrappers: num(profile, 'resultResealedRecord'), resealedProjectWrappers: num(profile, 'resultResealedProject'), revokedCredentials: num(profile, 'resultRevoked') };
|
|
487
|
+
// Post-commit order: successor active (done) → terminalize/clean the holder (persisted binding, NO unlock) →
|
|
488
|
+
// durable journal delete → strip the aux (→ clean active) → (lease release by combinator) → stdout.
|
|
489
|
+
cleanupHolder(deps, str(profile, 'holderProfileName'), str(profile, 'serviceAccountId'), str(profile, 'holderCredentialId'));
|
|
490
|
+
journalDelete(ctx.leaseCtx);
|
|
491
|
+
const p = profile;
|
|
492
|
+
const clean = {
|
|
493
|
+
schemaVersion: 1,
|
|
494
|
+
flow: 'standard',
|
|
495
|
+
stage: 'active',
|
|
496
|
+
serviceAccountId: p.serviceAccountId,
|
|
497
|
+
baseUrl: p.baseUrl,
|
|
498
|
+
principalType: 'service_account',
|
|
499
|
+
mode: 'identity_rotation',
|
|
500
|
+
operationId: p.operationId,
|
|
501
|
+
credentialId: p.credentialId,
|
|
502
|
+
patId: p.patId,
|
|
503
|
+
bearer: p.bearer,
|
|
504
|
+
capPublicKeyB64: p.capPublicKeyB64,
|
|
505
|
+
capPrivateKeyB64: p.capPrivateKeyB64,
|
|
506
|
+
};
|
|
507
|
+
assertSecure(deps, replaceProfile(deps.root, ctx.successorName, 'active_pending_cleanup', clean, deps.fs));
|
|
508
|
+
return { operationId: ctx.operationId, successorCredentialId: str(profile, 'credentialId'), ...result };
|
|
509
|
+
}
|
|
510
|
+
// Resume from a clean `active` (crash after the strip, before stdout): the cleanup + journal delete already ran;
|
|
511
|
+
// recover the closed result via status (successor bearer, no holder).
|
|
512
|
+
const st = validateStatus(await client.saGetIdentityRotationStatus(str(profile, 'serviceAccountId'), ctx.operationId, { bearer: str(profile, 'bearer') }), ctx.operationId);
|
|
513
|
+
if (st.status !== 'committed')
|
|
514
|
+
throw new CliError('sa_identity_rotation_not_resumable');
|
|
515
|
+
const result = validateCommitResult(st.result, ctx.operationId, str(profile, 'credentialId'));
|
|
516
|
+
return { operationId: ctx.operationId, successorCredentialId: str(profile, 'credentialId'), resealedRecordWrappers: result.resealedRecordWrappers, resealedProjectWrappers: result.resealedProjectWrappers, revokedCredentials: result.revokedCredentials };
|
|
517
|
+
}
|
|
518
|
+
/** Terminalize the local holder profile by NAME (its credential was revoked by the commit) — NO unlock. Idempotent:
|
|
519
|
+
* absent → done; an ALREADY-terminal holder that is OURS → done; a divergent holder (different SA/credential) fails
|
|
520
|
+
* closed and is NEVER terminalized — including when it is ALREADY terminal (R4: identity is validated before the
|
|
521
|
+
* terminal short-circuit, so a substituted/foreign terminal profile at this name is caught, evidence preserved). */
|
|
522
|
+
function cleanupHolder(deps, holderName, serviceAccountId, holderCredentialId) {
|
|
523
|
+
const p = tryLoadProfile(deps, holderName);
|
|
524
|
+
if (!p)
|
|
525
|
+
return;
|
|
526
|
+
// R4 — validate the binding FIRST, on EVERY stage (terminal included). A divergent SA/credential/flow → fail closed
|
|
527
|
+
// and never touch the profile (evidence conserved), whether it is `active` or already `terminal`.
|
|
528
|
+
if (p.flow !== 'standard' || p.serviceAccountId !== serviceAccountId || str(p, 'credentialId') !== holderCredentialId) {
|
|
529
|
+
throw new CliError('sa_identity_rotation_holder_mismatch');
|
|
530
|
+
}
|
|
531
|
+
if (p.stage === 'terminal')
|
|
532
|
+
return; // OURS and already terminalized (idempotent resume) → nothing to do
|
|
533
|
+
if (p.stage !== 'active')
|
|
534
|
+
throw new CliError('sa_identity_rotation_holder_mismatch'); // unexpected own-stage → fail closed
|
|
535
|
+
const pr = p;
|
|
536
|
+
const terminal = {
|
|
537
|
+
schemaVersion: 1,
|
|
538
|
+
flow: 'standard',
|
|
539
|
+
stage: 'terminal',
|
|
540
|
+
serviceAccountId: pr.serviceAccountId,
|
|
541
|
+
baseUrl: pr.baseUrl,
|
|
542
|
+
principalType: 'service_account',
|
|
543
|
+
mode: pr.mode,
|
|
544
|
+
credentialId: pr.credentialId,
|
|
545
|
+
terminalStatus: 'revoked',
|
|
546
|
+
terminalReason: 'identity_rotated',
|
|
547
|
+
patId: pr.patId,
|
|
548
|
+
};
|
|
549
|
+
assertSecure(deps, replaceProfile(deps.root, holderName, 'active', terminal, deps.fs)); // self-locks
|
|
550
|
+
}
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* airctrl CLI — thin binary entry (U9b-3b §10.c#15.H). ALL logic lives in the importable, side-effect-free
|
|
4
|
+
* core (`./cli.js`); this file is the ONLY thing that executes. It maps a thrown stable-coded error to
|
|
5
|
+
* EXACTLY ONE stderr line (`airctrl: <code>` or `airctrl: sa_reconciliation_required reason=<reason>`),
|
|
6
|
+
* never a raw message/path/secret, and sets `process.exitCode` (never `process.exit`, which would truncate
|
|
7
|
+
* pending stdout/stderr — Node v22). A successful command's exit code (incl. `run`'s child code) is returned
|
|
8
|
+
* by the core.
|
|
9
|
+
*/
|
|
10
|
+
import { runPublicCli, toStableError } from './cli.js';
|
|
11
|
+
async function main() {
|
|
12
|
+
try {
|
|
13
|
+
process.exitCode = await runPublicCli(process.argv.slice(2));
|
|
14
|
+
}
|
|
15
|
+
catch (e) {
|
|
16
|
+
const { code, reason } = toStableError(e);
|
|
17
|
+
process.stderr.write(`airctrl: ${code}${reason ? ` reason=${reason}` : ''}\n`);
|
|
18
|
+
process.exitCode = 1;
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
void main();
|