-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapprovals.js
More file actions
448 lines (418 loc) · 14.9 KB
/
Copy pathapprovals.js
File metadata and controls
448 lines (418 loc) · 14.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
import {
appendFileSync, readFileSync, existsSync, mkdirSync,
openSync, closeSync, writeSync, unlinkSync, statSync,
} from 'node:fs';
import { dirname } from 'node:path';
import { createHash, randomBytes } from 'node:crypto';
import { getProvider, resolveProvider } from './signing/index.js';
import { resolveAllowedSigners, generateAllowedSigners } from './signing/ssh.js';
import { getAgentcliPaths } from './home.js';
// Concurrency: `claimApproval` is the atomic public primitive that
// enforceApprovalGate uses. It acquires an fs-lock on <approvals>.lock
// (openSync 'wx'), re-reads the log inside the critical section, finds a
// matching pending grant, appends a consume event, and releases the lock.
// Concurrent claims of the same grant serialize to exactly one winner;
// losers re-read and either find a different pending grant or throw
// approval_required. Locks older than LOCK_STALE_MS are treated as
// abandoned (crashed holder) and removed.
const APPROVAL_RECORD_VERSION = 1;
const DEFAULT_TTL_S = 3600;
const LOCK_SUFFIX = '.lock';
const LOCK_TIMEOUT_MS = 5000;
const LOCK_STALE_MS = 30000;
const LOCK_POLL_MS = 25;
// Shared memory used for sync sleep during lock backoff. Allocated once per
// process rather than per-retry.
const LOCK_SLEEP_BUF = new Int32Array(new SharedArrayBuffer(4));
function sleepSync(ms) {
Atomics.wait(LOCK_SLEEP_BUF, 0, 0, ms);
}
function withApprovalsLock(approvalsPath, fn, {
timeoutMs = LOCK_TIMEOUT_MS,
staleMs = LOCK_STALE_MS,
pollMs = LOCK_POLL_MS,
now = () => Date.now(),
} = {}) {
mkdirSync(dirname(approvalsPath), { recursive: true });
const lockPath = `${approvalsPath}${LOCK_SUFFIX}`;
const deadline = now() + timeoutMs;
let fd;
while (true) {
try {
fd = openSync(lockPath, 'wx');
writeSync(fd, `${process.pid}\n`);
break;
} catch (err) {
if (err.code !== 'EEXIST') throw err;
// Lock held. Check staleness and potentially break it.
try {
const st = statSync(lockPath);
if (now() - st.mtimeMs > staleMs) {
try { unlinkSync(lockPath); } catch { /* someone else cleaned up */ }
continue;
}
} catch {
// Lock vanished between EEXIST and stat; retry immediately.
continue;
}
if (now() >= deadline) {
throw Object.assign(
new Error(`Timed out acquiring approvals lock at ${lockPath} after ${timeoutMs}ms`),
{ code: 'approval_lock_timeout' }
);
}
sleepSync(pollMs);
}
}
try {
closeSync(fd);
return fn();
} finally {
try { unlinkSync(lockPath); } catch { /* already removed */ }
}
}
export function approvalPolicyRequiresApproval(approval) {
if (!approval) return false;
const policy = approval.policy || (approval.required ? 'manual' : null);
return policy === 'manual';
}
export function approvalPolicyAutoRejects(approval) {
return approval?.policy === 'auto-reject';
}
function canonicalStringify(value) {
if (value === null || typeof value !== 'object') return JSON.stringify(value);
if (Array.isArray(value)) return `[${value.map(canonicalStringify).join(',')}]`;
const keys = Object.keys(value).sort();
return `{${keys.map(k => `${JSON.stringify(k)}:${canonicalStringify(value[k])}`).join(',')}}`;
}
export function computeTaskApprovalHash({ workflowId, task }) {
const material = {
workflow_id: workflowId,
task_id: task.id,
shell: {
program: task.shell?.program ?? null,
args: task.shell?.args ?? [],
cwd: task.shell?.cwd ?? null,
},
identity_ref: task.identity?.ref ?? null,
approval_policy: task.approval?.policy ?? (task.approval?.required ? 'manual' : null),
approval_risk_level: task.approval?.risk_level ?? null,
};
return `sha256:${createHash('sha256').update(canonicalStringify(material)).digest('hex')}`;
}
function readApprovalsLog(approvalsPath) {
if (!approvalsPath || !existsSync(approvalsPath)) return [];
const content = readFileSync(approvalsPath, 'utf8').trim();
if (!content) return [];
const events = [];
for (const line of content.split('\n')) {
if (!line.trim()) continue;
try {
events.push(JSON.parse(line));
} catch {
// Skip malformed lines (partial writes, crash-interrupted appends) so
// one bad record cannot DoS every subsequent exec. The corresponding
// grant is simply ignored rather than blocking the whole file.
}
}
return events;
}
function writeApprovalEvent(event, { approvalsPath }) {
mkdirSync(dirname(approvalsPath), { recursive: true });
appendFileSync(approvalsPath, JSON.stringify(event) + '\n', 'utf8');
}
function generateApprovalId() {
return randomBytes(16).toString('hex');
}
function foldEvents(events) {
const grants = new Map();
const consumed = new Map();
const revoked = new Map();
for (const e of events) {
if (e.kind === 'grant') {
grants.set(e.approval_id, e);
} else if (e.kind === 'consume') {
consumed.set(e.approval_id, e);
} else if (e.kind === 'revoke') {
revoked.set(e.approval_id, e);
}
}
return { grants, consumed, revoked };
}
function effectiveStatus(grant, consumed, revoked, nowMs) {
if (revoked.has(grant.approval_id)) return 'revoked';
if (consumed.has(grant.approval_id)) return 'consumed';
if (grant.expires_at && Date.parse(grant.expires_at) <= nowMs) return 'expired';
return 'pending';
}
export function listApprovals({ env = process.env, status: statusFilter, workflowId, taskId } = {}) {
const paths = getAgentcliPaths({ env });
const events = readApprovalsLog(paths.approvals);
const { grants, consumed, revoked } = foldEvents(events);
const now = Date.now();
const records = [];
for (const grant of grants.values()) {
const status = effectiveStatus(grant, consumed, revoked, now);
if (statusFilter && statusFilter !== 'all' && status !== statusFilter) continue;
if (workflowId && grant.workflow_id !== workflowId) continue;
if (taskId && grant.task_id !== taskId) continue;
const consume = consumed.get(grant.approval_id);
const revoke = revoked.get(grant.approval_id);
records.push({
approval_id: grant.approval_id,
workflow_id: grant.workflow_id,
task_id: grant.task_id,
task_hash: grant.task_hash,
approver: grant.approver,
reason: grant.reason,
granted_at: grant.granted_at,
expires_at: grant.expires_at,
status,
consumed_at: consume?.consumed_at ?? null,
consumed_by_execution_id: consume?.execution_id ?? null,
revoked_at: revoke?.revoked_at ?? null,
revoked_by: revoke?.revoked_by ?? null,
revoke_reason: revoke?.reason ?? null,
signature: grant.signature
? { method: grant.signature.method, key_fingerprint: grant.signature.key_fingerprint }
: null,
});
}
records.sort((a, b) => (a.granted_at < b.granted_at ? -1 : 1));
return records;
}
export function findValidApproval({
workflowId,
taskId,
taskHash,
approvalId,
env = process.env,
now = Date.now(),
}) {
const paths = getAgentcliPaths({ env });
const events = readApprovalsLog(paths.approvals);
const { grants, consumed, revoked } = foldEvents(events);
const candidates = [];
for (const grant of grants.values()) {
if (approvalId && grant.approval_id !== approvalId) continue;
if (grant.workflow_id !== workflowId) continue;
if (grant.task_id !== taskId) continue;
if (grant.task_hash !== taskHash) continue;
const status = effectiveStatus(grant, consumed, revoked, now);
if (status !== 'pending') continue;
candidates.push(grant);
}
if (candidates.length === 0) return null;
candidates.sort((a, b) => (a.granted_at < b.granted_at ? -1 : 1));
return candidates[0];
}
// Atomically find a matching pending grant and mark it consumed.
// Returns the consumed grant object, or null if no match. Concurrent callers
// serialize on the approvals lockfile; at most one wins per grant.
export function claimApproval({
workflowId,
taskId,
taskHash,
approvalId,
executionId,
env = process.env,
now = () => Date.now(),
lockOptions,
}) {
const paths = getAgentcliPaths({ env });
return withApprovalsLock(paths.approvals, () => {
const grant = findValidApproval({
workflowId, taskId, taskHash, approvalId, env, now: now(),
});
if (!grant) return null;
const consumedAt = new Date(now()).toISOString();
appendFileSync(
paths.approvals,
JSON.stringify({
v: APPROVAL_RECORD_VERSION,
kind: 'consume',
approval_id: grant.approval_id,
execution_id: executionId,
consumed_at: consumedAt,
}) + '\n',
'utf8'
);
return grant;
}, lockOptions);
}
function buildApprovalSignaturePayload(grant) {
return canonicalStringify({
v: APPROVAL_RECORD_VERSION,
kind: 'approval',
approval_id: grant.approval_id,
workflow_id: grant.workflow_id,
task_id: grant.task_id,
task_hash: grant.task_hash,
approver: grant.approver,
reason: grant.reason ?? null,
granted_at: grant.granted_at,
expires_at: grant.expires_at,
});
}
export function verifyApprovalSignature(grant, { env = process.env } = {}) {
if (!grant.signature) return { verified: null, reason: 'unsigned' };
const provider = getProvider(grant.signature.method?.replace(/-signature$/, '') || 'ssh');
if (!provider) return { verified: false, reason: `unknown signer "${grant.signature.method}"` };
// Tamper check: rebuild the canonical payload from the current grant fields
// and compare against the payload that was signed at grant time. An attacker
// who edits approver/reason/expires_at/task_hash in the ndjson after signing
// would leave signature.signed_payload untouched; the divergence catches it.
// The ssh provider only re-verifies that signature matches signed_payload,
// so without this check, post-sign field edits would go undetected.
const expectedPayload = buildApprovalSignaturePayload(grant);
if (grant.signature.signed_payload !== expectedPayload) {
return {
verified: false,
reason: 'grant fields do not match signed payload (possible tampering)',
};
}
const paths = getAgentcliPaths({ env });
let allowedSigners = resolveAllowedSigners({ env, statePath: paths.allowed_signers });
if (!allowedSigners && grant.signature.method === 'ssh-signature') {
// First-use bootstrap: mirror the `agentcli verify` command's behavior
// so a fresh install can round-trip grants without a manual setup step.
allowedSigners = generateAllowedSigners({
principal: grant.approver,
outputPath: paths.allowed_signers,
});
if (!allowedSigners) {
return {
verified: false,
reason: 'no allowed_signers file and no SSH public keys found to generate one',
};
}
}
return provider.verify(grant.signature, {
allowedSignersPath: allowedSigners,
principal: grant.approver,
});
}
export function grantApproval({
manifest,
workflowId,
taskId,
approver,
reason,
ttlS = DEFAULT_TTL_S,
signer,
signingKey,
env = process.env,
now = Date.now(),
}) {
if (!manifest || typeof manifest !== 'object') {
throw Object.assign(new Error('manifest is required'), { code: 'invalid_argument' });
}
if (!taskId) {
throw Object.assign(new Error('taskId is required'), { code: 'invalid_argument' });
}
if (!approver) {
throw Object.assign(new Error('approver is required (pass --by <principal>)'), { code: 'invalid_argument' });
}
const workflows = Array.isArray(manifest.workflows) ? manifest.workflows : [];
const workflow = workflowId
? workflows.find(w => w.id === workflowId)
: (workflows.length === 1 ? workflows[0] : null);
if (!workflow) {
throw Object.assign(
new Error(workflowId ? `workflow "${workflowId}" not found` : 'manifest has multiple workflows; pass --workflow <id>'),
{ code: 'invalid_argument' }
);
}
const task = (workflow.tasks || []).find(t => t.id === taskId);
if (!task) {
throw Object.assign(new Error(`task "${taskId}" not found in workflow "${workflow.id}"`), { code: 'invalid_argument' });
}
if (!task.approval) {
throw Object.assign(
new Error(`task "${taskId}" has no approval policy; nothing to approve`),
{ code: 'invalid_argument' }
);
}
if (!approvalPolicyRequiresApproval(task.approval) && !approvalPolicyAutoRejects(task.approval)) {
throw Object.assign(
new Error(`task "${taskId}" policy is "${task.approval.policy || 'none'}"; approval grant not meaningful`),
{ code: 'invalid_argument' }
);
}
if (approvalPolicyAutoRejects(task.approval)) {
throw Object.assign(
new Error(`task "${taskId}" policy is "auto-reject"; approvals cannot override`),
{ code: 'policy_forbids_approval' }
);
}
const taskHash = computeTaskApprovalHash({ workflowId: workflow.id, task });
const grantedAt = new Date(now).toISOString();
const expiresAt = new Date(now + ttlS * 1000).toISOString();
const approvalId = generateApprovalId();
const grant = {
v: APPROVAL_RECORD_VERSION,
kind: 'grant',
approval_id: approvalId,
workflow_id: workflow.id,
task_id: task.id,
task_hash: taskHash,
risk_level: task.approval.risk_level ?? null,
approver,
reason: reason ?? null,
granted_at: grantedAt,
expires_at: expiresAt,
signature: null,
};
const provider = resolveProvider({ signer, env });
if (provider.name !== 'none') {
const config = provider.resolve({ env, signingKey });
if (config) {
const payload = buildApprovalSignaturePayload(grant);
const sigResult = provider.sign(payload, config);
if (sigResult.signed) {
grant.signature = sigResult.attestation;
} else {
grant.signature = null;
}
}
}
const paths = getAgentcliPaths({ env });
writeApprovalEvent(grant, { approvalsPath: paths.approvals });
return {
approval_id: approvalId,
workflow_id: workflow.id,
task_id: task.id,
task_hash: taskHash,
risk_level: task.approval.risk_level ?? null,
approver,
reason: reason ?? null,
granted_at: grantedAt,
expires_at: expiresAt,
signature: grant.signature
? { method: grant.signature.method, key_fingerprint: grant.signature.key_fingerprint }
: null,
};
}
export function consumeApproval({ approvalId, executionId, env = process.env, now = Date.now() }) {
const paths = getAgentcliPaths({ env });
const event = {
v: APPROVAL_RECORD_VERSION,
kind: 'consume',
approval_id: approvalId,
execution_id: executionId,
consumed_at: new Date(now).toISOString(),
};
writeApprovalEvent(event, { approvalsPath: paths.approvals });
}
export function revokeApproval({ approvalId, revokedBy, reason, env = process.env, now = Date.now() }) {
const paths = getAgentcliPaths({ env });
const event = {
v: APPROVAL_RECORD_VERSION,
kind: 'revoke',
approval_id: approvalId,
revoked_by: revokedBy ?? null,
reason: reason ?? null,
revoked_at: new Date(now).toISOString(),
};
writeApprovalEvent(event, { approvalsPath: paths.approvals });
}