@airctrl/cli 0.0.0-stage → 0.3.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 +2006 -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 +482 -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 +312 -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,262 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* U9b-2 · Multi-profile store — one file per credential at `<root>/.airctrl/sa/<name>.json`
|
|
3
|
+
* (§10.b #1/#3/#4/#5). CREATE is exclusive (no overwrite). REPLACE advances the stage under the
|
|
4
|
+
* per-profile lock ONLY along a ratified `current → next` edge with all binding invariants held.
|
|
5
|
+
* Deletion is stage-gated: a normal delete requires `terminal`; the ONLY other removal is the
|
|
6
|
+
* ratified local abort of an unprovisioned LEGACY profile (`legacy_source`/`capability_prepared`,
|
|
7
|
+
* no remote credential yet). Errors are stable and never echo profile contents.
|
|
8
|
+
*
|
|
9
|
+
* U9b-3a-bis (§10.c#16, F2): every entry point takes an injectable {@link FsOps} (default `REAL_FS`) and
|
|
10
|
+
* uses the SAME instance end-to-end (lock/load/replace/delete) — NO direct `node:fs`. Reads and deletes
|
|
11
|
+
* gate on a REGULAR file first (via the SSOT `assertRegularFile`), so a symlink/FIFO/socket/device managed
|
|
12
|
+
* leaf is never read or unlinked.
|
|
13
|
+
*/
|
|
14
|
+
import { join } from 'node:path';
|
|
15
|
+
import { StoreError, errnoOf } from './errors.js';
|
|
16
|
+
import { canonicalJson } from './canonical.js';
|
|
17
|
+
import { assertProfileName } from './names.js';
|
|
18
|
+
import { saDir, profileFile, profileLock, migrationLease, ensureSaDir, assertSaChain, assertRegularFile } from './paths.js';
|
|
19
|
+
import { atomicCreate, atomicReplace, evidenceSecure } from './atomic-write.js';
|
|
20
|
+
import { durableDelete } from './durable-delete.js';
|
|
21
|
+
import { acquireLock } from './lock.js';
|
|
22
|
+
import { REAL_FS } from './fsops.js';
|
|
23
|
+
import { validateProfile, assertTransition } from './schema.js';
|
|
24
|
+
const PROFILE_LOCK_CODES = {
|
|
25
|
+
busy: 'sa_profile_busy',
|
|
26
|
+
stale: 'sa_profile_lock_stale',
|
|
27
|
+
mismatch: 'sa_profile_lock_owner_mismatch',
|
|
28
|
+
corrupt: 'sa_profile_lock_corrupt',
|
|
29
|
+
};
|
|
30
|
+
/** Acquire the per-profile lock (held only during local filesystem work; NEVER during HTTP). */
|
|
31
|
+
export function acquireProfileLock(root, name, fs = REAL_FS) {
|
|
32
|
+
assertProfileName(name);
|
|
33
|
+
const dir = ensureSaDir(root, fs);
|
|
34
|
+
return acquireLock(join(dir, profileLock(name)), PROFILE_LOCK_CODES, fs);
|
|
35
|
+
}
|
|
36
|
+
const MIGRATION_LEASE_CODES = {
|
|
37
|
+
busy: 'sa_migration_busy',
|
|
38
|
+
stale: 'sa_migration_lease_stale',
|
|
39
|
+
mismatch: 'sa_migration_lease_owner_mismatch',
|
|
40
|
+
corrupt: 'sa_migration_lease_corrupt',
|
|
41
|
+
};
|
|
42
|
+
/**
|
|
43
|
+
* U9b-4 · acquire the per-profile MIGRATION LEASE — a DISTINCT O_EXCL lock file (`${name}.migration.lease`) that a
|
|
44
|
+
* `sa migrate` run holds across the WHOLE flow (unlock/prepare/status/complete), so concurrent migrations of the
|
|
45
|
+
* SAME profile serialize. Reuses the same `acquireLock` primitive as `acquireProfileLock`/`acquireHandoffLease`:
|
|
46
|
+
* O_EXCL fail-fast; a LIVE owner → `sa_migration_busy`; a same-host DEAD pid → `sa_migration_lease_stale`; NO
|
|
47
|
+
* auto-removal / TTL stealing / waiting; ownership nonce+pid+host verified on `assertOwned`/`release`;
|
|
48
|
+
* symlink/special/lstat failures keep the existing path/integrity codes. The brief profile lock is NEVER held
|
|
49
|
+
* during HTTP and is a separate namespace (`${name}.lock`).
|
|
50
|
+
*/
|
|
51
|
+
export function acquireMigrationLease(root, name, fs = REAL_FS) {
|
|
52
|
+
assertProfileName(name);
|
|
53
|
+
const dir = ensureSaDir(root, fs);
|
|
54
|
+
return acquireLock(join(dir, migrationLease(name)), MIGRATION_LEASE_CODES, fs);
|
|
55
|
+
}
|
|
56
|
+
/** Create a NEW profile exclusively. Fails `sa_store_dest_exists` if the name is taken. */
|
|
57
|
+
export function createProfile(root, name, profile, fs = REAL_FS) {
|
|
58
|
+
assertProfileName(name);
|
|
59
|
+
const validated = validateProfile(profile);
|
|
60
|
+
const dir = ensureSaDir(root, fs);
|
|
61
|
+
return atomicCreate(dir, profileFile(name), canonicalJson(validated), fs);
|
|
62
|
+
}
|
|
63
|
+
/** Load and validate a profile. Missing → `sa_profile_not_found`; unreadable/invalid → `sa_profile_corrupt`. */
|
|
64
|
+
export function loadProfile(root, name, fs = REAL_FS) {
|
|
65
|
+
assertProfileName(name);
|
|
66
|
+
assertSaChain(root, fs);
|
|
67
|
+
const path = join(saDir(root), profileFile(name));
|
|
68
|
+
// Regular-file gate BEFORE read (F2): absent → not_found; symlink → sa_store_symlink_rejected; lstat-fail →
|
|
69
|
+
// sa_store_lstat_failed; special → corrupt. NEVER readFileSync a non-regular inode.
|
|
70
|
+
assertRegularFile(path, { notFound: 'sa_profile_not_found', notRegular: 'sa_profile_corrupt' }, fs);
|
|
71
|
+
let raw;
|
|
72
|
+
try {
|
|
73
|
+
raw = fs.readFileSync(path);
|
|
74
|
+
}
|
|
75
|
+
catch (e) {
|
|
76
|
+
if (errnoOf(e) === 'ENOENT')
|
|
77
|
+
throw new StoreError('sa_profile_not_found');
|
|
78
|
+
throw new StoreError('sa_profile_corrupt', errnoOf(e));
|
|
79
|
+
}
|
|
80
|
+
let parsed;
|
|
81
|
+
try {
|
|
82
|
+
parsed = JSON.parse(raw);
|
|
83
|
+
}
|
|
84
|
+
catch {
|
|
85
|
+
throw new StoreError('sa_profile_corrupt');
|
|
86
|
+
}
|
|
87
|
+
try {
|
|
88
|
+
return validateProfile(parsed);
|
|
89
|
+
}
|
|
90
|
+
catch {
|
|
91
|
+
throw new StoreError('sa_profile_corrupt');
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
/**
|
|
95
|
+
* Advance a profile to `next` under the per-profile lock. The current on-disk stage MUST equal
|
|
96
|
+
* `expectedStage` AND `current → next` must be a ratified edge with all invariants held
|
|
97
|
+
* (assertTransition). Otherwise `sa_profile_unexpected_state` / `sa_profile_transition_invalid`
|
|
98
|
+
* with the file untouched.
|
|
99
|
+
*/
|
|
100
|
+
export function replaceProfile(root, name, expectedStage, next, fs = REAL_FS) {
|
|
101
|
+
const validated = validateProfile(next);
|
|
102
|
+
const lock = acquireProfileLock(root, name, fs);
|
|
103
|
+
try {
|
|
104
|
+
const current = loadProfile(root, name, fs);
|
|
105
|
+
if (current.stage !== expectedStage)
|
|
106
|
+
throw new StoreError('sa_profile_unexpected_state');
|
|
107
|
+
assertTransition(current, validated);
|
|
108
|
+
return atomicReplace(saDir(root), profileFile(name), canonicalJson(validated), fs);
|
|
109
|
+
}
|
|
110
|
+
finally {
|
|
111
|
+
lock.release();
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
/** Delete a profile DURABLY ONLY when it is in stage `terminal`. Other stages → `sa_profile_not_terminal` (intact). */
|
|
115
|
+
export function deleteTerminalProfile(root, name, fs = REAL_FS) {
|
|
116
|
+
return removeGated(root, name, (p) => p.stage === 'terminal', 'sa_profile_not_terminal', fs);
|
|
117
|
+
}
|
|
118
|
+
/**
|
|
119
|
+
* Abort an UNPROVISIONED legacy profile (`legacy_source` / `capability_prepared`, no remote credential
|
|
120
|
+
* yet) via a DURABLE managed delete — the ratified local abort (§10.b). Any other stage → `sa_profile_not_abortable`.
|
|
121
|
+
*/
|
|
122
|
+
export function abortUnprovisionedLegacyProfile(root, name, fs = REAL_FS) {
|
|
123
|
+
return removeGated(root, name, (p) => p.flow === 'legacy_migration' && (p.stage === 'legacy_source' || p.stage === 'capability_prepared'), 'sa_profile_not_abortable', fs);
|
|
124
|
+
}
|
|
125
|
+
/**
|
|
126
|
+
* Validate-and-durably-delete a profile under a SINGLE per-profile lock hold (U9b-3e-3 §18.9 F1). Closes the
|
|
127
|
+
* TOCTOU between a caller's canonical binding check and the unlink: acquires the lock ONCE, re-reads the profile
|
|
128
|
+
* UNDER the lock, runs `classify(profile)` on that fresh read, and only deletes when `classify` returns `'delete'`.
|
|
129
|
+
* - profile absent at lock time → `{outcome:'absent'}` (no `beforeDelete`, no delete);
|
|
130
|
+
* - `classify` → `'not_terminal'` → `{outcome:'not_terminal'}` (the caller re-drives; no delete, no `beforeDelete`);
|
|
131
|
+
* - `classify` → `'delete'` → run `beforeDelete` (e.g. the handoff durable-delete) UNDER the lock, THEN durable-delete
|
|
132
|
+
* the profile → `{outcome:'deleted', result}`;
|
|
133
|
+
* - `classify` may THROW a stable code (e.g. a substituted/contrary terminal → `sa_receipt_mismatch`); the profile is
|
|
134
|
+
* never deleted and `beforeDelete` never runs.
|
|
135
|
+
* `beforeDelete` runs strictly AFTER the exact match is confirmed and BEFORE the profile unlink, all while the lock is
|
|
136
|
+
* held — so a concurrent replace/delete of the profile is fail-fast `sa_profile_busy` and can never substitute the
|
|
137
|
+
* terminal between the check and the unlink.
|
|
138
|
+
*
|
|
139
|
+
* ERROR PRECEDENCE (U9b-3e-3 §18.9 F1): a NAIVE `finally { lock.release() }` would let a release throw REPLACE a
|
|
140
|
+
* functional primary error. Instead the functional result/error is captured, `lock.release()` is attempted EXACTLY
|
|
141
|
+
* once, and: a functional PRIMARY is re-thrown by identity (a release failure never substitutes it); a functional
|
|
142
|
+
* SUCCESS whose release fails collapses to the stable `sa_profile_lock_release_failed` (never a raw OS message/path).
|
|
143
|
+
* NOT a secure erase.
|
|
144
|
+
*/
|
|
145
|
+
/**
|
|
146
|
+
* U4 Capa 3 · durable claim-budget bump (F4). SAME-stage `identity_prepared` mutation: atomically increment
|
|
147
|
+
* `claimAttempts` (0→1→2) BEFORE each claim HTTP, preserving EVERY other binding byte-for-byte, under the
|
|
148
|
+
* per-profile lock (acquired briefly, NEVER held during HTTP). Range fail-closed: at 2 the budget is exhausted
|
|
149
|
+
* → `sa_identity_rotation_claim_budget_exhausted`. Uses the atomic-write SSOT (temp+rename+fsync). Release
|
|
150
|
+
* precedence is falsy-safe (a primary error wins over a release error). Not `identity_prepared` → transition-invalid.
|
|
151
|
+
*/
|
|
152
|
+
export function bumpIdentityRotationClaimAttempts(root, name, fs = REAL_FS) {
|
|
153
|
+
assertProfileName(name);
|
|
154
|
+
const lock = acquireProfileLock(root, name, fs);
|
|
155
|
+
let result;
|
|
156
|
+
let primary;
|
|
157
|
+
let hasPrimary = false;
|
|
158
|
+
try {
|
|
159
|
+
const current = loadProfile(root, name, fs);
|
|
160
|
+
if (current.flow !== 'standard' || current.mode !== 'identity_rotation' || current.stage !== 'identity_prepared') {
|
|
161
|
+
throw new StoreError('sa_profile_transition_invalid');
|
|
162
|
+
}
|
|
163
|
+
const attempts = current.claimAttempts;
|
|
164
|
+
if (typeof attempts !== 'number' || !Number.isInteger(attempts) || attempts < 0)
|
|
165
|
+
throw new StoreError('sa_profile_schema_invalid');
|
|
166
|
+
if (attempts >= 2)
|
|
167
|
+
throw new StoreError('sa_identity_rotation_claim_budget_exhausted');
|
|
168
|
+
const next = { ...current, claimAttempts: attempts + 1 };
|
|
169
|
+
validateProfile(next); // still a valid identity_prepared profile (ONLY claimAttempts changed)
|
|
170
|
+
const ev = atomicReplace(ensureSaDir(root, fs), profileFile(name), canonicalJson(next), fs);
|
|
171
|
+
// R1 — the budget bump is a durable pre-HTTP checkpoint: verify its PersistenceEvidence through the SSOT
|
|
172
|
+
// `evidenceSecure` with `requireCleanTemp:true` (a residual temp is a write failure for a receipt-grade
|
|
173
|
+
// write). Insecure permissions/file/directory/temp → fail CLOSED here, so the claim HTTP that would follow
|
|
174
|
+
// never fires on an un-durable/insecure attempts counter.
|
|
175
|
+
if (!evidenceSecure(ev, fs, { requireCleanTemp: true }))
|
|
176
|
+
throw new StoreError('sa_identity_rotation_claim_persist_insecure');
|
|
177
|
+
result = { claimAttempts: attempts + 1 };
|
|
178
|
+
}
|
|
179
|
+
catch (e) {
|
|
180
|
+
primary = e;
|
|
181
|
+
hasPrimary = true;
|
|
182
|
+
}
|
|
183
|
+
let hasReleaseErr = false;
|
|
184
|
+
try {
|
|
185
|
+
lock.release();
|
|
186
|
+
}
|
|
187
|
+
catch {
|
|
188
|
+
hasReleaseErr = true;
|
|
189
|
+
}
|
|
190
|
+
if (hasPrimary)
|
|
191
|
+
throw primary;
|
|
192
|
+
if (hasReleaseErr)
|
|
193
|
+
throw new StoreError('sa_profile_lock_release_failed');
|
|
194
|
+
return result;
|
|
195
|
+
}
|
|
196
|
+
export function deleteProfileUnderLock(root, name, classify, beforeDelete, fs = REAL_FS) {
|
|
197
|
+
const lock = acquireProfileLock(root, name, fs);
|
|
198
|
+
let result;
|
|
199
|
+
let primary = null;
|
|
200
|
+
try {
|
|
201
|
+
let current = null;
|
|
202
|
+
try {
|
|
203
|
+
current = loadProfile(root, name, fs);
|
|
204
|
+
}
|
|
205
|
+
catch (e) {
|
|
206
|
+
if (e instanceof StoreError && e.code === 'sa_profile_not_found')
|
|
207
|
+
result = { outcome: 'absent' };
|
|
208
|
+
else
|
|
209
|
+
throw e; // corrupt/path preserved
|
|
210
|
+
}
|
|
211
|
+
if (current) {
|
|
212
|
+
const action = classify(current); // throws a stable code for a substituted/contrary terminal
|
|
213
|
+
if (action === 'not_terminal')
|
|
214
|
+
result = { outcome: 'not_terminal' };
|
|
215
|
+
else {
|
|
216
|
+
beforeDelete(); // handoff durable-delete UNDER the lock, only once the EXACT terminal is confirmed present
|
|
217
|
+
result = { outcome: 'deleted', result: durableDelete(join(saDir(root), profileFile(name)), (f) => assertSaChain(root, f), fs) };
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
catch (e) {
|
|
222
|
+
primary = e;
|
|
223
|
+
}
|
|
224
|
+
let releaseErr = null;
|
|
225
|
+
try {
|
|
226
|
+
lock.release(); // exactly once
|
|
227
|
+
}
|
|
228
|
+
catch (e) {
|
|
229
|
+
releaseErr = e;
|
|
230
|
+
}
|
|
231
|
+
if (primary)
|
|
232
|
+
throw primary; // the functional primary WINS by identity; a release failure never substitutes it
|
|
233
|
+
if (releaseErr)
|
|
234
|
+
throw new StoreError('sa_profile_lock_release_failed'); // functional success + release failure → stable code, no raw/path
|
|
235
|
+
return result; // set whenever there was no primary
|
|
236
|
+
}
|
|
237
|
+
/**
|
|
238
|
+
* Stage-gated DURABLE removal under the per-profile lock (U9b-3e-P0 §10.c#18.5). Loads+validates the profile
|
|
239
|
+
* to enforce `allow` (a non-matching stage → `rejectCode`, file untouched); an absent profile OR an allowed
|
|
240
|
+
* one is removed via the SSOT {@link durableDelete} (unlink + `fsyncDir(parent)` — the absent path STILL
|
|
241
|
+
* flushes the dir so a crash-consistent absence is provable). Metadata durability, NOT a secure erase.
|
|
242
|
+
*/
|
|
243
|
+
function removeGated(root, name, allow, rejectCode, fs) {
|
|
244
|
+
const lock = acquireProfileLock(root, name, fs);
|
|
245
|
+
try {
|
|
246
|
+
let current = null;
|
|
247
|
+
try {
|
|
248
|
+
current = loadProfile(root, name, fs);
|
|
249
|
+
}
|
|
250
|
+
catch (e) {
|
|
251
|
+
if (!(e instanceof StoreError && e.code === 'sa_profile_not_found'))
|
|
252
|
+
throw e; // corrupt/path preserved
|
|
253
|
+
}
|
|
254
|
+
if (current && !allow(current))
|
|
255
|
+
throw new StoreError(rejectCode); // wrong stage → reject, file untouched
|
|
256
|
+
// current === null (absent) OR allowed → durable delete; the absent path still `fsyncDir`s the parent.
|
|
257
|
+
return durableDelete(join(saDir(root), profileFile(name)), (f) => assertSaChain(root, f), fs);
|
|
258
|
+
}
|
|
259
|
+
finally {
|
|
260
|
+
lock.release();
|
|
261
|
+
}
|
|
262
|
+
}
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* U9b-3a · Receipt store at `<root>/.airctrl/sa/receipts/<uuid>.json` (§10.c#14).
|
|
3
|
+
*
|
|
4
|
+
* A non-secret evidence record for an ADMIN cancel/revoke (two exact variants — see {@link validateReceipt}).
|
|
5
|
+
* CREATE is atomic + EXCLUSIVE with NO reconcile: a regenerated receipt uses a NEW receiptId, so an EEXIST is
|
|
6
|
+
* a genuine collision (`sa_store_dest_exists`), never a silent overwrite. The id is a STRICT canonical UUID
|
|
7
|
+
* (not the generic name allowlist). A receipt is RETAINED as non-secret evidence after reconciliation (U9b-3e-3
|
|
8
|
+
* §18.9 never deletes it — the earlier "consume receipt" wording is superseded); this module supplies only
|
|
9
|
+
* create/load/delete primitives (the delete is used by non-reconcile callers only). FsOps is injectable end-to-end.
|
|
10
|
+
*/
|
|
11
|
+
import { join } from 'node:path';
|
|
12
|
+
import { StoreError } from './errors.js';
|
|
13
|
+
import { canonicalJson } from './canonical.js';
|
|
14
|
+
import { assertReceiptId } from './names.js';
|
|
15
|
+
import { receiptDir, receiptFile, ensureReceiptDir, assertReceiptChain, assertRegularFile } from './paths.js';
|
|
16
|
+
import { atomicCreate } from './atomic-write.js';
|
|
17
|
+
import { REAL_FS } from './fsops.js';
|
|
18
|
+
import { validateReceipt } from './schema.js';
|
|
19
|
+
/** Persist a NEW receipt EXCLUSIVELY (validated + canonical). EEXIST → `sa_store_dest_exists` (no reconcile). */
|
|
20
|
+
export function createReceipt(root, id, receipt, fs = REAL_FS) {
|
|
21
|
+
assertReceiptId(id);
|
|
22
|
+
const validated = validateReceipt(receipt);
|
|
23
|
+
const dir = ensureReceiptDir(root, fs);
|
|
24
|
+
return atomicCreate(dir, receiptFile(id), canonicalJson(validated), fs);
|
|
25
|
+
}
|
|
26
|
+
/** Load + validate a receipt. Missing → `sa_receipt_not_found`; unreadable/invalid → `sa_receipt_corrupt`. */
|
|
27
|
+
export function loadReceipt(root, id, fs = REAL_FS) {
|
|
28
|
+
assertReceiptId(id);
|
|
29
|
+
assertReceiptChain(root, fs);
|
|
30
|
+
const path = join(receiptDir(root), receiptFile(id));
|
|
31
|
+
// Regular-file gate BEFORE read (F2): absent → not_found; symlink → sa_store_symlink_rejected; lstat-fail →
|
|
32
|
+
// sa_store_lstat_failed; special → corrupt. NEVER readFileSync a non-regular inode.
|
|
33
|
+
assertRegularFile(path, { notFound: 'sa_receipt_not_found', notRegular: 'sa_receipt_corrupt' }, fs);
|
|
34
|
+
let raw;
|
|
35
|
+
try {
|
|
36
|
+
raw = fs.readFileSync(path);
|
|
37
|
+
}
|
|
38
|
+
catch (e) {
|
|
39
|
+
if (e?.code === 'ENOENT')
|
|
40
|
+
throw new StoreError('sa_receipt_not_found');
|
|
41
|
+
throw new StoreError('sa_receipt_corrupt');
|
|
42
|
+
}
|
|
43
|
+
let parsed;
|
|
44
|
+
try {
|
|
45
|
+
parsed = JSON.parse(raw);
|
|
46
|
+
}
|
|
47
|
+
catch {
|
|
48
|
+
throw new StoreError('sa_receipt_corrupt');
|
|
49
|
+
}
|
|
50
|
+
try {
|
|
51
|
+
return validateReceipt(parsed);
|
|
52
|
+
}
|
|
53
|
+
catch {
|
|
54
|
+
throw new StoreError('sa_receipt_corrupt');
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
/** Delete a receipt (logical, best-effort). Missing → `absent`. */
|
|
58
|
+
export function deleteReceipt(root, id, fs = REAL_FS) {
|
|
59
|
+
assertReceiptId(id);
|
|
60
|
+
assertReceiptChain(root, fs);
|
|
61
|
+
const path = join(receiptDir(root), receiptFile(id));
|
|
62
|
+
// Never silently unlink a symlink/special inode (F2). Absent → 'absent'.
|
|
63
|
+
if (assertRegularFile(path, { notRegular: 'sa_store_not_regular_file' }, fs) === 'absent') {
|
|
64
|
+
return { outcome: 'absent' };
|
|
65
|
+
}
|
|
66
|
+
try {
|
|
67
|
+
fs.unlinkSync(path);
|
|
68
|
+
return { outcome: 'deleted' };
|
|
69
|
+
}
|
|
70
|
+
catch (e) {
|
|
71
|
+
if (e?.code === 'ENOENT')
|
|
72
|
+
return { outcome: 'absent' };
|
|
73
|
+
throw new StoreError('sa_store_io_error');
|
|
74
|
+
}
|
|
75
|
+
}
|
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* U9b-2 · Principal resolution + D12 precedence (§10.b #7). Pure and discriminated: it
|
|
3
|
+
* returns exactly one fully-formed principal or throws a stable code — never a partially
|
|
4
|
+
* valid object, never a field-by-field mix of env/profile/handoff/config.
|
|
5
|
+
*
|
|
6
|
+
* Order (ratified): a COMPLETE SA env bundle wins and does NOT even load a profile; a
|
|
7
|
+
* partial/contradictory SA env fails closed; `--profile` dominates `AC_SA_PROFILE`; a bare
|
|
8
|
+
* `AC_TOKEN` is a human; legacy requires the explicit `AC_SA_PRINCIPAL=service_account_legacy`
|
|
9
|
+
* marker (no autodetection); `config.json` is human/admin-only and never completes an SA bundle.
|
|
10
|
+
*
|
|
11
|
+
* NOT wired to the CLI dispatcher here — that is U9b-3.
|
|
12
|
+
*/
|
|
13
|
+
import { homedir } from 'node:os';
|
|
14
|
+
import { StoreError } from './errors.js';
|
|
15
|
+
import { isCanonicalB64 } from './canonical.js';
|
|
16
|
+
import { normalizeBaseUrl, resolveEffectiveBaseUrl } from './base-url.js';
|
|
17
|
+
import { assertProfileName } from './names.js';
|
|
18
|
+
import { loadProfile } from './profile-store.js';
|
|
19
|
+
import { validateProfile } from './schema.js';
|
|
20
|
+
import { loadConfigStrict, DEFAULT_BASE_URL } from '../config.js';
|
|
21
|
+
const present = (x) => x !== undefined && x.trim() !== '';
|
|
22
|
+
const defined = (x) => x !== undefined;
|
|
23
|
+
const setButEmpty = (x) => x !== undefined && x.trim() === '';
|
|
24
|
+
export function resolvePrincipal(input = {}) {
|
|
25
|
+
const env = input.env ?? process.env;
|
|
26
|
+
const loadHumanConfig = input.loadHumanConfig ?? (() => loadConfigStrict());
|
|
27
|
+
const token = env.AC_TOKEN;
|
|
28
|
+
const credId = env.AC_SA_CREDENTIAL_ID;
|
|
29
|
+
const capPriv = env.AC_SA_CAP_PRIVATE_KEY_B64;
|
|
30
|
+
const saId = env.AC_SA_SERVICE_ACCOUNT_ID; // U9b-3e-2 (§10.b#7.bis): OPTIONAL companion of the active bundle
|
|
31
|
+
const apiBase = env.AC_API_BASE_URL;
|
|
32
|
+
const marker = env.AC_SA_PRINCIPAL;
|
|
33
|
+
const profileEnv = env.AC_SA_PROFILE;
|
|
34
|
+
const profileFlag = input.profileFlag;
|
|
35
|
+
const hasToken = present(token);
|
|
36
|
+
const hasCredId = present(credId);
|
|
37
|
+
const hasCapPriv = present(capPriv);
|
|
38
|
+
const hasSaId = present(saId);
|
|
39
|
+
const hasApiBase = present(apiBase);
|
|
40
|
+
const hasMarker = present(marker);
|
|
41
|
+
// A DEFINED-but-empty SA field is still an SA-bundle attempt — it must NEVER degrade to HUMAN. The optional
|
|
42
|
+
// `AC_SA_SERVICE_ACCOUNT_ID` companion counts as an active-bundle signal: alone/partial it fails closed as
|
|
43
|
+
// `sa_env_bundle_incomplete`, and with a legacy marker it collides via `sa_principal_bundle_conflict`.
|
|
44
|
+
const definedActiveField = defined(credId) || defined(capPriv) || defined(saId);
|
|
45
|
+
// AC_SA_PRINCIPAL defined at all must be the exact legacy discriminant (empty/whitespace/unknown → fail).
|
|
46
|
+
if (defined(marker) && marker.trim() !== 'service_account_legacy')
|
|
47
|
+
throw new StoreError('sa_principal_unknown');
|
|
48
|
+
// Legacy marker cannot coexist with any (even empty) active-capability field.
|
|
49
|
+
if (hasMarker && definedActiveField)
|
|
50
|
+
throw new StoreError('sa_principal_bundle_conflict');
|
|
51
|
+
// FULL ACTIVE bundle → wins completely; profile is NOT loaded, selectors ignored. The optional
|
|
52
|
+
// `AC_SA_SERVICE_ACCOUNT_ID` companion is NOT required to resolve the core bundle; if DEFINED it must be
|
|
53
|
+
// non-empty/whitespace-safe (a defined-but-empty companion is an error, never silent absence).
|
|
54
|
+
if (hasToken && hasCredId && hasCapPriv) {
|
|
55
|
+
if (!hasApiBase)
|
|
56
|
+
throw new StoreError('sa_env_baseurl_missing');
|
|
57
|
+
if (!isCanonicalB64(capPriv, 32))
|
|
58
|
+
throw new StoreError('sa_env_cap_private_invalid');
|
|
59
|
+
if (defined(saId) && !hasSaId)
|
|
60
|
+
throw new StoreError('sa_env_service_account_id_invalid');
|
|
61
|
+
return {
|
|
62
|
+
kind: 'sa_env_active',
|
|
63
|
+
bearer: token.trim(),
|
|
64
|
+
credentialId: credId.trim(),
|
|
65
|
+
capPrivateKeyB64: capPriv.trim(),
|
|
66
|
+
...(hasSaId ? { serviceAccountId: saId.trim() } : {}),
|
|
67
|
+
baseUrl: normalizeBaseUrl(apiBase),
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
// FULL LEGACY bundle → wins completely; selectors ignored.
|
|
71
|
+
if (hasMarker) {
|
|
72
|
+
if (!hasToken)
|
|
73
|
+
throw new StoreError('sa_env_bundle_incomplete');
|
|
74
|
+
if (!hasApiBase)
|
|
75
|
+
throw new StoreError('sa_env_baseurl_missing');
|
|
76
|
+
return { kind: 'sa_env_legacy', bearer: token.trim(), baseUrl: normalizeBaseUrl(apiBase) };
|
|
77
|
+
}
|
|
78
|
+
// Any active SA field defined (even empty) but no complete bundle → fail closed (never HUMAN).
|
|
79
|
+
if (definedActiveField)
|
|
80
|
+
throw new StoreError('sa_env_bundle_incomplete');
|
|
81
|
+
// Explicitly-empty selectors are an error (not "absent").
|
|
82
|
+
if (setButEmpty(profileFlag) || setButEmpty(profileEnv))
|
|
83
|
+
throw new StoreError('sa_profile_selector_empty');
|
|
84
|
+
const hasProfileFlag = present(profileFlag);
|
|
85
|
+
const hasProfileEnv = present(profileEnv);
|
|
86
|
+
if (hasProfileFlag || hasProfileEnv) {
|
|
87
|
+
// AC_TOKEN + profile selector WITHOUT a complete SA bundle → fail closed (ratified).
|
|
88
|
+
if (hasToken)
|
|
89
|
+
throw new StoreError('sa_token_profile_conflict');
|
|
90
|
+
const profileName = (hasProfileFlag ? profileFlag : profileEnv).trim(); // flag dominates
|
|
91
|
+
assertProfileName(profileName);
|
|
92
|
+
// A DEFINED-but-empty AC_API_BASE_URL is NOT "absent" — it fails closed like an SA env bundle.
|
|
93
|
+
if (setButEmpty(apiBase))
|
|
94
|
+
throw new StoreError('sa_env_baseurl_missing');
|
|
95
|
+
const loadProfileByName = input.loadProfileByName ?? ((n) => loadProfile(input.profileRoot ?? homedir(), n));
|
|
96
|
+
const raw = loadProfileByName(profileName); // exactly once; throws sa_profile_not_found / _corrupt
|
|
97
|
+
// Re-validate here too: an injected loader could return unvalidated runtime data. A structurally
|
|
98
|
+
// invalid object fails closed as `sa_profile_corrupt` (never leaks `sa_profile_schema_invalid`).
|
|
99
|
+
let profile;
|
|
100
|
+
try {
|
|
101
|
+
profile = validateProfile(raw);
|
|
102
|
+
}
|
|
103
|
+
catch {
|
|
104
|
+
throw new StoreError('sa_profile_corrupt');
|
|
105
|
+
}
|
|
106
|
+
// Profile baseUrl is authoritative; AC_API_BASE_URL accepted only if it normalizes identically.
|
|
107
|
+
const baseUrl = resolveEffectiveBaseUrl(profile.baseUrl, hasApiBase ? apiBase.trim() : undefined);
|
|
108
|
+
return { kind: 'sa_profile', profileName, profile, baseUrl };
|
|
109
|
+
}
|
|
110
|
+
// Human / none. `config.json` is fail-closed on corrupt (present-corrupt → throws, even with AC_TOKEN).
|
|
111
|
+
const cfg = loadHumanConfig();
|
|
112
|
+
if (hasToken) {
|
|
113
|
+
const baseUrl = hasApiBase ? apiBase.trim() : (cfg?.baseUrl ?? DEFAULT_BASE_URL);
|
|
114
|
+
return { kind: 'human', bearer: token.trim(), baseUrl, defaultProject: cfg?.defaultProject };
|
|
115
|
+
}
|
|
116
|
+
if (cfg) {
|
|
117
|
+
return {
|
|
118
|
+
kind: 'human',
|
|
119
|
+
bearer: cfg.token,
|
|
120
|
+
baseUrl: hasApiBase ? apiBase.trim() : cfg.baseUrl,
|
|
121
|
+
defaultProject: cfg.defaultProject,
|
|
122
|
+
};
|
|
123
|
+
}
|
|
124
|
+
return { kind: 'none' };
|
|
125
|
+
}
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* U9b-3a · Rotation artifact store at `<root>/.airctrl/sa/rotations/<operationId>.json` (§10.c#14).
|
|
3
|
+
*
|
|
4
|
+
* A NON-SECRET record produced by an ADMIN rotation authorize: `{operationId, credentialId, expiresAt,
|
|
5
|
+
* serviceAccountId, baseUrl}` and nothing else (any secret field is rejected by the schema). The file name
|
|
6
|
+
* IS the canonical-UUID operationId. CREATE is atomic + exclusive; a retry after the remote commit with the
|
|
7
|
+
* SAME canonical document → `{outcome:'reconciled', …PersistenceEvidence}`; a different document → `sa_rotation_artifact_conflict`
|
|
8
|
+
* (never overwrite). Protocol-agnostic: U9b-3c orchestrates the artifact-before-handoff-delete ordering; this
|
|
9
|
+
* module only supplies the primitives. FsOps is injectable end-to-end for fault-injection.
|
|
10
|
+
*/
|
|
11
|
+
import { join } from 'node:path';
|
|
12
|
+
import { StoreError } from './errors.js';
|
|
13
|
+
import { canonicalJson } from './canonical.js';
|
|
14
|
+
import { assertRotationOperationId } from './names.js';
|
|
15
|
+
import { rotationDir, rotationFile, ensureRotationDir, assertRotationChain, assertRegularFile } from './paths.js';
|
|
16
|
+
import { atomicCreateIdempotent } from './atomic-write.js';
|
|
17
|
+
import { durableDelete } from './durable-delete.js';
|
|
18
|
+
import { REAL_FS } from './fsops.js';
|
|
19
|
+
import { validateRotationArtifact } from './schema.js';
|
|
20
|
+
/** Persist a NEW rotation artifact idempotently (validated + canonical; keyed by operationId). */
|
|
21
|
+
export function createRotationArtifact(root, artifact, fs = REAL_FS) {
|
|
22
|
+
const validated = validateRotationArtifact(artifact);
|
|
23
|
+
assertRotationOperationId(validated.operationId);
|
|
24
|
+
const dir = ensureRotationDir(root, fs);
|
|
25
|
+
return atomicCreateIdempotent(dir, rotationFile(validated.operationId), canonicalJson(validated), { validate: validateRotationArtifact, conflictCode: 'sa_rotation_artifact_conflict' }, fs);
|
|
26
|
+
}
|
|
27
|
+
/** Load + validate a rotation artifact. Missing → `sa_rotation_artifact_not_found`; invalid → `sa_rotation_artifact_corrupt`. */
|
|
28
|
+
export function loadRotationArtifact(root, operationId, fs = REAL_FS) {
|
|
29
|
+
assertRotationOperationId(operationId);
|
|
30
|
+
assertRotationChain(root, fs);
|
|
31
|
+
const path = join(rotationDir(root), rotationFile(operationId));
|
|
32
|
+
// Regular-file gate BEFORE read (F2): absent → not_found; symlink → sa_store_symlink_rejected; lstat-fail →
|
|
33
|
+
// sa_store_lstat_failed; special → corrupt. NEVER readFileSync a non-regular inode.
|
|
34
|
+
assertRegularFile(path, { notFound: 'sa_rotation_artifact_not_found', notRegular: 'sa_rotation_artifact_corrupt' }, fs);
|
|
35
|
+
let raw;
|
|
36
|
+
try {
|
|
37
|
+
raw = fs.readFileSync(path);
|
|
38
|
+
}
|
|
39
|
+
catch (e) {
|
|
40
|
+
if (e?.code === 'ENOENT')
|
|
41
|
+
throw new StoreError('sa_rotation_artifact_not_found');
|
|
42
|
+
throw new StoreError('sa_rotation_artifact_corrupt');
|
|
43
|
+
}
|
|
44
|
+
let parsed;
|
|
45
|
+
try {
|
|
46
|
+
parsed = JSON.parse(raw);
|
|
47
|
+
}
|
|
48
|
+
catch {
|
|
49
|
+
throw new StoreError('sa_rotation_artifact_corrupt');
|
|
50
|
+
}
|
|
51
|
+
try {
|
|
52
|
+
return validateRotationArtifact(parsed);
|
|
53
|
+
}
|
|
54
|
+
catch {
|
|
55
|
+
throw new StoreError('sa_rotation_artifact_corrupt');
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* Delete a rotation artifact DURABLY (U9b-3e-P0 §10.c#18.5): unlink + `fsyncDir(parent)` via the SSOT
|
|
60
|
+
* {@link durableDelete}, so a crash after unlink cannot resurrect the entry. Missing → `absent` (still
|
|
61
|
+
* flushes the dir). Metadata crash-consistency, NOT a secure erase.
|
|
62
|
+
*/
|
|
63
|
+
export function deleteRotationArtifact(root, operationId, fs = REAL_FS) {
|
|
64
|
+
assertRotationOperationId(operationId);
|
|
65
|
+
return durableDelete(join(rotationDir(root), rotationFile(operationId)), (f) => assertRotationChain(root, f), fs);
|
|
66
|
+
}
|