From adb9b2c3d93751c351239803c99a0b674aa15c0f Mon Sep 17 00:00:00 2001 From: Sphia Sadek Date: Wed, 25 Nov 2026 13:53:41 +0000 Subject: [PATCH 01/19] fix(orchestration): exactly-once concurrency seat release (#1003) Per-user concurrency was a counter incremented on admission and decremented on completion; retries and races (finalizer replay, cancel vs completion, a lost DynamoDB reply, the stranded-task reconciler) could release a seat twice or never. - Each admitted task carries a concurrency_slot marker (held -> released). acquireTaskSlot / releaseTaskSlot (shared/task-concurrency.ts) change the marker and the counter in one transaction: acquire needs SUBMITTED with no marker and room under the cap; release needs a held marker on a terminal task. Lost replies are recovered from the marker; transaction conflicts retry with bounded jitter. - Admission, finalization (release in finally), failTask, the orchestrator's early-return paths and the stranded-task reconciler all release through the marker; no handler decrements active_count directly. confirm-uploads no longer reserves at submit; the orchestrator owns admission. - A held task can never be re-queued (SUBMITTED -> QUEUED and the admission queue require no marker). - An approval wait that outlives the poll window finalizes to FAILED. It used to attempt the invalid AWAITING_APPROVAL -> TIMED_OUT, leave the task active and still free its seat. A finalization that cannot reach a terminal state now throws and is retried, keeping the seat. - The concurrency reconciler reads counters, then strongly reads every reservation, repairs only under the observed reservation_version, and releases terminal reservations left by interrupted cleanup. Users with unmarked active tasks (admitted before this change) are skipped until they settle. - DynamoDB Local race suite (15 cases) runs when ABCA_DDB_LOCAL_ENDPOINT is set; ORCHESTRATOR.md documents the scheme and the upgrade/drain note. Rebased onto main after the Lambda MicroVM approval lifecycle (#904): the MicroVM supervisor-failure path no longer decrements the counter itself. finalizeTask keeps the worker-ownership check (a changed owner neither mutates the task nor releases its seat) and releases in `finally`; the MicroVM finalization tests assert the release instead of the decrement. --- cdk/src/constructs/concurrency-reconciler.ts | 7 +- .../constructs/stranded-task-reconciler.ts | 4 +- cdk/src/constructs/user-concurrency-table.ts | 3 +- cdk/src/handlers/confirm-uploads.ts | 94 +---- cdk/src/handlers/orchestrate-task.ts | 5 + cdk/src/handlers/reconcile-admission-queue.ts | 4 +- cdk/src/handlers/reconcile-concurrency.ts | 195 ++++++----- cdk/src/handlers/reconcile-stranded-tasks.ts | 32 +- cdk/src/handlers/shared/orchestrator.ts | 132 +++----- cdk/src/handlers/shared/task-concurrency.ts | 232 +++++++++++++ .../handlers/orchestrate-task-handler.test.ts | 5 + cdk/test/handlers/orchestrate-task.test.ts | 111 +++--- .../reconcile-admission-queue.test.ts | 2 +- .../handlers/reconcile-concurrency.test.ts | 295 ++++++---------- .../handlers/reconcile-stranded-tasks.test.ts | 31 +- cdk/test/handlers/shared/orchestrator.test.ts | 22 +- .../shared/task-concurrency-local.test.ts | 320 ++++++++++++++++++ .../handlers/shared/task-concurrency.test.ts | 205 +++++++++++ docs/design/ORCHESTRATOR.md | 12 +- .../content/docs/architecture/Orchestrator.md | 12 +- 20 files changed, 1170 insertions(+), 553 deletions(-) create mode 100644 cdk/src/handlers/shared/task-concurrency.ts create mode 100644 cdk/test/handlers/shared/task-concurrency-local.test.ts create mode 100644 cdk/test/handlers/shared/task-concurrency.test.ts diff --git a/cdk/src/constructs/concurrency-reconciler.ts b/cdk/src/constructs/concurrency-reconciler.ts index c0fed93dd..b28a9e1b6 100644 --- a/cdk/src/constructs/concurrency-reconciler.ts +++ b/cdk/src/constructs/concurrency-reconciler.ts @@ -41,7 +41,7 @@ const RECONCILER_MEMORY_MB = 256; */ export interface ConcurrencyReconcilerProps { /** - * The DynamoDB task table (has UserStatusIndex GSI). + * The DynamoDB task table (reservations are scanned from the base table). */ readonly taskTable: dynamodb.ITable; @@ -59,8 +59,8 @@ export interface ConcurrencyReconcilerProps { /** * Scheduled Lambda that reconciles user concurrency counters by comparing - * the active_count in the concurrency table against actual active tasks - * in the task table. Corrects drift caused by orchestrator crashes. + * active_count against saved task reservations, including approval waits. + * Releases terminal reservations left behind by interrupted cleanup. */ export class ConcurrencyReconciler extends Construct { public readonly fn: lambda.NodejsFunction; @@ -89,6 +89,7 @@ export class ConcurrencyReconciler extends Construct { }); props.taskTable.grantReadData(this.fn); + props.taskTable.grant(this.fn, 'dynamodb:UpdateItem'); props.userConcurrencyTable.grantReadWriteData(this.fn); const schedule = props.schedule ?? Duration.minutes(DEFAULT_SCHEDULE_MINUTES); diff --git a/cdk/src/constructs/stranded-task-reconciler.ts b/cdk/src/constructs/stranded-task-reconciler.ts index 681564b79..95470ad75 100644 --- a/cdk/src/constructs/stranded-task-reconciler.ts +++ b/cdk/src/constructs/stranded-task-reconciler.ts @@ -55,7 +55,7 @@ export interface StrandedTaskReconcilerProps { /** TaskEventsTable (handler writes task_stranded + task_failed events). */ readonly taskEventsTable: dynamodb.ITable; - /** UserConcurrencyTable (handler decrements active_count on fail). */ + /** UserConcurrencyTable (handler releases the task-owned reservation on fail). */ readonly userConcurrencyTable: dynamodb.ITable; /** @@ -142,7 +142,7 @@ export class StrandedTaskReconciler extends Construct { props.taskTable.grantReadWriteData(this.fn); // TaskEvents: write task_stranded + task_failed events. props.taskEventsTable.grantWriteData(this.fn); - // Concurrency: decrement active_count on fail. + // Concurrency: read/release a task-owned reservation transactionally. props.userConcurrencyTable.grantReadWriteData(this.fn); const schedule = props.schedule ?? Duration.minutes(DEFAULT_SCHEDULE_MINUTES); diff --git a/cdk/src/constructs/user-concurrency-table.ts b/cdk/src/constructs/user-concurrency-table.ts index 223fd3213..200f6a890 100644 --- a/cdk/src/constructs/user-concurrency-table.ts +++ b/cdk/src/constructs/user-concurrency-table.ts @@ -49,7 +49,8 @@ export interface UserConcurrencyTableProps { * * Schema: user_id (PK). Each item holds an atomic counter (active_count) * representing the number of currently running tasks for the user. - * The application layer uses conditional updates for increment/decrement. + * The application layer changes the counter and its reservation_version in + * transactions with per-task reservation markers. */ export class UserConcurrencyTable extends Construct { /** diff --git a/cdk/src/handlers/confirm-uploads.ts b/cdk/src/handlers/confirm-uploads.ts index a4d9c42fb..40760bdac 100644 --- a/cdk/src/handlers/confirm-uploads.ts +++ b/cdk/src/handlers/confirm-uploads.ts @@ -148,7 +148,7 @@ export async function handler(event: APIGatewayProxyEvent, context: Context): Pr } // 6b. Pre-check concurrency before expensive screening (fail-fast). - // The actual atomic increment happens in transitionToSubmitted after screening + // The orchestrator reserves capacity atomically after successful submission. // passes. This read-only check avoids wasting Bedrock calls when the user is // already at their concurrency limit. const preCheckAdmitted = await preCheckConcurrency(task.user_id); @@ -464,13 +464,8 @@ async function transitionToSubmitted( const now = new Date().toISOString(); const taskId = task.task_id; - // Admission control — check concurrency before transitioning - const admitted = await checkConcurrency(task.user_id); - if (!admitted) { - return errorResponse(429, ErrorCode.RATE_LIMIT_EXCEEDED, - 'User concurrency limit reached. Wait for a running task to finish or cancel one, then retry.', requestId); - } - + // Submission does not reserve capacity. The orchestrator owns atomic + // admission for every task, including confirmed uploads and queue pickups. // Conditional DynamoDB write: status PENDING_UPLOADS → SUBMITTED try { await ddb.send(new UpdateCommand({ @@ -492,9 +487,7 @@ async function transitionToSubmitted( })); } catch (err: any) { if (err.name === 'ConditionalCheckFailedException') { - // Another caller already transitioned (e.g. cleanup Lambda cancelled - // the task). Roll back the concurrency counter we just incremented. - await decrementConcurrency(task.user_id); + // Another caller already transitioned (e.g. cleanup cancelled the task). // Return current state (idempotent) const current = await ddb.send(new GetCommand({ TableName: TABLE_NAME, @@ -505,9 +498,6 @@ async function transitionToSubmitted( } return errorResponse(404, ErrorCode.TASK_NOT_FOUND, 'Task not found.', requestId); } - // Roll back concurrency counter on any other DDB error (throttling, - // network timeout, etc.) to prevent permanent slot leaks. - await decrementConcurrency(task.user_id); throw err; } @@ -550,7 +540,7 @@ async function transitionToSubmitted( }); } catch (orchErr) { orchestratorInvokeFailed = true; - logger.error('Failed to invoke orchestrator after confirm-uploads — task will be picked up by StrandedTaskReconciler', { + logger.error('Orchestrator dispatch could not be confirmed after confirm-uploads; stranded-task cleanup fails tasks that remain stuck', { error: orchErr instanceof Error ? orchErr.message : String(orchErr), task_id: taskId, request_id: requestId, @@ -568,8 +558,8 @@ async function transitionToSubmitted( }; const responseBody = toTaskDetail(updatedTask); if (orchestratorInvokeFailed) { - (responseBody as any).warning = 'Task was submitted successfully but orchestration dispatch failed. ' + - 'The task will be picked up automatically within minutes by the background reconciler.'; + (responseBody as any).warning = 'Task was submitted, but starting the worker could not be confirmed. ' + + 'Check task status before retrying. Background cleanup marks tasks that remain stuck as failed.'; } return successResponse(200, responseBody, requestId); } @@ -770,8 +760,8 @@ async function buildScreeningConfig(): Promise { /** * Non-mutating read to check if the user is at their concurrency limit. - * Used as a fast pre-check before expensive screening; the actual atomic - * increment happens in checkConcurrency() during transitionToSubmitted. + * Used as an advisory pre-check before expensive screening. The orchestrator + * reserves capacity atomically after submission, queuing if capacity fills. */ async function preCheckConcurrency(userId: string): Promise { try { @@ -783,7 +773,7 @@ async function preCheckConcurrency(userId: string): Promise { return activeCount < MAX_CONCURRENT; } catch (err: any) { // Only swallow DDB throttling errors — these are transient and the atomic - // check in transitionToSubmitted is the authoritative gate. + // orchestrator admission transaction is the authoritative gate. const throttleErrors = ['ProvisionedThroughputExceededException', 'RequestLimitExceeded', 'ThrottlingException']; if (throttleErrors.includes(err?.name)) { logger.warn('Pre-check concurrency throttled — allowing request to proceed', { @@ -803,67 +793,3 @@ async function preCheckConcurrency(userId: string): Promise { throw err; } } - -async function checkConcurrency(userId: string): Promise { - try { - await ddb.send(new UpdateCommand({ - TableName: CONCURRENCY_TABLE_NAME, - Key: { user_id: userId }, - UpdateExpression: 'SET active_count = if_not_exists(active_count, :zero) + :one, updated_at = :now', - ConditionExpression: 'attribute_not_exists(active_count) OR active_count < :max', - ExpressionAttributeValues: { - ':zero': 0, - ':one': 1, - ':max': MAX_CONCURRENT, - ':now': new Date().toISOString(), - }, - })); - return true; - } catch (err: any) { - if (err.name === 'ConditionalCheckFailedException') { - return false; - } - throw err; - } -} - -async function decrementConcurrency(userId: string): Promise { - const maxAttempts = 3; - for (let attempt = 0; attempt < maxAttempts; attempt++) { - try { - await ddb.send(new UpdateCommand({ - TableName: CONCURRENCY_TABLE_NAME, - Key: { user_id: userId }, - UpdateExpression: 'SET active_count = active_count - :one, updated_at = :now', - ConditionExpression: 'attribute_exists(active_count) AND active_count > :zero', - ExpressionAttributeValues: { - ':one': 1, - ':zero': 0, - ':now': new Date().toISOString(), - }, - })); - return; - } catch (err: any) { - if (err.name === 'ConditionalCheckFailedException') { - // Counter already at 0 or doesn't exist — nothing to roll back - return; - } - if (attempt < maxAttempts - 1) { - // Retry transient DDB errors (throttling, network) with backoff - await new Promise(resolve => setTimeout(resolve, 100 * Math.pow(2, attempt))); - continue; - } - logger.error('Failed to decrement concurrency counter after retries (leak possible)', { - user_id: userId, - attempts: maxAttempts, - error: err instanceof Error ? err.message : String(err), - metric_type: 'concurrency_counter_leak', - }); - throw new Error( - `Concurrency counter decrement failed for user ${userId} after ${maxAttempts} attempts. ` + - 'Manual intervention may be required to reset the counter.', - { cause: err }, - ); - } - } -} diff --git a/cdk/src/handlers/orchestrate-task.ts b/cdk/src/handlers/orchestrate-task.ts index 82ef0df9d..2c7d341a3 100644 --- a/cdk/src/handlers/orchestrate-task.ts +++ b/cdk/src/handlers/orchestrate-task.ts @@ -46,6 +46,7 @@ import { runPreflightChecks } from './shared/preflight'; import { isAutoRetried, startSessionWithRetry } from './shared/session-start-retry'; import { deleteEcsPayload } from './shared/strategies/ecs-strategy'; import { deleteMicrovmPayload } from './shared/strategies/lambda-microvm-strategy'; +import { releaseTaskSlot } from './shared/task-concurrency'; import type { TaskRecord } from './shared/types'; import { workflowIsReadOnly, workflowRequiresRepo } from './shared/workflows'; @@ -149,6 +150,9 @@ const durableHandler: DurableExecutionHandler = asyn }); if (!admitted) { + // A task cancelled after its seat was taken returns it here; the marker + // makes this a no-op for a queued or never-admitted task. + await context.step('release-before-admission', () => releaseTaskSlot(taskId, task.user_id)); return; } @@ -184,6 +188,7 @@ const durableHandler: DurableExecutionHandler = asyn }); if (!preflightPassed) { + await context.step('release-before-work', () => releaseTaskSlot(taskId, task.user_id)); return; } diff --git a/cdk/src/handlers/reconcile-admission-queue.ts b/cdk/src/handlers/reconcile-admission-queue.ts index 0b08c48bf..849ca9785 100644 --- a/cdk/src/handlers/reconcile-admission-queue.ts +++ b/cdk/src/handlers/reconcile-admission-queue.ts @@ -213,7 +213,9 @@ async function requeueAfterInvokeFailure(taskId: string): Promise { TableName: TASK_TABLE, Key: { task_id: { S: taskId } }, UpdateExpression: 'SET #s = :queued, updated_at = :now, status_created_at = :sca', - ConditionExpression: '#s = :submitted', + // A lost invoke response may hide a successful admission. Never put a + // task that now holds capacity back into the no-reservation queue. + ConditionExpression: '#s = :submitted AND attribute_not_exists(concurrency_slot)', ExpressionAttributeNames: { '#s': 'status' }, ExpressionAttributeValues: { ':queued': { S: 'QUEUED' }, diff --git a/cdk/src/handlers/reconcile-concurrency.ts b/cdk/src/handlers/reconcile-concurrency.ts index 008f0e8a2..4e0828aee 100644 --- a/cdk/src/handlers/reconcile-concurrency.ts +++ b/cdk/src/handlers/reconcile-concurrency.ts @@ -17,108 +17,139 @@ * SOFTWARE. */ -import { DynamoDBClient, ScanCommand, QueryCommand, UpdateItemCommand } from '@aws-sdk/client-dynamodb'; +import { randomUUID } from 'node:crypto'; +import { ScanCommand, type ScanCommandOutput, UpdateCommand } from '@aws-sdk/lib-dynamodb'; +import { ACTIVE_STATUSES, TERMINAL_STATUSES } from '../constructs/task-status'; import { logger } from './shared/logger'; -import { makeClient } from './shared/ua'; +import { releaseTaskSlot, type ReservationTask } from './shared/task-concurrency'; +import { makeDocClient } from './shared/ua'; -const ddb = makeClient(DynamoDBClient); +const ddb = makeDocClient(); const TASK_TABLE = process.env.TASK_TABLE_NAME!; -const CONCURRENCY_TABLE = process.env.USER_CONCURRENCY_TABLE_NAME!; +const COUNTER_TABLE = process.env.USER_CONCURRENCY_TABLE_NAME!; -/** - * Count actual active tasks for a user by querying the UserStatusIndex GSI. - */ -async function countActiveTasks(userId: string): Promise { - let count = 0; - let lastKey: Record | undefined; - - do { - const resp = await ddb.send(new QueryCommand({ - TableName: TASK_TABLE, - IndexName: 'UserStatusIndex', - KeyConditionExpression: 'user_id = :uid', - FilterExpression: '#s IN (:s1, :s2, :s3, :s4)', - ExpressionAttributeNames: { '#s': 'status' }, - ExpressionAttributeValues: { - ':uid': { S: userId }, - ':s1': { S: 'SUBMITTED' }, - ':s2': { S: 'HYDRATING' }, - ':s3': { S: 'RUNNING' }, - ':s4': { S: 'FINALIZING' }, - }, - Select: 'COUNT', - ExclusiveStartKey: lastKey, - })); - count += resp.Count ?? 0; - lastKey = resp.LastEvaluatedKey; - } while (lastKey); +interface CounterSnapshot { + readonly user_id: string; + readonly active_count?: number; + readonly reservation_version?: string; +} - return count; +interface Reservations { + held: number; + ambiguous: boolean; + terminal: string[]; } /** - * Scheduled handler: scan the concurrency table and reconcile each user's - * active_count against actual active tasks in the task table. + * Read counters BEFORE scanning reservations. Every reservation mutation also + * changes its counter revision; a conditional repair then detects changes + * anywhere during the scan, including an increment/decrement with no net change. + * Strong base-table reads avoid the GSI lag that can hide a newly held slot. */ export async function handler(): Promise { logger.info('Concurrency reconciler started'); - let corrected = 0; - let scanned = 0; - let errors = 0; + const counters = new Map(); let lastKey: Record | undefined; - do { - const scanResp = await ddb.send(new ScanCommand({ - TableName: CONCURRENCY_TABLE, + const page: ScanCommandOutput = await ddb.send(new ScanCommand({ + TableName: COUNTER_TABLE, + ConsistentRead: true, + ProjectionExpression: 'user_id, active_count, reservation_version', ExclusiveStartKey: lastKey, })); + for (const row of page.Items ?? []) { + if (typeof row.user_id === 'string') counters.set(row.user_id, row as CounterSnapshot); + } + lastKey = page.LastEvaluatedKey; + } while (lastKey); - for (const rawItem of scanResp.Items ?? []) { - const userId = rawItem.user_id?.S; - const storedCount = Number(rawItem.active_count?.N ?? '0'); - if (!userId) continue; - scanned++; - - try { - const actualCount = await countActiveTasks(userId); + const reservations = new Map(); + do { + const page: ScanCommandOutput = await ddb.send(new ScanCommand({ + TableName: TASK_TABLE, + ConsistentRead: true, + ProjectionExpression: 'task_id, user_id, #status, concurrency_slot', + ExpressionAttributeNames: { '#status': 'status' }, + ExclusiveStartKey: lastKey, + })); + for (const row of page.Items ?? []) { + const task = row as ReservationTask; + if (!task.task_id || !task.user_id) continue; + const active = ACTIVE_STATUSES.some(status => status === task.status); + if (!task.concurrency_slot && !active) continue; + const owned = reservations.get(task.user_id) ?? { held: 0, ambiguous: false, terminal: [] }; + if (task.concurrency_slot?.state === 'held') { + // Terminal tasks still own their seat until release commits. Repair + // that total first, then release terminal reservations through the + // same transaction used by the orchestrator and stranded-task cleaner. + owned.held++; + if (TERMINAL_STATUSES.some(status => status === task.status)) owned.terminal.push(task.task_id); + } else if (active || (task.concurrency_slot && task.concurrency_slot.state !== 'released')) { + // Older active tasks and not-yet-admitted SUBMITTED tasks cannot be + // distinguished by status. Wait for them to settle; never guess a count. + owned.ambiguous = true; + } + reservations.set(task.user_id, owned); + } + lastKey = page.LastEvaluatedKey; + } while (lastKey); - if (storedCount !== actualCount) { - logger.info('Drift detected', { userId, storedCount, actualCount }); - try { - await ddb.send(new UpdateItemCommand({ - TableName: CONCURRENCY_TABLE, - Key: { user_id: { S: userId } }, - UpdateExpression: 'SET active_count = :count, updated_at = :now', - ConditionExpression: 'active_count = :stored', - ExpressionAttributeValues: { - ':count': { N: String(actualCount) }, - ':now': { S: new Date().toISOString() }, - ':stored': { N: String(storedCount) }, - }, - })); - corrected++; - } catch (updateErr: unknown) { - if (updateErr && typeof updateErr === 'object' && 'name' in updateErr && updateErr.name === 'ConditionalCheckFailedException') { - logger.info('Concurrent update detected, skipping', { userId }); - } else { - throw updateErr; - } + let corrected = 0; + let errors = 0; + const users = new Set([...counters.keys(), ...reservations.keys()]); + for (const userId of users) { + const snapshot = counters.get(userId); + const owned = reservations.get(userId) ?? { held: 0, ambiguous: false, terminal: [] }; + try { + const stored = snapshot?.active_count ?? 0; + if (!Number.isSafeInteger(stored)) throw new Error('Concurrency counter is not an integer'); + if (owned.ambiguous) { + logger.warn('Skipping capacity repair while task reservation ownership is ambiguous', { + user_id: userId, error_id: 'CONCURRENCY_RESERVATION_UNKNOWN', + }); + } else if (stored !== owned.held) { + const conditions: string[] = []; + const values: Record = { + ':count': owned.held, ':now': new Date().toISOString(), ':version': randomUUID(), + }; + if (!snapshot) { + conditions.push('attribute_not_exists(user_id)'); + } else { + conditions.push('attribute_exists(user_id)'); + if (snapshot.active_count === undefined) {conditions.push('attribute_not_exists(active_count)');} else { + conditions.push('active_count = :stored'); + values[':stored'] = stored; + } + if (snapshot.reservation_version === undefined) {conditions.push('attribute_not_exists(reservation_version)');} else { + conditions.push('reservation_version = :observed'); + values[':observed'] = snapshot.reservation_version; } } - } catch (err: unknown) { - errors++; - logger.warn('Per-user reconciliation failed, continuing', { - userId, - error: err instanceof Error ? err.message : String(err), - }); + try { + await ddb.send(new UpdateCommand({ + TableName: COUNTER_TABLE, + Key: { user_id: userId }, + UpdateExpression: 'SET active_count = :count, updated_at = :now, reservation_version = :version', + ConditionExpression: conditions.join(' AND '), + ExpressionAttributeValues: values, + })); + corrected++; + logger.info('Corrected capacity counter from saved reservations', { + user_id: userId, stored_count: stored, reservation_count: owned.held, + }); + } catch (error) { + if ((error as { name?: string })?.name !== 'ConditionalCheckFailedException') throw error; + logger.info('Capacity changed during reconciliation; skipped stale repair', { user_id: userId }); + } } + for (const taskId of owned.terminal) await releaseTaskSlot(taskId, userId); + } catch (error) { + errors++; + logger.warn('Per-user capacity reconciliation failed, continuing', { user_id: userId, error: String(error) }); } - - lastKey = scanResp.LastEvaluatedKey; - } while (lastKey); - - if (errors === scanned && scanned > 0) { - logger.error('All users failed reconciliation — possible systemic issue', { scanned, errors }); } - logger.info('Concurrency reconciler finished', { scanned, corrected, errors }); + if (errors === users.size && users.size > 0) { + logger.error('All users failed reconciliation — possible systemic issue', { scanned: users.size, errors }); + } + logger.info('Concurrency reconciler finished', { scanned: users.size, corrected, errors }); } diff --git a/cdk/src/handlers/reconcile-stranded-tasks.ts b/cdk/src/handlers/reconcile-stranded-tasks.ts index ed03500ee..869551b3a 100644 --- a/cdk/src/handlers/reconcile-stranded-tasks.ts +++ b/cdk/src/handlers/reconcile-stranded-tasks.ts @@ -48,12 +48,12 @@ import { } from '@aws-sdk/client-dynamodb'; import { ulid } from 'ulid'; import { logger } from './shared/logger'; +import { releaseTaskSlot } from './shared/task-concurrency'; import { makeClient } from './shared/ua'; const ddb = makeClient(DynamoDBClient); const TASK_TABLE = process.env.TASK_TABLE_NAME!; const EVENTS_TABLE = process.env.TASK_EVENTS_TABLE_NAME!; -const CONCURRENCY_TABLE = process.env.USER_CONCURRENCY_TABLE_NAME!; /** Stranded-task timeout. The orchestrator Lambda is async-invoked and * the agent runtime has a cold-start path; 1200 s covers Lambda retries @@ -290,32 +290,10 @@ async function failStrandedTask(task: StrandedCandidate): Promise { } } - // 3. Release the concurrency slot. Best-effort; drift is later corrected - // by the concurrency reconciler. - try { - await ddb.send(new UpdateItemCommand({ - TableName: CONCURRENCY_TABLE, - Key: { user_id: { S: task.user_id } }, - UpdateExpression: 'SET active_count = active_count - :one, updated_at = :now', - ConditionExpression: 'active_count > :zero', - ExpressionAttributeValues: { - ':one': { N: '1' }, - ':zero': { N: '0' }, - ':now': { S: now }, - }, - })); - } catch (decrErr: unknown) { - if (decrErr && typeof decrErr === 'object' && 'name' in decrErr - && decrErr.name !== 'ConditionalCheckFailedException') { - logger.warn('Failed to decrement concurrency for stranded task', { - task_id: task.task_id, - user_id: task.user_id, - error: decrErr instanceof Error ? decrErr.message : String(decrErr), - }); - } - // ConditionalCheckFailedException means the counter is already 0 — - // drift the concurrency reconciler will eventually catch. - } + // 3. Release this task's reservation. The marker makes the release exactly + // once even if the orchestrator finalizes the same task; a failure here + // leaves the seat held, which the concurrency reconciler then releases. + await releaseTaskSlot(task.task_id, task.user_id); return true; } diff --git a/cdk/src/handlers/shared/orchestrator.ts b/cdk/src/handlers/shared/orchestrator.ts index cced582cb..51d6fda11 100644 --- a/cdk/src/handlers/shared/orchestrator.ts +++ b/cdk/src/handlers/shared/orchestrator.ts @@ -36,6 +36,7 @@ import { parseRef } from './registry/ref'; import { RegistryResolutionError, type ResolvedAsset } from './registry/types'; import { loadRepoConfig, type BlueprintConfig, type ComputeType } from './repo-config'; import { resolveUrlAttachments } from './resolve-url-attachments'; +import { acquireTaskSlot, releaseTaskSlot } from './task-concurrency'; import { APPROVAL_GATE_CAP_MAX, APPROVAL_GATE_CAP_MIN, type AgentAttachmentPayload, type AttachmentRecord, type TaskRecord } from './types'; import { makeClient, makeDocClient } from './ua'; import { computeTtlEpoch, DEFAULT_MAX_TURNS } from './validation'; @@ -44,7 +45,6 @@ const ddb = makeDocClient(); const TABLE_NAME = process.env.TASK_TABLE_NAME!; const EVENTS_TABLE_NAME = process.env.TASK_EVENTS_TABLE_NAME!; -const CONCURRENCY_TABLE_NAME = process.env.USER_CONCURRENCY_TABLE_NAME!; const RUNTIME_ARN = process.env.RUNTIME_ARN!; const MAX_CONCURRENT = Number(process.env.MAX_CONCURRENT_TASKS_PER_USER ?? '3'); const TASK_RETENTION_DAYS = Number(process.env.TASK_RETENTION_DAYS ?? '90'); @@ -184,31 +184,12 @@ export async function loadTask(taskId: string, consistentRead = false): Promise< } /** - * Admission control: check user concurrency and increment counter. + * Admission control: acquire or recover this task's capacity reservation. * @param task - the task record. * @returns true if admitted, false if concurrency limit reached. */ export async function admissionControl(task: TaskRecord): Promise { - try { - await ddb.send(new UpdateCommand({ - TableName: CONCURRENCY_TABLE_NAME, - Key: { user_id: task.user_id }, - UpdateExpression: 'SET active_count = if_not_exists(active_count, :zero) + :one, updated_at = :now', - ConditionExpression: 'attribute_not_exists(active_count) OR active_count < :max', - ExpressionAttributeValues: { - ':zero': 0, - ':one': 1, - ':max': MAX_CONCURRENT, - ':now': new Date().toISOString(), - }, - })); - return true; - } catch (err: unknown) { - if (err && typeof err === 'object' && 'name' in err && err.name === 'ConditionalCheckFailedException') { - return false; - } - throw err; - } + return acquireTaskSlot(task.task_id, task.user_id, MAX_CONCURRENT); } /** @@ -260,7 +241,10 @@ export async function transitionTask( } } - let condition = '#status = :fromStatus'; + // An admitted task holds a reservation; it must never be queued again. + let condition = fromStatus === TaskStatus.SUBMITTED && toStatus === TaskStatus.QUEUED + ? '#status = :fromStatus AND attribute_not_exists(concurrency_slot)' + : '#status = :fromStatus'; if (expectedMicrovmId) { // A MicroVM transition applies only while the task still names this worker. condition += ' AND compute_type = :microvmType AND session_id = :microvmId AND compute_metadata.microvmId = :microvmId'; @@ -1028,7 +1012,12 @@ export async function pollTaskStatus( } /** - * Finalize a task: write terminal status, emit events, release concurrency. + * Finalize a task: write terminal status, emit events, release its reservation. + * + * The reservation is released in ``finally`` and only once the task is + * terminal (``releaseTaskSlot`` checks its marker), so a crash, an event + * failure, a durable replay or a competing cleaner cannot release it twice, + * and a still-active task keeps its seat. * @param taskId - the task ID. * @param pollState - the final poll state. * @param userId - the user who owns the task. @@ -1047,7 +1036,11 @@ export async function finalizeTask( logger.warn('MicroVM finalization skipped after worker ownership changed', { task_id: taskId, microvm_id: expectedId }); return false; } - await finalizeTaskOutcome(taskId, pollState, userId, task); + try { + await finalizeTaskOutcome(taskId, pollState, task); + } finally { + await releaseTaskSlot(taskId, userId); + } return true; } @@ -1058,7 +1051,6 @@ export async function finalizeTask( async function finalizeMicrovmSupervisorFailure( taskId: string, pollState: PollState, - userId: string, currentStatus: TaskStatusType, correlation: ReturnType['correlation'], ): Promise { @@ -1079,7 +1071,6 @@ async function finalizeMicrovmSupervisorFailure( await emitTaskEvent(taskId, `task_${winner.status.toLowerCase()}`, { final_status: winner.status, poll_attempts: pollState.attempts, }, correlation); - await decrementConcurrency(userId); return; } await emitTaskEvent(taskId, timeout ? 'task_timed_out' : 'task_failed', { @@ -1088,17 +1079,16 @@ async function finalizeMicrovmSupervisorFailure( microvm_id: pollState.microvmSupervisor?.microvmId, poll_attempts: pollState.attempts, }, correlation); - await decrementConcurrency(userId); } -async function finalizeTaskOutcome(taskId: string, pollState: PollState, userId: string, task: TaskRecord): Promise { +async function finalizeTaskOutcome(taskId: string, pollState: PollState, task: TaskRecord): Promise { const currentStatus = task.status; // Correlation envelope on this function's own log lines too, not just the // events it emits — admission→terminal logs must join by {user_id, repo}. const { log, correlation } = envelopeFor(task); if (pollState.microvmFailureReason && !TERMINAL_STATUSES.includes(currentStatus)) { - await finalizeMicrovmSupervisorFailure(taskId, pollState, userId, currentStatus, correlation); + await finalizeMicrovmSupervisorFailure(taskId, pollState, currentStatus, correlation); return; } @@ -1130,7 +1120,7 @@ async function finalizeTaskOutcome(taskId: string, pollState: PollState, userId: transitioned = true; } catch (err) { // Task may have transitioned concurrently (e.g. agent wrote terminal status). - // Re-read to avoid double-decrement or contradictory events. + // Re-read to report the terminal status that actually won. log.warn('Finalization transition to FAILED (heartbeat) failed, task may have transitioned concurrently', { error: err instanceof Error ? err.message : String(err), }); @@ -1140,7 +1130,6 @@ async function finalizeTaskOutcome(taskId: string, pollState: PollState, userId: reason: 'agent_heartbeat_stale', poll_attempts: pollState.attempts, }, correlation); - await decrementConcurrency(userId); } else { // Transition failed — re-read task to determine actual state. // If already terminal the block below will handle TTL + concurrency. @@ -1151,10 +1140,9 @@ async function finalizeTaskOutcome(taskId: string, pollState: PollState, userId: final_status: reread.status, poll_attempts: pollState.attempts, }, correlation); - await decrementConcurrency(userId); } else { - log.warn('Heartbeat path: task in unexpected state after failed transition, releasing concurrency', { status: reread.status }); - await decrementConcurrency(userId); + log.warn('Heartbeat path: task in unexpected state after failed transition, keeping its reservation until terminal', { status: reread.status }); + throw new Error(`Heartbeat finalization left task ${taskId} active in ${reread.status}`); } } return; @@ -1221,15 +1209,14 @@ async function finalizeTaskOutcome(taskId: string, pollState: PollState, userId: final_status: currentStatus, poll_attempts: pollState.attempts, }, correlation); - await decrementConcurrency(userId); return; } - // If still RUNNING / FINALIZING / AWAITING_APPROVAL after the poll - // window closes, terminate the task through an allowed transition: approval - // waits permit FAILED, not TIMED_OUT, and reaching the execution limit is not - // a human denial. The stranded-approval reconciler remains a secondary - // safety net for tasks the orchestrator already lost track of. + // If still RUNNING / FINALIZING / AWAITING_APPROVAL after the poll window + // closes, terminate through an allowed transition: AWAITING_APPROVAL permits + // FAILED, not TIMED_OUT. The previous TIMED_OUT attempt for an approval wait + // was rejected by VALID_TRANSITIONS, left the task active, and still freed + // its seat. if ( currentStatus === TaskStatus.RUNNING || currentStatus === TaskStatus.FINALIZING @@ -1245,8 +1232,14 @@ async function finalizeTaskOutcome(taskId: string, pollState: PollState, userId: : 'Orchestrator poll timeout exceeded', }); } catch (err) { - // Task may have transitioned concurrently — re-read and accept + // Accept a committed terminal winner; otherwise retry finalization. log.warn('Finalization transition failed, task may have transitioned concurrently', { error: err instanceof Error ? err.message : String(err) }); + const winner = await loadTask(taskId, true); + if (!TERMINAL_STATUSES.includes(winner.status)) throw err; + await emitTaskEvent(taskId, `task_${winner.status.toLowerCase()}`, { + final_status: winner.status, poll_attempts: pollState.attempts, + }, correlation); + return; } await emitTaskEvent(taskId, terminalStatus === TaskStatus.FAILED ? 'task_failed' : 'task_timed_out', { reason: currentStatus === TaskStatus.AWAITING_APPROVAL @@ -1254,7 +1247,6 @@ async function finalizeTaskOutcome(taskId: string, pollState: PollState, userId: : 'poll_timeout', poll_attempts: pollState.attempts, }, correlation); - await decrementConcurrency(userId); return; } @@ -1268,18 +1260,23 @@ async function finalizeTaskOutcome(taskId: string, pollState: PollState, userId: }); } catch (err) { log.warn('Finalization transition from HYDRATING failed, task may have transitioned concurrently', { error: err instanceof Error ? err.message : String(err) }); + const winner = await loadTask(taskId, true); + if (!TERMINAL_STATUSES.includes(winner.status)) throw err; + await emitTaskEvent(taskId, `task_${winner.status.toLowerCase()}`, { + final_status: winner.status, poll_attempts: pollState.attempts, + }, correlation); + return; } await emitTaskEvent(taskId, 'task_failed', { reason: 'session_never_started', poll_attempts: pollState.attempts, }, correlation); - await decrementConcurrency(userId); return; } - // Unexpected state — log and release concurrency + // Unexpected active state — retain its reservation until terminal. log.error('Unexpected task state during finalization', { status: currentStatus }); - await decrementConcurrency(userId); + throw new Error(`Cannot finalize task ${taskId} in ${currentStatus}`); } /** @@ -1335,7 +1332,7 @@ export async function queueTask(task: TaskRecord): Promise { * @param fromStatus - the current status. * @param errorMessage - the error reason. * @param userId - the user who owns the task. - * @param releaseConcurrency - whether to decrement the concurrency counter. + * @param releaseConcurrency - whether to release this task's held reservation. * @param repo - optional target repo (`owner/repo`) for the correlation * envelope; omit for repo-less workflows. */ @@ -1359,41 +1356,18 @@ export async function failTask( log.warn('Failed to transition task to FAILED', { error: err instanceof Error ? err.message : String(err), }); + // Only a committed terminal state may release; an active task keeps its seat. + const current = await loadTask(taskId, true); + if (!TERMINAL_STATUSES.includes(current.status)) throw err; } - // Only emit / release concurrency after a successful transition. Callers such as - // orchestrate-task rethrow after failTask; Durable Execution retries the step and - // would otherwise re-run emit + decrement while the task is already FAILED. - if (transitioned) { - await emitTaskEvent(taskId, 'task_failed', { error_message: errorMessage }, { user_id: userId, repo }); - if (releaseConcurrency) { - await decrementConcurrency(userId); - } - } -} - -/** - * Decrement the user's concurrency counter (best-effort). - * @param userId - the user ID. - */ -async function decrementConcurrency(userId: string): Promise { + // A replay may find the FAILED write already committed. Events remain + // transition-owned; releasing the marker-guarded reservation is safe to repeat. try { - await ddb.send(new UpdateCommand({ - TableName: CONCURRENCY_TABLE_NAME, - Key: { user_id: userId }, - UpdateExpression: 'SET active_count = active_count - :one, updated_at = :now', - ConditionExpression: 'active_count > :zero', - ExpressionAttributeValues: { - ':one': 1, - ':zero': 0, - ':now': new Date().toISOString(), - }, - })); - } catch (err: unknown) { - if (err && typeof err === 'object' && 'name' in err && err.name === 'ConditionalCheckFailedException') { - logger.info('Concurrency counter already at zero, nothing to decrement', { user_id: userId }); - } else { - logger.warn('Failed to decrement concurrency counter', { user_id: userId, error: err instanceof Error ? err.message : String(err) }); + if (transitioned) { + await emitTaskEvent(taskId, 'task_failed', { error_message: errorMessage }, { user_id: userId, repo }); } + } finally { + if (releaseConcurrency) await releaseTaskSlot(taskId, userId); } } diff --git a/cdk/src/handlers/shared/task-concurrency.ts b/cdk/src/handlers/shared/task-concurrency.ts new file mode 100644 index 000000000..d8afffef0 --- /dev/null +++ b/cdk/src/handlers/shared/task-concurrency.ts @@ -0,0 +1,232 @@ +/** + * MIT No Attribution + * + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +import { randomUUID } from 'node:crypto'; +import { setTimeout as delay } from 'node:timers/promises'; +import { GetCommand, TransactWriteCommand } from '@aws-sdk/lib-dynamodb'; +import { ACTIVE_STATUSES, TaskStatus, TERMINAL_STATUSES } from '../../constructs/task-status'; +import { logger } from './logger'; +import { makeDocClient } from './ua'; + +/** Internal TaskTable data; a released task cannot acquire another reservation. */ +export interface ReservationTask { + readonly task_id: string; + readonly user_id: string; + readonly status: string; + readonly concurrency_slot?: { + readonly state: 'held' | 'released'; + readonly acquired_at: string; + readonly released_at?: string; + }; +} + +const ddb = makeDocClient(); +const TASK_TABLE = process.env.TASK_TABLE_NAME!; +const COUNTER_TABLE = process.env.USER_CONCURRENCY_TABLE_NAME!; + +function terminal(status: string): boolean { + return TERMINAL_STATUSES.some(value => value === status); +} + +async function readTask(taskId: string, userId: string): Promise { + const result = await ddb.send(new GetCommand({ + TableName: TASK_TABLE, Key: { task_id: taskId }, ConsistentRead: true, + })); + const task = result.Item as ReservationTask | undefined; + if (task && task.user_id !== userId) throw new Error('Concurrency reservation owner does not match task owner'); + return task; +} + +function conditionalFailure(error: unknown, index: number): boolean { + const failure = error as { name?: string; CancellationReasons?: { Code?: string }[] }; + return failure?.name === 'TransactionCanceledException' + && failure.CancellationReasons?.[index]?.Code === 'ConditionalCheckFailed'; +} + +/** + * The SDK does not retry TransactionCanceledException when another task is + * updating the same user's counter. Retry only explicit transaction conflicts; + * conditional failures still belong to the admission/release state machine. + */ +async function sendReservationTransaction( + command: TransactWriteCommand, + taskId: string, + userId: string, +): Promise { + const maxAttempts = 5; + const baseDelayMs = 50; + for (let attempt = 1; attempt <= maxAttempts; attempt++) { + try { + // Keep the exact transaction and client token across retries. + await ddb.send(command); + return; + } catch (error) { + const failure = error as { name?: string; CancellationReasons?: { Code?: string }[] }; + const codes = failure?.CancellationReasons?.map(reason => reason.Code); + const conflict = failure?.name === 'TransactionCanceledException' + && codes?.includes('TransactionConflict') + && codes.every(code => code === 'None' || code === 'TransactionConflict'); + if (!conflict) throw error; + if (attempt === maxAttempts) { + logger.warn('Capacity transaction contention exhausted bounded retries', { + task_id: taskId, + user_id: userId, + attempts: attempt, + error_id: 'CONCURRENCY_TRANSACTION_CONFLICT', + cancellation_codes: codes, + }); + throw error; + } + await delay(Math.floor(Math.random() * baseDelayMs * 2 ** (attempt - 1))); + } + } +} + +/** Reserve once per task, including after a lost transaction acknowledgement. */ +export async function acquireTaskSlot(taskId: string, userId: string, limit: number): Promise { + const current = await readTask(taskId, userId); + if (!current) throw new Error(`Cannot reserve capacity for missing task ${taskId}`); + if (current.concurrency_slot?.state === 'held') { + return ACTIVE_STATUSES.some(status => status === current.status); + } + if (current.status !== TaskStatus.SUBMITTED || current.concurrency_slot) return false; + + const now = new Date().toISOString(); + const revision = randomUUID(); + try { + await sendReservationTransaction(new TransactWriteCommand({ + ClientRequestToken: revision, + TransactItems: [ + { + Update: { + TableName: TASK_TABLE, + Key: { task_id: taskId }, + UpdateExpression: 'SET concurrency_slot = :slot', + ConditionExpression: 'user_id = :user AND #status = :submitted AND attribute_not_exists(concurrency_slot)', + ExpressionAttributeNames: { '#status': 'status' }, + ExpressionAttributeValues: { + ':slot': { state: 'held', acquired_at: now }, + ':user': userId, + ':submitted': TaskStatus.SUBMITTED, + }, + }, + }, + { + Update: { + TableName: COUNTER_TABLE, + Key: { user_id: userId }, + UpdateExpression: 'SET active_count = if_not_exists(active_count, :zero) + :one, ' + + 'updated_at = :now, reservation_version = :version', + ConditionExpression: 'attribute_not_exists(active_count) OR active_count < :max', + ExpressionAttributeValues: { + ':zero': 0, ':one': 1, ':max': limit, ':now': now, ':version': revision, + }, + }, + }, + ], + }), taskId, userId); + return true; + } catch (error) { + // A competing invocation or a lost successful response may have reserved it. + const latest = await readTask(taskId, userId); + if (latest?.concurrency_slot?.state === 'held') { + return ACTIVE_STATUSES.some(status => status === latest.status); + } + if (!latest || latest.status !== TaskStatus.SUBMITTED || latest.concurrency_slot) return false; + if (conditionalFailure(error, 1)) return false; // Capacity was full. + throw error; // Throttling/conflict/outage is not evidence that capacity is full. + } +} + +/** + * Return a terminal task's reservation atomically with its counter update. + * Never infer ownership from status alone: legacy/unadmitted tasks have no + * marker and cannot return another task's seat. Reconciliation handles drift. + */ +export async function releaseTaskSlot(taskId: string, userId: string): Promise { + const current = await readTask(taskId, userId); + if (!current || !terminal(current.status) || current.concurrency_slot?.state !== 'held') return false; + + let emptyCounter = false; + for (let attempt = 0; attempt < 2; attempt++) { + const now = new Date().toISOString(); + const revision = randomUUID(); + try { + await sendReservationTransaction(new TransactWriteCommand({ + ClientRequestToken: revision, + TransactItems: [ + { + Update: { + TableName: TASK_TABLE, + Key: { task_id: taskId }, + UpdateExpression: 'SET concurrency_slot.#state = :released, concurrency_slot.released_at = :now', + ConditionExpression: 'user_id = :user AND concurrency_slot.#state = :held ' + + 'AND #status IN (:completed, :failed, :cancelled, :timedOut)', + ExpressionAttributeNames: { '#state': 'state', '#status': 'status' }, + ExpressionAttributeValues: { + ':user': userId, + ':held': 'held', + ':released': 'released', + ':now': now, + ':completed': TaskStatus.COMPLETED, + ':failed': TaskStatus.FAILED, + ':cancelled': TaskStatus.CANCELLED, + ':timedOut': TaskStatus.TIMED_OUT, + }, + }, + }, + { + Update: { + TableName: COUNTER_TABLE, + Key: { user_id: userId }, + UpdateExpression: emptyCounter + ? 'SET active_count = if_not_exists(active_count, :zero), updated_at = :now, reservation_version = :version' + : 'SET active_count = active_count - :one, updated_at = :now, reservation_version = :version', + ConditionExpression: emptyCounter + ? 'attribute_not_exists(active_count) OR active_count >= :zero' + : 'active_count > :zero', + ExpressionAttributeValues: { + ':zero': 0, ...(!emptyCounter && { ':one': 1 }), ':now': now, ':version': revision, + }, + }, + }, + ], + }), taskId, userId); + if (emptyCounter) { + logger.warn('Released task reservation whose counter was already empty', { + task_id: taskId, user_id: userId, error_id: 'CONCURRENCY_EMPTY_COUNTER', + }); + } + return true; + } catch (error) { + const latest = await readTask(taskId, userId); + if (latest?.concurrency_slot?.state === 'released') return false; + if (!latest || !terminal(latest.status) || latest.concurrency_slot?.state !== 'held') return false; + if (!emptyCounter && conditionalFailure(error, 1)) { + // This attempt observed no positive count. Close its marker without + // subtracting from seats reserved since then. A concurrent repair may + // leave an overcount, which a later revision-guarded sweep can correct. + emptyCounter = true; + continue; + } + throw error; + } + } + throw new Error(`Could not release capacity reservation for task ${taskId}`); +} diff --git a/cdk/test/handlers/orchestrate-task-handler.test.ts b/cdk/test/handlers/orchestrate-task-handler.test.ts index b0c9dde05..4c1738d3d 100644 --- a/cdk/test/handlers/orchestrate-task-handler.test.ts +++ b/cdk/test/handlers/orchestrate-task-handler.test.ts @@ -94,6 +94,11 @@ jest.mock('../../src/handlers/shared/compute-strategy', () => ({ }), })); jest.mock('../../src/handlers/shared/strategies/ecs-strategy', () => ({ deleteEcsPayload: jest.fn() })); +// Seat accounting has its own suite (task-concurrency*.test.ts); here the handler's steps only. +jest.mock('../../src/handlers/shared/task-concurrency', () => ({ + acquireTaskSlot: jest.fn(), + releaseTaskSlot: jest.fn().mockResolvedValue(undefined), +})); jest.mock('../../src/handlers/shared/strategies/lambda-microvm-strategy', () => ({ deleteMicrovmPayload: jest.fn() })); process.env.LINEAR_WORKSPACE_REGISTRY_TABLE_NAME = 'LinearWorkspaceRegistry'; diff --git a/cdk/test/handlers/orchestrate-task.test.ts b/cdk/test/handlers/orchestrate-task.test.ts index 244270b1f..7d2b3a169 100644 --- a/cdk/test/handlers/orchestrate-task.test.ts +++ b/cdk/test/handlers/orchestrate-task.test.ts @@ -19,6 +19,12 @@ // --- Mocks --- const mockDdbSend = jest.fn(); +const mockAcquireTaskSlot = jest.fn(); +const mockReleaseTaskSlot = jest.fn(); +jest.mock('../../src/handlers/shared/task-concurrency', () => ({ + acquireTaskSlot: (...args: unknown[]) => mockAcquireTaskSlot(...args), + releaseTaskSlot: (...args: unknown[]) => mockReleaseTaskSlot(...args), +})); jest.mock('@aws-sdk/client-dynamodb', () => ({ DynamoDBClient: jest.fn(() => ({})) })); jest.mock('@aws-sdk/lib-dynamodb', () => ({ DynamoDBDocumentClient: { from: jest.fn(() => ({ send: mockDdbSend })) }, @@ -108,6 +114,8 @@ beforeEach(() => { jest.clearAllMocks(); ulidCounter = 0; mockLoadRepoConfig.mockResolvedValue(null); + mockAcquireTaskSlot.mockReset().mockResolvedValue(true); + mockReleaseTaskSlot.mockReset().mockResolvedValue(true); }); describe('loadTask', () => { @@ -124,22 +132,16 @@ describe('loadTask', () => { }); describe('admissionControl', () => { - test('returns true when concurrency slot is available', async () => { - mockDdbSend.mockResolvedValueOnce({}); - const result = await admissionControl(baseTask as any); - expect(result).toBe(true); + test('reserves using the task identity and configured user limit', async () => { + expect(await admissionControl(baseTask as any)).toBe(true); + expect(mockAcquireTaskSlot).toHaveBeenCalledWith('TASK001', 'user-123', 3); }); - - test('returns false when concurrency limit reached', async () => { - const condErr = new Error('Conditional check failed'); - condErr.name = 'ConditionalCheckFailedException'; - mockDdbSend.mockRejectedValueOnce(condErr); - const result = await admissionControl(baseTask as any); - expect(result).toBe(false); + test('returns false when no reservation was acquired', async () => { + mockAcquireTaskSlot.mockResolvedValue(false); + expect(await admissionControl(baseTask as any)).toBe(false); }); - - test('throws on unexpected DDB errors', async () => { - mockDdbSend.mockRejectedValueOnce(new Error('DynamoDB error')); + test('propagates an outage so durable execution can retry', async () => { + mockAcquireTaskSlot.mockRejectedValue(new Error('DynamoDB error')); await expect(admissionControl(baseTask as any)).rejects.toThrow('DynamoDB error'); }); }); @@ -1312,9 +1314,6 @@ describe('finalizeTask', () => { compute_metadata: { microvmId: 'vm', endpoint: 'https://vm.example' }, }); - const concurrencyDecrements = () => mockDdbSend.mock.calls.filter(([command]) => - String(command.input?.UpdateExpression ?? '').includes('active_count = active_count - :one')); - test.each(['AWAITING_APPROVAL', 'RUNNING', 'HYDRATING'])('supervisor failure strongly reads %s and conditionally fails only its worker', async status => { mockDdbSend.mockResolvedValueOnce({ Item: { ...vmTask(), status } }).mockResolvedValue({}); await finalizeTask('TASK001', { @@ -1330,7 +1329,7 @@ describe('finalizeTask', () => { ':microvmId': 'vm', ':attr_error_message': 'MicroVM supervisor: substrate-read-failed', }); - expect(concurrencyDecrements()).toHaveLength(1); + expect(mockReleaseTaskSlot).toHaveBeenCalledWith('TASK001', 'user-123'); }); test('supervisor finalization preserves a committed cancellation', async () => { @@ -1349,7 +1348,7 @@ describe('finalizeTask', () => { attempts: 3, microvmSupervisor: supervisor, microvmFailureReason: 'substrate-read-failed', }, 'user-123')).resolves.toBe(false); expect(mockDdbSend).toHaveBeenCalledTimes(1); - expect(concurrencyDecrements()).toHaveLength(0); + expect(mockReleaseTaskSlot).not.toHaveBeenCalled(); }); test.each([['RUNNING', 'TIMED_OUT'], ['AWAITING_APPROVAL', 'FAILED'], ['HYDRATING', 'FAILED']])( @@ -1524,34 +1523,33 @@ describe('finalizeTask', () => { expect(eventCall.input.Item.metadata.reason).toBe('session_never_started'); }); - test('releases concurrency for unexpected task state', async () => { + test('an unexpected active state keeps its reservation and is retried', async () => { mockDdbSend .mockResolvedValueOnce({ Item: { ...baseTask, status: 'SUBMITTED' } }) // loadTask - .mockResolvedValue({}); // decrementConcurrency - await finalizeTask('TASK001', { attempts: 5, lastStatus: 'SUBMITTED' }, 'user-123'); - // Should still call decrementConcurrency (UpdateCommand for user concurrency) - const lastCall = mockDdbSend.mock.calls[mockDdbSend.mock.calls.length - 1][0]; - expect(lastCall.input.Key).toEqual({ user_id: 'user-123' }); + .mockResolvedValue({}); + await expect(finalizeTask('TASK001', { attempts: 5, lastStatus: 'SUBMITTED' }, 'user-123')) + .rejects.toThrow('Cannot finalize task TASK001 in SUBMITTED'); + // Release is still attempted, but the marker keeps an active task's seat. + expect(mockReleaseTaskSlot).toHaveBeenCalledWith('TASK001', 'user-123'); }); - test('resolves without throwing when decrementConcurrency hits ConditionalCheckFailedException', async () => { - const condErr = new Error('Conditional check failed'); - condErr.name = 'ConditionalCheckFailedException'; + test('approval wait past the poll window fails (a valid transition) instead of timing out', async () => { mockDdbSend - .mockResolvedValueOnce({ Item: { ...baseTask, status: 'COMPLETED', memory_written: true } }) // loadTask - .mockResolvedValueOnce({}) // TTL stamp - .mockResolvedValueOnce({}) // emitTaskEvent - .mockRejectedValueOnce(condErr); // decrementConcurrency CCF - await expect(finalizeTask('TASK001', { attempts: 10, lastStatus: 'COMPLETED' }, 'user-123')).resolves.toBe(true); + .mockResolvedValueOnce({ Item: { ...baseTask, status: 'AWAITING_APPROVAL' } }) // loadTask + .mockResolvedValue({}); + await finalizeTask('TASK001', { attempts: 5, lastStatus: 'AWAITING_APPROVAL' }, 'user-123'); + const transition = mockDdbSend.mock.calls.find(([command]) => command.input?.ExpressionAttributeValues?.[':toStatus'])?.[0]; + expect(transition.input.ExpressionAttributeValues[':toStatus']).toBe('FAILED'); + expect(mockReleaseTaskSlot).toHaveBeenCalledWith('TASK001', 'user-123'); }); - test('resolves without throwing when decrementConcurrency hits a non-CCF error', async () => { + test('a release failure propagates so durable execution retries finalization', async () => { mockDdbSend .mockResolvedValueOnce({ Item: { ...baseTask, status: 'COMPLETED', memory_written: true } }) // loadTask - .mockResolvedValueOnce({}) // TTL stamp - .mockResolvedValueOnce({}) // emitTaskEvent - .mockRejectedValueOnce(new Error('DDB timeout')); // decrementConcurrency non-CCF - await expect(finalizeTask('TASK001', { attempts: 10, lastStatus: 'COMPLETED' }, 'user-123')).resolves.toBe(true); + .mockResolvedValue({}); + mockReleaseTaskSlot.mockRejectedValueOnce(new Error('DDB timeout')); + await expect(finalizeTask('TASK001', { attempts: 10, lastStatus: 'COMPLETED' }, 'user-123')) + .rejects.toThrow('DDB timeout'); }); }); @@ -1565,8 +1563,7 @@ describe('failTask', () => { test('releases concurrency when requested', async () => { mockDdbSend.mockResolvedValue({}); await failTask('TASK001', 'HYDRATING', 'hydration error', 'user-123', true); - // transitionTask + emitTaskEvent + decrementConcurrency = 3 calls - expect(mockDdbSend).toHaveBeenCalledTimes(3); + expect(mockReleaseTaskSlot).toHaveBeenCalledWith('TASK001', 'user-123'); }); test('transitions from HYDRATING to FAILED when called with HYDRATING status', async () => { @@ -1578,24 +1575,29 @@ describe('failTask', () => { expect(transitionCall.input.ExpressionAttributeValues[':toStatus']).toBe('FAILED'); }); - test('handles transition failure gracefully without emitting when not transitioned', async () => { - mockDdbSend.mockRejectedValueOnce(new Error('Condition failed')); // transitionTask only + test('a committed terminal winner is accepted without another failure event', async () => { + mockDdbSend.mockRejectedValueOnce(new Error('Condition failed')) + .mockResolvedValueOnce({ Item: { ...baseTask, status: 'CANCELLED' } }); await expect(failTask('TASK001', 'SUBMITTED', 'error', 'user-123', false)).resolves.toBeUndefined(); - expect(mockDdbSend).toHaveBeenCalledTimes(1); + expect(mockDdbSend.mock.calls.some(([command]) => command._type === 'Put')).toBe(false); + }); + + test('failure to persist a terminal state propagates without releasing an active task', async () => { + mockDdbSend.mockRejectedValueOnce(new Error('write unavailable')) + .mockResolvedValueOnce({ Item: { ...baseTask, status: 'HYDRATING' } }); + await expect(failTask('TASK001', 'HYDRATING', 'error', 'user-123', true)).rejects.toThrow('write unavailable'); + expect(mockReleaseTaskSlot).not.toHaveBeenCalled(); }); - test('second failTask does not re-emit or re-decrement when transition fails (idempotent under step retry)', async () => { + test('failure replay rechecks release without duplicating the failure event', async () => { mockDdbSend.mockResolvedValue({}); await failTask('TASK001', 'HYDRATING', 'first failure', 'user-123', true); - expect(mockDdbSend).toHaveBeenCalledTimes(3); // transition + emit + decrement - mockDdbSend.mockClear(); - const condErr = new Error('The conditional request failed'); - condErr.name = 'ConditionalCheckFailedException'; - mockDdbSend.mockRejectedValueOnce(condErr); // already FAILED — transition no-ops - - await expect(failTask('TASK001', 'HYDRATING', 'durable replay', 'user-123', true)).resolves.toBeUndefined(); - expect(mockDdbSend).toHaveBeenCalledTimes(1); // transition attempt only; no Put, no concurrency Update + mockDdbSend.mockRejectedValueOnce(new Error('already FAILED')) + .mockResolvedValueOnce({ Item: { ...baseTask, status: 'FAILED' } }); + await expect(failTask('TASK001', 'HYDRATING', 'replay', 'user-123', true)).resolves.toBeUndefined(); + expect(mockDdbSend.mock.calls.some(([command]) => command._type === 'Put')).toBe(false); + expect(mockReleaseTaskSlot).toHaveBeenCalledTimes(2); }); }); @@ -1844,9 +1846,8 @@ describe('finalizeTask — memory fallback', () => { // Should not throw — the try-catch in finalizeTask prevents crash await finalizeTask('TASK001', { attempts: 10, lastStatus: 'COMPLETED' }, 'user-123'); expect(mockWriteMinimalEpisode).toHaveBeenCalled(); - // decrementConcurrency should still be called (last UpdateCommand for user concurrency) - const lastCall = mockDdbSend.mock.calls[mockDdbSend.mock.calls.length - 1][0]; - expect(lastCall.input.Key).toEqual({ user_id: 'user-123' }); + // The reservation is still released after the fail-open memory write. + expect(mockReleaseTaskSlot).toHaveBeenCalledWith('TASK001', 'user-123'); }); test('converts string duration_s and cost_usd to numbers', async () => { diff --git a/cdk/test/handlers/reconcile-admission-queue.test.ts b/cdk/test/handlers/reconcile-admission-queue.test.ts index 6d3983fe3..38f4894de 100644 --- a/cdk/test/handlers/reconcile-admission-queue.test.ts +++ b/cdk/test/handlers/reconcile-admission-queue.test.ts @@ -279,7 +279,7 @@ describe('reconcile-admission-queue — races and failures', () => { expect(updates[0].input.ConditionExpression).toBe('#s = :queued'); expect(updates[0].input.ExpressionAttributeValues[':submitted']).toEqual({ S: 'SUBMITTED' }); // Restore: guarded on SUBMITTED, sets QUEUED with a fresh QUEUED# status key. - expect(updates[1].input.ConditionExpression).toBe('#s = :submitted'); + expect(updates[1].input.ConditionExpression).toBe('#s = :submitted AND attribute_not_exists(concurrency_slot)'); expect(updates[1].input.ExpressionAttributeValues[':queued']).toEqual({ S: 'QUEUED' }); expect(updates[1].input.ExpressionAttributeValues[':sca'].S).toMatch(/^QUEUED#/); }); diff --git a/cdk/test/handlers/reconcile-concurrency.test.ts b/cdk/test/handlers/reconcile-concurrency.test.ts index d93e1bf9d..ae58dc687 100644 --- a/cdk/test/handlers/reconcile-concurrency.test.ts +++ b/cdk/test/handlers/reconcile-concurrency.test.ts @@ -17,214 +17,127 @@ * SOFTWARE. */ -// --- Mocks --- -const mockDdbSend = jest.fn(); -jest.mock('@aws-sdk/client-dynamodb', () => ({ - DynamoDBClient: jest.fn(() => ({ send: mockDdbSend })), - ScanCommand: jest.fn((input: unknown) => ({ _type: 'Scan', input })), - QueryCommand: jest.fn((input: unknown) => ({ _type: 'Query', input })), - UpdateItemCommand: jest.fn((input: unknown) => ({ _type: 'UpdateItem', input })), +const mockSend = jest.fn(); +const mockRelease = jest.fn(); +jest.mock('@aws-sdk/lib-dynamodb', () => ({ + ScanCommand: jest.fn((input: unknown) => ({ kind: 'scan', input })), + UpdateCommand: jest.fn((input: unknown) => ({ kind: 'update', input })), +})); +jest.mock('../../src/handlers/shared/ua', () => ({ makeDocClient: () => ({ send: mockSend }) })); +jest.mock('../../src/handlers/shared/task-concurrency', () => ({ + releaseTaskSlot: (...args: unknown[]) => mockRelease(...args), })); - -// Set env vars before importing process.env.TASK_TABLE_NAME = 'Tasks'; -process.env.USER_CONCURRENCY_TABLE_NAME = 'UserConcurrency'; - +process.env.USER_CONCURRENCY_TABLE_NAME = 'Counters'; import { handler } from '../../src/handlers/reconcile-concurrency'; +function held(id: string, user = 'user', status = 'RUNNING') { + return { task_id: id, user_id: user, status, concurrency_slot: { state: 'held' } }; +} +function seed(counters: object[], tasks: object[]) { + mockSend.mockResolvedValueOnce({ Items: counters }).mockResolvedValueOnce({ Items: tasks }).mockResolvedValue({}); +} +function updates() { + return mockSend.mock.calls.filter(([command]) => command.kind === 'update').map(([command]) => command.input); +} beforeEach(() => { - jest.clearAllMocks(); + mockSend.mockReset(); + mockRelease.mockReset().mockResolvedValue(true); }); -describe('reconcile-concurrency handler', () => { - test('completes without errors when no users exist', async () => { - mockDdbSend.mockResolvedValueOnce({ Items: [], LastEvaluatedKey: undefined }); - await handler(); - expect(mockDdbSend).toHaveBeenCalledTimes(1); - }); - - test('no update when stored count matches actual count', async () => { - // Scan returns one user with active_count=2 - mockDdbSend - .mockResolvedValueOnce({ - Items: [{ user_id: { S: 'user-1' }, active_count: { N: '2' } }], - LastEvaluatedKey: undefined, - }) - // Query returns count=2 (matching) - .mockResolvedValueOnce({ Count: 2, LastEvaluatedKey: undefined }); - - await handler(); - - // 1 scan + 1 query = 2 calls, no UpdateItemCommand - expect(mockDdbSend).toHaveBeenCalledTimes(2); - const calls = mockDdbSend.mock.calls; - const updateCalls = calls.filter((c: any[]) => c[0]._type === 'UpdateItem'); - expect(updateCalls).toHaveLength(0); - }); - - test('fires UpdateItemCommand with ConditionExpression when count drifts', async () => { - // Scan returns one user with active_count=5 - mockDdbSend - .mockResolvedValueOnce({ - Items: [{ user_id: { S: 'user-1' }, active_count: { N: '5' } }], - LastEvaluatedKey: undefined, - }) - // Query returns actual count=2 (drift) - .mockResolvedValueOnce({ Count: 2, LastEvaluatedKey: undefined }) - // Update succeeds - .mockResolvedValueOnce({}); - - await handler(); - - // 1 scan + 1 query + 1 update = 3 calls - expect(mockDdbSend).toHaveBeenCalledTimes(3); - const updateCall = mockDdbSend.mock.calls[2][0]; - expect(updateCall._type).toBe('UpdateItem'); - // Verify ConditionExpression for TOCTOU protection - expect(updateCall.input.ConditionExpression).toBe('active_count = :stored'); - expect(updateCall.input.ExpressionAttributeValues[':stored']).toEqual({ N: '5' }); - expect(updateCall.input.ExpressionAttributeValues[':count']).toEqual({ N: '2' }); - }); - - test('continues to next user on ConditionalCheckFailedException', async () => { - const condErr = new Error('Conditional check failed'); - condErr.name = 'ConditionalCheckFailedException'; - - mockDdbSend - // Scan returns two users - .mockResolvedValueOnce({ - Items: [ - { user_id: { S: 'user-1' }, active_count: { N: '5' } }, - { user_id: { S: 'user-2' }, active_count: { N: '3' } }, - ], - LastEvaluatedKey: undefined, - }) - // User-1: query returns 2 (drift) - .mockResolvedValueOnce({ Count: 2, LastEvaluatedKey: undefined }) - // User-1: update fails with CCF - .mockRejectedValueOnce(condErr) - // User-2: query returns 1 (drift) - .mockResolvedValueOnce({ Count: 1, LastEvaluatedKey: undefined }) - // User-2: update succeeds - .mockResolvedValueOnce({}); - - await handler(); - - // 1 scan + 2 queries + 2 updates = 5 calls - expect(mockDdbSend).toHaveBeenCalledTimes(5); - }); - - test('continues to next user when query fails', async () => { - mockDdbSend - // Scan returns two users - .mockResolvedValueOnce({ - Items: [ - { user_id: { S: 'user-1' }, active_count: { N: '2' } }, - { user_id: { S: 'user-2' }, active_count: { N: '3' } }, - ], - LastEvaluatedKey: undefined, - }) - // User-1: query throws - .mockRejectedValueOnce(new Error('DynamoDB timeout')) - // User-2: query returns 3 (matches) - .mockResolvedValueOnce({ Count: 3, LastEvaluatedKey: undefined }); - - await handler(); - - // 1 scan + 2 queries (one failed) = 3 calls - expect(mockDdbSend).toHaveBeenCalledTimes(3); - }); +test('empty tables complete without writes', async () => { + seed([], []); + await handler(); + expect(updates()).toEqual([]); + expect(mockRelease).not.toHaveBeenCalled(); +}); - test('handles scan pagination', async () => { - mockDdbSend - // First scan page - .mockResolvedValueOnce({ - Items: [{ user_id: { S: 'user-1' }, active_count: { N: '1' } }], - LastEvaluatedKey: { user_id: { S: 'user-1' } }, - }) - // User-1 query - .mockResolvedValueOnce({ Count: 1, LastEvaluatedKey: undefined }) - // Second scan page - .mockResolvedValueOnce({ - Items: [{ user_id: { S: 'user-2' }, active_count: { N: '2' } }], - LastEvaluatedKey: undefined, - }) - // User-2 query - .mockResolvedValueOnce({ Count: 2, LastEvaluatedKey: undefined }); +test('approval waits count as held seats and a matching counter needs no repair', async () => { + seed([{ user_id: 'user', active_count: 2, reservation_version: 'v1' }], + [held('one'), held('two', 'user', 'AWAITING_APPROVAL')]); + await handler(); + expect(updates()).toEqual([]); + expect(mockRelease).not.toHaveBeenCalled(); +}); - await handler(); +test('repairs drift only while the observed count and reservation revision still match', async () => { + seed([{ user_id: 'user', active_count: 5, reservation_version: 'v1' }], [held('one'), held('two')]); + await handler(); + expect(updates()).toEqual([expect.objectContaining({ + Key: { user_id: 'user' }, + ConditionExpression: 'attribute_exists(user_id) AND active_count = :stored AND reservation_version = :observed', + ExpressionAttributeValues: expect.objectContaining({ ':count': 2, ':stored': 5, ':observed': 'v1' }), + })]); +}); - // 2 scans + 2 queries = 4 calls - expect(mockDdbSend).toHaveBeenCalledTimes(4); +test('missing counters are recreated only if no reservation writer has created them meanwhile', async () => { + seed([], [held('one')]); + await handler(); + expect(updates()[0]).toMatchObject({ + ConditionExpression: 'attribute_not_exists(user_id)', + ExpressionAttributeValues: { ':count': 1 }, }); +}); - test('handles query pagination for countActiveTasks', async () => { - mockDdbSend - // Scan - .mockResolvedValueOnce({ - Items: [{ user_id: { S: 'user-1' }, active_count: { N: '0' } }], - LastEvaluatedKey: undefined, - }) - // First query page: count=3, has more - .mockResolvedValueOnce({ - Count: 3, - LastEvaluatedKey: { user_id: { S: 'user-1' }, task_id: { S: 'T3' } }, - }) - // Second query page: count=2, done - .mockResolvedValueOnce({ Count: 2, LastEvaluatedKey: undefined }) - // Update (drift: stored=0 vs actual=5) - .mockResolvedValueOnce({}); - - await handler(); +test('legacy counter repair checks that a version has not been installed concurrently', async () => { + seed([{ user_id: 'user', active_count: 4 }], [held('one')]); + await handler(); + expect(updates()[0].ConditionExpression).toContain('attribute_not_exists(reservation_version)'); +}); - // 1 scan + 2 queries + 1 update = 4 calls - expect(mockDdbSend).toHaveBeenCalledTimes(4); - const updateCall = mockDdbSend.mock.calls[3][0]; - expect(updateCall._type).toBe('UpdateItem'); - expect(updateCall.input.ExpressionAttributeValues[':count']).toEqual({ N: '5' }); - }); +test('ambiguous legacy active tasks prevent guessing a count', async () => { + seed([{ user_id: 'user', active_count: 5 }], [{ task_id: 'legacy', user_id: 'user', status: 'AWAITING_APPROVAL' }]); + await handler(); + expect(updates()).toEqual([]); +}); - test('skips items without user_id', async () => { - mockDdbSend.mockResolvedValueOnce({ - Items: [{ active_count: { N: '1' } }], // no user_id - LastEvaluatedKey: undefined, - }); +test('queued and unadmitted terminal tasks do not inflate the count', async () => { + seed([{ user_id: 'user', active_count: 3 }], [ + { task_id: 'queued', user_id: 'user', status: 'QUEUED' }, + { task_id: 'failed', user_id: 'user', status: 'FAILED' }, + ]); + await handler(); + expect(updates()[0].ExpressionAttributeValues[':count']).toBe(0); +}); - await handler(); +test('counts terminal held markers before asking shared cleanup to release them', async () => { + seed([{ user_id: 'user', active_count: 0, reservation_version: 'v1' }], [held('done', 'user', 'FAILED'), held('live')]); + await handler(); + expect(updates()[0].ExpressionAttributeValues[':count']).toBe(2); + expect(mockRelease).toHaveBeenCalledWith('done', 'user'); + expect(mockSend.mock.invocationCallOrder.at(-1)!).toBeLessThan(mockRelease.mock.invocationCallOrder[0]); +}); - // Only the scan call, no query or update - expect(mockDdbSend).toHaveBeenCalledTimes(1); - }); +test('a changed revision skips stale repair and still tries terminal cleanup', async () => { + seed([{ user_id: 'user', active_count: 3, reservation_version: 'v1' }], [held('done', 'user', 'FAILED')]); + mockSend.mockRejectedValueOnce(Object.assign(new Error('changed'), { name: 'ConditionalCheckFailedException' })); + await handler(); + expect(updates()).toHaveLength(1); + expect(mockRelease).toHaveBeenCalledWith('done', 'user'); +}); - test('continues to next user when UpdateItemCommand fails with non-CCF error', async () => { - mockDdbSend - // Scan returns two users with drift - .mockResolvedValueOnce({ - Items: [ - { user_id: { S: 'user-1' }, active_count: { N: '5' } }, - { user_id: { S: 'user-2' }, active_count: { N: '4' } }, - ], - LastEvaluatedKey: undefined, - }) - // User-1: query returns 2 (drift) - .mockResolvedValueOnce({ Count: 2, LastEvaluatedKey: undefined }) - // User-1: update fails with non-CCF error - .mockRejectedValueOnce(new Error('InternalServerError')) - // User-2: query returns 1 (drift) - .mockResolvedValueOnce({ Count: 1, LastEvaluatedKey: undefined }) - // User-2: update succeeds - .mockResolvedValueOnce({}); +test('one user repair failure does not stop the next user', async () => { + seed([{ user_id: 'one', active_count: 3 }, { user_id: 'two', active_count: 3 }], []); + mockSend.mockRejectedValueOnce(new Error('unavailable')); + await handler(); + expect(updates().map(update => update.Key.user_id)).toEqual(['one', 'two']); +}); - await handler(); +test('scans every counter page before strongly scanning every task page', async () => { + mockSend.mockResolvedValueOnce({ Items: [{ user_id: 'user', active_count: 2 }], LastEvaluatedKey: { user_id: 'user' } }) + .mockResolvedValueOnce({ Items: [] }) + .mockResolvedValueOnce({ Items: [held('one')], LastEvaluatedKey: { task_id: 'one' } }) + .mockResolvedValueOnce({ Items: [held('two')] }); + await handler(); + expect(mockSend.mock.calls.map(([command]) => [command.input.TableName, command.input.ConsistentRead])) + .toEqual([['Counters', true], ['Counters', true], ['Tasks', true], ['Tasks', true]]); + expect(mockSend.mock.calls[3][0].input.ExclusiveStartKey).toEqual({ task_id: 'one' }); +}); - // 1 scan + 2 queries + 2 updates = 5 calls - expect(mockDdbSend).toHaveBeenCalledTimes(5); - // Verify user-2's update was still attempted and succeeded - const updateCalls = mockDdbSend.mock.calls.filter((c: any[]) => c[0]._type === 'UpdateItem'); - expect(updateCalls).toHaveLength(2); - // User-2's update should have the correct values - const user2Update = updateCalls[1][0]; - expect(user2Update.input.Key).toEqual({ user_id: { S: 'user-2' } }); - expect(user2Update.input.ExpressionAttributeValues[':count']).toEqual({ N: '1' }); - }); +test('an incomplete task scan aborts before any partial count is installed', async () => { + mockSend.mockResolvedValueOnce({ Items: [{ user_id: 'user', active_count: 2 }] }) + .mockResolvedValueOnce({ Items: [held('one')], LastEvaluatedKey: { task_id: 'one' } }) + .mockRejectedValueOnce(new Error('scan unavailable')); + await expect(handler()).rejects.toThrow('scan unavailable'); + expect(updates()).toEqual([]); }); diff --git a/cdk/test/handlers/reconcile-stranded-tasks.test.ts b/cdk/test/handlers/reconcile-stranded-tasks.test.ts index 8f2477388..bee5b250b 100644 --- a/cdk/test/handlers/reconcile-stranded-tasks.test.ts +++ b/cdk/test/handlers/reconcile-stranded-tasks.test.ts @@ -19,6 +19,11 @@ // --- Mocks --- const mockDdbSend = jest.fn(); +const mockRelease = jest.fn(); +jest.mock('../../src/handlers/shared/task-concurrency', () => ({ + releaseTaskSlot: (...args: unknown[]) => mockRelease(...args), +})); +beforeEach(() => mockRelease.mockReset().mockResolvedValue(true)); jest.mock('@aws-sdk/client-dynamodb', () => ({ DynamoDBClient: jest.fn(() => ({ send: mockDdbSend })), QueryCommand: jest.fn((input: unknown) => ({ _type: 'Query', input })), @@ -89,7 +94,7 @@ describe('reconcile-stranded-tasks', () => { expect(mockDdbSend).toHaveBeenCalledTimes(3); }); - test('task older than 1200s → fails + emits events + decrements concurrency', async () => { + test('task older than 1200s → fails + emits events + releases its reservation', async () => { const ancient = new Date(Date.now() - 25 * 60 * 1000).toISOString(); // 25 min ago primeResponses([ // Query SUBMITTED returns one stranded candidate. @@ -103,7 +108,6 @@ describe('reconcile-stranded-tasks', () => { {}, // conditional UpdateItem → FAILED {}, // PutItem task_stranded event {}, // PutItem task_failed event - {}, // UpdateItem decrement concurrency { Items: [] }, // Query HYDRATING { Items: [] }, // Query AWAITING_APPROVAL ]); @@ -138,10 +142,12 @@ describe('reconcile-stranded-tasks', () => { // The task row expires with its events. expect(input.ExpressionAttributeValues[':ttl'].N).toBe((putCalls[0][0].input as { Item: { ttl: { N: string } } }).Item.ttl.N); - // Concurrency decrement. - const decrementCall = (mockDdbSend.mock.calls as [{ _type: string; input: Record }][]) - .find(([c]) => c._type === 'UpdateItem' && String(c.input.UpdateExpression).includes('active_count')); - expect(decrementCall).toBeDefined(); + // The task-owned reservation is released through the marker-guarded path, + // never by decrementing the shared counter directly. + expect(mockRelease).toHaveBeenCalledTimes(1); + const directDecrement = (mockDdbSend.mock.calls as [{ _type: string; input: Record }][]) + .find(([c]) => String(c.input.UpdateExpression ?? '').includes('active_count')); + expect(directDecrement).toBeUndefined(); }); test('#441: task with old created_at but FRESH status_created_at is NOT failed (freshly picked up from the queue)', async () => { @@ -168,8 +174,9 @@ describe('reconcile-stranded-tasks', () => { await handler(); // Only the 3 status queries — the fresh task is filtered in-code, so - // NO transition / event / decrement writes fire. + // NO transition / event / release writes fire. expect(mockDdbSend).toHaveBeenCalledTimes(3); + expect(mockRelease).not.toHaveBeenCalled(); }); test('#441: task with old created_at AND old status_created_at is still failed (genuinely stranded)', async () => { @@ -186,7 +193,6 @@ describe('reconcile-stranded-tasks', () => { {}, // conditional UpdateItem → FAILED {}, // PutItem task_stranded event {}, // PutItem task_failed event - {}, // UpdateItem decrement concurrency { Items: [] }, // HYDRATING { Items: [] }, // AWAITING_APPROVAL ]); @@ -221,7 +227,6 @@ describe('reconcile-stranded-tasks', () => { {}, // conditional UpdateItem → FAILED {}, // PutItem task_stranded event {}, // PutItem task_failed event - {}, // UpdateItem decrement concurrency { Items: [] }, // HYDRATING { Items: [] }, // AWAITING_APPROVAL ]); @@ -280,7 +285,6 @@ describe('reconcile-stranded-tasks', () => { {}, // PutItem task_stranded event {}, // PutItem task_failed event {}, // PutItem approval_stranded milestone (Chunk 10 new) - {}, // UpdateItem decrement concurrency ]); await handler(); @@ -433,7 +437,7 @@ describe('reconcile-stranded-tasks', () => { }); test('test_logs_WARN_with_RECONCILER_PARTIAL_FAILURE_when_some_tasks_fail', async () => { - // One success (4 writes), one failure (throws on UpdateItem). + // One success (3 writes), one failure (throws on UpdateItem). const ancient = new Date(Date.now() - 25 * 60 * 1000).toISOString(); const ddbErr = Object.assign(new Error('DDB throttled'), { name: 'ProvisionedThroughputExceededException' }); primeResponses([ @@ -447,7 +451,6 @@ describe('reconcile-stranded-tasks', () => { {}, // UpdateItem t-ok (transition) → success {}, // PutItem task_stranded event {}, // PutItem task_failed event - {}, // UpdateItem decrement concurrency ddbErr, // UpdateItem t-fail (transition) → throws { Items: [] }, // HYDRATING query { Items: [] }, // AWAITING_APPROVAL query @@ -473,8 +476,8 @@ describe('reconcile-stranded-tasks', () => { mockTaskRow({ task_id: 't-2', user_id: 'u-b', created_at: ancient }), ], }, - {}, {}, {}, {}, // t-1: transition + 2 events + decrement - {}, {}, {}, {}, // t-2: transition + 2 events + decrement + {}, {}, {}, // t-1: transition + 2 events + {}, {}, {}, // t-2: transition + 2 events { Items: [] }, // HYDRATING { Items: [] }, // AWAITING_APPROVAL ]); diff --git a/cdk/test/handlers/shared/orchestrator.test.ts b/cdk/test/handlers/shared/orchestrator.test.ts index cf5ce1fe5..17a34b1aa 100644 --- a/cdk/test/handlers/shared/orchestrator.test.ts +++ b/cdk/test/handlers/shared/orchestrator.test.ts @@ -33,6 +33,12 @@ jest.mock('@aws-sdk/client-s3', () => ({ S3Client: jest.fn(() => ({ send: jest.f const mockLogger = { info: jest.fn(), warn: jest.fn(), error: jest.fn(), child: jest.fn() }; jest.mock('../../../src/handlers/shared/logger', () => ({ logger: mockLogger })); +const mockReleaseTaskSlot = jest.fn().mockResolvedValue(undefined); +jest.mock('../../../src/handlers/shared/task-concurrency', () => ({ + acquireTaskSlot: jest.fn(), + releaseTaskSlot: (...args: unknown[]) => mockReleaseTaskSlot(...args), +})); + process.env.TASK_TABLE_NAME = 'Tasks'; process.env.TASK_EVENTS_TABLE_NAME = 'TaskEvents'; process.env.USER_CONCURRENCY_TABLE_NAME = 'Concurrency'; @@ -74,10 +80,9 @@ function primeReread(status: string): void { }, } : {})); } -/** Finalization returns the user's concurrency slot through the counter table. */ -function concurrencyDecrements() { - return commandsOfType('Update').filter(command => - String(command.input.UpdateExpression).includes('active_count = active_count - :one')); +/** Finalization returns the task's reservation through releaseTaskSlot (exactly once, #1003). */ +function slotReleases(): unknown[][] { + return mockReleaseTaskSlot.mock.calls; } function finish(substrate: SessionStatus, polledStatus = TaskStatus.RUNNING) { return finalizeTask('TASK001', { @@ -218,12 +223,12 @@ describe('MicroVM terminal finalization', () => { primeReread(status); await finish({ status: 'completed' }); expect(commandsOfType('Get')[0].input.ConsistentRead).toBe(true); - // Terminal TTL stamp plus the concurrency decrement; no status transition. - expect(commandsOfType('Update')).toHaveLength(2); + // Terminal TTL stamp only (the reservation goes back through releaseTaskSlot); no status transition. + expect(commandsOfType('Update')).toHaveLength(1); expect(commandsOfType('Update').some(command => String(command.input.ConditionExpression ?? '').includes(':fromStatus'))).toBe(false); expect((commandsOfType('Put')[0].input.Item as Record).event_type).toBe(`task_${status.toLowerCase()}`); - expect(concurrencyDecrements()).toHaveLength(1); + expect(slotReleases()).toHaveLength(1); }, ); @@ -237,7 +242,6 @@ describe('MicroVM terminal finalization', () => { 'MICROVM_SUBSTRATE_TERMINATED: MicroVM substrate terminated before the agent wrote a terminal status: host fault (hypervisor evicted the guest)', ); expect(classifyError(String(values[':attr_error_message']))?.retryable).toBe(true); - expect(concurrencyDecrements()).toHaveLength(1); - expect(concurrencyDecrements()[0].input.Key).toEqual({ user_id: 'user-1' }); + expect(slotReleases()).toEqual([['TASK001', 'user-1']]); }); }); diff --git a/cdk/test/handlers/shared/task-concurrency-local.test.ts b/cdk/test/handlers/shared/task-concurrency-local.test.ts new file mode 100644 index 000000000..e669fca56 --- /dev/null +++ b/cdk/test/handlers/shared/task-concurrency-local.test.ts @@ -0,0 +1,320 @@ +/** + * MIT No Attribution + * + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +/** + * Opt-in real DynamoDB Local tests: + * ABCA_DDB_LOCAL_ENDPOINT=http://127.0.0.1: mise run testf -- task-concurrency-local + * The endpoint is restricted to loopback and every client uses dummy credentials. + */ +import { randomUUID } from 'node:crypto'; +import { CreateTableCommand, DeleteTableCommand, DynamoDBClient } from '@aws-sdk/client-dynamodb'; +import { DeleteCommand, DynamoDBDocumentClient, GetCommand, PutCommand, ScanCommand, UpdateCommand } from '@aws-sdk/lib-dynamodb'; + +const endpoint = process.env.ABCA_DDB_LOCAL_ENDPOINT; +if (endpoint && (new URL(endpoint).hostname !== '127.0.0.1' || new URL(endpoint).protocol !== 'http:')) { + throw new Error('Capacity integration tests require an http://127.0.0.1 DynamoDB Local endpoint'); +} +const mockBeforeSend = jest.fn(); +const mockAfterSend = jest.fn(); +const mockClients: DynamoDBDocumentClient[] = []; +jest.mock('../../../src/handlers/shared/ua', () => { + const actual = jest.requireActual('../../../src/handlers/shared/ua'); + return { + ...actual, + makeDocClient: () => { + const client = actual.makeDocClient({ + endpoint: process.env.ABCA_DDB_LOCAL_ENDPOINT ?? 'http://127.0.0.1:1', + region: 'us-east-1', + credentials: { accessKeyId: 'local', secretAccessKey: 'local' }, + }); + const send = client.send.bind(client); + client.send = async (command: unknown) => { + await mockBeforeSend(command); + const result = await send(command); + await mockAfterSend(command, result); + return result; + }; + mockClients.push(client); + return client; + }, + }; +}); + +const suffix = randomUUID(); +const tasks = `capacity-tasks-${suffix}`; +const counters = `capacity-counters-${suffix}`; +const events = `capacity-events-${suffix}`; +Object.assign(process.env, { + TASK_TABLE_NAME: tasks, + USER_CONCURRENCY_TABLE_NAME: counters, + TASK_EVENTS_TABLE_NAME: events, + MEMORY_ID: '', +}); + +import { handler as reconcile } from '../../../src/handlers/reconcile-concurrency'; +import { failTask, finalizeTask } from '../../../src/handlers/shared/orchestrator'; +import { acquireTaskSlot, releaseTaskSlot } from '../../../src/handlers/shared/task-concurrency'; + +const raw = new DynamoDBClient({ + endpoint: endpoint ?? 'http://127.0.0.1:1', + region: 'us-east-1', + credentials: { accessKeyId: 'local', secretAccessKey: 'local' }, +}); +const admin = DynamoDBDocumentClient.from(raw); +const local = endpoint ? describe : describe.skip; +jest.setTimeout(30_000); + +local('task capacity against DynamoDB Local', () => { + beforeAll(async () => { + for (const [name, key] of [[tasks, 'task_id'], [counters, 'user_id'], [events, 'task_id']]) { + await raw.send(new CreateTableCommand({ + TableName: name, + BillingMode: 'PAY_PER_REQUEST', + AttributeDefinitions: [ + { AttributeName: key, AttributeType: 'S' }, + ...(name === events ? [{ AttributeName: 'event_id', AttributeType: 'S' as const }] : []), + ], + KeySchema: [ + { AttributeName: key, KeyType: 'HASH' }, + ...(name === events ? [{ AttributeName: 'event_id', KeyType: 'RANGE' as const }] : []), + ], + })); + } + }); + beforeEach(async () => { + mockBeforeSend.mockReset(); + mockAfterSend.mockReset(); + for (const [name, key] of [[tasks, 'task_id'], [counters, 'user_id'], [events, 'task_id']]) { + const page = await admin.send(new ScanCommand({ TableName: name })); + for (const item of page.Items ?? []) { + await admin.send(new DeleteCommand({ + TableName: name, + Key: { [key]: item[key], ...(name === events && { event_id: item.event_id }) }, + })); + } + } + }); + afterAll(async () => { + for (const name of [tasks, counters, events]) await raw.send(new DeleteTableCommand({ TableName: name })); + for (const client of mockClients) client.destroy(); + raw.destroy(); + }); + + async function seed(id: string, initialStatus = 'SUBMITTED', user = 'user') { + await admin.send(new PutCommand({ + TableName: tasks, + Item: { + task_id: id, user_id: user, status: initialStatus, memory_written: true, + }, + })); + } + async function status(id: string, value: string) { + await admin.send(new UpdateCommand({ + TableName: tasks, + Key: { task_id: id }, + UpdateExpression: 'SET #status = :status', + ExpressionAttributeNames: { '#status': 'status' }, + ExpressionAttributeValues: { ':status': value }, + })); + } + async function task(id: string) { + return (await admin.send(new GetCommand({ + TableName: tasks, Key: { task_id: id }, ConsistentRead: true, + }))).Item!; + } + async function count() { + return (await admin.send(new GetCommand({ + TableName: counters, Key: { user_id: 'user' }, ConsistentRead: true, + }))).Item?.active_count ?? 0; + } + async function twoSeats() { + await seed('one'); + await seed('two'); + await acquireTaskSlot('one', 'user', 3); + await acquireTaskSlot('two', 'user', 3); + } + + test('crash replay of real finalization preserves the other task reservation', async () => { + await twoSeats(); + await status('one', 'COMPLETED'); + await finalizeTask('one', { attempts: 10 }, 'user'); + await finalizeTask('one', { attempts: 10 }, 'user'); + expect(await count()).toBe(1); + expect((await task('one')).concurrency_slot.state).toBe('released'); + expect((await task('two')).concurrency_slot.state).toBe('held'); + }); + + test('simultaneous admission of one task creates exactly one reservation', async () => { + await seed('one'); + const results = await Promise.allSettled(Array.from({ length: 5 }, () => acquireTaskSlot('one', 'user', 3))); + expect(results.some(result => result.status === 'fulfilled' && result.value)).toBe(true); + expect(await acquireTaskSlot('one', 'user', 3)).toBe(true); + expect(await count()).toBe(1); + }); + + test('different tasks cannot exceed the admission cap', async () => { + const ids = ['a', 'b', 'c', 'd']; + for (const id of ids) await seed(id); + await Promise.allSettled(ids.map(id => acquireTaskSlot(id, 'user', 2))); + // Retry any transaction conflicts serially, as durable execution does. + for (const id of ids) await acquireTaskSlot(id, 'user', 2); + expect(await count()).toBe(2); + // Four fixed fixture reads; no input-dependent fan-out. + // eslint-disable-next-line @cdklabs/promiseall-no-unbounded-parallelism + const rows = await Promise.all([task('a'), task('b'), task('c'), task('d')]); + expect(rows.filter(row => row.concurrency_slot?.state === 'held')).toHaveLength(2); + }); + + test.each(['acquire', 'release'])('a lost committed %s response is recovered from the marker', async (operation) => { + await seed('one'); + if (operation === 'release') { + await acquireTaskSlot('one', 'user', 3); + await status('one', 'FAILED'); + } + mockAfterSend.mockImplementationOnce((command) => { + if (command.constructor.name === 'GetCommand') { + mockAfterSend.mockImplementationOnce(() => { throw new Error('transaction response lost'); }); + } + }); + if (operation === 'acquire') await acquireTaskSlot('one', 'user', 3); + else await releaseTaskSlot('one', 'user'); + expect(await count()).toBe(operation === 'acquire' ? 1 : 0); + expect((await task('one')).concurrency_slot.state).toBe(operation === 'acquire' ? 'held' : 'released'); + }); + + test('competing finalizers and direct cleanup only release once', async () => { + await twoSeats(); + await status('one', 'CANCELLED'); + await Promise.allSettled([ + finalizeTask('one', { attempts: 0 }, 'user'), + finalizeTask('one', { attempts: 0 }, 'user'), + releaseTaskSlot('one', 'user'), + ]); + await releaseTaskSlot('one', 'user'); + expect(await count()).toBe(1); + }); + + test('start failure and replay release a held slot once', async () => { + await twoSeats(); + await status('one', 'HYDRATING'); + await failTask('one', 'HYDRATING', 'start failed', 'user', true); + await failTask('one', 'HYDRATING', 'start failed', 'user', true); + expect(await count()).toBe(1); + expect((await task('one')).status).toBe('FAILED'); + }); + + test('approval waits retain capacity through reconciliation', async () => { + await twoSeats(); + await status('one', 'AWAITING_APPROVAL'); + expect(await releaseTaskSlot('one', 'user')).toBe(false); + await reconcile(); + expect(await count()).toBe(2); + }); + + test('queued and unadmitted terminal tasks cannot release another reservation', async () => { + await seed('running'); + await acquireTaskSlot('running', 'user', 3); + await seed('queued', 'QUEUED'); + await seed('cancelled', 'CANCELLED'); + expect(await acquireTaskSlot('queued', 'user', 3)).toBe(false); + await releaseTaskSlot('queued', 'user'); + await releaseTaskSlot('cancelled', 'user'); + expect(await count()).toBe(1); + }); + + test('owner mismatch changes neither the reservation nor counter', async () => { + await seed('one'); + await expect(acquireTaskSlot('one', 'someone-else', 3)).rejects.toThrow('owner'); + expect(await count()).toBe(0); + expect((await task('one')).concurrency_slot).toBeUndefined(); + }); + + test('cancellation between the read and admission transaction wins', async () => { + await seed('one'); + mockBeforeSend.mockImplementation(async (command) => { + if (command.constructor.name === 'TransactWriteCommand') { + mockBeforeSend.mockReset(); + await status('one', 'CANCELLED'); + } + }); + expect(await acquireTaskSlot('one', 'user', 3)).toBe(false); + expect(await count()).toBe(0); + }); + + test('an empty counter release preserves an admission that races into the empty-counter branch', async () => { + await seed('one'); + await acquireTaskSlot('one', 'user', 3); + await status('one', 'FAILED'); + await admin.send(new DeleteCommand({ TableName: counters, Key: { user_id: 'user' } })); + await seed('two'); + mockBeforeSend.mockImplementation(async (command) => { + if (command.constructor.name === 'TransactWriteCommand' + && command.input.TransactItems[1].Update.UpdateExpression.includes('if_not_exists')) { + mockBeforeSend.mockReset(); + await acquireTaskSlot('two', 'user', 3); + } + }); + await releaseTaskSlot('one', 'user'); + expect(await count()).toBe(1); + expect((await task('one')).concurrency_slot.state).toBe('released'); + expect((await task('two')).concurrency_slot.state).toBe('held'); + }); + + test('periodic cleanup recovers a crash between terminal status and release', async () => { + await twoSeats(); + await status('one', 'TIMED_OUT'); + await reconcile(); + await finalizeTask('one', { attempts: 10 }, 'user'); + expect(await count()).toBe(1); + }); + + test('an ambiguous legacy active task prevents guessing a replacement count', async () => { + await twoSeats(); + await seed('legacy', 'AWAITING_APPROVAL'); + await reconcile(); + expect(await count()).toBe(2); + expect((await task('legacy')).concurrency_slot).toBeUndefined(); + }); + + test('a revision change blocks stale repair even when the counter returns to its original number', async () => { + await seed('one'); + await acquireTaskSlot('one', 'user', 3); + await admin.send(new UpdateCommand({ + TableName: counters, + Key: { user_id: 'user' }, + UpdateExpression: 'SET active_count = :zero', + ExpressionAttributeValues: { ':zero': 0 }, + })); + mockAfterSend.mockImplementation(async (command) => { + if (command.constructor.name === 'ScanCommand' && command.input.TableName === tasks) { + mockAfterSend.mockReset(); + await seed('two'); + await acquireTaskSlot('two', 'user', 3); + await status('one', 'COMPLETED'); + await releaseTaskSlot('one', 'user'); + } + }); + await reconcile(); + // Admission then release brought the count back to zero, but changed its + // revision. The old scan must not write its answer into this new state. + expect(await count()).toBe(0); + await reconcile(); + expect(await count()).toBe(1); + }); +}); diff --git a/cdk/test/handlers/shared/task-concurrency.test.ts b/cdk/test/handlers/shared/task-concurrency.test.ts new file mode 100644 index 000000000..95b5e9f5a --- /dev/null +++ b/cdk/test/handlers/shared/task-concurrency.test.ts @@ -0,0 +1,205 @@ +/** + * MIT No Attribution + * + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +const mockSend = jest.fn(); +jest.mock('node:timers/promises', () => ({ + setTimeout: jest.fn().mockResolvedValue(undefined), +})); +jest.mock('@aws-sdk/lib-dynamodb', () => ({ + GetCommand: jest.fn((input: unknown) => ({ kind: 'get', input })), + TransactWriteCommand: jest.fn((input: unknown) => ({ kind: 'transaction', input })), +})); +jest.mock('../../../src/handlers/shared/ua', () => ({ + makeDocClient: () => ({ send: mockSend }), +})); +process.env.TASK_TABLE_NAME = 'Tasks'; +process.env.USER_CONCURRENCY_TABLE_NAME = 'Counters'; + +import { setTimeout as delay } from 'node:timers/promises'; +import { acquireTaskSlot, releaseTaskSlot } from '../../../src/handlers/shared/task-concurrency'; + +const base = { task_id: 'task', user_id: 'user', status: 'SUBMITTED' }; +const held = { state: 'held', acquired_at: '2026-09-13T00:00:00Z' }; +function cancelled(index: number) { + return Object.assign(new Error('transaction cancelled'), { + name: 'TransactionCanceledException', + CancellationReasons: [0, 1].map(i => ({ Code: i === index ? 'ConditionalCheckFailed' : 'None' })), + }); +} +beforeEach(() => { + mockSend.mockReset(); + jest.mocked(delay).mockClear(); +}); + +function conflict(codes = ['None', 'TransactionConflict']) { + return Object.assign(new Error('transaction conflict'), { + name: 'TransactionCanceledException', + CancellationReasons: codes.map(Code => ({ Code })), + }); +} + +test.each(['acquire', 'release'])('%s retries counter contention with the identical guarded transaction', async operation => { + mockSend.mockResolvedValueOnce({ + Item: operation === 'acquire' ? base : { ...base, status: 'COMPLETED', concurrency_slot: held }, + }).mockRejectedValueOnce(conflict()).mockRejectedValueOnce(conflict()).mockResolvedValueOnce({}); + const result = operation === 'acquire' + ? await acquireTaskSlot('task', 'user', 10) + : await releaseTaskSlot('task', 'user'); + expect(result).toBe(true); + const transactions = mockSend.mock.calls.filter(([command]) => command.kind === 'transaction'); + expect(transactions).toHaveLength(3); + expect(transactions[1][0]).toBe(transactions[0][0]); + expect(transactions[2][0]).toBe(transactions[0][0]); + expect(delay).toHaveBeenCalledTimes(2); +}); + +test('persistent contention stays bounded and propagates the original error', async () => { + const error = conflict(); + mockSend.mockImplementation(async command => { + if (command.kind === 'get') return { Item: { ...base, status: 'COMPLETED', concurrency_slot: held } }; + throw error; + }); + await expect(releaseTaskSlot('task', 'user')).rejects.toBe(error); + expect(mockSend.mock.calls.filter(([command]) => command.kind === 'transaction')).toHaveLength(5); + expect(delay).toHaveBeenCalledTimes(4); + for (const [index, call] of jest.mocked(delay).mock.calls.entries()) { + expect(call[0]).toBeGreaterThanOrEqual(0); + expect(call[0]).toBeLessThan(50 * 2 ** index); + } +}); + +test('a mixed conflict and capacity condition failure follows normal admission without retrying', async () => { + mockSend.mockResolvedValueOnce({ Item: base }) + .mockRejectedValueOnce(conflict(['TransactionConflict', 'ConditionalCheckFailed'])) + .mockResolvedValueOnce({ Item: base }); + expect(await acquireTaskSlot('task', 'user', 10)).toBe(false); + expect(delay).not.toHaveBeenCalled(); +}); + +test('admission atomically ties a counter increment to an owned SUBMITTED task', async () => { + mockSend.mockResolvedValueOnce({ Item: base }).mockResolvedValueOnce({}); + expect(await acquireTaskSlot('task', 'user', 3)).toBe(true); + const transaction = mockSend.mock.calls[1][0].input; + expect(transaction.TransactItems).toHaveLength(2); + expect(transaction.TransactItems[0].Update).toMatchObject({ + TableName: 'Tasks', + Key: { task_id: 'task' }, + ConditionExpression: 'user_id = :user AND #status = :submitted AND attribute_not_exists(concurrency_slot)', + ExpressionAttributeValues: { ':slot': { state: 'held' }, ':user': 'user', ':submitted': 'SUBMITTED' }, + }); + expect(transaction.TransactItems[1].Update).toMatchObject({ + TableName: 'Counters', + Key: { user_id: 'user' }, + ConditionExpression: 'attribute_not_exists(active_count) OR active_count < :max', + ExpressionAttributeValues: { ':max': 3, ':version': transaction.ClientRequestToken }, + }); +}); + +test.each(['SUBMITTED', 'HYDRATING', 'RUNNING', 'AWAITING_APPROVAL', 'FINALIZING'])( + 'replaying admission in %s reuses the held reservation', async (status) => { + mockSend.mockResolvedValueOnce({ Item: { ...base, status, concurrency_slot: held } }); + expect(await acquireTaskSlot('task', 'user', 3)).toBe(true); + expect(mockSend).toHaveBeenCalledTimes(1); + }, +); + +test('a full counter declines admission without leaving a marker', async () => { + mockSend.mockResolvedValueOnce({ Item: base }).mockRejectedValueOnce(cancelled(1)) + .mockResolvedValueOnce({ Item: base }); + expect(await acquireTaskSlot('task', 'user', 3)).toBe(false); +}); + +test('a transaction outage is not misreported as a full counter', async () => { + mockSend.mockResolvedValueOnce({ Item: base }).mockRejectedValueOnce(new Error('throttled')) + .mockResolvedValueOnce({ Item: base }); + await expect(acquireTaskSlot('task', 'user', 3)).rejects.toThrow('throttled'); +}); + +test('a lost admission response recovers the committed held marker', async () => { + mockSend.mockResolvedValueOnce({ Item: base }).mockRejectedValueOnce(new Error('response lost')) + .mockResolvedValueOnce({ Item: { ...base, concurrency_slot: held } }); + expect(await acquireTaskSlot('task', 'user', 3)).toBe(true); +}); + +test('a cancelled task cannot acquire capacity', async () => { + mockSend.mockResolvedValueOnce({ Item: { ...base, status: 'CANCELLED' } }); + expect(await acquireTaskSlot('task', 'user', 3)).toBe(false); +}); + +test('a released task cannot reacquire even if its status is changed', async () => { + mockSend.mockResolvedValueOnce({ Item: { ...base, concurrency_slot: { ...held, state: 'released' } } }); + expect(await acquireTaskSlot('task', 'user', 3)).toBe(false); +}); + +test('owner mismatch never writes', async () => { + mockSend.mockResolvedValueOnce({ Item: base }); + await expect(acquireTaskSlot('task', 'other', 3)).rejects.toThrow('owner'); + expect(mockSend).toHaveBeenCalledTimes(1); +}); + +test.each(['COMPLETED', 'FAILED', 'CANCELLED', 'TIMED_OUT'])( + '%s releases the marker and count in one guarded transaction', async (status) => { + mockSend.mockResolvedValueOnce({ Item: { ...base, status, concurrency_slot: held } }) + .mockResolvedValueOnce({}); + expect(await releaseTaskSlot('task', 'user')).toBe(true); + const transaction = mockSend.mock.calls[1][0].input; + expect(transaction.TransactItems[0].Update).toMatchObject({ + ConditionExpression: 'user_id = :user AND concurrency_slot.#state = :held AND #status IN (:completed, :failed, :cancelled, :timedOut)', + ExpressionAttributeValues: { ':released': 'released', ':held': 'held' }, + }); + expect(transaction.TransactItems[1].Update).toMatchObject({ + UpdateExpression: 'SET active_count = active_count - :one, updated_at = :now, reservation_version = :version', + ConditionExpression: 'active_count > :zero', + }); + }, +); + +test('an active task retains its slot', async () => { + mockSend.mockResolvedValueOnce({ Item: { ...base, status: 'AWAITING_APPROVAL', concurrency_slot: held } }); + expect(await releaseTaskSlot('task', 'user')).toBe(false); + expect(mockSend).toHaveBeenCalledTimes(1); +}); + +test('unadmitted or legacy terminal tasks do not return another task seat', async () => { + mockSend.mockResolvedValueOnce({ Item: { ...base, status: 'FAILED' } }); + expect(await releaseTaskSlot('task', 'user')).toBe(false); +}); + +test('release recovers a competing commit or lost successful response', async () => { + mockSend.mockResolvedValueOnce({ Item: { ...base, status: 'FAILED', concurrency_slot: held } }) + .mockRejectedValueOnce(new Error('response lost')) + .mockResolvedValueOnce({ Item: { ...base, status: 'FAILED', concurrency_slot: { ...held, state: 'released' } } }); + expect(await releaseTaskSlot('task', 'user')).toBe(false); +}); + +test('an empty counter closes the marker without subtracting from later admissions', async () => { + const row = { Item: { ...base, status: 'FAILED', concurrency_slot: held } }; + mockSend.mockResolvedValueOnce(row).mockRejectedValueOnce(cancelled(1)) + .mockResolvedValueOnce(row).mockResolvedValueOnce({}); + expect(await releaseTaskSlot('task', 'user')).toBe(true); + const update = mockSend.mock.calls[3][0].input.TransactItems[1].Update; + expect(update.UpdateExpression).toBe('SET active_count = if_not_exists(active_count, :zero), updated_at = :now, reservation_version = :version'); + expect(update.ExpressionAttributeValues).not.toHaveProperty(':one'); +}); + +test('a release outage propagates with the held marker intact', async () => { + const row = { Item: { ...base, status: 'FAILED', concurrency_slot: held } }; + mockSend.mockResolvedValueOnce(row).mockRejectedValueOnce(new Error('unavailable')).mockResolvedValueOnce(row); + await expect(releaseTaskSlot('task', 'user')).rejects.toThrow('unavailable'); +}); diff --git a/docs/design/ORCHESTRATOR.md b/docs/design/ORCHESTRATOR.md index 07b3309a4..54041c475 100644 --- a/docs/design/ORCHESTRATOR.md +++ b/docs/design/ORCHESTRATOR.md @@ -353,10 +353,18 @@ Each task runs in its own isolated compute session with no shared mutable state ### Counter management -- **UserConcurrency** - DynamoDB item per user with `active_count`. Incremented atomically (`active_count < max`) at admission, decremented at finalization. +- **UserConcurrency** - DynamoDB item per user with `active_count` and a `reservation_version` that changes on every reservation mutation. +- **Per-task reservation marker** - each admitted task carries `concurrency_slot` (`held` → `released`, with timestamps). The seat is taken and returned only in a DynamoDB transaction that changes the marker and the counter together (`shared/task-concurrency.ts`): + - **Acquire** requires the task to be `SUBMITTED` with no marker and the counter below the cap. A lost successful response is recovered by re-reading the marker, and a task can never acquire twice. + - **Release** requires the marker to be `held` and the task terminal. Every caller (finalization, `failTask`, the stranded-task reconciler, the concurrency reconciler) can therefore attempt it, and exactly one transaction returns the seat. An active task, including one in `AWAITING_APPROVAL`, keeps its seat. + - A task that holds a marker can never be moved back to `QUEUED`. - **SystemConcurrency** - Single DynamoDB item, same pattern. -Concurrency is always released in `finalizeTask` (step 6), never inside the poll loop. ECS poll failure paths call `failTask` with `releaseConcurrency: false` to transition the task to `FAILED` without decrementing — `finalizeTask` handles the single decrement after re-reading the task state. The heartbeat-detected crash path also guards against double-decrement by only releasing the counter after a successful state transition. If the transition fails (task already terminal), it re-reads and acts accordingly. +Finalization releases in a `finally` block after writing the outcome, so a crash, a failed event write or a durable replay still releases exactly once. A finalization that cannot reach a terminal state throws and is retried, and the task keeps its seat. An approval wait that outlives the poll window finalizes to `FAILED` (a valid transition from `AWAITING_APPROVAL`). Previously it attempted the invalid `TIMED_OUT` and freed the seat of a task that was still active. + +**Reconciliation** reads the counters first, then strongly reads every reservation, and repairs a counter only with a condition on the `reservation_version` it observed, so concurrent admissions and releases are never overwritten. It also releases terminal reservations left by interrupted cleanup. A user with an active task that has no marker (admitted before this scheme, or not yet admitted) is skipped until it settles. The reconciler never guesses a count. + +**Upgrading** a stack: tasks admitted by the previous code have no marker, so no release path returns a seat on their behalf, and the reconciler skips their user while they are active. Drain in-flight tasks before deploying, or expect those users' counters to be corrected only after their old tasks finish. ## Implementation diff --git a/docs/src/content/docs/architecture/Orchestrator.md b/docs/src/content/docs/architecture/Orchestrator.md index d25085964..56a17d090 100644 --- a/docs/src/content/docs/architecture/Orchestrator.md +++ b/docs/src/content/docs/architecture/Orchestrator.md @@ -355,10 +355,18 @@ Each task runs in its own isolated compute session with no shared mutable state ### Counter management -- **UserConcurrency** - DynamoDB item per user with `active_count`. Incremented atomically (`active_count < max`) at admission, decremented at finalization. +- **UserConcurrency** - DynamoDB item per user with `active_count` and a `reservation_version` that changes on every reservation mutation. +- **Per-task reservation marker** - each admitted task carries `concurrency_slot` (`held` → `released`, with timestamps). The seat is taken and returned only in a DynamoDB transaction that changes the marker and the counter together (`shared/task-concurrency.ts`): + - **Acquire** requires the task to be `SUBMITTED` with no marker and the counter below the cap. A lost successful response is recovered by re-reading the marker, and a task can never acquire twice. + - **Release** requires the marker to be `held` and the task terminal. Every caller (finalization, `failTask`, the stranded-task reconciler, the concurrency reconciler) can therefore attempt it, and exactly one transaction returns the seat. An active task, including one in `AWAITING_APPROVAL`, keeps its seat. + - A task that holds a marker can never be moved back to `QUEUED`. - **SystemConcurrency** - Single DynamoDB item, same pattern. -Concurrency is always released in `finalizeTask` (step 6), never inside the poll loop. ECS poll failure paths call `failTask` with `releaseConcurrency: false` to transition the task to `FAILED` without decrementing — `finalizeTask` handles the single decrement after re-reading the task state. The heartbeat-detected crash path also guards against double-decrement by only releasing the counter after a successful state transition. If the transition fails (task already terminal), it re-reads and acts accordingly. +Finalization releases in a `finally` block after writing the outcome, so a crash, a failed event write or a durable replay still releases exactly once. A finalization that cannot reach a terminal state throws and is retried, and the task keeps its seat. An approval wait that outlives the poll window finalizes to `FAILED` (a valid transition from `AWAITING_APPROVAL`). Previously it attempted the invalid `TIMED_OUT` and freed the seat of a task that was still active. + +**Reconciliation** reads the counters first, then strongly reads every reservation, and repairs a counter only with a condition on the `reservation_version` it observed, so concurrent admissions and releases are never overwritten. It also releases terminal reservations left by interrupted cleanup. A user with an active task that has no marker (admitted before this scheme, or not yet admitted) is skipped until it settles. The reconciler never guesses a count. + +**Upgrading** a stack: tasks admitted by the previous code have no marker, so no release path returns a seat on their behalf, and the reconciler skips their user while they are active. Drain in-flight tasks before deploying, or expect those users' counters to be corrected only after their old tasks finish. ## Implementation From 07c917f36ea33bed203a91b772e48714737ec1f1 Mon Sep 17 00:00:00 2001 From: Sphia Sadek Date: Wed, 25 Nov 2026 14:02:02 +0000 Subject: [PATCH 02/19] feat(security): trusted approval writer so workers cannot write approval records (#1000) Workers wrote PENDING approval rows directly with task-scoped session credentials that live alongside the repository's code, so malicious or prompt-injected repo code could write any approval record for its task. - ApprovalRequestService (nested stack): IAM-authenticated API Gateway + request-approval Lambda. POST /tasks/{task_id} accepts only "create" (PENDING request + RUNNING -> AWAITING_APPROVAL, one transaction) and "timeout" (PENDING -> TIMED_OUT, conditioned on the task still awaiting that request). It validates a fixed field set, ownership and deadline_epoch, and sets the row TTL itself. - The session role may invoke only /tasks/${aws:PrincipalTag/task_id}; the approvals table moves to a task-scoped read-only grant (listing it as read/write as well fails synth). - Every backend gets APPROVAL_REQUESTS_API_URL: AgentCore runtime env, ECS task env (reserved key), MicroVM platform config (new required contract key approval_requests_api_url). - Agent: approval_requests.py signs requests (SigV4, no redirects, endpoint validated) and never sends retention; task_state routes create/timeout through it and refuses human statuses; hooks carry deadline_epoch. - ADR-025 records the decision. Also in this change: the orchestrator fixtures carry the required approvalRequestsApiUrl; the approval-requests stack's state-bearing resources are recorded in legacy-state-ids.json; the DynamoDB Local approval suite is opt-in; the MicroVM network-extraction fixture leaves out the vault; the AWAITING_APPROVAL transition keeps status_created_at; the emulator tier follows the trusted writer. Rebased onto main after the Lambda MicroVM approval lifecycle (#904): the hook keeps main's shared approval_deadline_epoch (the writer cross-checks the same created_at + timeout_s), the orchestrator passes both the MicroVM approvals table and APPROVAL_REQUESTS_API_URL, and the MicroVM checkpoint only condition-checks approval rows, which the read-only session role allows. --- agent/src/approval_requests.py | 120 ++++++++++ agent/src/task_state.py | 40 +++- agent/tests/test_approval_requests.py | 140 ++++++++++++ agent/tests/test_server.py | 4 +- agent/tests/test_task_state.py | 4 +- .../test_approval_transactions.py | 11 +- agent/tests_emulator/test_scoped_session.py | 56 ++++- cdk/src/constructs/agent-session-role.ts | 21 ++ .../constructs/approval-request-service.ts | 113 ++++++++++ cdk/src/constructs/ecs-agent-cluster.ts | 9 + cdk/src/constructs/task-orchestrator.ts | 6 + cdk/src/handlers/request-approval.ts | 212 ++++++++++++++++++ cdk/src/handlers/shared/response.ts | 2 + cdk/src/stacks/agent.ts | 17 +- .../constructs/agent-session-role.test.ts | 39 +++- .../approval-request-service.test.ts | 84 +++++++ cdk/test/constructs/task-orchestrator.test.ts | 2 + .../handlers/orchestrate-task-microvm.test.ts | 1 + .../handlers/request-approval-local.test.ts | 174 ++++++++++++++ cdk/test/handlers/request-approval.test.ts | 148 ++++++++++++ .../lambda-microvm-strategy.test.ts | 17 +- .../start-session-composition.test.ts | 1 + cdk/test/stacks/network.test.ts | 6 +- cdk/test/synthesis/legacy-state-ids.json | 10 + contracts/constants.json | 2 + .../ADR-025-trusted-approval-writer.md | 36 +++ .../Adr-025-trusted-approval-writer.md | 38 ++++ 27 files changed, 1287 insertions(+), 26 deletions(-) create mode 100644 agent/src/approval_requests.py create mode 100644 agent/tests/test_approval_requests.py create mode 100644 cdk/src/constructs/approval-request-service.ts create mode 100644 cdk/src/handlers/request-approval.ts create mode 100644 cdk/test/constructs/approval-request-service.test.ts create mode 100644 cdk/test/handlers/request-approval-local.test.ts create mode 100644 cdk/test/handlers/request-approval.test.ts create mode 100644 docs/decisions/ADR-025-trusted-approval-writer.md create mode 100644 docs/src/content/docs/decisions/Adr-025-trusted-approval-writer.md diff --git a/agent/src/approval_requests.py b/agent/src/approval_requests.py new file mode 100644 index 000000000..41f67b14b --- /dev/null +++ b/agent/src/approval_requests.py @@ -0,0 +1,120 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: MIT-0 + +"""IAM-signed requests to the control-plane approval writer.""" + +import json +import os +import re +from http import HTTPStatus +from urllib.parse import urlsplit + +import requests +from botocore.auth import SigV4Auth +from botocore.awsrequest import AWSRequest +from botocore.exceptions import ClientError + +from aws_session import get_session +from ua import sanitize_ua_value, static_user_agent_extra + +API_ENV = "APPROVAL_REQUESTS_API_URL" + + +def configured() -> bool: + available = bool(os.environ.get(API_ENV)) + if not available and os.environ.get("AGENT_SESSION_ROLE_ARN"): + raise RuntimeError( + "APPROVAL_REQUESTS_API_URL is required for cloud approval requests; " + "deploy matching CDK and worker images" + ) + return available + + +def record_request( + operation: str, + task_id: str, + request_id: str, + *, + approval: dict | None = None, + reason: str | None = None, +) -> None: + """Sign the task path with scoped credentials; never follow redirects.""" + endpoint = os.environ.get(API_ENV, "").rstrip("/") + parsed = urlsplit(endpoint) + match = re.fullmatch( + r"[a-z0-9]+\.execute-api\.([a-z0-9-]+)\.amazonaws\.com(?:\.cn)?", parsed.hostname or "" + ) + if ( + parsed.scheme != "https" + or not match + or parsed.username + or parsed.password + or parsed.port not in (None, 443) + or parsed.query + or parsed.fragment + or not re.fullmatch(r"/[A-Za-z0-9_-]+", parsed.path) + or not re.fullmatch(r"[A-Za-z0-9_-]{1,128}", task_id) + or operation not in {"create", "timeout"} + ): + raise ValueError("Invalid approval request endpoint, task id or operation") + payload = {"operation": operation, "task_id": task_id, "request_id": request_id} + if approval is not None: + # Retention is set by the trusted writer, never by the worker. + payload["approval"] = {key: value for key, value in approval.items() if key != "ttl"} + if reason is not None: + payload["reason"] = reason + body = json.dumps(payload, separators=(",", ":")).encode() + user_agent = static_user_agent_extra() + app_id = os.environ.get("AWS_SDK_UA_APP_ID") + if app_id: + user_agent += f" app/{sanitize_ua_value(app_id)}" + url = f"{endpoint}/tasks/{task_id}" + request = AWSRequest( + method="POST", + url=url, + data=body, + headers={"Content-Type": "application/json", "User-Agent": user_agent}, + ) + credentials = get_session().get_credentials() + if credentials is None: + raise RuntimeError("Approval request credentials unavailable") + SigV4Auth(credentials.get_frozen_credentials(), "execute-api", match.group(1)).add_auth(request) + response = requests.post( + url, + data=body, + headers=dict(request.headers), + timeout=(5, 20), + allow_redirects=False, + ) + try: + result = response.json() + except ValueError as exc: + raise RuntimeError( + f"Approval service returned invalid JSON (HTTP {response.status_code})" + ) from exc + data = result.get("data") if isinstance(result, dict) else None + if response.status_code == HTTPStatus.OK and isinstance(data, dict) and data.get("ok") is True: + return + error = result.get("error") if isinstance(result, dict) else None + code = ( + error.get("code", "ApprovalServiceUnavailable") + if isinstance(error, dict) + else "ApprovalServiceUnavailable" + ) + details = error.get("details") if isinstance(error, dict) else None + reasons = details.get("cancellation_reasons", []) if isinstance(details, dict) else [] + message = "Control plane did not acknowledge the approval write" + raise ClientError( + { + "Error": { + "Code": code, + "Message": message, + }, + "CancellationReasons": reasons, + "ResponseMetadata": { + "HTTPStatusCode": response.status_code, + "RequestId": error.get("request_id") if isinstance(error, dict) else None, + }, + }, + "RecordApprovalRequest", + ) diff --git a/agent/src/task_state.py b/agent/src/task_state.py index 589b53f29..c82efff53 100644 --- a/agent/src/task_state.py +++ b/agent/src/task_state.py @@ -7,7 +7,7 @@ import os import time -from typing import TypedDict +from typing import NotRequired, TypedDict from shell import log, log_error_cw @@ -34,6 +34,7 @@ class ApprovalRow(TypedDict): created_at: str timeout_s: int ttl: int + deadline_epoch: NotRequired[int] user_id: str repo: str @@ -654,6 +655,9 @@ def transact_write_approval_request( ) -> None: """Atomically record a pending approval + transition the task to AWAITING_APPROVAL. + The trusted approval service performs the transaction when configured. Direct + DynamoDB is retained only for unscoped local/legacy deployments. + Two items: 1. Put on ``TaskApprovalsTable`` with ``ConditionExpression: attribute_not_exists(request_id)`` — guards against ULID collisions @@ -670,6 +674,23 @@ def transact_write_approval_request( DDB-layer exceptions propagate so the hook's outer try/except can fail-closed with a specific reason. """ + import approval_requests + + if approval_requests.configured(): + try: + approval_requests.record_request( + "create", task_id, request_id, approval=dict(approval_row) + ) + return + except Exception as exc: + if _extract_error_code(exc) == "TransactionCanceledException": + reasons = _extract_cancellation_reasons(exc) + raise ApprovalWriteError( + f"approval write cancelled: reasons={reasons}", cancellation_reasons=reasons + ) from exc + raise + # Compatibility with unscoped legacy/local deployments. configured() rejects + # a missing service URL for cloud workers that use the session role. task_table, approvals_table = _require_tables() ddb = _get_ddb_client(client=client) @@ -806,6 +827,23 @@ def best_effort_update_approval_status( Returns ``True`` on successful write, ``False`` on ``ConditionalCheckFailedException``. All other errors propagate. """ + import approval_requests + + if new_status != "TIMED_OUT": + raise ValueError("Workers may record only non-human timeouts") + if approval_requests.configured(): + try: + approval_requests.record_request("timeout", task_id, request_id, reason=reason) + return True + except Exception as exc: + reasons = _extract_cancellation_reasons(exc) + if _extract_error_code(exc) == "TransactionCanceledException" and ( + reasons + and reasons[0].get("Code") == "ConditionalCheckFailed" + and all(reason.get("Code") == "None" for reason in reasons[1:]) + ): + return False + raise _, approvals_table = _require_tables() ddb = _get_ddb_client(client=client) diff --git a/agent/tests/test_approval_requests.py b/agent/tests/test_approval_requests.py new file mode 100644 index 000000000..9b7e453bb --- /dev/null +++ b/agent/tests/test_approval_requests.py @@ -0,0 +1,140 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: MIT-0 + +import json +from types import SimpleNamespace +from unittest.mock import MagicMock + +import pytest +from botocore.credentials import Credentials +from botocore.exceptions import ClientError + +import approval_requests as broker +import task_state + + +def pending_request() -> task_state.ApprovalRow: + return { + "task_id": "task", + "request_id": "request", + "tool_name": "Bash", + "tool_input_preview": '{"command":"git push"}', + "tool_input_sha256": "a" * 64, + "reason": "Protected operation", + "severity": "high", + "matching_rule_ids": ["protected"], + "status": "PENDING", + "created_at": "2026-09-18T00:00:00Z", + "timeout_s": 0, + "ttl": 1_800_000_000, + "user_id": "owner", + "repo": "owner/repo", + } + + +@pytest.fixture +def transport(monkeypatch): + monkeypatch.setenv(broker.API_ENV, "https://fixture.execute-api.us-east-1.amazonaws.com/v1/") + session = MagicMock() + session.get_credentials.return_value = Credentials( + "testing", "testing-secret", "testing-session" + ) + monkeypatch.setattr(broker, "get_session", lambda: session) + post = MagicMock( + return_value=SimpleNamespace(status_code=200, json=lambda: {"data": {"ok": True}}) + ) + monkeypatch.setattr(broker.requests, "post", post) + return post + + +def test_scoped_signature_binds_the_task_path_and_does_not_redirect(transport): + broker.record_request("create", "task", "request", approval={"status": "PENDING"}) + args, kwargs = transport.call_args + assert args == ("https://fixture.execute-api.us-east-1.amazonaws.com/v1/tasks/task",) + assert "execute-api/aws4_request" in kwargs["headers"]["Authorization"] + assert kwargs["headers"]["X-Amz-Security-Token"] == "testing-session" + assert "md/uksb-wt64nei4u6#agent" in kwargs["headers"]["User-Agent"] + assert kwargs["allow_redirects"] is False + assert json.loads(kwargs["data"])["task_id"] == "task" + + +@pytest.mark.parametrize( + "url", + [ + "http://fixture.execute-api.us-east-1.amazonaws.com/v1", + "https://attacker.example/v1", + "https://fixture.execute-api.us-east-1.amazonaws.com/v1?redirect=elsewhere", + ], +) +def test_rejects_untrusted_endpoints_before_signing(transport, monkeypatch, url): + monkeypatch.setenv(broker.API_ENV, url) + with pytest.raises(ValueError): + broker.record_request("create", "task", "request") + transport.assert_not_called() + + +def test_new_writers_use_service_instead_of_direct_dynamodb(transport, monkeypatch): + direct = MagicMock() + monkeypatch.setattr(task_state, "_get_ddb_client", direct) + task_state.transact_write_approval_request("task", "request", pending_request()) + assert task_state.best_effort_update_approval_status("task", "request", "TIMED_OUT") + assert transport.call_count == 2 + direct.assert_not_called() + + +@pytest.mark.parametrize("operation", ["create", "timeout"]) +def test_cloud_worker_missing_endpoint_reports_configuration_error(monkeypatch, operation): + monkeypatch.delenv(broker.API_ENV, raising=False) + monkeypatch.setenv("AGENT_SESSION_ROLE_ARN", "arn:aws:iam::123456789012:role/session") + direct = MagicMock() + monkeypatch.setattr(task_state, "_get_ddb_client", direct) + with pytest.raises(RuntimeError, match=r"APPROVAL_REQUESTS_API_URL.*matching CDK"): + if operation == "create": + task_state.transact_write_approval_request("task", "request", pending_request()) + else: + task_state.best_effort_update_approval_status("task", "request", "TIMED_OUT") + direct.assert_not_called() + + +@pytest.mark.parametrize("status", ["APPROVED", "DENIED", "PENDING", "CANCELLED"]) +def test_worker_api_cannot_record_a_human_decision(transport, status): + with pytest.raises(ValueError, match="non-human timeouts"): + task_state.best_effort_update_approval_status("task", "request", status) + transport.assert_not_called() + + +def test_uncertain_service_write_does_not_fall_back_to_direct_dynamodb(transport, monkeypatch): + direct = MagicMock() + monkeypatch.setattr(task_state, "_get_ddb_client", direct) + transport.side_effect = TimeoutError("reply lost") + with pytest.raises(TimeoutError): + task_state.transact_write_approval_request("task", "request", pending_request()) + direct.assert_not_called() + + +def test_timeout_race_preserves_human_winner_but_task_check_failure_is_not_benign(transport): + # Item 0 is the approval row (still PENDING?), item 1 the task check. + reasons = [{"Code": "ConditionalCheckFailed"}, {"Code": "None"}] + transport.return_value = SimpleNamespace( + status_code=409, + json=lambda: { + "error": { + "code": "TransactionCanceledException", + "details": {"cancellation_reasons": reasons}, + }, + }, + ) + # A human decision already replaced PENDING: the caller re-reads and honors it. + assert not task_state.best_effort_update_approval_status("task", "request", "TIMED_OUT") + # The task left AWAITING_APPROVAL: never silently treated as "human won". + reasons[:] = [{"Code": "None"}, {"Code": "ConditionalCheckFailed"}] + with pytest.raises(ClientError, match="did not acknowledge") as failure: + task_state.best_effort_update_approval_status("task", "request", "TIMED_OUT") + assert failure.value.response["Error"]["Code"] == "TransactionCanceledException" + + +def test_worker_never_sends_retention(transport): + broker.record_request("create", "task", "request", approval=dict(pending_request())) + sent = json.loads(transport.call_args.kwargs["data"])["approval"] + assert "ttl" not in sent + assert sent["status"] == "PENDING" diff --git a/agent/tests/test_server.py b/agent/tests/test_server.py index 42442b0e0..becaa0c90 100644 --- a/agent/tests/test_server.py +++ b/agent/tests/test_server.py @@ -1921,6 +1921,7 @@ def test_wire_contract_is_exactly_the_documented_key_set(self): "task_table_name": "TASK_TABLE_NAME", "task_events_table_name": "TASK_EVENTS_TABLE_NAME", "task_approvals_table_name": "TASK_APPROVALS_TABLE_NAME", + "approval_requests_api_url": "APPROVAL_REQUESTS_API_URL", "nudges_table_name": "NUDGES_TABLE_NAME", "log_group_name": "LOG_GROUP_NAME", "artifacts_bucket_name": "ARTIFACTS_BUCKET_NAME", @@ -1943,12 +1944,13 @@ def test_wire_contract_is_exactly_the_documented_key_set(self): "linear_workload_identity_name": "LINEAR_WORKLOAD_IDENTITY_NAME", } - def test_required_subset_is_exactly_the_four_run_blocking_keys(self): + def test_required_subset_is_exactly_the_run_blocking_keys(self): assert ( frozenset( { "task_table_name", "task_events_table_name", + "approval_requests_api_url", "github_token_secret_arn", "agent_session_role_arn", } diff --git a/agent/tests/test_task_state.py b/agent/tests/test_task_state.py index 32e70383c..94fc1a1a8 100644 --- a/agent/tests/test_task_state.py +++ b/agent/tests/test_task_state.py @@ -1041,12 +1041,12 @@ def test_reason_optional_attached(self, approval_tables_env): client.update_item.return_value = {} task_state.best_effort_update_approval_status( - "01KTASK", "01KREQ", "DENIED", reason="no prod pushes", client=client + "01KTASK", "01KREQ", "TIMED_OUT", reason="polling failed", client=client ) call = client.update_item.call_args assert "deny_reason = :reason" in call.kwargs["UpdateExpression"] - assert call.kwargs["ExpressionAttributeValues"][":reason"] == {"S": "no prod pushes"} + assert call.kwargs["ExpressionAttributeValues"][":reason"] == {"S": "polling failed"} def test_conditional_check_failed_returns_false(self, approval_tables_env): """IMPL-24 — this is the VM-throttle race signal the hook re-reads on.""" diff --git a/agent/tests_emulator/test_approval_transactions.py b/agent/tests_emulator/test_approval_transactions.py index cb06cd463..49fb38d86 100644 --- a/agent/tests_emulator/test_approval_transactions.py +++ b/agent/tests_emulator/test_approval_transactions.py @@ -113,11 +113,16 @@ def test_timeout_only_wins_while_the_request_is_still_pending( timed_out = task_state.best_effort_update_approval_status( running_task, pending_request, "TIMED_OUT" ) - late_denial = task_state.best_effort_update_approval_status( - running_task, pending_request, "DENIED", reason="too late" + second_timeout = task_state.best_effort_update_approval_status( + running_task, pending_request, "TIMED_OUT" ) + # A human decision is never the worker's to record (#1000). + with pytest.raises(ValueError, match="only non-human timeouts"): + task_state.best_effort_update_approval_status( + running_task, pending_request, "DENIED", reason="too late" + ) - assert (timed_out, late_denial) == (True, False) + assert (timed_out, second_timeout) == (True, False) row = task_state.get_approval_row(running_task, pending_request) assert row is not None assert row["status"] == "TIMED_OUT" diff --git a/agent/tests_emulator/test_scoped_session.py b/agent/tests_emulator/test_scoped_session.py index a5bf1c121..783bf232d 100644 --- a/agent/tests_emulator/test_scoped_session.py +++ b/agent/tests_emulator/test_scoped_session.py @@ -41,6 +41,12 @@ _ASSUMABLE_BY_ACCOUNT = {"AWS": f"arn:aws:iam::{EMULATOR_ACCOUNT_ID}:root"} # AgentSessionRole.DDB_ITEM_ACTIONS (Scan is deliberately absent). +_APPROVALS_READ_ACTIONS = [ + "dynamodb:GetItem", + "dynamodb:BatchGetItem", + "dynamodb:Query", + "dynamodb:ConditionCheckItem", +] _DDB_ITEM_ACTIONS = [ "dynamodb:GetItem", "dynamodb:BatchGetItem", @@ -72,12 +78,22 @@ def _session_role_policy(emulator) -> str: } }, } - for table in ( - emulator.task_table, - emulator.task_events_table, - emulator.task_approvals_table, - ) + for table in (emulator.task_table, emulator.task_events_table) ] + # Approvals are read-only for the session (#1000): workers observe decisions and + # use the rows in condition checks; requests go through the trusted writer. + statements.append( + { + "Effect": "Allow", + "Action": _APPROVALS_READ_ACTIONS, + "Resource": f"{table_arn}/{emulator.task_approvals_table}", + "Condition": { + "ForAllValues:StringEquals": { + "dynamodb:LeadingKeys": ["${aws:PrincipalTag/task_id}"] + } + }, + } + ) statements += [ { "Effect": "Allow", @@ -162,19 +178,39 @@ def test_agent_writes_its_own_events_trace_and_task_record(self, scoped, task_id # The terminal write moves updated_at with the status. assert record["updated_at"] == record["completed_at"] - def test_approval_gate_transaction_spans_both_of_the_tasks_tables(self, scoped, task_id): + def test_a_scoped_worker_cannot_open_a_gate_without_the_trusted_writer(self, scoped, task_id): + # Cloud workers request approvals through the trusted writer (#1000). Without + # its endpoint the request fails closed instead of writing the row itself. scoped.table(scoped.task_table).put_item(Item={"task_id": task_id, "status": "RUNNING"}) request_id = _generate_ulid() - row = approval_row(task_id, request_id) - task_state.transact_write_approval_request(task_id, request_id, row) - task_state.transact_resume_from_approval(task_id, request_id) + with pytest.raises(RuntimeError, match="APPROVAL_REQUESTS_API_URL is required"): + task_state.transact_write_approval_request( + task_id, request_id, approval_row(task_id, request_id) + ) - assert task_state.get_approval_row(task_id, request_id) == row + assert task_state.get_approval_row(task_id, request_id) is None record = task_state.get_task(task_id) assert record is not None assert record["status"] == "RUNNING" + def test_the_session_can_read_but_not_write_its_own_approval_rows(self, scoped, task_id): + request_id = _generate_ulid() + scoped.table(scoped.task_approvals_table).put_item(Item=approval_row(task_id, request_id)) + approvals = tenant_client("dynamodb") + key = {"task_id": {"S": task_id}, "request_id": {"S": request_id}} + + assert approvals.get_item(TableName=scoped.task_approvals_table, Key=key)["Item"] + with pytest.raises(ClientError) as denied: + approvals.update_item( + TableName=scoped.task_approvals_table, + Key=key, + UpdateExpression="SET #s = :s", + ExpressionAttributeNames={"#s": "status"}, + ExpressionAttributeValues={":s": {"S": "APPROVED"}}, + ) + assert denied.value.response["Error"]["Code"] == "AccessDeniedException" + class TestOtherTenantsDataIsOutOfReach: """Tripwire only — see the module docstring for what a denial here means.""" diff --git a/cdk/src/constructs/agent-session-role.ts b/cdk/src/constructs/agent-session-role.ts index 94ed12a0a..741e7be81 100644 --- a/cdk/src/constructs/agent-session-role.ts +++ b/cdk/src/constructs/agent-session-role.ts @@ -54,6 +54,14 @@ export interface AgentSessionRoleProps { */ readonly taskScopedTables: dynamodb.ITable[]; + /** + * Approvals table: READ-ONLY for the session (its own task's rows). Workers + * observe human decisions and use the rows in transaction condition checks, + * but write requests only through the trusted approval writer + * (`ApprovalRequestService`). Must not also appear in `taskScopedTables`. + */ + readonly approvalsTable?: dynamodb.ITable; + /** * Trace-artifacts bucket. The agent writes `traces//...`; * `s3:PutObject` is scoped to the `traces/${aws:PrincipalTag/user_id}/` @@ -170,6 +178,19 @@ export class AgentSessionRole extends Construct { // One statement per table keeps the resource ARNs explicit. The condition // requires the request's partition key (task_id) to equal the session's // task_id tag. ForAllValues is required by DynamoDB for LeadingKeys. + if (props.approvalsTable + && props.taskScopedTables.some((table) => table.tableArn === props.approvalsTable!.tableArn)) { + throw new Error('approvalsTable must not appear in taskScopedTables: workers may only read approval records'); + } + if (props.approvalsTable) { + this.role.addToPolicy(new iam.PolicyStatement({ + actions: ['dynamodb:GetItem', 'dynamodb:BatchGetItem', 'dynamodb:Query', 'dynamodb:ConditionCheckItem'], + resources: [props.approvalsTable.tableArn], + conditions: { + 'ForAllValues:StringEquals': { 'dynamodb:LeadingKeys': ['${aws:PrincipalTag/task_id}'] }, + }, + })); + } for (const table of props.taskScopedTables) { this.role.addToPolicy( new iam.PolicyStatement({ diff --git a/cdk/src/constructs/approval-request-service.ts b/cdk/src/constructs/approval-request-service.ts new file mode 100644 index 000000000..66470c85e --- /dev/null +++ b/cdk/src/constructs/approval-request-service.ts @@ -0,0 +1,113 @@ +/** + * MIT No Attribution + * + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +import * as path from 'node:path'; +import { Duration, NestedStack } from 'aws-cdk-lib'; +import * as apigw from 'aws-cdk-lib/aws-apigateway'; +import type * as dynamodb from 'aws-cdk-lib/aws-dynamodb'; +import * as iam from 'aws-cdk-lib/aws-iam'; +import { Architecture, Runtime } from 'aws-cdk-lib/aws-lambda'; +import { NodejsFunction } from 'aws-cdk-lib/aws-lambda-nodejs'; +import * as logs from 'aws-cdk-lib/aws-logs'; +import { NagSuppressions } from 'cdk-nag'; +import type { Construct } from 'constructs'; + +const REQUEST_TIMEOUT_SECONDS = 15; +/** + * Trusted approval writer. A separate API keeps routes inside this child stack. + * IAM binds a signed POST path to the session's task tag; direct Lambda invoke + * would lose that binding because Lambda does not expose caller session tags. + */ +export class ApprovalRequestService extends NestedStack { + public readonly api: apigw.RestApi; + public readonly fn: NodejsFunction; + + constructor(scope: Construct, id: string, props: { + taskTable: dynamodb.ITable; + approvalsTable: dynamodb.ITable; + }) { + super(scope, id); + this.fn = new NodejsFunction(this, 'RequestFn', { + entry: path.join(__dirname, '..', 'handlers', 'request-approval.ts'), + handler: 'handler', + runtime: Runtime.NODEJS_24_X, + architecture: Architecture.ARM_64, + timeout: Duration.seconds(REQUEST_TIMEOUT_SECONDS), + memorySize: 256, + environment: { + ABCA_COMPONENT: 'approval', + TASK_TABLE_NAME: props.taskTable.tableName, + TASK_APPROVALS_TABLE_NAME: props.approvalsTable.tableName, + }, + }); + this.fn.addToRolePolicy(new iam.PolicyStatement({ + actions: ['dynamodb:GetItem', 'dynamodb:UpdateItem', 'dynamodb:ConditionCheckItem'], + resources: [props.taskTable.tableArn], + })); + this.fn.addToRolePolicy(new iam.PolicyStatement({ + actions: ['dynamodb:PutItem', 'dynamodb:UpdateItem'], + resources: [props.approvalsTable.tableArn], + })); + const accessLogs = new logs.LogGroup(this, 'AccessLogs', { retention: logs.RetentionDays.ONE_MONTH }); + this.api = new apigw.RestApi(this, 'Api', { + description: 'IAM-authenticated worker approval requests; no human decision endpoint.', + // The parent TaskApi configures the regional API Gateway logging role. + cloudWatchRole: false, + deployOptions: { + stageName: 'v1', + accessLogDestination: new apigw.LogGroupLogDestination(accessLogs), + accessLogFormat: apigw.AccessLogFormat.jsonWithStandardFields(), + loggingLevel: apigw.MethodLoggingLevel.INFO, + throttlingRateLimit: 60, + throttlingBurstLimit: 100, + }, + }); + this.api.root.addResource('tasks').addResource('{task_id}').addMethod( + 'POST', new apigw.LambdaIntegration(this.fn, { allowTestInvoke: false }), + { authorizationType: apigw.AuthorizationType.IAM }, + ); + NagSuppressions.addResourceSuppressions(this.fn, [{ + id: 'AwsSolutions-IAM4', reason: 'AWSLambdaBasicExecutionRole provides Lambda runtime logging.', + }], true); + NagSuppressions.addResourceSuppressions(this.api, [ + { id: 'AwsSolutions-APIG2', reason: 'The handler validates request shape and allowed fields. Action descriptions and policy metadata remain worker assertions, not independently verified policy results.' }, + { id: 'AwsSolutions-APIG3', reason: 'Machine-only IAM-signed API; session policy restricts POST to its tagged task path, with stage throttling.' }, + { id: 'AwsSolutions-COG4', reason: 'Workers authenticate with task-scoped AWS credentials, not human Cognito credentials.' }, + ], true); + } + + /** No wildcard task path on production session credentials. */ + /** + * Deploy after the parent API's regional API Gateway logging account, which this + * API reuses instead of creating its own (it is one per Region). + * @param parentApi - the platform's task API. + */ + public reuseApiLogging(parentApi: apigw.RestApi): void { + const account = parentApi.node.tryFindChild('Account'); + if (account) this.node.addDependency(account); + } + + public grantRequests(grantee: iam.IGrantable): void { + grantee.grantPrincipal.addToPrincipalPolicy(new iam.PolicyStatement({ + actions: ['execute-api:Invoke'], + resources: [this.api.arnForExecuteApi('POST', '/tasks/${aws:PrincipalTag/task_id}', 'v1')], + conditions: { Null: { 'aws:PrincipalTag/task_id': 'false' } }, + })); + } +} diff --git a/cdk/src/constructs/ecs-agent-cluster.ts b/cdk/src/constructs/ecs-agent-cluster.ts index 626499214..db5251857 100644 --- a/cdk/src/constructs/ecs-agent-cluster.ts +++ b/cdk/src/constructs/ecs-agent-cluster.ts @@ -112,6 +112,13 @@ export interface EcsAgentClusterProps { */ readonly agentSessionRole?: AgentSessionRole; + /** + * Trusted approval writer base URL (ADR-025). The agent writes approval + * requests through it with its session credentials; required with + * `agentSessionRole`, which no longer writes the approvals table directly. + */ + readonly approvalRequestsApiUrl?: string; + /** * AgentCore Memory for cross-task learning. When provided, the ECS task role * is granted read+write on it so the agent's memory writes (write_task_episode @@ -277,6 +284,7 @@ const RESERVED_BUILD_ENV_KEYS = new Set([ 'ECS_PAYLOAD_BUCKET', 'ARTIFACTS_BUCKET_NAME', 'AGENT_SESSION_ROLE_ARN', + 'APPROVAL_REQUESTS_API_URL', 'CLAUDE_CODE_USE_BEDROCK', 'AWS_REGION', ]); @@ -452,6 +460,7 @@ export class EcsAgentCluster extends Construct { ...(props.agentSessionRole && { AGENT_SESSION_ROLE_ARN: props.agentSessionRole.role.roleArn, }), + ...(props.approvalRequestsApiUrl && { APPROVAL_REQUESTS_API_URL: props.approvalRequestsApiUrl }), // #319 outbound SDK solution attribution — set on the shared base so both // task defs emit `app/uksb-wt64nei4u6#{stack}`. ...(sdkUaAppId ? { AWS_SDK_UA_APP_ID: sdkUaAppId } : {}), diff --git a/cdk/src/constructs/task-orchestrator.ts b/cdk/src/constructs/task-orchestrator.ts index 8e84a4d0a..f0b4f6d2d 100644 --- a/cdk/src/constructs/task-orchestrator.ts +++ b/cdk/src/constructs/task-orchestrator.ts @@ -240,6 +240,11 @@ export interface TaskOrchestratorProps { * fails closed with `approval_write_failed`. */ readonly taskApprovalsTableName: string; + /** + * Trusted approval writer base URL (`APPROVAL_REQUESTS_API_URL`, ADR-025). + * Workers create PENDING requests and record timeouts through it. + */ + readonly approvalRequestsApiUrl: string; /** Nudges table (`NUDGES_TABLE_NAME`) the agent polls for mid-task nudges. */ readonly nudgesTableName: string; /** Application log group (`LOG_GROUP_NAME`) the agent writes progress logs to. */ @@ -526,6 +531,7 @@ export class TaskOrchestrator extends Construct { // backends. NO IAM grant accompanies any of these (see the prop docs). ...(props.agentPlatformConfig && { TASK_APPROVALS_TABLE_NAME: props.microvmConfig?.approvalsTable.tableName ?? props.agentPlatformConfig.taskApprovalsTableName, + APPROVAL_REQUESTS_API_URL: props.agentPlatformConfig.approvalRequestsApiUrl, NUDGES_TABLE_NAME: props.agentPlatformConfig.nudgesTableName, LOG_GROUP_NAME: props.agentPlatformConfig.logGroupName, ARTIFACTS_BUCKET_NAME: props.agentPlatformConfig.artifactsBucketName, diff --git a/cdk/src/handlers/request-approval.ts b/cdk/src/handlers/request-approval.ts new file mode 100644 index 000000000..a5222858e --- /dev/null +++ b/cdk/src/handlers/request-approval.ts @@ -0,0 +1,212 @@ +/** + * MIT No Attribution + * + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +import { GetCommand, TransactWriteCommand } from '@aws-sdk/lib-dynamodb'; +import type { APIGatewayProxyEvent, APIGatewayProxyResult } from 'aws-lambda'; +import constants from '../../../contracts/constants.json'; +import { TaskStatus } from '../constructs/task-status'; +import { logger } from './shared/logger'; +import { errorResponse, successResponse } from './shared/response'; +import { makeDocClient } from './shared/ua'; +import { computeTtlEpoch } from './shared/validation'; + +const ddb = makeDocClient(); +const TASKS = process.env.TASK_TABLE_NAME!; +const APPROVALS = process.env.TASK_APPROVALS_TABLE_NAME!; +const MAX_ID_LENGTH = 128; +const MAX_TEXT_LENGTH = 8192; +/** Matches the agent's CLEANUP_MARGIN_120S past an approval deadline. */ +const APPROVAL_CLEANUP_MARGIN_S = 120; +const DEFAULT_RETENTION_DAYS = 90; +const REQUEST_FIELDS = new Set([ + 'task_id', 'request_id', 'tool_name', 'tool_input_preview', 'tool_input_sha256', + 'reason', 'severity', 'matching_rule_ids', 'status', 'created_at', 'timeout_s', + 'deadline_epoch', 'user_id', 'repo', +]); + +interface RequestInput { + readonly operation: 'create' | 'timeout'; + readonly task_id: string; + readonly request_id: string; + readonly approval?: Record; + readonly reason?: string; +} + +function validShortText(value: unknown): value is string { + return typeof value === 'string' && value.length > 0 && value.length <= MAX_ID_LENGTH; +} + +function validId(value: unknown): value is string { + return validShortText(value) && /^[A-Za-z0-9][A-Za-z0-9_-]*$/.test(value); +} + +/** Never copy decision, notification, retention or arbitrary caller fields. */ +function validateRequest(input: RequestInput, task: Record): Record { + const row = input.approval; + if (!row || Object.keys(row).some(key => !REQUEST_FIELDS.has(key)) + || row.task_id !== input.task_id || row.request_id !== input.request_id + || row.user_id !== task.user_id || row.repo !== (task.repo ?? '') + || row.status !== 'PENDING' + || !validShortText(row.tool_name) || typeof row.tool_input_preview !== 'string' || row.tool_input_preview.length > MAX_TEXT_LENGTH + || typeof row.tool_input_sha256 !== 'string' || !/^[a-f0-9]{64}$/.test(row.tool_input_sha256) + || typeof row.reason !== 'string' || row.reason.length > MAX_TEXT_LENGTH + || !['low', 'medium', 'high'].includes(row.severity as string) + || !Array.isArray(row.matching_rule_ids) || row.matching_rule_ids.length > 500 + || !row.matching_rule_ids.every(validShortText) + || typeof row.created_at !== 'string' || !Number.isFinite(Date.parse(row.created_at)) + || typeof row.timeout_s !== 'number' || !Number.isInteger(row.timeout_s) + || row.timeout_s < 0 || row.timeout_s > constants.approval_timeout_s.max + || (row.timeout_s === 0 ? row.deadline_epoch !== undefined + : row.deadline_epoch !== Math.floor(Date.parse(row.created_at) / 1000) + row.timeout_s)) { + throw new Error('APPROVAL_REQUEST_INVALID'); + } + return { ...row, ttl: approvalRowTtl(row.created_at as string, row.timeout_s as number) }; +} + +/** + * Retention is set here, never by the worker: the gate deadline plus the agent's + * cleanup margin (as the agent computed it before this writer existed), or the + * task retention period for a request without an automatic deadline. + */ +export function approvalRowTtl(createdAt: string, timeoutS: number): number { + const created = Math.floor(Date.parse(createdAt) / 1000); + return timeoutS > 0 + ? created + timeoutS + APPROVAL_CLEANUP_MARGIN_S + : computeTtlEpoch(Number(process.env.TASK_RETENTION_DAYS ?? DEFAULT_RETENTION_DAYS)); +} + +/** + * Worker-callable writer: creates pending requests or records a non-human timeout. + * Human decisions remain exclusively in approve/deny handlers. Workers have no + * direct approvals-table write permission, including whole-row replacement. + */ +export async function recordWorkerRequest(input: RequestInput): Promise> { + if (!input || !validId(input.task_id) || !validId(input.request_id) + || !['create', 'timeout'].includes(input.operation)) { + return { ok: false, code: 'APPROVAL_REQUEST_INVALID' }; + } + try { + const task = (await ddb.send(new GetCommand({ + TableName: TASKS, Key: { task_id: input.task_id }, ConsistentRead: true, + }))).Item; + if (!task || typeof task.user_id !== 'string') return { ok: false, code: 'APPROVAL_TASK_MISSING' }; + if (input.operation === 'create') { + const row = validateRequest(input, task); + await ddb.send(new TransactWriteCommand({ + TransactItems: [{ + Put: { + TableName: APPROVALS, + Item: row, + ConditionExpression: 'attribute_not_exists(request_id)', + }, + }, { + Update: { + TableName: TASKS, + Key: { task_id: input.task_id }, + // status_created_at moves with status, as on every other transition: the + // stranded-approval sweep and `ops stuck-tasks` measure from it. + UpdateExpression: 'SET #status = :awaiting, awaiting_approval_request_id = :request, status_created_at = :sca', + ConditionExpression: '#status = :running AND user_id = :user', + ExpressionAttributeNames: { '#status': 'status' }, + ExpressionAttributeValues: { + ':awaiting': TaskStatus.AWAITING_APPROVAL, + ':running': TaskStatus.RUNNING, + ':request': input.request_id, + ':user': task.user_id, + ':sca': `${TaskStatus.AWAITING_APPROVAL}#${new Date().toISOString()}`, + }, + }, + }], + })); + } else { + // A worker may fail closed after a deadline or polling failure; it cannot + // turn either into human DENIED/APPROVED or replace an existing decision. + if (input.approval !== undefined || (input.reason !== undefined + && (typeof input.reason !== 'string' || input.reason.length > MAX_TEXT_LENGTH))) { + return { ok: false, code: 'APPROVAL_REQUEST_INVALID' }; + } + await ddb.send(new TransactWriteCommand({ + TransactItems: [{ + Update: { + TableName: APPROVALS, + Key: { task_id: input.task_id, request_id: input.request_id }, + UpdateExpression: 'SET #status = :timeout, decided_at = :now' + + (input.reason !== undefined ? ', deny_reason = :reason' : ''), + ConditionExpression: '#status = :pending AND user_id = :user', + ExpressionAttributeNames: { '#status': 'status' }, + ExpressionAttributeValues: { + ':timeout': 'TIMED_OUT', + ':pending': 'PENDING', + ':user': task.user_id, + ':now': new Date().toISOString(), + ...(input.reason !== undefined ? { ':reason': input.reason } : {}), + }, + }, + }, { + ConditionCheck: { + TableName: TASKS, + Key: { task_id: input.task_id }, + ConditionExpression: '#status = :awaiting AND awaiting_approval_request_id = :request AND user_id = :user', + ExpressionAttributeNames: { '#status': 'status' }, + ExpressionAttributeValues: { ':awaiting': TaskStatus.AWAITING_APPROVAL, ':request': input.request_id, ':user': task.user_id }, + }, + }], + })); + } + return { ok: true }; + } catch (error) { + const failure = error as { name?: string; message?: string; CancellationReasons?: { Code?: string }[] }; + if (failure.message === 'APPROVAL_REQUEST_INVALID') return { ok: false, code: failure.message }; + const reasons = failure.CancellationReasons?.map(reason => ({ Code: reason.Code })); + logger.warn('Worker approval request was not recorded', { + task_id: input.task_id, + request_id: input.request_id, + operation: input.operation, + error_type: failure.name, + cancellation_reasons: reasons, + }); + return { ok: false, code: failure.name ?? 'APPROVAL_WRITE_FAILED', cancellation_reasons: reasons }; + } +} + +/** IAM authorizes the signed task path before invoking this Lambda. */ +export async function handler(event: APIGatewayProxyEvent): Promise { + const requestId = event.requestContext?.requestId ?? 'unknown'; + if (!event.requestContext?.identity?.userArn || !validId(event.pathParameters?.task_id)) { + return errorResponse(403, 'APPROVAL_CALLER_UNAUTHENTICATED', 'IAM authentication required', requestId); + } + let input: RequestInput; + try { + input = JSON.parse(event.isBase64Encoded + ? Buffer.from(event.body ?? '', 'base64').toString('utf8') : event.body ?? ''); + } catch { + return errorResponse(400, 'APPROVAL_REQUEST_INVALID', 'Invalid JSON request', requestId); + } + if (!input || input.task_id !== event.pathParameters!.task_id) { + return errorResponse(400, 'APPROVAL_TASK_MISMATCH', 'Task must match the signed path', requestId); + } + const result = await recordWorkerRequest(input); + if (result.ok) return successResponse(200, result, requestId); + const code = String(result.code); + const statusCode = code === 'TransactionCanceledException' ? 409 + : code === 'APPROVAL_TASK_MISSING' ? 404 : code === 'APPROVAL_REQUEST_INVALID' ? 400 : 503; + return errorResponse(statusCode, code, 'Approval write was not acknowledged', requestId, { + cancellation_reasons: result.cancellation_reasons ?? [], + }); +} diff --git a/cdk/src/handlers/shared/response.ts b/cdk/src/handlers/shared/response.ts index 2a2068d81..7771b0638 100644 --- a/cdk/src/handlers/shared/response.ts +++ b/cdk/src/handlers/shared/response.ts @@ -132,6 +132,7 @@ export function errorResponse( code: string, message: string, requestId: string, + details?: Record, ): APIGatewayProxyResult { return { statusCode, @@ -141,6 +142,7 @@ export function errorResponse( code, message, request_id: requestId, + ...(details ? { details } : {}), }, }), }; diff --git a/cdk/src/stacks/agent.ts b/cdk/src/stacks/agent.ts index 276100253..d4e80b237 100644 --- a/cdk/src/stacks/agent.ts +++ b/cdk/src/stacks/agent.ts @@ -37,6 +37,7 @@ import { AgentSessionRole } from '../constructs/agent-session-role'; import { AgentNetwork, AgentVpc } from '../constructs/agent-vpc'; import { ApiKeyTable } from '../constructs/api-key-table'; import { ApprovalMetricsPublisherConsumer } from '../constructs/approval-metrics-publisher-consumer'; +import { ApprovalRequestService } from '../constructs/approval-request-service'; import { AttachmentsBucket } from '../constructs/attachments-bucket'; import { PLATFORM_DEFAULT_AUX_MODEL_ID, @@ -638,6 +639,15 @@ export class AgentStack extends Stack { ] as const).filter((webhookPath): webhookPath is LargeBodyWebhookPath => webhookPath !== false), }); + // Trusted approval writer (ADR-025): workers create PENDING requests and + // record timeouts through this IAM-authenticated API instead of writing + // the approvals table directly. Its own nested stack keeps the API out of + // the root stack's resource budget. + const approvalRequests = new ApprovalRequestService(this, 'ApprovalRequests', { + taskTable: taskTable.table, approvalsTable: taskApprovalsTable.table, + }); + approvalRequests.reuseApiLogging(taskApi.api); + // Agent asset registry API (#246) in its own NestedStack + RestApi so its // ~35 resources don't count against this root stack's 500-resource limit. // It authorizes against the SHARED Cognito user pool, so a caller's JWT works @@ -729,6 +739,7 @@ export class AgentStack extends Stack { // AWAITING_APPROVAL; absent → hook fails closed with // ``approval_write_failed`` (the `ApprovalTablesUnavailable` path). TASK_APPROVALS_TABLE_NAME: taskApprovalsTable.table.tableName, + APPROVAL_REQUESTS_API_URL: approvalRequests.api.url, // Hint for the hook's remaining-maxLifetime calculation (§6.5 // pseudocode line 793). Kept in sync with the AgentCore // lifecycle configuration below so drift is visible. 8 hours. @@ -953,9 +964,10 @@ export class AgentStack extends Stack { taskScopedTables: [ taskTable.table, taskEventsTable.table, - taskApprovalsTable.table, taskNudgesTable.table, ], + // Read-only: requests are written through the trusted approval writer. + approvalsTable: taskApprovalsTable.table, traceArtifactsBucket: traceArtifactsBucket.bucket, attachmentsBucket: attachmentsBucket.bucket, // Session-tagged Bedrock grant for cost attribution — the same @@ -964,6 +976,7 @@ export class AgentStack extends Stack { invokableModels: invokableBedrockModels, }); sessionRoleArnHolder = agentSessionRole.role.roleArn; + approvalRequests.grantRequests(agentSessionRole.role); // X-Ray tracing disabled — requires account-level UpdateTraceSegmentDestination // which needs CloudWatch Logs resource policy propagation. Re-enable via @@ -1262,6 +1275,7 @@ export class AgentStack extends Stack { // construct admits the task role to the trust and injects // AGENT_SESSION_ROLE_ARN into the container. agentSessionRole, + approvalRequestsApiUrl: approvalRequests.api.url, // ADR-019 P1: parity — grants the task role InvokeGateway + injects // ABCA_TOOL_GATEWAY_URL. Undefined unless --context enableToolGateway=true. toolGateway, @@ -1434,6 +1448,7 @@ export class AgentStack extends Stack { // of the resources they identify. agentPlatformConfig: { taskApprovalsTableName: taskApprovalsTable.table.tableName, + approvalRequestsApiUrl: approvalRequests.api.url, nudgesTableName: taskNudgesTable.table.tableName, logGroupName: agentLogGroup.logGroupName, // INTENTIONAL, not a wiring bug: both keys resolve to the SAME bucket diff --git a/cdk/test/constructs/agent-session-role.test.ts b/cdk/test/constructs/agent-session-role.test.ts index c4022350d..566f10340 100644 --- a/cdk/test/constructs/agent-session-role.test.ts +++ b/cdk/test/constructs/agent-session-role.test.ts @@ -55,14 +55,14 @@ function createStack() { taskScopedTables: [ taskTable, taskEventsTable, - taskApprovalsTable, taskNudgesTable, ], + approvalsTable: taskApprovalsTable, traceArtifactsBucket, attachmentsBucket, }); - return { stack, template: Template.fromStack(stack), computeRole, sessionRole }; + return { stack, template: Template.fromStack(stack), computeRole, sessionRole, taskApprovalsTable }; } function findComputeRolePolicy(template: Template) { @@ -108,7 +108,7 @@ describe('AgentSessionRole construct', () => { const actions = Array.isArray(s.Action) ? s.Action : [s.Action]; return actions.some((a: string) => a.startsWith('dynamodb:')); }); - // Four task-scoped tables → four conditioned statements. + // Three read/write task-scoped tables + the read-only approvals table. expect(ddbStatements).toHaveLength(4); for (const s of ddbStatements) { expect(s.Condition).toEqual({ @@ -390,3 +390,36 @@ describe.each([false, true])('session-role IAM audit with concrete environment % } }); }); + +describe('AgentSessionRole approvals table (trusted approval writer, ADR-025)', () => { + test('workers may only read their own approval rows', () => { + const { template, taskApprovalsTable, stack } = createStack(); + const statements = Object.entries(template.findResources('AWS::IAM::Policy')) + .filter(([id]) => id.includes('AgentSessionRole')) + .flatMap(([, policy]) => policy.Properties.PolicyDocument.Statement); + const approvalsArn = stack.resolve(taskApprovalsTable.tableArn); + const onApprovals = statements.filter((s: { Resource: unknown }) => + JSON.stringify(s.Resource) === JSON.stringify(approvalsArn)); + expect(onApprovals).toHaveLength(1); + expect([onApprovals[0].Action].flat().sort()).toEqual([ + 'dynamodb:BatchGetItem', 'dynamodb:ConditionCheckItem', 'dynamodb:GetItem', 'dynamodb:Query', + ]); + expect(onApprovals[0].Condition).toEqual({ + 'ForAllValues:StringEquals': { 'dynamodb:LeadingKeys': ['${aws:PrincipalTag/task_id}'] }, + }); + }); + + test('putting the approvals table back in taskScopedTables fails synth', () => { + const stack = new Stack(new App(), 'GuardStack'); + const table = new dynamodb.Table(stack, 'Approvals', { + partitionKey: { name: 'task_id', type: dynamodb.AttributeType.STRING }, + }); + expect(() => new AgentSessionRole(stack, 'SR', { + assumingRoles: [new iam.Role(stack, 'C', { assumedBy: new iam.ServicePrincipal('ecs-tasks.amazonaws.com') })], + taskScopedTables: [table], + approvalsTable: table, + traceArtifactsBucket: new s3.Bucket(stack, 'T'), + attachmentsBucket: new s3.Bucket(stack, 'A'), + })).toThrow('approvalsTable must not appear in taskScopedTables'); + }); +}); diff --git a/cdk/test/constructs/approval-request-service.test.ts b/cdk/test/constructs/approval-request-service.test.ts new file mode 100644 index 000000000..82dadc1f5 --- /dev/null +++ b/cdk/test/constructs/approval-request-service.test.ts @@ -0,0 +1,84 @@ +/** + * MIT No Attribution + * + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +import { App, Stack } from 'aws-cdk-lib'; +import { Template } from 'aws-cdk-lib/assertions'; +import * as dynamodb from 'aws-cdk-lib/aws-dynamodb'; +import * as iam from 'aws-cdk-lib/aws-iam'; +import { ApprovalRequestService } from '../../src/constructs/approval-request-service'; + +let root: Template; +let child: Template; +beforeAll(() => { + const stack = new Stack(new App(), 'ApprovalFixture', { + env: { account: '123456789012', region: 'us-east-1' }, + }); + const table = (id: string) => new dynamodb.Table(stack, id, { + partitionKey: { name: 'task_id', type: dynamodb.AttributeType.STRING }, + }); + const service = new ApprovalRequestService(stack, 'ApprovalRequests', { + taskTable: table('Tasks'), approvalsTable: table('Approvals'), + }); + const worker = new iam.Role(stack, 'WorkerSession', { + assumedBy: new iam.ServicePrincipal('ecs-tasks.amazonaws.com'), + }); + service.grantRequests(worker); + root = Template.fromStack(stack); + child = Template.fromStack(service); +}); + +test('requires IAM authentication on the only writable endpoint', () => { + child.resourceCountIs('AWS::ApiGateway::Method', 1); + child.hasResourceProperties('AWS::ApiGateway::Method', { + HttpMethod: 'POST', AuthorizationType: 'AWS_IAM', + }); +}); + +test('binds invocation to the session task tag and grants no direct Lambda invocation', () => { + const statements = Object.values(root.findResources('AWS::IAM::Policy')) + .flatMap(policy => policy.Properties.PolicyDocument.Statement); + expect(statements).toHaveLength(1); + expect(statements[0].Action).toBe('execute-api:Invoke'); + expect(JSON.stringify(statements[0].Resource)).toContain('/v1/POST/tasks/${aws:PrincipalTag/task_id}'); + expect(statements[0].Condition).toEqual({ Null: { 'aws:PrincipalTag/task_id': 'false' } }); +}); + +test('keeps the trusted writer and API infrastructure out of the parent resource budget', () => { + root.resourceCountIs('AWS::Lambda::Function', 0); + child.resourceCountIs('AWS::Lambda::Function', 1); + child.resourceCountIs('AWS::DynamoDB::Table', 0); +}); + +test('denies the writer delete, scan and whole-table reach, and exposes no unauthenticated route', () => { + const statements = Object.values(child.findResources('AWS::IAM::Policy')) + .flatMap(policy => policy.Properties.PolicyDocument.Statement); + const actions = statements.flatMap(statement => [statement.Action].flat()); + expect(actions.length).toBeGreaterThan(0); + for (const forbidden of ['dynamodb:DeleteItem', 'dynamodb:BatchWriteItem', 'dynamodb:Scan', 'dynamodb:Query', 'dynamodb:*']) { + expect(actions).not.toContain(forbidden); + } + // Table ARNs only: no index, stream or wildcard resource. + for (const statement of statements) { + expect(JSON.stringify(statement.Resource)).not.toMatch(/\*|\/index\/|\/stream\//); + } + for (const method of Object.values(child.findResources('AWS::ApiGateway::Method'))) { + expect(method.Properties.AuthorizationType).toBe('AWS_IAM'); + expect(method.Properties.ApiKeyRequired).not.toBe(true); + } +}); diff --git a/cdk/test/constructs/task-orchestrator.test.ts b/cdk/test/constructs/task-orchestrator.test.ts index 370365c4b..7edede99e 100644 --- a/cdk/test/constructs/task-orchestrator.test.ts +++ b/cdk/test/constructs/task-orchestrator.test.ts @@ -902,6 +902,7 @@ describe('TaskOrchestrator agentPlatformConfig (ADR-021 P2 platform_config trans ...(withConfig && { agentPlatformConfig: { taskApprovalsTableName: approvalsTable.tableName, + approvalRequestsApiUrl: 'https://api.example.com/v1/approval-requests', nudgesTableName: nudgesTable.tableName, logGroupName: '/aws/abca/application', artifactsBucketName: traceBucket.bucketName, @@ -960,6 +961,7 @@ describe('TaskOrchestrator agentPlatformConfig (ADR-021 P2 platform_config trans githubTokenSecretArn: 'arn:aws:secretsmanager:us-east-1:123456789012:secret:github-token-abc123', agentPlatformConfig: { taskApprovalsTableName: 'approvals', + approvalRequestsApiUrl: 'https://api.example.com/v1/approval-requests', nudgesTableName: 'nudges', logGroupName: '/aws/abca/application', artifactsBucketName: 'artifacts', diff --git a/cdk/test/handlers/orchestrate-task-microvm.test.ts b/cdk/test/handlers/orchestrate-task-microvm.test.ts index cccf05142..0ac2ae685 100644 --- a/cdk/test/handlers/orchestrate-task-microvm.test.ts +++ b/cdk/test/handlers/orchestrate-task-microvm.test.ts @@ -150,6 +150,7 @@ process.env.MICROVM_PAYLOAD_BUCKET = 'test-microvm-payload-bucket'; process.env.TASK_TABLE_NAME = 'Tasks'; process.env.APPROVAL_REQUESTS_API_URL = 'https://approval.execute-api.us-east-1.amazonaws.com/v1'; process.env.TASK_EVENTS_TABLE_NAME = 'TaskEvents'; +process.env.APPROVAL_REQUESTS_API_URL = 'https://fixture.execute-api.us-east-1.amazonaws.com/v1/'; process.env.USER_CONCURRENCY_TABLE_NAME = 'UserConcurrency'; process.env.TASK_RETENTION_DAYS = '90'; diff --git a/cdk/test/handlers/request-approval-local.test.ts b/cdk/test/handlers/request-approval-local.test.ts new file mode 100644 index 000000000..16c44abd1 --- /dev/null +++ b/cdk/test/handlers/request-approval-local.test.ts @@ -0,0 +1,174 @@ +/** + * MIT No Attribution + * + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +/** + * Real transaction conditions; loopback endpoint and dummy credentials only. + * Opt-in: start DynamoDB Local and set ABCA_DDB_LOCAL_ENDPOINT=http://127.0.0.1:8000 to run. + * Without it the suite is skipped; request-approval.test.ts covers the handler with mocks. + */ +import { randomUUID } from 'node:crypto'; +import { CreateTableCommand, DeleteTableCommand, DynamoDBClient } from '@aws-sdk/client-dynamodb'; +import { DynamoDBDocumentClient, GetCommand, PutCommand, TransactWriteCommand, UpdateCommand } from '@aws-sdk/lib-dynamodb'; + +const endpoint = process.env.ABCA_DDB_LOCAL_ENDPOINT; +if (endpoint && (new URL(endpoint).hostname !== '127.0.0.1' || new URL(endpoint).protocol !== 'http:')) { + throw new Error('Approval integration tests require an http://127.0.0.1 endpoint'); +} +const mockBeforeTransaction = jest.fn(); +let mockClient: DynamoDBDocumentClient; +jest.mock('../../src/handlers/shared/ua', () => ({ + makeDocClient: () => ({ + send: async (command: unknown) => { + if (command instanceof TransactWriteCommand) await mockBeforeTransaction(); + return mockClient.send(command as GetCommand); + }, + }), +})); +const suffix = randomUUID(); +const tasks = `approval-tasks-${suffix}`; +const approvals = `approval-requests-${suffix}`; +Object.assign(process.env, { TASK_TABLE_NAME: tasks, TASK_APPROVALS_TABLE_NAME: approvals }); +import { recordWorkerRequest } from '../../src/handlers/request-approval'; + +const raw = new DynamoDBClient({ + endpoint: endpoint ?? 'http://127.0.0.1:1', + region: 'us-east-1', + credentials: { accessKeyId: 'local', secretAccessKey: 'local' }, +}); +mockClient = DynamoDBDocumentClient.from(raw); +const local = endpoint ? describe : describe.skip; +jest.setTimeout(30_000); + +local('Trusted approval writer against DynamoDB Local', () => { + let taskId: string; + const gate = 'gate'; + const row = () => ({ + task_id: taskId, + request_id: gate, + user_id: 'owner', + repo: 'owner/repo', + tool_name: 'Bash', + tool_input_preview: '{"command":"git push"}', + tool_input_sha256: 'a'.repeat(64), + reason: 'Protected operation', + severity: 'high', + matching_rule_ids: ['protected'], + status: 'PENDING', + created_at: new Date().toISOString(), + timeout_s: 0, + }); + const create = () => recordWorkerRequest({ + operation: 'create', task_id: taskId, request_id: gate, approval: row(), + }); + const timeout = () => recordWorkerRequest({ + operation: 'timeout', task_id: taskId, request_id: gate, + }); + const read = async (table: string) => (await mockClient.send(new GetCommand({ + TableName: table, + Key: { task_id: taskId, ...(table === approvals ? { request_id: gate } : {}) }, + ConsistentRead: true, + }))).Item; + const change = async (table: string, field: string, value: string) => + mockClient.send(new UpdateCommand({ + TableName: table, + Key: { task_id: taskId, ...(table === approvals ? { request_id: gate } : {}) }, + UpdateExpression: 'SET #field = :value', + ExpressionAttributeNames: { '#field': field }, + ExpressionAttributeValues: { ':value': value }, + })); + beforeAll(async () => { + for (const table of [tasks, approvals]) { + await raw.send(new CreateTableCommand({ + TableName: table, + BillingMode: 'PAY_PER_REQUEST', + AttributeDefinitions: [{ AttributeName: 'task_id', AttributeType: 'S' }, + ...(table === approvals ? [{ AttributeName: 'request_id', AttributeType: 'S' as const }] : [])], + KeySchema: [{ AttributeName: 'task_id', KeyType: 'HASH' }, + ...(table === approvals ? [{ AttributeName: 'request_id', KeyType: 'RANGE' as const }] : [])], + })); + } + }); + afterAll(async () => { + try { for (const table of [tasks, approvals]) await raw.send(new DeleteTableCommand({ TableName: table })); } finally { raw.destroy(); } + }); + beforeEach(async () => { + taskId = randomUUID(); + mockBeforeTransaction.mockReset(); + await mockClient.send(new PutCommand({ + TableName: tasks, + Item: { + task_id: taskId, status: 'RUNNING', user_id: 'owner', repo: 'owner/repo', compute_type: 'lambda-microvm', + }, + })); + }); + + test('creates a durable pending request and its task pointer atomically', async () => { + expect(await create()).toEqual({ ok: true }); + expect(await read(approvals)).toMatchObject({ status: 'PENDING', timeout_s: 0 }); + // Retention comes from the writer, never the worker (no deadline: task retention). + expect((await read(approvals))?.ttl).toBeGreaterThan(Math.floor(Date.now() / 1000) + 80 * 86400); + expect(await read(tasks)).toMatchObject({ status: 'AWAITING_APPROVAL', awaiting_approval_request_id: gate }); + }); + test.each(['APPROVED', 'DENIED', 'CANCELLED'])('timeout preserves an existing %s decision', async status => { + await create(); + await change(approvals, 'status', status); + const before = await read(approvals); + expect(await timeout()).toMatchObject({ + ok: false, + code: 'TransactionCanceledException', + cancellation_reasons: [{ Code: 'ConditionalCheckFailed' }, { Code: 'None' }], + }); + expect(await read(approvals)).toEqual(before); + }); + test('only pending requests can transition to a non-human timeout', async () => { + await create(); + expect(await timeout()).toEqual({ ok: true }); + expect(await read(approvals)).toMatchObject({ status: 'TIMED_OUT' }); + expect(await read(approvals)).not.toHaveProperty('decision_source'); + }); + test('cancellation between read and write prevents both request and task changes', async () => { + mockBeforeTransaction.mockImplementationOnce(() => change(tasks, 'status', 'CANCELLED')); + expect(await create()).toMatchObject({ ok: false, code: 'TransactionCanceledException' }); + expect(await read(approvals)).toBeUndefined(); + expect(await read(tasks)).toMatchObject({ status: 'CANCELLED' }); + }); + test('timeout after the task left AWAITING_APPROVAL changes nothing', async () => { + await create(); + const before = await read(approvals); + mockBeforeTransaction.mockImplementationOnce(() => change(tasks, 'status', 'CANCELLED')); + const result = await timeout(); + expect(result).toMatchObject({ ok: false, code: 'TransactionCanceledException' }); + expect(result.cancellation_reasons).toEqual([{ Code: 'None' }, { Code: 'ConditionalCheckFailed' }]); + expect(await read(approvals)).toEqual(before); + }); + test('a second request cannot replace the first while the task waits', async () => { + await create(); + const result = await recordWorkerRequest({ + operation: 'create', + task_id: taskId, + request_id: 'replacement', + approval: { ...row(), request_id: 'replacement' }, + }); + expect(result).toMatchObject({ ok: false, code: 'TransactionCanceledException' }); + expect(await read(tasks)).toMatchObject({ awaiting_approval_request_id: gate }); + expect((await mockClient.send(new GetCommand({ + TableName: approvals, Key: { task_id: taskId, request_id: 'replacement' }, + }))).Item).toBeUndefined(); + }); +}); diff --git a/cdk/test/handlers/request-approval.test.ts b/cdk/test/handlers/request-approval.test.ts new file mode 100644 index 000000000..d876c59d7 --- /dev/null +++ b/cdk/test/handlers/request-approval.test.ts @@ -0,0 +1,148 @@ +/** + * MIT No Attribution + * + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +import type { APIGatewayProxyEvent } from 'aws-lambda'; + +const send = jest.fn(); +jest.mock('../../src/handlers/shared/ua', () => ({ makeDocClient: () => ({ send }) })); +import { approvalRowTtl, handler, recordWorkerRequest } from '../../src/handlers/request-approval'; + +const approval = { + task_id: 'task', + request_id: 'gate', + user_id: 'owner', + repo: 'owner/repo', + tool_name: 'Bash', + tool_input_preview: '{"command":"git push"}', + tool_input_sha256: 'a'.repeat(64), + reason: 'Protected operation', + severity: 'high', + matching_rule_ids: ['protected'], + status: 'PENDING', + created_at: '2026-09-18T00:00:00Z', + timeout_s: 0, +}; +const input = { operation: 'create' as const, task_id: 'task', request_id: 'gate', approval }; +let task: Record; +beforeEach(() => { + task = { user_id: 'owner', repo: 'owner/repo', compute_type: 'ecs', status: 'RUNNING' }; + send.mockReset().mockImplementation(async command => + command.constructor.name === 'GetCommand' ? { Item: task } : {}); +}); + +test.each([ + { status: 'APPROVED' }, { status: 'DENIED' }, + { notified_linear_approval_requested: true }, { decision_source: 'forged' }, + { decided_at: 'now' }, { scope: 'all' }, { ttl: 1 }, { user_id: 'other' }, { repo: 'other/repo' }, +])('rejects forged decision/notification fields and ownership: %j', async changes => { + expect(await recordWorkerRequest({ ...input, approval: { ...approval, ...changes } })) + .toMatchObject({ ok: false, code: 'APPROVAL_REQUEST_INVALID' }); + expect(send).toHaveBeenCalledTimes(1); +}); + +test('records only the pending request, guarded by current task ownership and status', async () => { + expect(await recordWorkerRequest(input)).toEqual({ ok: true }); + const items = send.mock.calls[1][0].input.TransactItems; + expect(items[0].Put.Item).toEqual({ ...approval, ttl: approvalRowTtl(approval.created_at, approval.timeout_s) }); + expect(items[0].Put.ConditionExpression).toBe('attribute_not_exists(request_id)'); + expect(items[1].Update.ConditionExpression).toBe('#status = :running AND user_id = :user'); + expect(items[1].Update.ExpressionAttributeValues[':user']).toBe('owner'); + // The stranded-approval sweep measures from the time the task entered AWAITING_APPROVAL. + expect(items[1].Update.UpdateExpression).toContain('status_created_at = :sca'); + expect(items[1].Update.ExpressionAttributeValues[':sca']).toMatch(/^AWAITING_APPROVAL#\d{4}-\d{2}-\d{2}T/); +}); + +test('every backend uses the same two-item transaction (no worker lease on this branch)', async () => { + for (const computeType of ['agentcore', 'ecs', 'lambda-microvm']) { + send.mockClear(); + task.compute_type = computeType; + await recordWorkerRequest(input); + expect(send.mock.calls[1][0].input.TransactItems).toHaveLength(2); + } +}); + +test('retention is set by the writer from the validated deadline, never by the worker', () => { + const created = Date.parse('2026-09-18T00:00:00Z') / 1000; + expect(approvalRowTtl('2026-09-18T00:00:00Z', 300)).toBe(created + 300 + 120); + // No automatic deadline: the task retention period instead. + const noDeadline = approvalRowTtl('2026-09-18T00:00:00Z', 0); + expect(noDeadline).toBeGreaterThan(Math.floor(Date.now() / 1000) + 80 * 86400); +}); + +test('timeout cannot overwrite a human decision or resume the task', async () => { + await recordWorkerRequest({ operation: 'timeout', task_id: 'task', request_id: 'gate' }); + const items = send.mock.calls[1][0].input.TransactItems; + expect(items[0].Update.ExpressionAttributeValues[':timeout']).toBe('TIMED_OUT'); + expect(items[0].Update.ConditionExpression).toBe('#status = :pending AND user_id = :user'); + expect(items[1].ConditionCheck.ConditionExpression).toContain('awaiting_approval_request_id = :request'); + expect(items[1].Update).toBeUndefined(); +}); + +test('preserves cancellation reasons without returning request contents', async () => { + send.mockRejectedValueOnce({ + name: 'TransactionCanceledException', + CancellationReasons: [ + { Code: 'ConditionalCheckFailed', Item: { secret: 'must not return' } }, + ], + }); + expect(await recordWorkerRequest(input)).toEqual({ + ok: false, code: 'TransactionCanceledException', cancellation_reasons: [{ Code: 'ConditionalCheckFailed' }], + }); +}); + +test('requires IAM caller identity and refuses body/path task substitution', async () => { + const event = { + body: JSON.stringify(input), + pathParameters: { task_id: 'other-task' }, + requestContext: { identity: { userArn: 'arn:aws:sts::123456789012:assumed-role/Session/task' } }, + } as unknown as APIGatewayProxyEvent; + expect((await handler(event)).statusCode).toBe(400); + expect(send).not.toHaveBeenCalled(); + expect((await handler({ ...event, requestContext: {} } as APIGatewayProxyEvent)).statusCode).toBe(403); +}); + +test('accepts the signed path for the matching request', async () => { + const result = await handler({ + body: JSON.stringify(input), + pathParameters: { task_id: 'task' }, + requestContext: { identity: { userArn: 'arn:aws:sts::123456789012:assumed-role/Session/task' } }, + } as unknown as APIGatewayProxyEvent); + expect(result.statusCode).toBe(200); + expect(JSON.parse(result.body)).toEqual({ data: { ok: true } }); +}); + +test('reports service failures as unavailable with a request ID, not invalid input', async () => { + send.mockRejectedValueOnce({ name: 'ProvisionedThroughputExceededException' }); + const result = await handler({ + body: JSON.stringify(input), + pathParameters: { task_id: 'task' }, + requestContext: { requestId: 'api-request', identity: { userArn: 'worker' } }, + } as unknown as APIGatewayProxyEvent); + expect(result.statusCode).toBe(503); + expect(JSON.parse(result.body)).toMatchObject({ + error: { code: 'ProvisionedThroughputExceededException', request_id: 'api-request' }, + }); +}); + +test.each(['*', 'task/*', '../task', 'task?x', 'task#lease', 'task\n'])('rejects unsafe task/request/worker identifiers %j before database access', async id => { + for (const key of ['task_id', 'request_id']) { + expect(await recordWorkerRequest({ ...input, [key]: id })).toEqual({ ok: false, code: 'APPROVAL_REQUEST_INVALID' }); + } + expect(send).not.toHaveBeenCalled(); +}); diff --git a/cdk/test/handlers/shared/strategies/lambda-microvm-strategy.test.ts b/cdk/test/handlers/shared/strategies/lambda-microvm-strategy.test.ts index 579f2c92d..42e8b35d8 100644 --- a/cdk/test/handlers/shared/strategies/lambda-microvm-strategy.test.ts +++ b/cdk/test/handlers/shared/strategies/lambda-microvm-strategy.test.ts @@ -57,6 +57,7 @@ delete process.env.MICROVM_INGRESS_CONNECTOR_ARNS; process.env.TASK_TABLE_NAME = TASK_TABLE_NAME; process.env.TASK_EVENTS_TABLE_NAME = TASK_EVENTS_TABLE_NAME; +process.env.APPROVAL_REQUESTS_API_URL = 'https://fixture.execute-api.us-east-1.amazonaws.com/v1/'; process.env.GITHUB_TOKEN_SECRET_ARN = GITHUB_TOKEN_SECRET_ARN; process.env.AGENT_SESSION_ROLE_ARN = AGENT_SESSION_ROLE_ARN; for (const optional of [ @@ -145,6 +146,7 @@ const BLUEPRINT: BlueprintConfig = { compute_type: 'lambda-microvm', runtime_arn const EXPECTED_PLATFORM_CONFIG = { task_table_name: TASK_TABLE_NAME, task_events_table_name: TASK_EVENTS_TABLE_NAME, + approval_requests_api_url: 'https://fixture.execute-api.us-east-1.amazonaws.com/v1/', github_token_secret_arn: GITHUB_TOKEN_SECRET_ARN, agent_session_role_arn: AGENT_SESSION_ROLE_ARN, }; @@ -1339,6 +1341,7 @@ describe('buildMicrovmPlatformConfig — the MicroVM substitute for a deploy-tim TASK_TABLE_NAME: 'tasks', TASK_EVENTS_TABLE_NAME: 'events', TASK_APPROVALS_TABLE_NAME: 'approvals', + APPROVAL_REQUESTS_API_URL: 'https://fixture.execute-api.us-east-1.amazonaws.com/v1/', NUDGES_TABLE_NAME: 'nudges', LOG_GROUP_NAME: '/aws/abca/application', ARTIFACTS_BUCKET_NAME: 'artifacts-bucket', @@ -1375,6 +1378,7 @@ describe('buildMicrovmPlatformConfig — the MicroVM substitute for a deploy-tim 'task_table_name', 'task_events_table_name', 'task_approvals_table_name', + 'approval_requests_api_url', 'nudges_table_name', 'log_group_name', 'artifacts_bucket_name', @@ -1396,17 +1400,18 @@ describe('buildMicrovmPlatformConfig — the MicroVM substitute for a deploy-tim 'linear_vault_enabled', 'linear_workload_identity_name', ]); - expect(MICROVM_PLATFORM_CONFIG_KEYS).toHaveLength(17); + expect(MICROVM_PLATFORM_CONFIG_KEYS).toHaveLength(18); // snake_case on the wire, matching every other key in the /run envelope. for (const key of MICROVM_PLATFORM_CONFIG_KEYS) { expect(key).toMatch(/^[a-z][a-z0-9_]*$/); } }); - test('pins the REQUIRED subset — these four are what a task cannot start without', () => { + test('pins the REQUIRED subset — what a task cannot start without', () => { expect([...MICROVM_PLATFORM_CONFIG_REQUIRED_KEYS]).toEqual([ 'task_table_name', 'task_events_table_name', + 'approval_requests_api_url', 'github_token_secret_arn', 'agent_session_role_arn', ]); @@ -1438,6 +1443,7 @@ describe('buildMicrovmPlatformConfig — the MicroVM substitute for a deploy-tim const config = buildMicrovmPlatformConfig({ TASK_TABLE_NAME: 'tasks', TASK_EVENTS_TABLE_NAME: 'events', + APPROVAL_REQUESTS_API_URL: 'https://fixture.execute-api.us-east-1.amazonaws.com/v1/', GITHUB_TOKEN_SECRET_ARN: 'arn:aws:secretsmanager:us-east-1:123456789012:secret:gh-AbCdEf', AGENT_SESSION_ROLE_ARN: 'arn:aws:iam::123456789012:role/SessionRole', }); @@ -1447,6 +1453,7 @@ describe('buildMicrovmPlatformConfig — the MicroVM substitute for a deploy-tim expect(Object.keys(config)).toEqual([ 'task_table_name', 'task_events_table_name', + 'approval_requests_api_url', 'github_token_secret_arn', 'agent_session_role_arn', ]); @@ -1483,6 +1490,7 @@ describe('buildMicrovmPlatformConfig — the MicroVM substitute for a deploy-tim test.each([ ['TASK_TABLE_NAME', 'task_table_name'], ['TASK_EVENTS_TABLE_NAME', 'task_events_table_name'], + ['APPROVAL_REQUESTS_API_URL', 'approval_requests_api_url'], ['GITHUB_TOKEN_SECRET_ARN', 'github_token_secret_arn'], ['AGENT_SESSION_ROLE_ARN', 'agent_session_role_arn'], ])('throws naming %s when it is missing', (envVar, wireKey) => { @@ -1500,7 +1508,7 @@ describe('buildMicrovmPlatformConfig — the MicroVM substitute for a deploy-tim // One redeploy should fix all of them; reporting one per attempt turns a // misconfiguration into four round-trips. expect(() => buildMicrovmPlatformConfig({})).toThrow( - /task_table_name.*task_events_table_name.*github_token_secret_arn.*agent_session_role_arn/s, + /task_table_name.*task_events_table_name.*approval_requests_api_url.*github_token_secret_arn.*agent_session_role_arn/s, ); }); @@ -1601,6 +1609,7 @@ describe('buildMicrovmPlatformConfig — the MicroVM substitute for a deploy-tim describe('LambdaMicrovmComputeStrategy with the FULL platform_config environment', () => { const OPTIONAL_ENV: Record = { TASK_APPROVALS_TABLE_NAME: 'approvals', + APPROVAL_REQUESTS_API_URL: 'https://fixture.execute-api.us-east-1.amazonaws.com/v1/', NUDGES_TABLE_NAME: 'nudges', LOG_GROUP_NAME: '/aws/abca/application', ARTIFACTS_BUCKET_NAME: 'artifacts-bucket', @@ -1633,7 +1642,7 @@ describe('LambdaMicrovmComputeStrategy with the FULL platform_config environment const expected = { ...EXPECTED_PLATFORM_CONFIG, ...buildMicrovmPlatformConfig() }; const envelope = JSON.parse(mockSend.mock.calls[0][0].input.runHookPayload); expect(envelope.platform_config).toEqual(expected); - expect(Object.keys(envelope.platform_config)).toHaveLength(13); + expect(Object.keys(envelope.platform_config)).toHaveLength(14); expect(JSON.parse(mockS3Send.mock.calls[0][0].input.Body).platform_config).toEqual(expected); }); }); diff --git a/cdk/test/handlers/start-session-composition.test.ts b/cdk/test/handlers/start-session-composition.test.ts index 460c644e5..7e9a2e71d 100644 --- a/cdk/test/handlers/start-session-composition.test.ts +++ b/cdk/test/handlers/start-session-composition.test.ts @@ -84,6 +84,7 @@ jest.mock('ulid', () => ({ ulid: jest.fn(() => `ULID${ulidCounter++}`) })); process.env.TASK_TABLE_NAME = 'Tasks'; process.env.TASK_EVENTS_TABLE_NAME = 'TaskEvents'; +process.env.APPROVAL_REQUESTS_API_URL = 'https://fixture.execute-api.us-east-1.amazonaws.com/v1/'; process.env.USER_CONCURRENCY_TABLE_NAME = 'UserConcurrency'; process.env.RUNTIME_ARN = 'arn:aws:bedrock-agentcore:us-east-1:123456789012:runtime/test'; process.env.MAX_CONCURRENT_TASKS_PER_USER = '3'; diff --git a/cdk/test/stacks/network.test.ts b/cdk/test/stacks/network.test.ts index a4b17daf9..6cf94108d 100644 --- a/cdk/test/stacks/network.test.ts +++ b/cdk/test/stacks/network.test.ts @@ -140,7 +140,11 @@ describe.each(['agentcore', 'ecs', 'lambda-microvm'] as const)('%s network extra 'bedrockGeoRegion': 'global', 'enableToolGateway': true, 'enableAgentRegistry': true, - 'enableLinearIdentityVault': true, + // The vault adds no network resources. The MicroVM profile with every + // other option on sits at the 490-resource root budget on main (#852), + // so the trusted approval writer's nested stack (+1) would push the + // inline baseline over it. Leave the vault out there only. + 'enableLinearIdentityVault': compute !== 'lambda-microvm', 'github:sha': 'fixture-revision', ...(zones ? { [AGENTCORE_AZS_CONTEXT_KEY]: zones } : {}), ...(compute === 'lambda-microvm' ? { diff --git a/cdk/test/synthesis/legacy-state-ids.json b/cdk/test/synthesis/legacy-state-ids.json index 2c00047e1..159713ef3 100644 --- a/cdk/test/synthesis/legacy-state-ids.json +++ b/cdk/test/synthesis/legacy-state-ids.json @@ -29,6 +29,11 @@ "logicalId": "ApprovalMetricsPublisherConsumerApprovalMetricsPublisherLogsCD5D42B2", "type": "AWS::Logs::LogGroup" }, + { + "template": "backgroundagent-dev.template.json", + "logicalId": "ApprovalRequestsNestedStackApprovalRequestsNestedStackResource7951430F", + "type": "AWS::CloudFormation::Stack" + }, { "template": "backgroundagent-dev.template.json", "logicalId": "AttachmentsBucket28B3CCF2", @@ -234,6 +239,11 @@ "logicalId": "WebhookTable610F8307", "type": "AWS::DynamoDB::Table" }, + { + "template": "backgroundagentdevApprovalRequestsCA2748DA.nested.template.json", + "logicalId": "AccessLogs8B620ECA", + "type": "AWS::Logs::LogGroup" + }, { "template": "backgroundagentdevRegistryApiF3ADADE2.nested.template.json", "logicalId": "ApiAccessLogsE9DF007D", diff --git a/contracts/constants.json b/contracts/constants.json index 5ebd494ff..0ff962ad2 100644 --- a/contracts/constants.json +++ b/contracts/constants.json @@ -41,6 +41,7 @@ "task_table_name": "TASK_TABLE_NAME", "task_events_table_name": "TASK_EVENTS_TABLE_NAME", "task_approvals_table_name": "TASK_APPROVALS_TABLE_NAME", + "approval_requests_api_url": "APPROVAL_REQUESTS_API_URL", "nudges_table_name": "NUDGES_TABLE_NAME", "log_group_name": "LOG_GROUP_NAME", "artifacts_bucket_name": "ARTIFACTS_BUCKET_NAME", @@ -59,6 +60,7 @@ "required": [ "task_table_name", "task_events_table_name", + "approval_requests_api_url", "github_token_secret_arn", "agent_session_role_arn" ], diff --git a/docs/decisions/ADR-025-trusted-approval-writer.md b/docs/decisions/ADR-025-trusted-approval-writer.md new file mode 100644 index 000000000..e86953da6 --- /dev/null +++ b/docs/decisions/ADR-025-trusted-approval-writer.md @@ -0,0 +1,36 @@ +# ADR-025: Trusted approval writer + +**Status:** proposed +**Date:** 2026-11-05 + +## Context + +When a Cedar soft-deny gate fires, the agent records a `PENDING` approval row and moves its task to `AWAITING_APPROVAL`. Until now it wrote that row **directly** to the approvals DynamoDB table, using its task-scoped session credentials. The session role granted item-level read **and write** on the table, limited only by a `dynamodb:LeadingKeys` condition on the task's own ID. + +Those credentials live in the same container that runs the repository's code: builds, tests, scripts. Malicious or prompt-injected repository code can therefore use them to write any approval record for its own task. That includes replacing a pending request with an approved one. The defect affects every backend: AgentCore, ECS and Lambda MicroVMs. + +## Decision + +Use a small IAM-authenticated API and Lambda as the **only** worker-facing approval writer. + +- **Interface.** `POST /tasks/{task_id}` accepts exactly two operations: `create` (a `PENDING` request) and `timeout` (close a still-`PENDING` request as `TIMED_OUT`). It cannot record a human approval or denial, a decision source, notification markers, scope, or retention. +- **Binding.** The session role may invoke only `POST /tasks/${aws:PrincipalTag/task_id}`, so a worker can reach only its own task's path. Direct Lambda invocation is not granted, because Lambda does not expose caller session tags. +- **Validation.** The handler accepts only a fixed field set. It requires the row's owner and repository to match the task, and checks that `deadline_epoch` equals `created_at + timeout_s`. The writer itself sets the row's TTL from the validated deadline (plus the agent's 120 s cleanup margin), or from the task retention period when there is no automatic deadline. Workers no longer choose retention. +- **Atomicity.** `create` writes the request and transitions the task `RUNNING → AWAITING_APPROVAL` in one transaction, conditioned on the task's owner and state, and on no existing row with that ID. `timeout` updates only a `PENDING` row owned by the task's user, conditioned on the task still awaiting that request. A human decision that won the race leaves the transaction cancelled, and the worker re-reads and honors it. +- **Session role.** The approvals table leaves the session role's read/write task-scoped tables. The role keeps task-scoped **read-only** access (`GetItem`, `BatchGetItem`, `Query`, `ConditionCheckItem`), which is enough to poll decisions. Listing the table in both places fails synth. +- **Human decisions** remain exclusive to the owner-authenticated approve/deny handlers. +- **Wiring.** Every backend receives the API URL: the AgentCore runtime env, the ECS task env, and the Lambda MicroVM platform config (a required `approval_requests_api_url` contract key). The service is a nested stack, so it does not consume root-stack resource budget. + +## Consequences + +- **Upgrade order.** Images built before this change still write the table directly, and the new IAM policy denies that. Deploy matching infrastructure and images together, with in-flight tasks drained. A worker with a session role but no API URL fails closed at its first gate (`APPROVAL_REQUESTS_API_URL is required`). It does not fall back to direct writes. +- **Availability.** The service adds one signed request per creation and per closure, and becomes an availability dependency. A failure denies permission to proceed; it never becomes consent. +- **Limits of validation.** The service validates record shape and ownership, not the truth of worker-supplied policy descriptions. A preview can be truncated and is not proof of the full tool input. `TIMED_OUT` also covers a worker polling failure, so it is not proof that a human deadline elapsed. +- **Residual trust.** The compute role still chooses session tags when assuming the session role. This API protects the decision-writing boundary. It does not isolate a compromised worker from its ambient compute credentials. +- **Local and legacy paths.** Unscoped local runs with no session role keep the direct-table path for development. + +## References + +- [Issue #1000](https://github.com/aws-samples/sample-autonomous-cloud-coding-agents/issues/1000) +- [Approval trust boundaries](../design/CEDAR_HITL_GATES.md) +- [ADR-021: Lambda MicroVM compute backend](./ADR-021-lambda-microvms-compute-backend.md) diff --git a/docs/src/content/docs/decisions/Adr-025-trusted-approval-writer.md b/docs/src/content/docs/decisions/Adr-025-trusted-approval-writer.md new file mode 100644 index 000000000..690119234 --- /dev/null +++ b/docs/src/content/docs/decisions/Adr-025-trusted-approval-writer.md @@ -0,0 +1,38 @@ +--- +title: "ADR-025: Trusted approval writer" +--- + +**Status:** proposed +**Date:** 2026-11-05 + +## Context + +When a Cedar soft-deny gate fires, the agent records a `PENDING` approval row and moves its task to `AWAITING_APPROVAL`. Until now it wrote that row **directly** to the approvals DynamoDB table, using its task-scoped session credentials. The session role granted item-level read **and write** on the table, limited only by a `dynamodb:LeadingKeys` condition on the task's own ID. + +Those credentials live in the same container that runs the repository's code: builds, tests, scripts. Malicious or prompt-injected repository code can therefore use them to write any approval record for its own task. That includes replacing a pending request with an approved one. The defect affects every backend: AgentCore, ECS and Lambda MicroVMs. + +## Decision + +Use a small IAM-authenticated API and Lambda as the **only** worker-facing approval writer. + +- **Interface.** `POST /tasks/{task_id}` accepts exactly two operations: `create` (a `PENDING` request) and `timeout` (close a still-`PENDING` request as `TIMED_OUT`). It cannot record a human approval or denial, a decision source, notification markers, scope, or retention. +- **Binding.** The session role may invoke only `POST /tasks/${aws:PrincipalTag/task_id}`, so a worker can reach only its own task's path. Direct Lambda invocation is not granted, because Lambda does not expose caller session tags. +- **Validation.** The handler accepts only a fixed field set. It requires the row's owner and repository to match the task, and checks that `deadline_epoch` equals `created_at + timeout_s`. The writer itself sets the row's TTL from the validated deadline (plus the agent's 120 s cleanup margin), or from the task retention period when there is no automatic deadline. Workers no longer choose retention. +- **Atomicity.** `create` writes the request and transitions the task `RUNNING → AWAITING_APPROVAL` in one transaction, conditioned on the task's owner and state, and on no existing row with that ID. `timeout` updates only a `PENDING` row owned by the task's user, conditioned on the task still awaiting that request. A human decision that won the race leaves the transaction cancelled, and the worker re-reads and honors it. +- **Session role.** The approvals table leaves the session role's read/write task-scoped tables. The role keeps task-scoped **read-only** access (`GetItem`, `BatchGetItem`, `Query`, `ConditionCheckItem`), which is enough to poll decisions. Listing the table in both places fails synth. +- **Human decisions** remain exclusive to the owner-authenticated approve/deny handlers. +- **Wiring.** Every backend receives the API URL: the AgentCore runtime env, the ECS task env, and the Lambda MicroVM platform config (a required `approval_requests_api_url` contract key). The service is a nested stack, so it does not consume root-stack resource budget. + +## Consequences + +- **Upgrade order.** Images built before this change still write the table directly, and the new IAM policy denies that. Deploy matching infrastructure and images together, with in-flight tasks drained. A worker with a session role but no API URL fails closed at its first gate (`APPROVAL_REQUESTS_API_URL is required`). It does not fall back to direct writes. +- **Availability.** The service adds one signed request per creation and per closure, and becomes an availability dependency. A failure denies permission to proceed; it never becomes consent. +- **Limits of validation.** The service validates record shape and ownership, not the truth of worker-supplied policy descriptions. A preview can be truncated and is not proof of the full tool input. `TIMED_OUT` also covers a worker polling failure, so it is not proof that a human deadline elapsed. +- **Residual trust.** The compute role still chooses session tags when assuming the session role. This API protects the decision-writing boundary. It does not isolate a compromised worker from its ambient compute credentials. +- **Local and legacy paths.** Unscoped local runs with no session role keep the direct-table path for development. + +## References + +- [Issue #1000](https://github.com/aws-samples/sample-autonomous-cloud-coding-agents/issues/1000) +- [Approval trust boundaries](/sample-autonomous-cloud-coding-agents/architecture/cedar-hitl-gates) +- [ADR-021: Lambda MicroVM compute backend](/sample-autonomous-cloud-coding-agents/decisions/adr-021-lambda-microvms-compute-backend) From 21ebe93d0fbc711286d4e6abc9f20b6d9618cd6e Mon Sep 17 00:00:00 2001 From: Sphia Sadek Date: Wed, 25 Nov 2026 14:16:10 +0000 Subject: [PATCH 03/19] fix(security): payload bootstrap v2 for ECS and Lambda MicroVMs (#1002) Workers no longer read a shared payload bucket or receive deployment identifiers baked into images. - The coordinator publishes an IAM-readable deployment manifest (bootstrap/.json) and a per-task payload, and hands the worker a small launch reference with a short-lived signed one-object URL for its own payload.json. MicroVM sends it as runHookPayload (always under the 4 KB cap); ECS sends it as AGENT_PAYLOAD_REF, consumed by load_ecs_payload() before the pipeline imports. - Worker credentials get GetObject on bootstrap/* only; other object reads and listing are denied, so a task cannot read another task's payload (#700). The coordinator signs reads and deletes payload.json/launch.json at finalize; lifecycle reaps leftovers. - Signed URLs are redacted from MicroVM error messages and logs. - Old unsigned envelopes (inline hook, S3 pointer, AGENT_PAYLOAD, AGENT_PAYLOAD_S3_URI) are rejected: deploy the coordinator and images together with in-flight tasks drained (docs/verification/645-payload-bootstrap.md). - The orchestrator role now overflows its inline policy; its overflow policy gets the same documented cdk-nag suppression as the runtime and Linear webhook roles. Extracted from the #904 working branch onto main's flat MicroVM layout, without start receipts or P3 lifecycle code. Also in this change: every ARN-shaped platform-config field must be listed in the contract's arn_keys (#817 item 3, enforced both ways by the sync check); the new lint, dead-code and typecheck gates pass; dead verification links are dropped. Rebased onto main after the Lambda MicroVM approval lifecycle (#904): - the v2 launch reference is produced in deliverRunHookPayload, after the start receipt is claimed, so a replayed start rewrites the same objects; the v1 inline/S3-pointer envelope and its tests are gone - terminate-failure logs keep main's identity-only fields (no error text, so no signed URL can reach a log) - the MicroVM execution role keeps main's description: the least-privilege bootstrap cannot update a role description - the orchestrator overflow suppression keeps main's scoped appliesTo list - vulture (newer on main) also allowlists the override's `req` parameter - tests follow the nested MicroVM layout, and the stack counts include the trusted approval writer's nested stack and Lambda --- agent/.vulture_allowlist.py | 8 + agent/README.md | 26 +- agent/src/payload_bootstrap.py | 195 ++++ agent/src/server.py | 347 +------ agent/tests/test_payload_bootstrap.py | 302 ++++++ agent/tests/test_server.py | 880 +++--------------- cdk/src/constructs/ecs-agent-cluster.ts | 32 +- cdk/src/constructs/ecs-payload-bucket.ts | 25 +- cdk/src/constructs/lambda-microvm-compute.ts | 20 +- .../payload-bootstrap-permissions.ts | 67 ++ cdk/src/constructs/task-orchestrator.ts | 22 +- cdk/src/handlers/shared/payload-bootstrap.ts | 183 ++++ .../shared/strategies/ecs-strategy.ts | 142 +-- .../strategies/lambda-microvm-strategy.ts | 171 +--- cdk/src/stacks/agent.ts | 10 +- cdk/test/constructs/ecs-agent-cluster.test.ts | 10 +- .../constructs/lambda-microvm-compute.test.ts | 14 +- .../payload-bootstrap-permissions.test.ts | 67 ++ cdk/test/constructs/task-orchestrator.test.ts | 15 +- .../handlers/orchestrate-task-microvm.test.ts | 24 +- .../handlers/shared/payload-bootstrap.test.ts | 160 ++++ .../shared/strategies/ecs-strategy.test.ts | 194 ++-- .../lambda-microvm-strategy.test.ts | 368 ++------ .../start-session-composition.test.ts | 15 +- cdk/test/scripts/check-constants-sync.test.ts | 25 + cdk/test/stacks/agent.test.ts | 19 +- contracts/constants.json | 9 + contracts/constants.md | 35 +- ...ADR-021-lambda-microvms-compute-backend.md | 35 +- docs/design/COMPUTE.md | 2 +- docs/design/SECURITY.md | 5 +- docs/src/content/docs/architecture/Compute.md | 2 +- .../src/content/docs/architecture/Security.md | 5 +- ...Adr-021-lambda-microvms-compute-backend.md | 35 +- docs/verification/645-payload-bootstrap.md | 127 +++ scripts/check-constants-sync.ts | 32 + 36 files changed, 1749 insertions(+), 1879 deletions(-) create mode 100644 agent/src/payload_bootstrap.py create mode 100644 agent/tests/test_payload_bootstrap.py create mode 100644 cdk/src/constructs/payload-bootstrap-permissions.ts create mode 100644 cdk/src/handlers/shared/payload-bootstrap.ts create mode 100644 cdk/test/constructs/payload-bootstrap-permissions.test.ts create mode 100644 cdk/test/handlers/shared/payload-bootstrap.test.ts create mode 100644 docs/verification/645-payload-bootstrap.md diff --git a/agent/.vulture_allowlist.py b/agent/.vulture_allowlist.py index 8e8eb6bdf..240711782 100644 --- a/agent/.vulture_allowlist.py +++ b/agent/.vulture_allowlist.py @@ -14,3 +14,11 @@ # cd agent && uv run vulture src --make-whitelist # # Keep this list MINIMAL. Prefer deleting dead code over allowlisting it. + +# payload_bootstrap._NoRedirect.redirect_request overrides urllib's +# HTTPRedirectHandler.redirect_request and refuses every redirect, so it reads +# none of its arguments. The parameter names are fixed by the override (renaming +# one fails ty's invalid-method-override), and `newurl` and `req` are the ones vulture +# does not see used elsewhere. +newurl # unused variable (src/payload_bootstrap.py:31) +req # unused variable (src/payload_bootstrap.py:31) diff --git a/agent/README.md b/agent/README.md index 93b02ea5b..f2d09a464 100644 --- a/agent/README.md +++ b/agent/README.md @@ -265,23 +265,25 @@ Baked secrets are **reported, not enforced**: `warnings` lists the names (never `microvmId` is parsed defensively and **arrives empty in practice**: the service sends `""` here, unlike `/run` where it is populated (live-verified, ADR-021 P2-F8). So an empty id is expected-normal, not a degraded read — and this hook therefore **cannot** join the guest's record to the control-plane one. `/run`'s `hook accepted task_id=… microvm_id=…` line carries that correlation; `/terminate`'s value is the pipeline-state snapshot it reports. -**`POST /aws/lambda-microvms/runtime/v1/run`** — Payload delivery. Validates the body, installs `platform_config` (below), starts the pipeline in a background thread (the same `_extract_invocation_params` → `_spawn_background` path `/invocations` uses), and returns 200 inside the 1–60 s hook budget. Body: +**`POST /aws/lambda-microvms/runtime/v1/run`** — Authenticate and download a task, install `platform_config` (below), start the pipeline in a background thread, and return 200 inside the hook budget. Protocol v2 is implemented locally; real AWS permission/network/expiry verification remains pending (repository runbook: `docs/verification/645-payload-bootstrap.md`). + +`runHookPayload` is a JSON **string** passed through by `RunMicrovm`, containing: ```json { - "microvmId": "microvm-b44b69d9-…", - "runHookPayload": "{\"agent_payload_s3_uri\": \"s3://bucket//payload.json\", \"platform_config\": {…}}" + "version": 2, + "task_id": "TASK001", + "bootstrap_s3_uri": "s3://deployment-bucket/bootstrap/.json", + "payload_url": "", + "expires_at": 1789312500000 } ``` -`runHookPayload` is an opaque **string** the service passes through from `RunMicrovm`. ABCA's contract for it is one of two shapes, mirroring the ECS container env contract (`AGENT_PAYLOAD` / `AGENT_PAYLOAD_S3_URI`): +The worker reads the deployment manifest with its ambient AWS role, which explicitly denies object reads outside that bucket's `bootstrap/*` prefix. It downloads the task using the coordinator's short-lived signed URL, verifies the task identity, and requires the task's configuration to equal the manifest. The digest in the manifest filename checks its bytes; IAM authenticates its origin. The entire reference must fit **4,096 bytes**. Manifests and task payloads are capped at **16 KiB** and **8 MiB**. Redirects, environment proxies and hosts/paths other than the task's regional S3 object are rejected. -| Envelope | When | -|---|---| -| `{"agent_payload": {…}, "platform_config": {…}}` | the whole orchestrator payload inline — only when it fits | -| `{"agent_payload_s3_uri": "s3://bucket/key", "platform_config": {…}}` | pointer to the payload in the platform payload bucket | +ECS uses the same reference in `AGENT_PAYLOAD_REF`, with an empty manifest config because deployment settings already come from its task definition/overrides. `load_ecs_payload()` removes the capability environment variable before importing the pipeline. Neither backend accepts the old unsigned `AGENT_PAYLOAD`, `AGENT_PAYLOAD_S3_URI`, inline hook or S3-pointer formats. Roll out the matching coordinator, worker images and policies with admissions paused and old tasks drained; the runbook records upgrade and rollback steps. -The service caps `runHookPayload` at **4 096 bytes**, so the **pointer form is the normal one** — a hydrated payload is essentially always larger. Fetching it needs no new env var: the MicroVM execution role holds read-only access to that bucket and the URI carries bucket + key. +A presigned URL is a temporary download permission: **never log it**. Its requested lifetime is at most 900 seconds, shortened by known signer credential expiry; initial creation requires at least 300 seconds. The coordinator privately saves the exact URL for retries and deletes the payload and saved launch reference at finalization. An expired saved reference fails rather than being silently re-signed. #### `platform_config` — the agent's env, delivered per task (P2) @@ -291,7 +293,7 @@ On AgentCore and ECS the agent's non-secret platform env arrives as runtime env { "platform_config": { "task_table_name": "…", "github_token_secret_arn": "arn:…" } } ``` -Each snake_case key installs into its UPPER_SNAKE env var, and a payload value **wins** over any image/pre-existing value (the payload describes the live deployment; the snapshot describes a past one). Installation happens **before** any credential or pipeline initialisation — the very next step resolves the GitHub token from `GITHUB_TOKEN_SECRET_ARN`. Everything the hook logs before that point goes to stdout only (`[server/run-pre-config]`), for the same reason the build hooks do: the CloudWatch writer resolves AWS credentials and pins `boto3.DEFAULT_SESSION` (its credentials; the region is re-resolved per client), and until the install has run the only environment available is whatever the snapshot baked. The single AWS call allowed before the install is the S3 payload fetch, because the config is inside the object being fetched. The allowlist lives in `contracts/constants.json` → `microvm_platform_config` (produced by the orchestrator, consumed here; shape enforced by `mise run check:constants-sync`): +Each snake_case key installs into its UPPER_SNAKE env var, and a payload value **wins** over any image/pre-existing value (the payload describes the live deployment; the snapshot describes a past one). Installation happens **before** task credential, secret or pipeline initialisation — the very next step resolves the GitHub token from `GITHUB_TOKEN_SECRET_ARN`. Everything the hook logs before that point goes to stdout only (`[server/run-pre-config]`), for the same reason the build hooks do: the CloudWatch writer resolves AWS credentials and can cache credential state in `boto3.DEFAULT_SESSION` (environment-derived region is re-read for new clients), and until the install has run the only environment available is whatever the snapshot baked. Before installation, bootstrap reads the deployment manifest through the attributed S3 client and downloads the single task object over signed HTTPS. Other pre-install diagnostics remain stdout-only. The allowlist lives in `contracts/constants.json` → `microvm_platform_config` (produced by the orchestrator, consumed here; shape enforced by `mise run check:constants-sync`): | Key | Env var | Required | |---|---|---| @@ -309,9 +311,9 @@ Each snake_case key installs into its UPPER_SNAKE env var, and a payload value * | `aws_sdk_ua_app_id` | `AWS_SDK_UA_APP_ID` | | | `anthropic_default_haiku_model` | `ANTHROPIC_DEFAULT_HAIKU_MODEL` | | -Values are **non-secret identifiers only** — secrets are still fetched at `/run` time from Secrets Manager using the ARNs delivered here, so the snapshot stays secret-free. The allowlist **fails closed**: these values land in `os.environ` of the process that spawns the agent's tool subprocesses, so an unrecognised key is an env-injection attempt (`LD_PRELOAD`, `AWS_ENDPOINT_URL`, …) and the whole run is rejected with nothing installed. Blank/`null` values for optional keys are skipped rather than clobbering an image value; blank required keys are rejected. An envelope with no `platform_config` at all is accepted with a loud warning (the image and the orchestrator deploy on independent cadences). +Values are **non-secret identifiers only** — secrets are still fetched at `/run` time from Secrets Manager using the ARNs delivered here, so task secrets need not be baked into the snapshot. The build-hook warning is not proof that a hand-built image contains no secrets. The allowlist **fails closed**: these values land in `os.environ` of the process that spawns the agent's tool subprocesses, so an unrecognised key is an env-injection attempt (`LD_PRELOAD`, `AWS_ENDPOINT_URL`, …) and the whole run is rejected with nothing installed. Blank/`null` values for optional keys are skipped rather than clobbering an image value; blank required keys are rejected. A verified MicroVM payload must contain `platform_config`; there is no baked-environment fallback. Control characters and inconsistent ARN account/partition fields are also rejected. ARN consistency alone is not deployment authentication: v2 supplies that through the IAM-read manifest and exact configuration comparison, including same-account workspace identifiers ([#817](https://github.com/aws-samples/sample-autonomous-cloud-coding-agents/issues/817)). -Rejections are structured so they are readable in the MicroVM log group: `400 MICROVM_RUN_PAYLOAD_INVALID` (unusable envelope — retrying the same body cannot help), `500 MICROVM_RUN_PAYLOAD_UNREADABLE` (the S3 fetch failed), `400 MICROVM_RUN_PLATFORM_CONFIG_INVALID` (key off the allowlist, non-object block, or non-string value — fix the producer), `400 MICROVM_RUN_PLATFORM_CONFIG_INCOMPLETE` (a required key missing or blank — fix the deployment wiring), `400 TASK_RECORD_INCOMPLETE` (same validator and vocabulary as `/invocations`). +Rejections are structured so they are readable in the MicroVM log group: `400 MICROVM_RUN_PAYLOAD_INVALID` (unusable envelope — retrying the same body cannot help), `500 MICROVM_RUN_PAYLOAD_UNREADABLE` (manifest/payload read or stored bytes failed), `400 MICROVM_RUN_PLATFORM_CONFIG_INVALID` (key off the allowlist, non-object block, or non-string value — fix the producer), `400 MICROVM_RUN_PLATFORM_CONFIG_INCOMPLETE` (a required key missing or blank — fix the deployment wiring), `400 TASK_RECORD_INCOMPLETE` (same validator and vocabulary as `/invocations`). **`POST /aws/lambda-microvms/runtime/v1/suspend`** and **`/resume`** — Runtime hooks (P3, `microvm_http.py`). `/suspend` drains acknowledged progress and verifies the task is safely parked at its approval gate within the hook budget; when that is unsafe it answers **200 `declined`** and the guest keeps working, because any non-200 answer makes the service terminate the VM. `/resume` refreshes task-scoped and ambient credentials, re-reads the gate and reseeds CSPRNGs before the coding barrier opens; after a declined suspend it answers 200 `not-suspended`. `/terminate` closes the coding barrier first. Inside the guest, the Claude CLI gets credentials from a loopback container-credential broker (`microvm_credentials.py`) that renews them before signing with expired keys. diff --git a/agent/src/payload_bootstrap.py b/agent/src/payload_bootstrap.py new file mode 100644 index 000000000..9188e7c93 --- /dev/null +++ b/agent/src/payload_bootstrap.py @@ -0,0 +1,195 @@ +"""Authenticate deployment settings before reading one task's payload. + +The ambient worker role can GetObject only under its deployment's bootstrap/ +prefix, with an explicit deny outside that prefix (including public buckets). +Only the coordinator can write those manifests. The payload itself is fetched +without worker credentials, using a single-object capability. Never log it. +""" + +from __future__ import annotations + +import hashlib +import json +import os +import re +from typing import Any, override +from urllib.error import HTTPError +from urllib.parse import parse_qs, urlsplit +from urllib.request import HTTPRedirectHandler, ProxyHandler, build_opener + +from shared_constants import SHARED_CONSTANTS + +CONTRACT = SHARED_CONSTANTS["payload_bootstrap"] + + +class PayloadFetchError(RuntimeError): + """Authenticated bootstrap or payload bytes could not be read; contains no URL.""" + + +class _NoRedirect(HTTPRedirectHandler): + @override + def redirect_request(self, req, fp, code, msg, headers, newurl): + return None + + +def _object(raw: bytes, label: str) -> dict: + try: + value = json.loads(raw) + except (UnicodeError, ValueError): + raise PayloadFetchError(f"{label} is not valid JSON") from None + if not isinstance(value, dict): + raise PayloadFetchError(f"{label} must contain an object") + return value + + +def _manifest(uri: str, backend: str) -> tuple[str, dict]: + parsed = urlsplit(uri) + if ( + parsed.scheme != "s3" + or not re.fullmatch(r"[a-z0-9][a-z0-9.-]{1,61}[a-z0-9]", parsed.netloc) + or parsed.query + or parsed.fragment + ): + raise ValueError("bootstrap_s3_uri must identify a deployment manifest") + key = parsed.path.removeprefix("/") + expected = re.fullmatch(re.escape(CONTRACT["manifest_prefix"]) + r"([a-f0-9]{64})\.json", key) + if not expected: + raise ValueError("bootstrap_s3_uri has an invalid manifest key") + + # Do not use a caller-supplied endpoint or default cached boto3 session. + from botocore.config import Config + + from aws_session import platform_client + + try: + client = platform_client( + "s3", + config=Config(connect_timeout=5, read_timeout=10, retries={"max_attempts": 2}), + ) + response = client.get_object(Bucket=parsed.netloc, Key=key) + body = response["Body"] + try: + length = response.get("ContentLength") + if not isinstance(length, int) or not 0 < length <= CONTRACT["max_manifest_bytes"]: + raise PayloadFetchError("deployment manifest has an invalid length") + raw = body.read(CONTRACT["max_manifest_bytes"] + 1) + if len(raw) != length: + raise PayloadFetchError("deployment manifest body is incomplete") + finally: + body.close() + except PayloadFetchError: + raise + except Exception as exc: + # SDK/HTTP exception text can contain URLs. Expose only the class. + raise PayloadFetchError(f"deployment manifest read failed ({type(exc).__name__})") from None + if hashlib.sha256(raw).hexdigest() != expected[1]: + raise PayloadFetchError("deployment manifest digest does not match its key") + manifest = _object(raw, "deployment manifest") + if manifest.get("version") != CONTRACT["version"] or manifest.get("backend") != backend: + raise ValueError("deployment manifest version/backend does not match this worker") + if not isinstance(manifest.get("platform_config"), dict): + raise ValueError("deployment manifest has no platform configuration") + return parsed.netloc, manifest["platform_config"] + + +def _payload_url(url: str, bucket: str, task_id: str) -> None: + """Permit only the exact object's regional S3 HTTPS endpoint, without redirects.""" + try: + parsed = urlsplit(url) + query = parse_qs(parsed.query, keep_blank_values=True, strict_parsing=True) + if any(len(values) != 1 for values in query.values()): + raise ValueError + _access_key, _date, region, service, terminator = query["X-Amz-Credential"][0].split("/") + if ( + service != "s3" + or terminator != "aws4_request" + or not re.fullmatch(r"[a-z]{2}(?:-[a-z]+)+-\d", region) + or query["X-Amz-Algorithm"] != ["AWS4-HMAC-SHA256"] + or query["X-Amz-SignedHeaders"] != ["host"] + or not re.fullmatch(r"[a-f0-9]{64}", query["X-Amz-Signature"][0]) + or not 0 < int(query["X-Amz-Expires"][0]) <= CONTRACT["url_ttl_seconds"] + or parsed.scheme != "https" + or parsed.username is not None + or parsed.password is not None + or parsed.port is not None + or parsed.fragment + ): + raise ValueError + suffix = "amazonaws.com.cn" if region.startswith("cn-") else "amazonaws.com" + host = f"s3.{region}.{suffix}" + valid = ( + parsed.netloc == f"{bucket}.{host}" and parsed.path == f"/{task_id}/payload.json" + ) or (parsed.netloc == host and parsed.path == f"/{bucket}/{task_id}/payload.json") + if not valid: + raise ValueError + except (KeyError, IndexError, TypeError, ValueError): + raise ValueError("payload reference must sign this task's exact S3 object") from None + + +def _download(url: str) -> dict: + # Disable environment proxies and redirects. No AWS credential provider is + # involved; S3 authorizes the coordinator's signature on this one object. + opener = build_opener(ProxyHandler({}), _NoRedirect()) + try: + with opener.open(url, timeout=10) as response: + length = int(response.headers.get("Content-Length", "0")) + if not 0 < length <= CONTRACT["max_payload_bytes"]: + raise PayloadFetchError("task payload has an invalid length") + raw = response.read(CONTRACT["max_payload_bytes"] + 1) + if len(raw) != length: + raise PayloadFetchError("task payload body is incomplete") + return _object(raw, "task payload") + except PayloadFetchError: + raise + except HTTPError as exc: + raise PayloadFetchError(f"task payload download returned HTTP {exc.code}") from None + except Exception as exc: + raise PayloadFetchError(f"task payload download failed ({type(exc).__name__})") from None + + +def resolve_payload_reference(reference: Any, backend: str) -> tuple[dict, dict]: + if not isinstance(reference, dict) or reference.get("version") != CONTRACT["version"]: + raise ValueError( + "payload bootstrap v2 is required; deploy a matching coordinator and image" + ) + task_id = reference.get("task_id") + uri = reference.get("bootstrap_s3_uri") + url = reference.get("payload_url") + if ( + not isinstance(task_id, str) + or not re.fullmatch(r"[A-Za-z0-9_-]{1,128}", task_id) + or not isinstance(uri, str) + or not isinstance(url, str) + ): + raise ValueError("payload reference is missing task identity or download coordinates") + bucket, config = _manifest(uri, backend) + _payload_url(url, bucket, task_id) + document = _download(url) + payload = document.get("agent_payload") + if ( + document.get("version") != CONTRACT["version"] + or document.get("task_id") != task_id + or not isinstance(payload, dict) + or payload.get("task_id") != task_id + ): + raise ValueError("downloaded payload does not belong to the referenced task") + if document.get("platform_config") != config: + raise ValueError( + "payload configuration does not match the authenticated deployment manifest" + ) + return payload, config + + +def load_ecs_payload() -> dict: + """Consume the capability before task subprocesses can inherit the environment.""" + raw = os.environ.pop("AGENT_PAYLOAD_REF", "") + if not raw: + raise ValueError("AGENT_PAYLOAD_REF is required; deploy a matching coordinator and image") + try: + reference = json.loads(raw) + except (UnicodeError, ValueError) as exc: + raise ValueError("AGENT_PAYLOAD_REF is not valid JSON") from exc + if not isinstance(reference, dict) or reference.get("task_id") != os.environ.get("TASK_ID"): + raise ValueError("payload reference does not match the ECS task identity") + payload, _ = resolve_payload_reference(reference, "ecs") + return payload diff --git a/agent/src/server.py b/agent/src/server.py index 66c869335..eb90b6546 100644 --- a/agent/src/server.py +++ b/agent/src/server.py @@ -845,7 +845,6 @@ async def invoke_agent(request: Request, body: InvocationRequest): app.add_api_route(f"{MICROVM_HOOK_PREFIX}/resume", microvm_resume, methods=["POST"]) #: ``s3://`` scheme prefix for the out-of-band payload pointer. -_S3_URI_SCHEME = "s3://" # --- platform_config allowlist (ADR-021 P2) -------------------------------- # WHY the agent's platform env arrives in the ``/run`` payload at all, instead of @@ -897,70 +896,15 @@ async def invoke_agent(request: Request, body: InvocationRequest): #: WHAT THIS BUYS, STATED PRECISELY — because the honest answer is narrower than #: "stops secret exfiltration", and overstating it would hide the residual gap. #: -#: The key allowlist above stops a payload setting ``LD_PRELOAD``; it does not stop -#: a payload pointing an *allowlisted* key at a different resource. The value that -#: matters most is ``github_token_secret_arn``: ``config.resolve_github_token`` -#: fetches whatever ARN it names using the UNSCOPED execution role and caches the -#: raw ``SecretString`` into ``os.environ["GITHUB_TOKEN"]``, from which ``shell.py`` -#: hands the environment to every repo subprocess — i.e. into the model's tool -#: surface. So the value is worth validating. -#: -#: This check is DEFENCE IN DEPTH AND FAIL-FAST, not the primary control: -#: -#: * What actually stops a cross-account read today is IAM. Every grant on the -#: execution role is account-scoped by construction — ``grantRead`` on the GitHub -#: PAT secret, and the ``bgagent-linear-oauth-*`` / ``bgagent-jira-oauth-*`` -#: prefix grants built with ``stack.formatArn`` (``lambda-microvm-compute.ts``). -#: A foreign-account ARN therefore AccessDenies with or without this check. What -#: this adds is a structured 400 at the door instead of an opaque -#: ``AccessDeniedException`` mid-startup, and a guard that still holds if a -#: future grant is ever widened. -#: * What this check does NOT stop is an IN-ACCOUNT redirect. The channel-OAuth -#: grants are prefix grants (unavoidable: the CLI mints ``bgagent-*-oauth-`` -#: at setup, so the names are unknown at synth), so a block whose anchor and -#: whose ``github_token_secret_arn`` name the SAME account but a DIFFERENT -#: workspace's OAuth secret is accepted here. Partition + account is the only -#: boundary this check enforces; it is not a per-workspace authorization check. -#: * That residual gap is currently unreachable from the guest, which is why it is -#: left open. ``platform_config`` is produced by the orchestrator Lambda and the -#: MicroVM execution role holds ``grantRead`` ONLY on the payload bucket -#: (``payloadBucket.grantRead``), so a running MicroVM can read another task's -#: payload but cannot write one. Reaching the in-account case requires already -#: controlling the orchestrator's environment or the bucket's write path. -#: -#: ESCALATION: if the payload path ever becomes less trusted — a third-party -#: producer, an operator-editable envelope, or any grant that lets the guest write -#: the payload bucket — this must grow into a name-shape check that ties -#: ``github_token_secret_arn`` to the task's own channel/workspace, because -#: partition+account pinning provably does not cover that case. -#: -#: The prefix grant itself is at ECS parity. The ASYMMETRY that makes value -#: validation worth doing here at all is new to this backend: on ECS these ARNs -#: arrive as deploy-time container env; here they arrive in a network payload. +#: The allowlist restricts environment-variable names; ARN shape/account checks +#: below are defense in depth. Startup settings come from an IAM-authenticated +#: bootstrap manifest read before the task payload. That independent manifest +#: pins the exact GitHub secret and other deployment identifiers, including valid +#: cross-region secrets. A same-payload account anchor alone cannot do that. MICROVM_PLATFORM_CONFIG_ARN_KEYS: frozenset[str] = frozenset(_PLATFORM_CONFIG_CONTRACT["arn_keys"]) -#: The key whose ARN supplies the partition/account every other ARN is checked -#: against. -#: -#: Deliberately a payload key rather than ``os.environ`` or an STS call. -#: ``os.environ`` is empty here by construction (nothing is baked into the -#: snapshot — see ``imageEnvironmentVariables``), so anchoring on the environment -#: would silently degrade this whole check to shape-only in the intended -#: deployment. An ``sts:GetCallerIdentity`` is not available either: this runs -#: BEFORE ``platform_config`` is installed, on the path that must make zero AWS -#: calls beyond the S3 payload fetch. -#: -#: CONSEQUENCE, stated plainly: because the anchor travels in the same block as the -#: values it validates, this check enforces INTERNAL CONSISTENCY of the block, not -#: agreement with the account the guest is actually running in. A block that names -#: one foreign account throughout is self-consistent and passes here — it then -#: fails at IAM, which is the control that really holds (see -#: :data:`MICROVM_PLATFORM_CONFIG_ARN_KEYS`). ``agent_session_role_arn`` is still -#: the best available anchor: it is REQUIRED (so always present when this check -#: runs, which is what stops disarm-by-omission) and it is the one value whose -#: misdirection costs the attacker the run rather than gaining them anything — a -#: foreign session role fails closed at ``sts:AssumeRole`` -#: (``SessionScopingError``). +#: Consistency anchor after manifest authentication, not deployment identity. +#: Required membership is enforced by the shared contract. MICROVM_PLATFORM_CONFIG_ACCOUNT_ANCHOR_KEY: str = _PLATFORM_CONFIG_CONTRACT["account_anchor_key"] _PLATFORM_CONFIG_KEY_RE = re.compile(r"^[a-z][a-z0-9_]*$") @@ -1044,6 +988,11 @@ def _validate_platform_config_contract() -> None: unknown_arn = sorted(MICROVM_PLATFORM_CONFIG_ARN_KEYS - set(MICROVM_PLATFORM_CONFIG_ENV_BY_KEY)) if unknown_arn: raise ValueError(f"{where}.arn_keys names key(s) absent from env_by_key: {unknown_arn}") + for key, env_name in MICROVM_PLATFORM_CONFIG_ENV_BY_KEY.items(): + if ( + key.endswith("_arn") or env_name.endswith("_ARN") + ) and key not in MICROVM_PLATFORM_CONFIG_ARN_KEYS: + raise ValueError(f"{where}: ARN-shaped key {key!r} is missing from arn_keys") anchor = MICROVM_PLATFORM_CONFIG_ACCOUNT_ANCHOR_KEY if anchor not in MICROVM_PLATFORM_CONFIG_ARN_KEYS: raise ValueError(f"{where}.account_anchor_key {anchor!r} must be one of arn_keys") @@ -1123,25 +1072,6 @@ def __init__(self, code: str, message: str) -> None: self.code = code -def _absent_required_platform_env() -> list[str]: - """Required ``platform_config`` env vars that are unset in the LIVE environment. - - The no-``platform_config`` path's audit. Checks the ENV VAR names rather than - the contract keys, because on that path the only possible source is whatever - the image snapshot baked — so the effective environment is the thing to - interrogate, and a value that arrived by any route counts. - - Blank/whitespace-only counts as absent, matching - :func:`_install_platform_config`'s own rule: CloudFormation renders an - unresolved value as ``""``, and an empty table name is not a table name. - """ - return sorted( - MICROVM_PLATFORM_CONFIG_ENV_BY_KEY[key] - for key in MICROVM_PLATFORM_CONFIG_REQUIRED_KEYS - if not os.environ.get(MICROVM_PLATFORM_CONFIG_ENV_BY_KEY[key], "").strip() - ) - - def _reject_foreign_arns(resolved: dict[str, str]) -> None: """Require every ARN-shaped value to agree with the anchor's partition + account. @@ -1445,176 +1375,27 @@ def _parse_terminate_microvm_id(raw: bytes) -> str: class MicrovmRunHookRequest(BaseModel): - """Body the MicroVM service POSTs to the ``/run`` hook. - - ``runHookPayload`` is the opaque STRING the orchestrator passed to - ``RunMicrovm`` — the service does not parse it. ABCA's contract for that - string (``lambda-microvm-strategy.ts``) is one of two shapes, mirroring the - ECS container env contract (``AGENT_PAYLOAD`` / ``AGENT_PAYLOAD_S3_URI``): - - * ``{"agent_payload": {...}, "platform_config": {...}}`` — inline. - * ``{"agent_payload_s3_uri": "s3://bucket/key", "platform_config": {...}}`` — - a pointer; the object at the URI carries the task payload (and a - ``platform_config`` copy, so either end of the fetch yields it). - - The pointer form is the DOMINANT one: the service caps ``runHookPayload`` at - 4 096 bytes and a hydrated payload is essentially always larger. - - ``platform_config`` (ADR-021 P2) is a SIBLING of ``agent_payload``, not a - field inside it: it configures the agent's *process*, whereas - ``agent_payload`` describes the *task* (``memory_id`` and friends stay - inside ``agent_payload``, unchanged). See ``_install_platform_config``. - - Both fields default to empty so a malformed call produces this module's - structured 400 rather than FastAPI's 422 — the service surfaces a 4xx as a - generic "client error" hook failure either way, and our own body is what ends - up in the MicroVM log group. + """Service request containing a serialized v2 payload reference. + + The reference identifies an IAM-authenticated deployment manifest and one + task's signed download URL. Unsigned inline and legacy S3 envelopes are + refused: this protocol requires a matching coordinator and agent image. + Missing fields reach our structured 400 instead of FastAPI's 422. """ microvmId: str = "" # service field name; camelCase on the wire runHookPayload: str = "" # service field name; camelCase on the wire -class _PayloadFetchError(Exception): - """A ``/run`` payload the agent could not READ, as opposed to could not PARSE. - - Exists purely to be *not* a ``ValueError``, because the ``/run`` handler - discriminates its 400 from its 500 on exactly that type and the two answers - make opposite promises to the operator: - - * 400 ``MICROVM_RUN_PAYLOAD_INVALID`` — "the orchestrator built a bad - envelope; retrying an identical body cannot help." - * 500 ``MICROVM_RUN_PAYLOAD_UNREADABLE`` — "the payload could not be read; - retrying CAN help." - - A truncated, racing, or half-written S3 object is the SECOND kind, but its - natural exception is ``json.JSONDecodeError`` — a ``ValueError`` subclass — so - it landed in the 400 branch and told the operator the orchestrator was at - fault when the orchestrator was fine and the object was bad. Only the - *pre-fetch* URI-shape check legitimately raises ``ValueError`` on this path, - which is why a blanket ``except ValueError`` is the wrong discriminator and - this type exists. - """ - - -def _fetch_microvm_payload_from_s3(uri: str) -> dict: - """Read and parse the out-of-band ``/run`` payload from S3. - - Same fetch the ECS boot command performs for ``AGENT_PAYLOAD_S3_URI``; the - MicroVM **execution role** holds the read grant, scoped to the platform - payload bucket. Errors propagate to the caller, which turns them into a - structured 400/500 — silently starting a pipeline with no payload would - produce a task that runs with an empty prompt. - - The URI-SHAPE check raises ``ValueError`` (the orchestrator's envelope is - wrong → 400). Everything AFTER the fetch raises :class:`_PayloadFetchError` - (the object is wrong → 500, retryable). See that class. - - Built through ``aws_session.platform_client`` so the call carries the ABCA - ``md/`` solution-attribution segment (#319). Platform, not tenant: the bucket - is platform-owned and — decisively — this is the ONE call that must happen - BEFORE ``platform_config`` is installed (the config is inside the object - being fetched), so ``AGENT_SESSION_ROLE_ARN`` may not be set yet and a - tenant-scoped client could not be built. ``platform_client`` does not touch - the cached session, so this call also cannot pin an unscoped session for the - rest of the task. The ``app/`` UA segment (native, from ``AWS_SDK_UA_APP_ID``) - is the one attribution field this single call can miss for the same - chicken-and-egg reason. - """ - remainder = uri[len(_S3_URI_SCHEME) :] - bucket, _, key = remainder.partition("/") - if not bucket or not key: - raise ValueError(f"agent_payload_s3_uri is not a bucket/key URI: {uri!r}") - - from aws_session import platform_client - - region = os.environ.get("AWS_REGION") or os.environ.get("AWS_DEFAULT_REGION") - client = platform_client("s3", region_name=region) - body = client.get_object(Bucket=bucket, Key=key)["Body"].read() - try: - payload = json.loads(body) - except ValueError as exc: - # ``JSONDecodeError`` IS a ``ValueError``, so without this re-raise a - # truncated or half-written object would be reported as an orchestrator - # envelope bug and marked non-retryable. Re-raised as the type the handler - # routes to its retryable 500. - raise _PayloadFetchError( - f"S3 payload at {uri!r} is not valid JSON ({exc}); the object may be " - "truncated or still being written" - ) from exc - if not isinstance(payload, dict): - raise _PayloadFetchError( - f"S3 payload at {uri!r} is {type(payload).__name__}, expected an object" - ) - return payload - - -def _resolve_microvm_run_payload(run_hook_payload: str) -> tuple[dict, Any]: - """Split the ``runHookPayload`` string into (agent payload, platform config). - - The second element is returned RAW (unvalidated) — ``_install_platform_config`` - owns its allowlist checks so the two failure classes get distinct wire codes. - ``None`` means the envelope carried no ``platform_config`` at all. - - Raises ``ValueError`` for every ENVELOPE shape the agent cannot act on — the - caller maps that onto its 400 ("the orchestrator built this; a retry cannot - help"). Problems with the CONTENT of a fetched S3 object raise - :class:`_PayloadFetchError` instead, which the caller maps onto its retryable - 500: the orchestrator's envelope was fine and the object was not. - """ - if not run_hook_payload.strip(): - raise ValueError("runHookPayload is empty") +def _resolve_microvm_run_payload(run_hook_payload: str) -> tuple[dict, dict]: + """Authenticate deployment settings and resolve the v2 task reference.""" + from payload_bootstrap import resolve_payload_reference try: - envelope = json.loads(run_hook_payload) - except json.JSONDecodeError as exc: - raise ValueError(f"runHookPayload is not valid JSON: {exc}") from exc - - if not isinstance(envelope, dict): - raise ValueError(f"runHookPayload must be a JSON object, got {type(envelope).__name__}") - - inline = envelope.get("agent_payload") - if inline is not None: - if not isinstance(inline, dict): - raise ValueError(f"agent_payload must be an object, got {type(inline).__name__}") - return inline, envelope.get("platform_config") - - uri = envelope.get("agent_payload_s3_uri") - if isinstance(uri, str) and uri.startswith(_S3_URI_SCHEME): - fetched = _fetch_microvm_payload_from_s3(uri) - # ``platform_config`` may sit beside the pointer (outer envelope) or - # inside the fetched object — the producer writes it in BOTH places on - # this path deliberately, so the agent gets it whichever end it reads. - # Inner first, outer as the fallback. - platform_config = fetched.get("platform_config") - if platform_config is None: - platform_config = envelope.get("platform_config") - # The fetched object is EITHER the same envelope shape as the inline form - # ({"agent_payload": …}) or the task payload itself with ``platform_config`` - # merged in at the top level (what the strategy writes today, and what P1 - # wrote without the config). Both are accepted because the image snapshot - # and the orchestrator Lambda deploy on independent cadences — a new image - # must not require a same-instant orchestrator. Discriminating on the - # ``agent_payload`` key is unambiguous: no orchestrator task payload has a - # field by that name. A stray ``platform_config`` key left in the bare - # form is inert — ``_extract_invocation_params`` reads named fields only. - nested = fetched.get("agent_payload") - if nested is None: - return fetched, platform_config - if not isinstance(nested, dict): - # Content of the FETCHED OBJECT, not of the envelope — so this is the - # retryable class, same as a truncated body. See ``_PayloadFetchError``. - raise _PayloadFetchError( - f"agent_payload in the S3 payload must be an object, got {type(nested).__name__}" - ) - return nested, platform_config - if uri is not None: - raise ValueError(f"agent_payload_s3_uri must be an s3:// URI, got {uri!r}") - - raise ValueError( - "runHookPayload envelope has neither agent_payload nor agent_payload_s3_uri " - f"(keys: {sorted(envelope)})" - ) + reference = json.loads(run_hook_payload) + except (UnicodeError, ValueError) as exc: + raise ValueError("runHookPayload is not valid JSON") from exc + return resolve_payload_reference(reference, "lambda-microvm") #: The ONE executable whose warm-up gates the snapshot, exec'd FIRST. @@ -2090,7 +1871,7 @@ def microvm_run(request: Request, body: MicrovmRunHookRequest): mechanism ``/invocations`` uses — ``_extract_invocation_params`` → ``_validate_required_params`` → ``_spawn_background`` — rather than a second, drifting payload mapper. The orchestrator payload is byte-identical across - substrates (AgentCore receives it as ``input``, ECS as ``AGENT_PAYLOAD``, + substrates (AgentCore receives it as ``input``, ECS through the authenticated payload reference, MicroVMs inside this envelope), which is what makes that reuse correct. ``platform_config`` (P2) is installed into ``os.environ`` FIRST — before @@ -2107,15 +1888,15 @@ def microvm_run(request: Request, body: MicrovmRunHookRequest): has, per ADR-021 sub-decision 3's identity delta. Sync ``def`` for the same reason as ``/ready``, and additionally because the - S3 payload fetch is a blocking boto3 call: in a threadpool it cannot stall + manifest read and signed download are blocking calls: in a threadpool it cannot stall the event loop. **Every log line before the install goes through ``_pre_config_log``** (stdout only). Until ``platform_config`` is in the environment, a ``_debug_cw`` here would resolve AWS credentials and pin ``boto3.DEFAULT_SESSION`` off whatever the snapshot happens to carry — the same defect the build hooks avoid, one - phase later. The single AWS call this phase is allowed to make is the S3 - payload fetch, because the config is inside the object being fetched. + phase later. Pre-install operations are the IAM-authenticated manifest read + and the single-object HTTPS download. Build hooks remain AWS-silent. """ _pre_config_log( f"/run hook received: microvm_id={body.microvmId!r} bytes={len(body.runHookPayload)}" @@ -2136,16 +1917,14 @@ def microvm_run(request: Request, body: MicrovmRunHookRequest): ) except Exception as exc: # Payload could not be READ: S3 AccessDenied / NoSuchKey / transient, or a - # `_PayloadFetchError` for an object that fetched but was truncated, + # `PayloadFetchError` for an object that fetched but was truncated, # non-JSON, or not an object. 500 so the failure is distinguishable from a - # malformed ENVELOPE (the 400 above) and is correctly reported as - # retryable, and loud enough to find in the MicroVM log group — via the - # response body, since the CloudWatch writer is off-limits until the config - # is installed. - _pre_config_log( - f"/run hook payload fetch FAILED [{type(exc).__name__}: {exc}]\n" - f"{traceback.format_exc()}" - ) + # malformed reference (the 400 above). The response body preserves the + # distinction while CloudWatch is off-limits before config installation. + # Corrupt stored bytes require repair, not an assumption that retry helps. + # A chained HTTP error may contain the bearer URL. Log only the + # bootstrap reader's sanitized message, never its exception chain. + _pre_config_log(f"/run hook payload fetch FAILED [{type(exc).__name__}: {exc}]") return JSONResponse( status_code=500, content={ @@ -2157,6 +1936,11 @@ def microvm_run(request: Request, body: MicrovmRunHookRequest): task_id_log = str(payload.get("task_id", "")) try: + if platform_config is None: + raise _PlatformConfigError( + "MICROVM_RUN_PLATFORM_CONFIG_INVALID", + "Authenticated platform configuration is required", + ) installed_env = _install_platform_config(platform_config) except _PlatformConfigError as exc: _pre_config_log(f"/run hook rejected: {exc}") @@ -2174,55 +1958,6 @@ def microvm_run(request: Request, body: MicrovmRunHookRequest): f"/run hook installed platform_config env: {installed_env}", task_id=task_id_log or None, ) - else: - # No `platform_config` — the legacy P1 envelope. This branch must NOT simply - # shrug: the required keys exist because without them the agent cannot write - # status/progress, resolve the GitHub token, or (decisively) - # tenant-scope its credentials — `aws_session.get_session` falls back to the - # ambient compute role with scoping silently OFF when - # `AGENT_SESSION_ROLE_ARN` is unset. So the check is re-run against the - # EFFECTIVE environment: a legacy or hand-built image that bakes those - # values still runs (that is the compatibility this branch is for), while - # version skew — a pre-Stage-B orchestrator launching a P2 image, which - # bakes nothing — is REJECTED instead of running unscoped. - # - # STILL pre-install, so the line is stdout only. A `_warn_cw` here would - # spawn the CloudWatch writer thread and pin `boto3.DEFAULT_SESSION` off the - # snapshot's baked env, which is the very defect this branch is reporting. - # Nothing is lost: on the intended deployment (no baked `LOG_GROUP_NAME`) - # `_warn_cw` would have degraded to this same stdout line, on a legacy image - # the log group would be the wrong one anyway, and the rejection reason also - # travels in the structured response body the service surfaces. - absent = _absent_required_platform_env() - if absent: - _pre_config_log( - f"/run hook REJECTED: no platform_config and the image snapshot does " - f"not supply required value(s) either: {absent}" - + (f" task_id={task_id_log!r}" if task_id_log else "") - ) - return JSONResponse( - status_code=400, - content={ - "code": "MICROVM_RUN_PLATFORM_CONFIG_INCOMPLETE", - "message": ( - "The /run envelope carried no platform_config and the image " - "snapshot does not carry the required values either, so this " - f"MicroVM cannot run a task: {absent} are unset. This is a " - "version skew — an orchestrator predating ADR-021 P2 launching " - "a P2 image, which bakes no environment by design. Refusing " - "rather than running with tenant scoping disabled. Redeploy the " - "orchestrator so it sends platform_config." - ), - "missing_env": absent, - }, - ) - _pre_config_log( - "/run hook received no platform_config; running on the image snapshot's " - "own environment, which is frozen at build time and which DOES supply " - "every required value. Expected only from an orchestrator that predates " - "ADR-021 P2 paired with an image that bakes its own configuration." - + (f" task_id={task_id_log!r}" if task_id_log else "") - ) try: params = _extract_invocation_params(payload, request) diff --git a/agent/tests/test_payload_bootstrap.py b/agent/tests/test_payload_bootstrap.py new file mode 100644 index 000000000..12c284ff1 --- /dev/null +++ b/agent/tests/test_payload_bootstrap.py @@ -0,0 +1,302 @@ +"""Real bootstrap parsing/stream handling with AWS and HTTPS service boundaries stubbed.""" + +import hashlib +import json +import traceback +from email.message import Message +from io import BytesIO +from unittest.mock import MagicMock +from urllib.error import HTTPError +from urllib.parse import urlencode + +import pytest +from botocore.response import StreamingBody +from fastapi.testclient import TestClient + +import aws_session +import payload_bootstrap as bootstrap +import server + + +class HttpBody(BytesIO): + def __init__(self, raw: bytes, length: int): + super().__init__(raw) + self.headers = {"Content-Length": str(length)} + + +def signed_url(task_id="task-1", bucket="payload-bucket", region="us-east-1"): + suffix = "amazonaws.com.cn" if region.startswith("cn-") else "amazonaws.com" + query = urlencode( + { + "X-Amz-Algorithm": "AWS4-HMAC-SHA256", + "X-Amz-Credential": f"EXAMPLE/20260913/{region}/s3/aws4_request", + "X-Amz-Date": "20260913T120000Z", + "X-Amz-Expires": "900", + "X-Amz-SignedHeaders": "host", + "X-Amz-Signature": "a" * 64, + "X-Amz-Security-Token": "BEARER-SECRET", + } + ) + return f"https://{bucket}.s3.{region}.{suffix}/{task_id}/payload.json?{query}" + + +@pytest.fixture +def transport(monkeypatch): + config = { + "task_table_name": "Tasks", + "task_events_table_name": "Events", + "agent_session_role_arn": "arn:aws:iam::123456789012:role/AgentSession", + "github_token_secret_arn": ( + "arn:aws:secretsmanager:us-west-2:123456789012:secret:github-token-123456" + ), + } + manifest = {"version": 2, "backend": "lambda-microvm", "platform_config": config} + raw_manifest = json.dumps(manifest).encode() + key = "bootstrap/" + hashlib.sha256(raw_manifest).hexdigest() + ".json" + reference = { + "version": 2, + "task_id": "task-1", + "bootstrap_s3_uri": f"s3://payload-bucket/{key}", + "payload_url": signed_url(), + "expires_at": 1800000000000, + } + payload = { + "task_id": "task-1", + "repo_url": "org/repo", + "prompt": "do it", + "github_token": "fake", + } + document = { + "version": 2, + "task_id": "task-1", + "agent_payload": payload, + "platform_config": config, + } + streams = [] + s3 = MagicMock() + + def get_object(**kwargs): + assert kwargs == {"Bucket": "payload-bucket", "Key": key} + body = StreamingBody(BytesIO(raw_manifest), len(raw_manifest)) + streams.append(body) + return {"Body": body, "ContentLength": len(raw_manifest)} + + s3.get_object.side_effect = get_object + platform = MagicMock(return_value=s3) + monkeypatch.setattr(aws_session, "platform_client", platform) + opener = MagicMock() + + def response(_url, **kwargs): + assert kwargs == {"timeout": 10} + raw = json.dumps(document).encode() + return HttpBody(raw, len(raw)) + + opener.open.side_effect = response + build = MagicMock(return_value=opener) + monkeypatch.setattr(bootstrap, "build_opener", build) + return { + "reference": reference, + "config": config, + "payload": payload, + "document": document, + "manifest": manifest, + "s3": s3, + "platform": platform, + "opener": opener, + "build": build, + "streams": streams, + } + + +def test_authenticates_manifest_before_downloading_and_preserves_cross_region_secret(transport): + payload, config = bootstrap.resolve_payload_reference(transport["reference"], "lambda-microvm") + assert payload == transport["payload"] + assert config == transport["config"] + assert ":us-west-2:" in config["github_token_secret_arn"] + transport["platform"].assert_called_once() + assert transport["platform"].call_args.args == ("s3",) + assert len(transport["streams"]) == 1 + assert transport["streams"][0]._raw_stream.closed + assert transport["opener"].open.call_args.args == (transport["reference"]["payload_url"],) + assert isinstance(transport["build"].call_args.args[1], bootstrap._NoRedirect) + assert transport["build"].call_args.args[0].proxies == {} + + +@pytest.mark.parametrize("reference", [{}, {"agent_payload": {}}, {"version": 1}, [], "raw"]) +def test_legacy_and_malformed_envelopes_never_read_or_start(reference, transport): + with pytest.raises(ValueError, match="v2 is required"): + bootstrap.resolve_payload_reference(reference, "lambda-microvm") + transport["platform"].assert_not_called() + + +@pytest.mark.parametrize( + "uri", + [ + "http://169.254.169.254/metadata", + "s3://payload-bucket/task-2/payload.json", + "s3://payload-bucket/bootstrap/../task-2/payload.json", + "s3://payload-bucket/bootstrap/not-a-digest.json", + "s3://payload-bucket/bootstrap/" + "a" * 64 + ".json?versionId=evil", + ], +) +def test_manifest_shape_rejects_other_objects_before_aws(transport, uri): + transport["reference"]["bootstrap_s3_uri"] = uri + with pytest.raises(ValueError): + bootstrap.resolve_payload_reference(transport["reference"], "lambda-microvm") + transport["platform"].assert_not_called() + + +def test_foreign_manifest_denial_prevents_download_and_config_install( + transport, monkeypatch, capfd +): + transport["s3"].get_object.side_effect = PermissionError("AccessDenied") + install = MagicMock() + spawn = MagicMock() + monkeypatch.setattr(server, "_install_platform_config", install) + monkeypatch.setattr(server, "_spawn_background", spawn) + with TestClient(server.app) as client: + response = client.post( + server.MICROVM_HOOK_PREFIX + "/run", + json={ + "microvmId": "mvm", + "runHookPayload": json.dumps(transport["reference"]), + }, + ) + assert response.status_code == 500 + assert response.json()["code"] == "MICROVM_RUN_PAYLOAD_UNREADABLE" + install.assert_not_called() + spawn.assert_not_called() + transport["opener"].open.assert_not_called() + assert "BEARER-SECRET" not in capfd.readouterr().out + + +def test_run_hook_never_logs_the_chained_http_error_url(transport, monkeypatch, capfd): + url = transport["reference"]["payload_url"] + transport["opener"].open.side_effect = HTTPError(url, 403, url, Message(), None) + install = MagicMock() + monkeypatch.setattr(server, "_install_platform_config", install) + with TestClient(server.app) as client: + response = client.post( + server.MICROVM_HOOK_PREFIX + "/run", + json={ + "microvmId": "mvm", + "runHookPayload": json.dumps(transport["reference"]), + }, + ) + assert response.status_code == 500 + install.assert_not_called() + assert "BEARER-SECRET" not in response.text + assert "BEARER-SECRET" not in capfd.readouterr().out + + +@pytest.mark.parametrize( + "mutate", + [ + lambda d: d["platform_config"].update( + github_token_secret_arn="arn:aws:secretsmanager:us-west-2:123456789012:secret:bgagent-linear-oauth-victim" + ), + lambda d: d.update(task_id="task-2"), + lambda d: d["agent_payload"].update(task_id="task-2"), + lambda d: d.update(platform_config=None), + ], + ids=["foreign-secret-arn", "document-task-id", "payload-task-id", "no-platform-config"], +) +def test_same_account_workspace_redirect_or_task_substitution_is_rejected(transport, mutate): + # Detach the document from the fixture's authenticated manifest values. + transport["document"]["platform_config"] = dict(transport["config"]) + mutate(transport["document"]) + with pytest.raises(ValueError): + bootstrap.resolve_payload_reference(transport["reference"], "lambda-microvm") + + +@pytest.mark.parametrize( + "url", + [ + "http://169.254.169.254/latest/meta-data", + signed_url(task_id="task-2"), + signed_url(bucket="another-bucket"), + signed_url().replace("amazonaws.com/", "amazonaws.com.evil.example/"), + signed_url().replace("https://", "https://user@"), + signed_url().replace("amazonaws.com/", "amazonaws.com:443/"), + signed_url() + "#fragment", + signed_url() + "&X-Amz-Signature=" + "b" * 64, + signed_url().replace("X-Amz-Expires=900", "X-Amz-Expires=999999"), + ], +) +def test_download_reference_rejects_wrong_task_hosts_redirect_coordinates_and_ambiguity( + transport, url +): + transport["reference"]["payload_url"] = url + with pytest.raises(ValueError, match="exact S3 object"): + bootstrap.resolve_payload_reference(transport["reference"], "lambda-microvm") + transport["opener"].open.assert_not_called() + + +@pytest.mark.parametrize( + "raw,length", + [ + (b'{"truncated":', 13), + (b"\xff", 1), + (b"[]", 2), + (b"{}", 40), + (b"{}", 0), + (b"{}", bootstrap.CONTRACT["max_payload_bytes"] + 1), + ], +) +def test_bad_payload_bytes_are_unreadable_not_bad_envelopes(transport, raw, length): + body = HttpBody(raw, length) + transport["opener"].open.side_effect = None + transport["opener"].open.return_value = body + with pytest.raises(bootstrap.PayloadFetchError): + bootstrap.resolve_payload_reference(transport["reference"], "lambda-microvm") + assert body.closed + + +@pytest.mark.parametrize("mode", ["digest", "short", "closed", "too_large", "array"]) +def test_bad_manifest_streams_fail_before_download_and_are_closed(transport, mode): + raw = b"[]" if mode == "array" else b"{}" + length = 100 if mode == "short" else len(raw) + if mode == "too_large": + length = bootstrap.CONTRACT["max_manifest_bytes"] + 1 + body = StreamingBody(BytesIO(raw), length) + if mode == "closed": + body.close() + transport["s3"].get_object.side_effect = None + transport["s3"].get_object.return_value = {"Body": body, "ContentLength": length} + with pytest.raises(bootstrap.PayloadFetchError): + bootstrap.resolve_payload_reference(transport["reference"], "lambda-microvm") + assert body._raw_stream.closed + transport["opener"].open.assert_not_called() + + +@pytest.mark.parametrize("code", [301, 307, 403, 500]) +def test_redirect_expiry_and_service_errors_do_not_echo_capabilities(transport, code): + url = transport["reference"]["payload_url"] + transport["opener"].open.side_effect = HTTPError(url, code, url, Message(), None) + with pytest.raises(bootstrap.PayloadFetchError, match=f"HTTP {code}") as error: + bootstrap.resolve_payload_reference(transport["reference"], "lambda-microvm") + assert "BEARER-SECRET" not in str(error.value) + # ECS's Python boot command can print an uncaught exception. Its formatted + # traceback must be safe too, not just the MicroVM route's JSON response. + assert "BEARER-SECRET" not in "".join(traceback.format_exception(error.value)) + assert bootstrap._NoRedirect().redirect_request(None, None, code, "", {}, url) is None + + +def test_ecs_consumes_reference_before_running_code(transport, monkeypatch): + monkeypatch.setenv("TASK_ID", "task-1") + monkeypatch.setenv("AGENT_PAYLOAD_REF", json.dumps(transport["reference"])) + resolve = MagicMock(return_value=(transport["payload"], {})) + monkeypatch.setattr(bootstrap, "resolve_payload_reference", resolve) + assert bootstrap.load_ecs_payload() == transport["payload"] + import os + + assert "AGENT_PAYLOAD_REF" not in os.environ + assert resolve.call_args.args[1] == "ecs" + + +def test_ecs_rejects_another_tasks_reference(transport, monkeypatch): + monkeypatch.setenv("TASK_ID", "task-2") + monkeypatch.setenv("AGENT_PAYLOAD_REF", json.dumps(transport["reference"])) + with pytest.raises(ValueError, match="ECS task identity"): + bootstrap.load_ecs_payload() + transport["platform"].assert_not_called() diff --git a/agent/tests/test_server.py b/agent/tests/test_server.py index becaa0c90..b970805b3 100644 --- a/agent/tests/test_server.py +++ b/agent/tests/test_server.py @@ -9,7 +9,6 @@ import threading import time from pathlib import Path -from types import SimpleNamespace from typing import Any from unittest.mock import MagicMock, patch @@ -1043,13 +1042,45 @@ def _platform_config(**overrides) -> dict: return config -def _run_hook_body(envelope: dict, microvm_id: str = "microvm-abc") -> dict: - """Wrap an ABCA payload envelope in the service's ``/run`` request body. +# Route tests isolate the authenticated transport boundary. The real manifest +# IAM/stream/URL consumer is exercised in test_payload_bootstrap.py. +_run_documents: dict[str, tuple[dict, Any]] = {} - The service passes ``runHookPayload`` through as an opaque STRING (it never - parses it), so the double encoding here is the real wire shape, not a test - artifact. - """ + +@pytest.fixture(autouse=True) +def _authenticated_test_transport(monkeypatch): + import payload_bootstrap + + _run_documents.clear() + monkeypatch.setattr( + payload_bootstrap, + "_manifest", + lambda uri, backend: ("payload-bucket", _run_documents[uri][1]), + ) + monkeypatch.setattr(payload_bootstrap, "_download", lambda url: _run_documents[url][0]) + yield + _run_documents.clear() + + +def _run_hook_body(envelope: dict, microvm_id: str = "microvm-abc") -> dict: + """Wrap pipeline/config fixtures in the current v2 service envelope.""" + from tests.test_payload_bootstrap import signed_url + + if "agent_payload" in envelope and isinstance(envelope["agent_payload"], dict): + payload = envelope["agent_payload"] + task_id = payload.get("task_id", "invalid") + config = envelope.get("platform_config", _platform_config()) + uri = f"s3://payload-bucket/bootstrap/{'a' * 64}.json" + url = signed_url(task_id=task_id) + document = { + "version": 2, + "task_id": task_id, + "agent_payload": payload, + "platform_config": config, + } + _run_documents[uri] = (document, config) + _run_documents[url] = (document, config) + envelope = {"version": 2, "task_id": task_id, "bootstrap_s3_uri": uri, "payload_url": url} return {"microvmId": microvm_id, "runHookPayload": json.dumps(envelope)} @@ -1434,21 +1465,16 @@ def fake_run(argv, **kwargs): assert "skipping best-effort warm-up of 'opt'" in capfd.readouterr().out -class TestMicrovmRunHookInlinePayload: - """Inline envelope: ``{"agent_payload": {...}}``. +class TestMicrovmRunHookVerifiedPayload: + """Map an authenticated v2 payload to the asynchronous task pipeline. - The exception rather than the rule — the service caps ``runHookPayload`` at - 4 096 bytes and a hydrated payload is larger — but it is the branch that - proves the payload→pipeline mapping without any S3 involvement. + The module fixture supplies manifest/download bytes; the shared consumer's + authentication and transport checks have their own regression suite. """ def test_accepts_the_payload_and_starts_the_pipeline_asynchronously( - self, client, monkeypatch, baked_platform_env + self, client, monkeypatch, cached_github_token ): - # `baked_platform_env`: this envelope carries no `platform_config`, which - # since review N2 requires the effective env to supply the required values - # (a legacy image that bakes its own). This class is about the - # payload->pipeline mapping, not about config delivery. started = threading.Event() seen: dict = {} @@ -1471,7 +1497,7 @@ def fake_run_task(**kwargs): "aws_region": "us-east-1", } }, - microvm_id="microvm-inline", + microvm_id="microvm-verified", ), ) @@ -1480,7 +1506,7 @@ def fake_run_task(**kwargs): assert body["status"] == "accepted" assert body["task_id"] == "t-microvm-1" # Echoed so a MicroVM log line can be joined to the control-plane id. - assert body["microvm_id"] == "microvm-inline" + assert body["microvm_id"] == "microvm-verified" assert started.wait(timeout=5.0), "pipeline thread did not start" # Same mapping the /invocations path performs: prompt→task_description, @@ -1489,11 +1515,7 @@ def fake_run_task(**kwargs): assert seen["repo_url"] == "org/repo" assert seen["task_description"] == "Fix the bug" - def test_returns_before_the_pipeline_finishes(self, client, monkeypatch, baked_platform_env): - # `baked_platform_env`: this envelope carries no `platform_config`, which - # since review N2 requires the effective env to supply the required values - # (a legacy image that bakes its own). This class is about the - # payload->pipeline mapping, not about config delivery. + def test_returns_before_the_pipeline_finishes(self, client, monkeypatch, cached_github_token): release = threading.Event() entered = threading.Event() @@ -1521,12 +1543,8 @@ def slow_run_task(**_kwargs): release.set() def test_uses_the_same_model_id_and_prompt_aliases_as_invocations( - self, client, monkeypatch, baked_platform_env + self, client, monkeypatch, cached_github_token ): - # `baked_platform_env`: this envelope carries no `platform_config`, which - # since review N2 requires the effective env to supply the required values - # (a legacy image that bakes its own). This class is about the - # payload->pipeline mapping, not about config delivery. seen: dict = {} started = threading.Event() @@ -1558,118 +1576,6 @@ def fake_run_task(**kwargs): assert seen["channel_source"] == "linear" -class TestMicrovmRunHookS3Payload: - """S3-pointer envelope: ``{"agent_payload_s3_uri": "s3://bucket/key"}``. - - The DOMINANT path on this backend: with a 4 096-byte ``runHookPayload`` cap, - any hydrated payload is offloaded to the platform payload bucket and only the - pointer travels in the hook body. - """ - - def test_fetches_the_payload_from_s3_and_starts_the_pipeline( - self, client, monkeypatch, baked_platform_env - ): - # `baked_platform_env`: this envelope carries no `platform_config`, which - # since review N2 requires the effective env to supply the required values - # (a legacy image that bakes its own). This class is about the - # payload->pipeline mapping, not about config delivery. - seen: dict = {} - started = threading.Event() - - def fake_run_task(**kwargs): - seen.update(kwargs) - started.set() - - fetched: dict = {} - - def fake_fetch(uri): - fetched["uri"] = uri - return {"task_id": "t-s3", "repo_url": "org/repo", "prompt": "from s3"} - - monkeypatch.setattr(server, "_fetch_microvm_payload_from_s3", fake_fetch) - monkeypatch.setattr(server, "run_task", fake_run_task) - monkeypatch.setattr(server.task_state, "write_terminal", MagicMock()) - - r = client.post( - RUN_HOOK, - json=_run_hook_body({"agent_payload_s3_uri": "s3://payload-bucket/t-s3/payload.json"}), - ) - - assert r.status_code == 200 - assert r.json()["task_id"] == "t-s3" - assert fetched["uri"] == "s3://payload-bucket/t-s3/payload.json" - assert started.wait(timeout=5.0) - assert seen["task_description"] == "from s3" - - def test_parses_bucket_and_key_out_of_the_uri(self, monkeypatch): - captured: dict = {} - - class _Body: - @staticmethod - def read(): - return b'{"task_id": "t-1", "repo_url": "o/r"}' - - class _S3: - @staticmethod - def get_object(**kwargs): - captured.update(kwargs) - return {"Body": _Body} - - import boto3 - - monkeypatch.setattr(boto3, "client", lambda *_a, **_k: _S3) - - payload = server._fetch_microvm_payload_from_s3("s3://my-bucket/prefix/t-1/payload.json") - - # Key keeps every slash after the bucket — a naive split would truncate it. - assert captured == {"Bucket": "my-bucket", "Key": "prefix/t-1/payload.json"} - assert payload == {"task_id": "t-1", "repo_url": "o/r"} - - def test_rejects_a_uri_with_no_key(self, monkeypatch): - with pytest.raises(ValueError, match="not a bucket/key URI"): - server._fetch_microvm_payload_from_s3("s3://bucket-only") - - def test_rejects_a_non_object_s3_body(self, monkeypatch): - class _Body: - @staticmethod - def read(): - return b"[1, 2, 3]" - - class _S3: - @staticmethod - def get_object(**_kwargs): - return {"Body": _Body} - - import boto3 - - monkeypatch.setattr(boto3, "client", lambda *_a, **_k: _S3) - - # `_PayloadFetchError`, NOT `ValueError` (review N1): the object is bad, not - # the orchestrator's envelope, so the handler must route it to its RETRYABLE - # 500 rather than the "retrying cannot help" 400. Asserting the type is the - # point — `ValueError` here would silently restore the misclassification. - with pytest.raises(server._PayloadFetchError, match="expected an object"): - server._fetch_microvm_payload_from_s3("s3://b/k") - assert not issubclass(server._PayloadFetchError, ValueError) - - def test_s3_failure_returns_500_and_starts_nothing(self, client, monkeypatch): - def boom(_uri): - raise RuntimeError("AccessDenied") - - monkeypatch.setattr(server, "_fetch_microvm_payload_from_s3", boom) - monkeypatch.setattr(server, "run_task", MagicMock()) - - r = client.post(RUN_HOOK, json=_run_hook_body({"agent_payload_s3_uri": "s3://bucket/key"})) - - # 500, not 400: the body was well-formed, the fetch was not. Retrying an - # identical body CAN help here, unlike a malformed envelope. - assert r.status_code == 500 - assert r.json()["code"] == "MICROVM_RUN_PAYLOAD_UNREADABLE" - assert "AccessDenied" in r.json()["message"] - with server._threads_lock: - assert server._active_threads == [] - - class TestMicrovmRunHookRejections: """Every shape the agent cannot act on must fail LOUDLY, before spawning. @@ -1680,15 +1586,15 @@ class TestMicrovmRunHookRejections: @pytest.mark.parametrize( "run_hook_payload,expected_fragment", [ - ("", "runHookPayload is empty"), - (" ", "runHookPayload is empty"), + ("", "not valid JSON"), + (" ", "not valid JSON"), ("not json at all", "not valid JSON"), - ('"a string"', "must be a JSON object"), - ("[1,2,3]", "must be a JSON object"), - ('{"agent_payload": "not-an-object"}', "agent_payload must be an object"), - ('{"agent_payload_s3_uri": "https://example.com/x"}', "must be an s3:// URI"), - ('{"agent_payload_s3_uri": 42}', "must be an s3:// URI"), - ('{"something_else": 1}', "neither agent_payload nor agent_payload_s3_uri"), + ('"a string"', "v2 is required"), + ("[1,2,3]", "v2 is required"), + ('{"agent_payload": "not-an-object"}', "v2 is required"), + ('{"agent_payload_s3_uri": "https://example.com/x"}', "v2 is required"), + ('{"agent_payload_s3_uri": 42}', "v2 is required"), + ('{"something_else": 1}', "v2 is required"), ], ) def test_returns_400_with_a_named_code( @@ -1717,9 +1623,9 @@ def test_a_missing_body_field_is_a_400_not_a_422(self, client, monkeypatch): assert r.json()["code"] == "MICROVM_RUN_PAYLOAD_INVALID" def test_incomplete_task_record_reuses_the_invocations_rejection_shape( - self, client, monkeypatch, baked_platform_env + self, client, monkeypatch, cached_github_token ): - # `baked_platform_env` so the run gets PAST config delivery and reaches the + # Cache the GitHub token so this test reaches the # task-record check this test is actually about. monkeypatch.setattr(server, "run_task", MagicMock()) @@ -1747,12 +1653,8 @@ class TestMicrovmRunHookHeaderPosture: """ def test_session_id_and_workload_token_resolve_empty( - self, client, monkeypatch, baked_platform_env + self, client, monkeypatch, cached_github_token ): - # `baked_platform_env`: this envelope carries no `platform_config`, which - # since review N2 requires the effective env to supply the required values - # (a legacy image that bakes its own). This class is about the - # payload->pipeline mapping, not about config delivery. seen: dict = {} started = threading.Event() @@ -1858,26 +1760,9 @@ def test_merge_branches_non_string_entries_filtered(self): @pytest.fixture -def baked_platform_env(env_guard): - """Simulate a legacy/hand-built image that BAKES its own required config. - - Needed by every ``/run`` test whose envelope carries no ``platform_config``. - Since review N2 the no-config branch re-runs the required-key check against the - EFFECTIVE environment and rejects when it is unsatisfied — because - ``aws_session`` silently drops tenant scoping when ``AGENT_SESSION_ROLE_ARN`` - is unset, and running a task unscoped is worse than refusing it. That check is - what this fixture satisfies, and satisfying it is exactly what a real legacy - image does: the compatibility path is "the snapshot supplies the values", not - "nobody supplies them". - - Depends on ``env_guard`` so the writes are reverted with everything else. - """ - for key in server.MICROVM_PLATFORM_CONFIG_REQUIRED_KEYS: - os.environ[server.MICROVM_PLATFORM_CONFIG_ENV_BY_KEY[key]] = _platform_config_value(key) - # A baked GITHUB_TOKEN_SECRET_ARN makes `resolve_github_token` reach for real - # Secrets Manager; pre-seeding its cache keeps these tests offline. Realistic - # for the image this fixture models, and it changes nothing they assert. - os.environ["GITHUB_TOKEN"] = "ghp_baked_for_tests" # noqa: S105 -- test placeholder, not a secret +def cached_github_token(env_guard): + """Keep pipeline mapping tests offline after authenticated config installation.""" + os.environ["GITHUB_TOKEN"] = "ghp_cached_for_tests" # noqa: S105 -- test placeholder yield @@ -1910,8 +1795,68 @@ def test_allowlist_is_sourced_from_the_shared_contract(self): from shared_constants import SHARED_CONSTANTS contract = SHARED_CONSTANTS["microvm_platform_config"] + assert set(contract) == {"env_by_key", "required", "arn_keys", "account_anchor_key"} assert contract["env_by_key"] == server.MICROVM_PLATFORM_CONFIG_ENV_BY_KEY assert frozenset(contract["required"]) == server.MICROVM_PLATFORM_CONFIG_REQUIRED_KEYS + assert frozenset(contract["arn_keys"]) == server.MICROVM_PLATFORM_CONFIG_ARN_KEYS + assert contract["account_anchor_key"] == server.MICROVM_PLATFORM_CONFIG_ACCOUNT_ANCHOR_KEY + + def test_arn_fields_and_account_anchor_are_explicitly_reviewed(self): + assert { + "github_token_secret_arn", + "linear_oauth_secret_arn", + "jira_oauth_secret_arn", + "agent_session_role_arn", + } == server.MICROVM_PLATFORM_CONFIG_ARN_KEYS + assert server.MICROVM_PLATFORM_CONFIG_ACCOUNT_ANCHOR_KEY == "agent_session_role_arn" + + @pytest.mark.parametrize( + "key,env_name", + [("new_resource_arn", "NEW_RESOURCE"), ("new_resource", "NEW_RESOURCE_ARN")], + ) + def test_new_arn_fields_cannot_omit_arn_validation(self, monkeypatch, key, env_name): + monkeypatch.setattr( + server, + "MICROVM_PLATFORM_CONFIG_ENV_BY_KEY", + {**server.MICROVM_PLATFORM_CONFIG_ENV_BY_KEY, key: env_name}, + ) + with pytest.raises(ValueError, match=r"ARN-shaped key.*missing from arn_keys"): + server._validate_platform_config_contract() + + monkeypatch.setattr( + server, + "MICROVM_PLATFORM_CONFIG_ARN_KEYS", + server.MICROVM_PLATFORM_CONFIG_ARN_KEYS | {key}, + ) + server._validate_platform_config_contract() + + @pytest.mark.parametrize( + "constant,value,error", + [ + ("MICROVM_PLATFORM_CONFIG_ARN_KEYS", frozenset(), "arn_keys must not be empty"), + ( + "MICROVM_PLATFORM_CONFIG_ARN_KEYS", + frozenset({"unknown_arn"}), + "arn_keys names key.*absent from env_by_key", + ), + ( + "MICROVM_PLATFORM_CONFIG_ACCOUNT_ANCHOR_KEY", + "task_table_name", + "must be one of arn_keys", + ), + ( + "MICROVM_PLATFORM_CONFIG_ACCOUNT_ANCHOR_KEY", + "linear_oauth_secret_arn", + "must also be listed in .required", + ), + ], + ) + def test_invalid_arn_contract_fails_before_serving_tasks( + self, monkeypatch, constant, value, error + ): + monkeypatch.setattr(server, constant, value) + with pytest.raises(ValueError, match=error): + server._validate_platform_config_contract() def test_wire_contract_is_exactly_the_documented_key_set(self): # Spelled out on purpose: this is the wire contract Stage B's producer is @@ -2320,20 +2265,10 @@ def test_an_arn_in_a_foreign_account_is_rejected(self, env_guard): assert "GITHUB_TOKEN_SECRET_ARN" not in os.environ def test_an_in_account_redirect_is_NOT_rejected(self, env_guard): - # The KNOWN LIMITATION, pinned as a test so it cannot be quietly mistaken for - # coverage. This check compares partition + account only, so a block naming - # another workspace's channel-OAuth secret in the SAME account is accepted — - # and the `bgagent-*-oauth-*` grants are prefix grants, so IAM would allow - # that read too. - # - # It is left open because it is currently unreachable from the guest: - # `platform_config` is produced by the orchestrator Lambda, and the MicroVM - # execution role holds `grantRead` ONLY on the payload bucket, so a running - # MicroVM can read another task's payload but cannot write one. - # - # If this test ever needs to flip to `pytest.raises`, the escalation is a - # name-shape check tying `github_token_secret_arn` to the task's own - # channel/workspace — see `MICROVM_PLATFORM_CONFIG_ARN_KEYS`. + # Unit scope: the installer checks internal ARN agreement, not origin. + # The v2 resolver authenticates the manifest and compares the downloaded + # config BEFORE calling this installer. Its own route/transport tests + # reject same-account workspace substitutions. installed = server._install_platform_config( _platform_config( github_token_secret_arn=( @@ -2345,10 +2280,8 @@ def test_an_in_account_redirect_is_NOT_rejected(self, env_guard): assert "GITHUB_TOKEN_SECRET_ARN" in installed def test_a_wholesale_partition_swap_is_NOT_rejected(self, env_guard): - # The other half of the same limitation, and the reason the docstrings say - # "internally consistent" rather than "pinned to this deployment": the anchor - # travels in the block it validates, so a payload that moves EVERY ARN to - # another partition agrees with itself and passes. IAM is what refuses it. + # A self-consistent block passes this internal-consistency helper. + # Deployment provenance is enforced earlier by the v2 bootstrap resolver. installed = server._install_platform_config( _platform_config( agent_session_role_arn=f"arn:aws-cn:iam::{_TEST_ACCOUNT}:role/r", @@ -2513,7 +2446,7 @@ def _payload(self, **extra) -> dict: **extra, } - def test_inline_envelope_installs_the_config_and_accepts_the_task( + def test_verified_payload_installs_the_config_and_accepts_the_task( self, client, monkeypatch, env_guard ): monkeypatch.setattr(server, "run_task", MagicMock()) @@ -2624,197 +2557,6 @@ def test_a_non_object_block_returns_400(self, client, monkeypatch, env_guard): assert r.status_code == 400 assert r.json()["code"] == "MICROVM_RUN_PLATFORM_CONFIG_INVALID" - def test_an_envelope_without_platform_config_is_accepted_when_the_image_bakes_it( - self, client, monkeypatch, baked_platform_env, capfd - ): - # P1 compatibility, PRECISELY scoped (review N2): image snapshot and - # orchestrator Lambda deploy on independent cadences, so a new image must not - # require a Stage-B orchestrator — PROVIDED the values come from somewhere. - # Here the image bakes them, which is what the compatibility path is for. - monkeypatch.setattr(server, "run_task", MagicMock()) - monkeypatch.setattr(server.task_state, "write_terminal", MagicMock()) - - r = client.post( - RUN_HOOK, - json=_run_hook_body({"agent_payload": self._payload(task_id="t-pc-baked")}), - ) - - assert r.status_code == 200 - # Still pre-install (nothing was installed), so the warning is stdout-only: - # `_warn_cw` here would spawn the CloudWatch thread off the snapshot's own - # baked env — the very thing it is warning about. See `TestMicrovmRunHook - # PreInstallAwsSilence`. - assert "[server/run-pre-config] /run hook received no platform_config" in ( - capfd.readouterr().out - ) - - def test_no_platform_config_and_no_baked_env_is_refused_not_run_unscoped( - self, client, monkeypatch, env_guard, capfd - ): - # Review N2, the version-skew case: a pre-Stage-B orchestrator launching a P2 - # image. The image bakes NOTHING by design (`imageEnvironmentVariables` - # defaults to `{}`), so nothing supplies `AGENT_SESSION_ROLE_ARN` — and - # `aws_session.get_session` silently falls back to the ambient compute role - # with tenant scoping OFF when it is unset. Refusing is the only correct - # answer; the previous behaviour was a 200 and a stdout breadcrumb. - run_task = MagicMock() - monkeypatch.setattr(server, "run_task", run_task) - monkeypatch.setattr(server.task_state, "write_terminal", MagicMock()) - for key in server.MICROVM_PLATFORM_CONFIG_REQUIRED_KEYS: - os.environ.pop(server.MICROVM_PLATFORM_CONFIG_ENV_BY_KEY[key], None) - - r = client.post(RUN_HOOK, json=_run_hook_body({"agent_payload": self._payload()})) - - assert r.status_code == 400 - body = r.json() - assert body["code"] == "MICROVM_RUN_PLATFORM_CONFIG_INCOMPLETE" - # The response NAMES the unset variables — the whole point is that a skewed - # deployment is diagnosable rather than mysterious. - assert body["missing_env"] == sorted( - server.MICROVM_PLATFORM_CONFIG_ENV_BY_KEY[key] - for key in server.MICROVM_PLATFORM_CONFIG_REQUIRED_KEYS - ) - assert "AGENT_SESSION_ROLE_ARN" in body["missing_env"] - # Nothing was started. - run_task.assert_not_called() - # And the rejection is attributable in the log, not just in the response. - assert "/run hook REJECTED: no platform_config" in capfd.readouterr().out - - def test_a_partially_baked_env_names_only_what_is_actually_missing( - self, client, monkeypatch, baked_platform_env - ): - # The realistic skew: an image that bakes SOME config. The rejection must - # name only the genuinely-unset variables, or an operator chases the wrong - # one. - monkeypatch.setattr(server, "run_task", MagicMock()) - monkeypatch.setattr(server.task_state, "write_terminal", MagicMock()) - os.environ.pop("AGENT_SESSION_ROLE_ARN", None) - - r = client.post(RUN_HOOK, json=_run_hook_body({"agent_payload": self._payload()})) - - assert r.status_code == 400 - assert r.json()["missing_env"] == ["AGENT_SESSION_ROLE_ARN"] - - def test_s3_pointer_takes_the_config_from_the_outer_envelope( - self, client, monkeypatch, env_guard - ): - # The producer's pointer form: the bare task payload lands in S3 and the - # config rides beside the pointer, inside the 4 KB hook body. - monkeypatch.setattr( - server, - "_fetch_microvm_payload_from_s3", - lambda _uri: self._payload(task_id="t-outer"), - ) - monkeypatch.setattr(server, "run_task", MagicMock()) - monkeypatch.setattr(server.task_state, "write_terminal", MagicMock()) - - r = client.post( - RUN_HOOK, - json=_run_hook_body( - { - "agent_payload_s3_uri": "s3://bucket/t-outer/payload.json", - "platform_config": _platform_config(task_table_name="outer-table"), - } - ), - ) - - assert r.status_code == 200 - assert r.json()["task_id"] == "t-outer" - assert os.environ["TASK_TABLE_NAME"] == "outer-table" - - def test_s3_pointer_takes_the_config_merged_into_the_fetched_object( - self, client, monkeypatch, env_guard - ): - # The producer ALSO merges the config into the S3 object, so the agent - # gets it whichever end of the fetch it reads. A stray platform_config key - # left in the bare payload is inert — the extractor reads named fields. - fetched = self._payload(task_id="t-inner") - fetched["platform_config"] = _platform_config(task_table_name="inner-table") - monkeypatch.setattr(server, "_fetch_microvm_payload_from_s3", lambda _uri: fetched) - monkeypatch.setattr(server, "run_task", MagicMock()) - monkeypatch.setattr(server.task_state, "write_terminal", MagicMock()) - - r = client.post( - RUN_HOOK, - json=_run_hook_body({"agent_payload_s3_uri": "s3://bucket/t-inner/payload.json"}), - ) - - assert r.status_code == 200 - assert r.json()["task_id"] == "t-inner" - assert os.environ["TASK_TABLE_NAME"] == "inner-table" - - def test_s3_object_may_itself_be_the_full_envelope(self, client, monkeypatch, env_guard): - monkeypatch.setattr( - server, - "_fetch_microvm_payload_from_s3", - lambda _uri: { - "agent_payload": self._payload(task_id="t-nested"), - "platform_config": _platform_config(task_table_name="nested-table"), - }, - ) - monkeypatch.setattr(server, "run_task", MagicMock()) - monkeypatch.setattr(server.task_state, "write_terminal", MagicMock()) - - r = client.post( - RUN_HOOK, - json=_run_hook_body({"agent_payload_s3_uri": "s3://bucket/t-nested/payload.json"}), - ) - - assert r.status_code == 200 - assert r.json()["task_id"] == "t-nested" - assert os.environ["TASK_TABLE_NAME"] == "nested-table" - - def test_the_fetched_object_wins_over_the_outer_envelope(self, client, monkeypatch, env_guard): - fetched = self._payload(task_id="t-prec") - fetched["platform_config"] = _platform_config(task_table_name="inner-wins") - monkeypatch.setattr(server, "_fetch_microvm_payload_from_s3", lambda _uri: fetched) - monkeypatch.setattr(server, "run_task", MagicMock()) - monkeypatch.setattr(server.task_state, "write_terminal", MagicMock()) - - r = client.post( - RUN_HOOK, - json=_run_hook_body( - { - "agent_payload_s3_uri": "s3://bucket/t-prec/payload.json", - "platform_config": _platform_config(task_table_name="outer-loses"), - } - ), - ) - - assert r.status_code == 200 - assert os.environ["TASK_TABLE_NAME"] == "inner-wins" - - def test_a_nested_agent_payload_of_the_wrong_type_is_a_retryable_500(self, client, monkeypatch): - # Review N1: this is a problem with the FETCHED OBJECT, not with the envelope - # the orchestrator built, so it belongs on the retryable 500 branch. The old - # 400 told the operator "the orchestrator built a bad envelope; retrying - # cannot help" — both halves wrong for a racing or half-written S3 object. - monkeypatch.setattr( - server, - "_fetch_microvm_payload_from_s3", - lambda _uri: {"agent_payload": "not-an-object"}, - ) - monkeypatch.setattr(server, "run_task", MagicMock()) - - r = client.post(RUN_HOOK, json=_run_hook_body({"agent_payload_s3_uri": "s3://b/k"})) - - assert r.status_code == 500 - assert r.json()["code"] == "MICROVM_RUN_PAYLOAD_UNREADABLE" - assert "agent_payload in the S3 payload must be an object" in r.json()["message"] - - def test_resolve_returns_the_config_alongside_the_payload(self): - payload, config = server._resolve_microvm_run_payload( - json.dumps({"agent_payload": {"task_id": "t"}, "platform_config": {"a": "b"}}) - ) - assert payload == {"task_id": "t"} - assert config == {"a": "b"} - - def test_resolve_returns_none_for_an_envelope_without_a_config(self): - _payload, config = server._resolve_microvm_run_payload( - json.dumps({"agent_payload": {"task_id": "t"}}) - ) - assert config is None - # -------------------------------------------------------------------------- # /validate + /terminate (ADR-021 P2) @@ -3057,12 +2799,8 @@ def test_never_writes_terminal_task_status(self, client, monkeypatch): write_heartbeat.assert_not_called() def test_returns_200_without_joining_a_running_pipeline( - self, client, monkeypatch, baked_platform_env + self, client, monkeypatch, cached_github_token ): - # `baked_platform_env`: this envelope carries no `platform_config`, which - # since review N2 requires the effective env to supply the required values - # (a legacy image that bakes its own). This class is about the - # payload->pipeline mapping, not about config delivery. # A drain can take minutes (that is lifespan's job on graceful shutdown); # the hook budget is 1-60 s, so /terminate must observe and return. release = threading.Event() @@ -3140,56 +2878,6 @@ def __iter__(self): assert "best-effort step failed" in capfd.readouterr().out -class TestMicrovmPayloadFetchAttribution: - """Every outbound AWS call carries ABCA's solution attribution (#319).""" - - def test_the_s3_payload_fetch_goes_through_the_attributed_factory(self, monkeypatch): - captured: dict = {} - - class _Body: - @staticmethod - def read(): - return b'{"task_id": "t-1"}' - - def fake_platform_client(service_name, **kwargs): - captured["service"] = service_name - captured["kwargs"] = kwargs - return SimpleNamespace(get_object=lambda **_kw: {"Body": _Body}) - - import aws_session - - monkeypatch.setattr(aws_session, "platform_client", fake_platform_client) - - assert server._fetch_microvm_payload_from_s3("s3://b/k") == {"task_id": "t-1"} - assert captured["service"] == "s3" - - def test_the_fetch_client_carries_the_md_user_agent_segment(self, monkeypatch): - # A naked boto3.client('s3') would silently drop the md/ segment. Assert on - # the OUTCOME (the UA on the config) rather than on which helper was used. - captured: dict = {} - - class _Body: - @staticmethod - def read(): - return b'{"task_id": "t-1"}' - - def fake_boto3_client(service_name, **kwargs): - captured["service"] = service_name - captured["config"] = kwargs.get("config") - return SimpleNamespace(get_object=lambda **_kw: {"Body": _Body}) - - import boto3 - - monkeypatch.setattr(boto3, "client", fake_boto3_client) - - server._fetch_microvm_payload_from_s3("s3://b/k") - - import ua - - assert captured["service"] == "s3" - assert ua.static_user_agent_extra() in captured["config"].user_agent_extra - - class TestSnapshotCredentialHygiene: """Nothing on the server's import or /ready path may cache an SDK session. @@ -3276,316 +2964,6 @@ def test_import_and_build_hooks_create_no_boto3_session(self): } -class TestMicrovmRunHookPreInstallAwsSilence: - """Before ``platform_config`` is installed, ``/run`` may touch exactly ONE AWS seam. - - Same defect class the build hooks avoid, one phase later: until the install has - run, ``LOG_GROUP_NAME`` is whatever the snapshot happens to carry, so a - ``_debug_cw`` on this path would resolve credentials and pin - ``boto3.DEFAULT_SESSION`` *before* the orchestrator's own region / - ``AWS_SDK_UA_APP_ID`` / session role are in the environment. The sole permitted - pre-install call is the S3 payload fetch, because the config is inside the - object being fetched. - - Every test here runs with a **baked ``LOG_GROUP_NAME``** — the hostile case the - fix exists for. Without it, ``_debug_cw`` degrades to stdout on its own and the - assertions would pass vacuously. - """ - - def _payload(self, **extra) -> dict: - return { - "task_id": "t-silent", - "repo_url": "org/repo", - "prompt": "do it", - "github_token": "ghp_x", - **extra, - } - - @pytest.fixture(autouse=True) - def _disable_background_pipeline(self, monkeypatch): - """Keep handler-only assertions isolated from asynchronous pipeline work. - - Mocking ``run_task`` is insufficient because ``_spawn_background`` returns - before its thread necessarily dereferences that global. Pytest can restore - the mock between parametrized cases while the prior thread is still - starting, letting it run the real pipeline under the next case's AWS seam - guard. Stub the spawn boundary instead: these tests specify only the - pre-install handler phase and none need a pipeline thread. - """ - monkeypatch.setattr(server, "_spawn_background", MagicMock()) - - @pytest.fixture - def seam_guard(self, monkeypatch): - """Arm every AWS/credential seam to raise until the pre-install phase is OVER. - - Two things end that phase, and only two: - - * ``_install_platform_config`` returning a **non-empty** env list — a real - install. Flipping on *any* return would be a hole big enough to drive B2 - through: the ``raw is None`` early return installs nothing and returns - ``[]``, so treating it as "installed" disarms the guard for the entire - legacy no-``platform_config`` path — which is exactly where a ``_warn_cw`` - was spawning the CloudWatch thread off the snapshot's baked env. - * ``_extract_invocation_params`` being entered. Past that point the legacy - path is *allowed* to talk to AWS: running on the snapshot's own env is the - documented P1-compatibility behaviour, so the accepted-line ``_debug_cw`` - and the pipeline below it are legitimate. Everything the handler does - *before* it — including the "no platform_config" warning — is not. - - A rejection path reaches neither, so the seams stay armed for the whole - request: a rejected run installed nothing and has no more right to an AWS - call than it had before. - """ - state: dict[str, Any] = { - "install_phase_done": False, - "installed_env": None, - "violations": [], - } - real_install = server._install_platform_config - real_extract = server._extract_invocation_params - - def spy_install(raw): - result = real_install(raw) - state["installed_env"] = result - if result: - state["install_phase_done"] = True - return result - - def spy_extract(*args, **kwargs): - state["install_phase_done"] = True - return real_extract(*args, **kwargs) - - monkeypatch.setattr(server, "_install_platform_config", spy_install) - monkeypatch.setattr(server, "_extract_invocation_params", spy_extract) - - def guard(name): - def _seam(*_args, **_kwargs): - if not state["install_phase_done"]: - state["violations"].append(name) - raise AssertionError(f"{name} touched before platform_config was installed") - return MagicMock() - - return _seam - - import boto3 - - import aws_session - - # Kept so a test can re-enable exactly the ONE permitted pre-install seam - # (the S3 payload fetch) and assert on it positively. - state["real_platform_client"] = aws_session.platform_client - - for module, attr in ( - (boto3, "client"), - (boto3, "Session"), - (aws_session, "platform_client"), - (aws_session, "tenant_client"), - (aws_session, "tenant_resource"), - (aws_session, "get_session"), - (server, "_debug_cw"), - (server, "_warn_cw"), - (server, "_debug_cw_exc"), - ): - monkeypatch.setattr(module, attr, guard(f"{module.__name__}.{attr}")) - - monkeypatch.setenv("LOG_GROUP_NAME", "/abca/agent") - return state - - @pytest.mark.parametrize("with_config", [True, False], ids=["with-config", "no-config"]) - def test_no_cloudwatch_or_credential_seam_is_touched_before_the_install( - self, client, monkeypatch, baked_platform_env, seam_guard, capfd, with_config - ): - # The ``no-config`` arm is the legacy P1 envelope, and it is the harder case: - # nothing is ever installed, so EVERY line up to param extraction — including - # the "running on the snapshot's frozen env" warning itself — is still - # pre-install. A ``_warn_cw`` there would spawn the CloudWatch writer thread - # and pin ``boto3.DEFAULT_SESSION`` off the baked ``LOG_GROUP_NAME`` this - # fixture sets, which is precisely the defect the warning is reporting. - # - # ``baked_platform_env`` (rather than ``env_guard``) so that arm reaches the - # ACCEPT path: since review N2 a no-config run with an unsatisfied effective - # env is refused, and a rejected run installs nothing and so proves nothing - # about the seams staying silent all the way to param extraction. Baking the - # env is also the only shape in which the no-config path is legitimate. - monkeypatch.setattr(server, "run_task", MagicMock()) - monkeypatch.setattr(server.task_state, "write_terminal", MagicMock()) - - envelope: dict[str, Any] = {"agent_payload": self._payload()} - if with_config: - envelope["platform_config"] = _platform_config() - - r = client.post(RUN_HOOK, json=_run_hook_body(envelope)) - - assert r.status_code == 200 - assert seam_guard["violations"] == [] - assert seam_guard["install_phase_done"] is True - if with_config: - assert seam_guard["installed_env"] - else: - # Vacuously "installed": the early return the flag must NOT trust. - assert seam_guard["installed_env"] == [] - # The warning still reaches an operator — stdout, via the pre-install sink. - assert ( - "[server/run-pre-config] /run hook received no platform_config" - in capfd.readouterr().out - ) - - def test_the_no_config_REJECTION_also_touches_no_seam( - self, client, monkeypatch, env_guard, seam_guard, capfd - ): - # Review N2's rejection is itself a pre-install path, and it emits a NEW log - # line — so it needs the same guarantee as every other rejection here: the - # refusal must not be the thing that pins `boto3.DEFAULT_SESSION` off the - # snapshot's baked `LOG_GROUP_NAME` (which `seam_guard` sets). - monkeypatch.setattr(server, "run_task", MagicMock()) - for key in server.MICROVM_PLATFORM_CONFIG_REQUIRED_KEYS: - os.environ.pop(server.MICROVM_PLATFORM_CONFIG_ENV_BY_KEY[key], None) - - r = client.post(RUN_HOOK, json=_run_hook_body({"agent_payload": self._payload()})) - - assert r.status_code == 400 - assert r.json()["code"] == "MICROVM_RUN_PLATFORM_CONFIG_INCOMPLETE" - assert seam_guard["violations"] == [] - assert "/run hook REJECTED: no platform_config" in capfd.readouterr().out - - def test_the_received_line_is_stdout_only( - self, client, monkeypatch, env_guard, seam_guard, capfd - ): - monkeypatch.setattr(server, "run_task", MagicMock()) - monkeypatch.setattr(server.task_state, "write_terminal", MagicMock()) - - client.post( - RUN_HOOK, - json=_run_hook_body( - {"agent_payload": self._payload(), "platform_config": _platform_config()}, - microvm_id="microvm-quiet", - ), - ) - - out = capfd.readouterr().out - assert "[server/run-pre-config] /run hook received:" in out - assert "microvm-quiet" in out - - def test_the_s3_payload_fetch_is_the_only_pre_install_aws_call( - self, client, monkeypatch, env_guard, seam_guard - ): - # The permitted exception, asserted positively: exactly one client, for s3, - # while the CloudWatch/credential seams stay armed. - services: list[str] = [] - - class _Body: - @staticmethod - def read(): - return json.dumps(self._payload(task_id="t-from-s3")).encode() - - def recording_client(service_name, **_kwargs): - services.append(service_name) - return SimpleNamespace(get_object=lambda **_kw: {"Body": _Body}) - - import boto3 - - import aws_session - - # Re-enable the one permitted seam, and only it: the fetch must still go - # through the attributed factory (#319), which delegates to boto3.client. - monkeypatch.setattr(aws_session, "platform_client", seam_guard["real_platform_client"]) - monkeypatch.setattr(boto3, "client", recording_client) - monkeypatch.setattr(server, "run_task", MagicMock()) - monkeypatch.setattr(server.task_state, "write_terminal", MagicMock()) - - r = client.post( - RUN_HOOK, - json=_run_hook_body( - { - "agent_payload_s3_uri": "s3://payload-bucket/t-from-s3/payload.json", - "platform_config": _platform_config(), - } - ), - ) - - assert r.status_code == 200 - assert r.json()["task_id"] == "t-from-s3" - assert services == ["s3"] - assert seam_guard["violations"] == [] - - def test_a_malformed_envelope_is_rejected_without_touching_a_seam( - self, client, monkeypatch, seam_guard, capfd - ): - monkeypatch.setattr(server, "run_task", MagicMock()) - - r = client.post(RUN_HOOK, json={"microvmId": "m", "runHookPayload": "not json"}) - - assert r.status_code == 400 - assert r.json()["code"] == "MICROVM_RUN_PAYLOAD_INVALID" - assert seam_guard["violations"] == [] - assert seam_guard["install_phase_done"] is False - # The reason still reaches an operator: stdout here, and the response body - # (which the MicroVM service surfaces) in every case. - assert "[server/run-pre-config] /run hook rejected:" in capfd.readouterr().out - - def test_a_failed_payload_fetch_is_reported_without_touching_a_seam( - self, client, monkeypatch, seam_guard, capfd - ): - def boom(_uri): - raise RuntimeError("AccessDenied") - - monkeypatch.setattr(server, "_fetch_microvm_payload_from_s3", boom) - monkeypatch.setattr(server, "run_task", MagicMock()) - - r = client.post(RUN_HOOK, json=_run_hook_body({"agent_payload_s3_uri": "s3://b/k"})) - - assert r.status_code == 500 - assert r.json()["code"] == "MICROVM_RUN_PAYLOAD_UNREADABLE" - assert seam_guard["violations"] == [] - out = capfd.readouterr().out - assert "[server/run-pre-config] /run hook payload fetch FAILED" in out - # The traceback is preserved on the stdout line (it is the only diagnostic - # the response body does not carry). - assert "Traceback" in out - - @pytest.mark.parametrize( - "config,expected_code", - [ - ({"ld_preload": "/tmp/evil.so"}, "MICROVM_RUN_PLATFORM_CONFIG_INVALID"), - ({"log_group_name": "lg"}, "MICROVM_RUN_PLATFORM_CONFIG_INCOMPLETE"), - ], - ) - def test_a_rejected_platform_config_touches_no_seam( - self, client, monkeypatch, env_guard, seam_guard, config, expected_code - ): - monkeypatch.setattr(server, "run_task", MagicMock()) - - r = client.post( - RUN_HOOK, - json=_run_hook_body({"agent_payload": self._payload(), "platform_config": config}), - ) - - assert r.status_code == 400 - assert r.json()["code"] == expected_code - # Nothing was installed, so nothing earned the right to an AWS call. - assert seam_guard["violations"] == [] - assert seam_guard["install_phase_done"] is False - - def test_the_accepted_line_correlates_task_and_microvm_ids( - self, client, monkeypatch, env_guard, capfd - ): - # The pre-install "received" line is stdout-only now, so the first line that - # reaches the task's log group has to join both ids by itself. - monkeypatch.setattr(server, "run_task", MagicMock()) - monkeypatch.setattr(server.task_state, "write_terminal", MagicMock()) - - client.post( - RUN_HOOK, - json=_run_hook_body( - {"agent_payload": self._payload(), "platform_config": _platform_config()}, - microvm_id="microvm-joined", - ), - ) - - out = capfd.readouterr().out - assert "/run hook accepted task_id='t-silent' microvm_id='microvm-joined'" in out - - class TestTerminateHookBodyTolerance: """``/terminate`` must answer 200 for ANY body — that is why it takes the raw request. diff --git a/cdk/src/constructs/ecs-agent-cluster.ts b/cdk/src/constructs/ecs-agent-cluster.ts index db5251857..135f1b4a8 100644 --- a/cdk/src/constructs/ecs-agent-cluster.ts +++ b/cdk/src/constructs/ecs-agent-cluster.ts @@ -39,6 +39,7 @@ import { resolveBedrockModelIds, } from './bedrock-models'; import { LinearIdentityVault } from './linear-identity-vault'; +import { grantWorkerBootstrap } from './payload-bootstrap-permissions'; import { buildAppId } from './solution-ua-aspect'; import { ToolGateway } from './tool-gateway'; @@ -71,14 +72,12 @@ export interface EcsAgentClusterProps { readonly taskSizing?: EcsTaskSizing; /** - * S3 bucket holding per-task ECS payloads. The orchestrator writes the - * payload (incl. the large hydrated_context, which can't fit in the 8 KB - * RunTask containerOverrides limit) here and passes only an - * `AGENT_PAYLOAD_S3_URI` pointer; the container fetches it on boot. The task - * role gets **read-only** on this bucket — the container runs untrusted repo - * code, so it must not be able to delete payloads (the trusted orchestrator - * owns write + delete). When omitted (isolated construct tests / deployments - * that still pass the payload inline), no grant or env var is added. + * S3 storage for deployment manifests, task payloads and private launch + * references. The v2 coordinator sends AGENT_PAYLOAD_REF, containing a + * single-object signed download URL. The task role can read only bootstrap/*; + * object reads elsewhere and bucket listing are explicitly denied. The + * coordinator owns writes and cleanup. Optional for isolated construct tests; + * production ECS launches require this bucket and a matching v2 image. */ readonly payloadBucket?: s3.IBucket; @@ -446,9 +445,8 @@ export class EcsAgentCluster extends Construct { LOG_GROUP_NAME: logGroup.logGroupName, GITHUB_TOKEN_SECRET_ARN: props.githubTokenSecret.secretArn, ...(props.memoryId && { MEMORY_ID: props.memoryId }), - // The payload bucket name so the orchestrator-issued AGENT_PAYLOAD_S3_URI - // can be fetched. (The orchestrator sets the URI per-task via container - // override; this is set here for parity with the runtime env.) + // Deployment metadata; the per-task AGENT_PAYLOAD_REF supplies the + // manifest URI and signed payload URL. IAM authenticates the manifest. ...(props.payloadBucket && { ECS_PAYLOAD_BUCKET: props.payloadBucket.bucketName }), // Artifact workflows (planning/analysis) deliver their document to // this bucket. The AgentCore runtime has ARTIFACTS_BUCKET_NAME; the ECS task @@ -604,13 +602,11 @@ export class EcsAgentCluster extends Construct { // agent assumes the SessionRole — stays on the task role). props.githubTokenSecret.grantRead(taskRole); - // Read-only on the ECS payload bucket so the container can fetch its payload - // (AGENT_PAYLOAD_S3_URI) at boot. READ only — the container runs untrusted - // repo code, so it must not be able to write or delete payloads (the trusted - // orchestrator owns write + delete). Stays on the task role (read once at - // startup, before the agent assumes any SessionRole). + // Only deployment manifests use worker credentials. The boot helper reads + // its exact task object through a signed URL and removes that capability + // from the environment before starting repository code. if (props.payloadBucket) { - props.payloadBucket.grantRead(taskRole); + grantWorkerBootstrap(props.payloadBucket, taskRole); } // Artifact workflows (planning/analysis) deliver their document to the @@ -743,7 +739,7 @@ export class EcsAgentCluster extends Construct { const taskRoleIam5 = [ { id: 'AwsSolutions-IAM5', - reason: 'DynamoDB index/* wildcards from CDK grantReadWriteData (UserConcurrencyTable, and task tables only when no SessionRole is wired); Secrets Manager wildcards from CDK grantRead (GitHub token) and the bgagent-linear-oauth-*/bgagent-jira-oauth-* prefix grant (ABCA-488 — per-workspace channel OAuth tokens are created by the CLI at setup, name unknown at synth, GetSecretValue only); CloudWatch Logs wildcards from CDK grantWrite; S3 object/* wildcard from CDK grantRead on the ECS payload bucket (read-only, scoped to that bucket — #502). Bedrock InvokeModel is scoped to explicit model/inference-profile ARNs (no wildcard resource). ec2:DescribeAvailabilityZones requires Resource:* (EC2 describe actions have no resource-level scoping) — read-only, no mutation/data access; needed so a CDK target repo\'s `cdk synth` build gate can resolve AZ context on a fresh clone (ECS-parity, no cdk.context.json cache in the container).', + reason: 'DynamoDB index/* wildcards from CDK grantReadWriteData (UserConcurrencyTable, and task tables only when no SessionRole is wired); Secrets Manager wildcards from CDK grantRead (GitHub token) and the bgagent-linear-oauth-*/bgagent-jira-oauth-* prefix grant (ABCA-488 — per-workspace channel OAuth tokens are created by the CLI at setup, name unknown at synth, GetSecretValue only); CloudWatch Logs wildcards from CDK grantWrite; Worker S3 GetObject is restricted to bootstrap/*; other object reads and payload-bucket listing are explicitly denied (#700). Bedrock InvokeModel is scoped to explicit model/inference-profile ARNs (no wildcard resource). ec2:DescribeAvailabilityZones requires Resource:* (EC2 describe actions have no resource-level scoping) — read-only, no mutation/data access; needed so a CDK target repo\'s `cdk synth` build gate can resolve AZ context on a fresh clone (ECS-parity, no cdk.context.json cache in the container).', }, ]; NagSuppressions.addResourceSuppressions(taskRole, [ diff --git a/cdk/src/constructs/ecs-payload-bucket.ts b/cdk/src/constructs/ecs-payload-bucket.ts index 87dc47553..4c1b07402 100644 --- a/cdk/src/constructs/ecs-payload-bucket.ts +++ b/cdk/src/constructs/ecs-payload-bucket.ts @@ -55,24 +55,17 @@ export interface EcsPayloadBucketProps { } /** - * S3 bucket for ECS task payloads (#502). + * Storage for ECS v2 bootstrap manifests, task payloads and private references. * - * The ECS compute strategy cannot pass the orchestrator payload (repo URL, - * prompt, and the large ``hydrated_context``) inline: a Fargate ``RunTask`` - * caps the entire ``containerOverrides`` blob at 8192 bytes, and the hydrated - * context routinely exceeds that, so the call is rejected with - * ``InvalidParameterException``. (AgentCore is unaffected — it passes the - * payload in the ``InvokeAgentRuntime`` request body, which has no comparable - * limit.) Instead, the orchestrator writes the payload to - * ``s3:////payload.json`` and passes only a small - * ``AGENT_PAYLOAD_S3_URI`` pointer in the override; the container fetches and - * parses it on boot. + * RunTask caps the entire overrides object at 8192 bytes. The coordinator + * writes task instructions to /payload.json and passes AGENT_PAYLOAD_REF, + * containing an authenticated-manifest URI and a signed one-object URL. + * EcsAgentCluster grants the worker only bootstrap/* reads and explicitly denies + * other object reads/listing. The coordinator owns writes, signing and cleanup. * - * Dedicated (not co-tenant with attachments/traces) so the boundary is - * structural: the ECS task role gets S3 **read** here and nowhere else, the - * attachments feature can never collide with payload keys, and the tight - * 1-day TTL is whole-bucket rather than a prefix-scoped rule grafted onto a - * shared bucket. + * A dedicated bucket separates boot data from attachments/traces and gives it + * a one-day lifecycle backstop. Finalize deletes payload.json and launch.json; + * shared deployment manifests expire through the lifecycle rule. * * Security / hygiene (parity with TraceArtifactsBucket): * - ``blockPublicAccess: BLOCK_ALL`` + ``enforceSSL: true`` — no public read, diff --git a/cdk/src/constructs/lambda-microvm-compute.ts b/cdk/src/constructs/lambda-microvm-compute.ts index d7f3ec041..c90353def 100644 --- a/cdk/src/constructs/lambda-microvm-compute.ts +++ b/cdk/src/constructs/lambda-microvm-compute.ts @@ -33,6 +33,7 @@ import { LAMBDA_MICROVM_SUPPORTED_REGIONS, isLambdaMicrovmRegionSupported } from import { AgentMemory } from './agent-memory'; import { AgentSessionRole } from './agent-session-role'; import { inferenceProfileId, resolveBedrockGeoRegion, resolveBedrockModelIds } from './bedrock-models'; +import { grantWorkerBootstrap } from './payload-bootstrap-permissions'; /** * Fallback expiry for /run payloads and private launch references. Finalization @@ -400,7 +401,7 @@ export class LambdaMicrovmCompute extends Construct { /** Unsuffixed key used by the manual builder and packaging helper. */ public readonly artifactBaseObjectKey: string; - /** S3 bucket holding oversized `/run` payloads (S3-pointer delivery). */ + /** S3 bucket holding bootstrap manifests, task payloads and private launch references. */ public readonly payloadBucket: s3.Bucket; /** Role Lambda assumes while building the snapshot image. */ @@ -707,9 +708,10 @@ export class LambdaMicrovmCompute extends Construct { // Platform task logs use a separate namespace from MicroVM service logs. props.applicationLogGroup?.grantWrite(this.executionRole); - // The guest reads its oversized `/run` payload from S3 before any tenant - // identity exists, so the grant is bucket-wide; finalize deletes the object. - this.payloadBucket.grantRead(this.executionRole); + // Authenticate only this deployment's manifests. Payload and launch reads + // using worker credentials are explicitly denied; one-object signed URLs + // carry the coordinator's authorization instead. + grantWorkerBootstrap(this.payloadBucket, this.executionRole); // Tenant access requires the task-scoped role; there is no direct-grant fallback. if (props.agentSessionRole) { @@ -926,9 +928,9 @@ export class LambdaMicrovmCompute extends Construct { reason: 'Artifact bucket holds versioned agent zip+Dockerfile build inputs read only by ' + 'the Lambda MicroVMs build role; the payload bucket holds ephemeral per-task /run payloads ' + `with a ${MICROVM_PAYLOAD_TTL_DAYS}-day TTL, written only by the orchestrator and ` - + 'read only by the MicroVM execution role, both scoped to the bucket. Object-level access ' - + 'logging (a second log bucket + CloudTrail data events) is not justified for these ' - + 'build inputs or for transient boot payloads.', + + 'read through single-object signed URLs; the worker reads only bootstrap manifests. Object-level access ' + + 'logging (a second log bucket + CloudTrail data events) is not justified for a single ' + + 'build input or for transient boot payloads.', }, ], true); @@ -937,8 +939,8 @@ export class LambdaMicrovmCompute extends Construct { id: 'AwsSolutions-IAM5', reason: 'CloudWatch Logs wildcard is the service-owned ' + `${MICROVM_LOG_GROUP_PREFIX}/* namespace (log stream names are minted per MicroVM, so no ` - + 'synth-time ARN exists); S3 object/* wildcard comes from CDK grantRead on the dedicated ' - + 'payload bucket (read-only, scoped to that bucket — ADR-021 sub-decision 3). The build ' + + 'synth-time ARN exists); worker S3 GetObject is limited to bootstrap/* in its payload bucket, ' + + 'with explicit denial outside that prefix and for bucket listing. The build ' + 'role\'s s3:GetObject names the selected artifact and manual-build key. On the execution ' + 'role (ADR-021 P2 runtime parity, mirroring the ECS task role): the second Logs grant is ' + 'CDK grantWrite (CreateLogStream + PutLogEvents only) on the SINGLE platform ' diff --git a/cdk/src/constructs/payload-bootstrap-permissions.ts b/cdk/src/constructs/payload-bootstrap-permissions.ts new file mode 100644 index 000000000..c6f215c0e --- /dev/null +++ b/cdk/src/constructs/payload-bootstrap-permissions.ts @@ -0,0 +1,67 @@ +/** + * MIT No Attribution + * + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +import * as iam from 'aws-cdk-lib/aws-iam'; +import * as s3 from 'aws-cdk-lib/aws-s3'; +import constants from '../../../contracts/constants.json'; + +/** Authenticate deployment settings with IAM; task payloads require a one-object capability. */ +export function grantWorkerBootstrap(bucket: s3.IBucket, worker: iam.IGrantable): void { + const manifests = bucket.arnForObjects(`${constants.payload_bootstrap.manifest_prefix}*`); + worker.grantPrincipal.addToPrincipalPolicy(new iam.PolicyStatement({ + actions: ['s3:GetObject'], + resources: [manifests], + })); + // An Allow alone is not an authentication boundary: another bucket could + // publicly grant access to an attacker's fake deployment manifest. + worker.grantPrincipal.addToPrincipalPolicy(new iam.PolicyStatement({ + effect: iam.Effect.DENY, + actions: ['s3:GetObject*'], + notResources: [manifests], + })); + worker.grantPrincipal.addToPrincipalPolicy(new iam.PolicyStatement({ + effect: iam.Effect.DENY, + actions: ['s3:List*'], + resources: [bucket.bucketArn], + })); +} + +export function grantCoordinatorPayloads(bucket: s3.IBucket, coordinator: iam.IGrantable): void { + // S3 returns AccessDenied rather than NoSuchKey for an absent launch record + // without ListBucket. Only the trusted coordinator needs this permission. + coordinator.grantPrincipal.addToPrincipalPolicy(new iam.PolicyStatement({ + actions: ['s3:ListBucket'], + resources: [bucket.bucketArn], + })); + const taskObjects = [ + bucket.arnForObjects('*/payload.json'), + bucket.arnForObjects(`*/${constants.payload_bootstrap.launch_filename}`), + ]; + coordinator.grantPrincipal.addToPrincipalPolicy(new iam.PolicyStatement({ + actions: ['s3:PutObject'], + resources: [ + ...taskObjects, + bucket.arnForObjects(`${constants.payload_bootstrap.manifest_prefix}*`), + ], + })); + coordinator.grantPrincipal.addToPrincipalPolicy(new iam.PolicyStatement({ + actions: ['s3:GetObject', 's3:DeleteObject'], + resources: taskObjects, + })); +} diff --git a/cdk/src/constructs/task-orchestrator.ts b/cdk/src/constructs/task-orchestrator.ts index f0b4f6d2d..0f02942b8 100644 --- a/cdk/src/constructs/task-orchestrator.ts +++ b/cdk/src/constructs/task-orchestrator.ts @@ -52,6 +52,8 @@ const ORCHESTRATOR_TIMEOUT_SECONDS = 60; /** Orchestrator Lambda memory (MB). */ const ORCHESTRATOR_MEMORY_MB = 1024; +import { grantCoordinatorPayloads } from './payload-bootstrap-permissions'; + /** * Properties for TaskOrchestrator construct. */ @@ -566,22 +568,10 @@ export class TaskOrchestrator extends Construct { props.attachmentsBucket.grantReadWrite(this.fn); } - // ECS payload bucket (#502): the orchestrator writes the payload before - // RunTask and deletes it at finalize. Write + delete only (it never reads - // its own payload back; the ECS container is the reader, with its own - // read-only grant from EcsAgentCluster). - if (props.ecsPayloadBucket) { - props.ecsPayloadBucket.grantPut(this.fn); - props.ecsPayloadBucket.grantDelete(this.fn); - } - - // ADR-021: MicroVM payload bucket. The strategy uploads an oversized /run - // payload and deletes it at finalize (`deleteMicrovmPayload`); it never - // reads it back — the MicroVM execution role is the reader. - if (props.microvmConfig) { - props.microvmConfig.payloadBucket.grantPut(this.fn); - props.microvmConfig.payloadBucket.grantDelete(this.fn); - } + // Publish manifests/payloads, sign one-object reads and persist private + // launch references for replay. Workers cannot read the launch records. + if (props.ecsPayloadBucket) grantCoordinatorPayloads(props.ecsPayloadBucket, this.fn); + if (props.microvmConfig) grantCoordinatorPayloads(props.microvmConfig.payloadBucket, this.fn); // Durable execution managed policy this.fn.role!.addManagedPolicy( diff --git a/cdk/src/handlers/shared/payload-bootstrap.ts b/cdk/src/handlers/shared/payload-bootstrap.ts new file mode 100644 index 000000000..0105ac225 --- /dev/null +++ b/cdk/src/handlers/shared/payload-bootstrap.ts @@ -0,0 +1,183 @@ +/** + * MIT No Attribution + * + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +import { createHash } from 'node:crypto'; +import { DeleteObjectCommand, GetObjectCommand, PutObjectCommand, S3Client } from '@aws-sdk/client-s3'; +import { getSignedUrl } from '@aws-sdk/s3-request-presigner'; +import constants from '../../../../contracts/constants.json'; +import { logger } from './logger'; +import { makeClient } from './ua'; + +export const PAYLOAD_BOOTSTRAP = constants.payload_bootstrap; +type Backend = 'ecs' | 'lambda-microvm'; + +export interface PayloadReference { + version: number; + task_id: string; + bootstrap_s3_uri: string; + payload_url: string; + expires_at: number; +} + +interface LaunchRecord { + fingerprint: string; + reference: PayloadReference; +} + +let client: S3Client | undefined; +function s3(): S3Client { + return client ??= makeClient(S3Client); +} + +function canonical(value: unknown): string { + return JSON.stringify(value, (_key, item: unknown) => + item && typeof item === 'object' && !Array.isArray(item) + ? Object.fromEntries(Object.entries(item).sort(([a], [b]) => a.localeCompare(b))) + : item); +} + +function sha256(value: string): string { + return createHash('sha256').update(value).digest('hex'); +} + +/** Never let SDK errors echo bearer URLs into task records or logs. */ +export function redactPayloadUrls(message: string): string { + return message.replace(/https?:\/\/[^\s"'<>\\]+/gi, url => + /X-Amz-/i.test(url) ? '[redacted payload URL]' : url); +} + +async function readObject(bucket: string, key: string): Promise { + try { + const response = await s3().send(new GetObjectCommand({ Bucket: bucket, Key: key })); + if (!response.Body) throw new Error('PAYLOAD_BOOTSTRAP_UNREADABLE: empty object response'); + return await response.Body.transformToString(); + } catch (error) { + if ((error as { name?: string }).name === 'NoSuchKey') return undefined; + throw error; + } +} + +/** Conditional creation, including recovery after a committed write loses its reply. */ +async function createOnce(bucket: string, key: string, body: string): Promise { + try { + await s3().send(new PutObjectCommand({ + Bucket: bucket, Key: key, Body: body, ContentType: 'application/json', IfNoneMatch: '*', + })); + return body; + } catch (error) { + const saved = await readObject(bucket, key); + if (saved !== undefined) return saved; + throw error; + } +} + +/** + * Save a single-object capability outside the agent-readable task table. + * Replays read the same launch.json; re-signing would change Run's request + * while reusing its clientToken. The worker can read only bootstrap/* using + * its own credentials, never payload.json or launch.json. + */ +export async function preparePayloadReference(input: { + bucket: string; + taskId: string; + backend: Backend; + payload: Record; + platformConfig?: Record; +}): Promise { + const { bucket, taskId, backend, payload } = input; + if (!/^[A-Za-z0-9_-]{1,128}$/.test(taskId) || payload.task_id !== taskId) { + throw new Error('PAYLOAD_BOOTSTRAP_INVALID: task identity does not match the payload'); + } + const manifest = canonical({ + version: PAYLOAD_BOOTSTRAP.version, backend, platform_config: input.platformConfig ?? {}, + }); + const manifestKey = `${PAYLOAD_BOOTSTRAP.manifest_prefix}${sha256(manifest)}.json`; + const payloadBody = canonical({ + version: PAYLOAD_BOOTSTRAP.version, + task_id: taskId, + agent_payload: payload, + platform_config: input.platformConfig ?? {}, + }); + if (Buffer.byteLength(manifest) > PAYLOAD_BOOTSTRAP.max_manifest_bytes + || Buffer.byteLength(payloadBody) > PAYLOAD_BOOTSTRAP.max_payload_bytes) { + throw new Error('PAYLOAD_BOOTSTRAP_TOO_LARGE: bootstrap manifest or task payload exceeds its byte limit'); + } + const fingerprint = sha256(canonical({ bucket, backend, manifest, payloadBody })); + const launchKey = `${taskId}/${PAYLOAD_BOOTSTRAP.launch_filename}`; + const accept = (saved: string): PayloadReference => { + const record = JSON.parse(saved) as LaunchRecord; + if (record.fingerprint !== fingerprint || record.reference?.task_id !== taskId) { + throw new Error('PAYLOAD_BOOTSTRAP_CONFLICT: task already has different launch instructions'); + } + if (record.reference.expires_at <= Date.now()) { + throw new Error('PAYLOAD_BOOTSTRAP_EXPIRED: inspect the existing launch; do not start a replacement task'); + } + return record.reference; + }; + + // Refresh only identical, public deployment settings so bucket lifecycle + // expiry cannot reap an old manifest just as a new task starts using it. + await s3().send(new PutObjectCommand({ + Bucket: bucket, Key: manifestKey, Body: manifest, ContentType: 'application/json', + })); + const existing = await readObject(bucket, launchKey); + if (existing !== undefined) return accept(existing); + + const payloadKey = `${taskId}/payload.json`; + const savedPayload = await createOnce(bucket, payloadKey, payloadBody); + if (savedPayload !== payloadBody) { + throw new Error('PAYLOAD_BOOTSTRAP_CONFLICT: task already has different stored instructions'); + } + const now = Date.now(); + const credentials = await s3().config.credentials(); + const lifetime = Math.min( + PAYLOAD_BOOTSTRAP.url_ttl_seconds, + credentials.expiration + ? Math.floor((credentials.expiration.getTime() - now) / 1000) + : PAYLOAD_BOOTSTRAP.url_ttl_seconds, + ); + if (lifetime < PAYLOAD_BOOTSTRAP.minimum_url_lifetime_seconds) { + throw new Error('PAYLOAD_BOOTSTRAP_CREDENTIALS_EXPIRING: refresh coordinator credentials before launch'); + } + const url = await getSignedUrl(s3(), new GetObjectCommand({ + Bucket: bucket, Key: payloadKey, + }), { expiresIn: lifetime }); + const reference: PayloadReference = { + version: PAYLOAD_BOOTSTRAP.version, + task_id: taskId, + bootstrap_s3_uri: `s3://${bucket}/${manifestKey}`, + payload_url: url, + expires_at: now + lifetime * 1000, + }; + const record = canonical({ fingerprint, reference }); + return accept(await createOnce(bucket, launchKey, record)); +} + +/** Delete both task instructions and their saved capability; shared manifests expire by lifecycle. */ +export async function deletePayloadReference(bucket: string, taskId: string): Promise { + for (const filename of ['payload.json', PAYLOAD_BOOTSTRAP.launch_filename]) { + try { + await s3().send(new DeleteObjectCommand({ Bucket: bucket, Key: `${taskId}/${filename}` })); + } catch (error) { + logger.warn('Payload bootstrap cleanup failed (non-fatal)', { + task_id: taskId, filename, error: (error as { name?: string }).name ?? 'UnknownError', + }); + } + } +} diff --git a/cdk/src/handlers/shared/strategies/ecs-strategy.ts b/cdk/src/handlers/shared/strategies/ecs-strategy.ts index 02da21ee2..a9653dfe2 100644 --- a/cdk/src/handlers/shared/strategies/ecs-strategy.ts +++ b/cdk/src/handlers/shared/strategies/ecs-strategy.ts @@ -18,9 +18,9 @@ */ import { ECSClient, RunTaskCommand, DescribeTasksCommand, StopTaskCommand } from '@aws-sdk/client-ecs'; -import { S3Client, PutObjectCommand, DeleteObjectCommand } from '@aws-sdk/client-s3'; import type { ComputeStrategy, SessionControlOptions, SessionHandle, SessionLifecycleResult, SessionStatus } from '../compute-strategy'; import { logger } from '../logger'; +import { deletePayloadReference, preparePayloadReference, redactPayloadUrls } from '../payload-bootstrap'; import type { BlueprintConfig } from '../repo-config'; import { makeClient } from '../ua'; import { DEFAULT_MAX_TURNS } from '../validation'; @@ -33,14 +33,6 @@ function getClient(): ECSClient { return sharedClient; } -let sharedS3Client: S3Client | undefined; -function getS3Client(): S3Client { - if (!sharedS3Client) { - sharedS3Client = makeClient(S3Client); - } - return sharedS3Client; -} - const ECS_CLUSTER_ARN = process.env.ECS_CLUSTER_ARN; const ECS_TASK_DEFINITION_ARN = process.env.ECS_TASK_DEFINITION_ARN; /** @@ -79,45 +71,23 @@ function toTaskDefinitionFamily(ref: string): string { const ECS_SECURITY_GROUP = process.env.ECS_SECURITY_GROUP; const ECS_CONTAINER_NAME = process.env.ECS_CONTAINER_NAME ?? 'AgentContainer'; const ECS_PAYLOAD_BUCKET = process.env.ECS_PAYLOAD_BUCKET; +const ECS_OVERRIDES_LIMIT_BYTES = 8192; -/** - * Inline-payload size (bytes) above which we warn that RunTask will likely - * reject the call when no payload bucket is configured. ECS caps the TOTAL - * containerOverrides blob at 8192 bytes; the other env vars + command consume - * some of that, so 6 KB of payload is the practical danger line. - */ -const INLINE_PAYLOAD_WARN_BYTES = 6144; - -/** - * S3 object key for a task's ECS payload. One object per task under its own - * task-id prefix; deleted by the orchestrator at finalize (see - * ``deleteEcsPayload``), with the bucket's 1-day lifecycle rule as a backstop. - */ -function ecsPayloadKey(taskId: string): string { - return `${taskId}/payload.json`; +function safeLaunchError(error: unknown): Error { + const safe = new Error(redactPayloadUrls(error instanceof Error ? error.message : String(error))); + safe.name = error instanceof Error ? error.name : 'Error'; + return safe; } /** - * Delete a task's ECS payload object. Best-effort: a failed delete must never + * Delete a task's ECS payload and private launch reference. A failed delete must never * fail the task — the bucket's 1-day lifecycle rule reaps it regardless. Called * from the orchestrator's ``finalize`` step once the task is terminal. No-ops * when the payload bucket isn't configured (AgentCore-only deployments). */ export async function deleteEcsPayload(taskId: string): Promise { if (!ECS_PAYLOAD_BUCKET) return; - try { - await getS3Client().send(new DeleteObjectCommand({ - Bucket: ECS_PAYLOAD_BUCKET, - Key: ecsPayloadKey(taskId), - })); - logger.info('Deleted ECS payload object', { task_id: taskId }); - } catch (err) { - // Non-fatal — the lifecycle rule is the backstop. - logger.warn('Failed to delete ECS payload object (non-fatal)', { - task_id: taskId, - error: err instanceof Error ? err.message : String(err), - }); - } + await deletePayloadReference(ECS_PAYLOAD_BUCKET, taskId); } export class EcsComputeStrategy implements ComputeStrategy { @@ -180,43 +150,18 @@ export class EcsComputeStrategy implements ComputeStrategy { // that request. We override the container command to invoke run_task() // directly with the full orchestrator payload (including hydrated_context). // This avoids the server entirely and runs the agent in batch mode. - const payloadJson = JSON.stringify(payload); - - // The payload (especially hydrated_context) routinely exceeds the 8192-byte - // cap that ECS RunTask enforces on the TOTAL containerOverrides blob, which - // rejected the call with InvalidParameterException. Write the payload to S3 - // and pass only a small pointer (AGENT_PAYLOAD_S3_URI); the container fetches - // it on boot. The inline AGENT_PAYLOAD remains as a fallback for small - // payloads / deployments without a payload bucket configured. - let payloadS3Uri: string | undefined; - if (ECS_PAYLOAD_BUCKET) { - const key = ecsPayloadKey(taskId); - await getS3Client().send(new PutObjectCommand({ - Bucket: ECS_PAYLOAD_BUCKET, - Key: key, - Body: payloadJson, - ContentType: 'application/json', - })); - payloadS3Uri = `s3://${ECS_PAYLOAD_BUCKET}/${key}`; - logger.info('Wrote ECS payload to S3', { - task_id: taskId, - bytes: payloadJson.length, - uri: payloadS3Uri, - }); - } else if (payloadJson.length > INLINE_PAYLOAD_WARN_BYTES) { - // No bucket configured AND the payload is large enough that the inline - // path will almost certainly blow the 8192-byte overrides cap. Surface a - // clear cause rather than a raw InvalidParameterException from RunTask. - logger.warn('ECS payload is large but ECS_PAYLOAD_BUCKET is not set — RunTask may reject it (see #502)', { - task_id: taskId, - bytes: payloadJson.length, - }); + if (!ECS_PAYLOAD_BUCKET) { + throw new Error('PAYLOAD_BOOTSTRAP_INVALID: ECS_PAYLOAD_BUCKET is required; deploy matching infrastructure'); } + const reference = await preparePayloadReference({ + bucket: ECS_PAYLOAD_BUCKET, taskId, backend: 'ecs', payload, + }).catch((error: unknown) => { + throw safeLaunchError(error); + }); const containerEnv = [ { name: 'TASK_ID', value: taskId }, { name: 'REPO_URL', value: String(payload.repo_url ?? '') }, - ...(payload.prompt ? [{ name: 'TASK_DESCRIPTION', value: String(payload.prompt) }] : []), ...(payload.issue_number ? [{ name: 'ISSUE_NUMBER', value: String(payload.issue_number) }] : []), // Single source of truth with the hydrate path in `orchestrator.ts`, which // resolves the same default via `DEFAULT_MAX_TURNS`. A literal here would @@ -227,47 +172,34 @@ export class EcsComputeStrategy implements ComputeStrategy { ...(blueprintConfig.model_id ? [{ name: 'ANTHROPIC_MODEL', value: blueprintConfig.model_id }] : []), ...(blueprintConfig.system_prompt_overrides ? [{ name: 'SYSTEM_PROMPT_OVERRIDES', value: blueprintConfig.system_prompt_overrides }] : []), { name: 'CLAUDE_CODE_USE_BEDROCK', value: '1' }, - // Prefer the S3 pointer; fall back to the inline payload when no bucket is - // configured (keeps small-payload / AgentCore-only deployments working with - // no behavior change). - ...(payloadS3Uri - ? [{ name: 'AGENT_PAYLOAD_S3_URI', value: payloadS3Uri }] - : [{ name: 'AGENT_PAYLOAD', value: payloadJson }]), + { name: 'AGENT_PAYLOAD_REF', value: JSON.stringify(reference) }, ...(payload.github_token_secret_arn ? [{ name: 'GITHUB_TOKEN_SECRET_ARN', value: String(payload.github_token_secret_arn) }] : []), ...(payload.memory_id ? [{ name: 'MEMORY_ID', value: String(payload.memory_id) }] : []), ]; - // Override the container command to run a Python one-liner that: - // 1. Loads the payload — from S3 (AGENT_PAYLOAD_S3_URI) when set, else the - // inline AGENT_PAYLOAD env var (fallback). - // 2. Calls entrypoint.run_task_from_payload(p), which maps the WHOLE payload - // dict to run_task's signature (rename prompt→task_description / - // model_id→anthropic_model, filter to accepted params, coerce str/int). - // This replaces an older hand-listed kwarg subset that silently dropped - // fields such as channel_source/channel_metadata (which meant no - // Linear/Jira reactions or channel MCP on ECS), build_command, - // cedar_policies, base_branch/merge_branches, attachments, trace, user_id, - // etc. Single source of truth in the agent, unit-tested (see - // test_run_task_from_payload). - // 3. Exits with code 0 on success, 1 on failure. - // This bypasses the uvicorn server entirely — no HTTP, no OTEL noise. + // Consume the one-object capability before importing/running the pipeline. + // The helper removes it from os.environ so repo subprocesses do not inherit it. const bootCommand = [ 'python', '-c', - 'import json, os, sys; ' - + 'sys.path.insert(0, "/app/src"); ' + 'import sys; sys.path.insert(0, "/app/src"); ' + + 'from payload_bootstrap import load_ecs_payload; p = load_ecs_payload(); ' + 'from entrypoint import run_task_from_payload; ' - + '_uri = os.environ.get("AGENT_PAYLOAD_S3_URI"); ' - + 'p = (' - + 'json.loads(__import__("boto3").client("s3").get_object(' - + 'Bucket=_uri.split("/",3)[2], Key=_uri.split("/",3)[3])["Body"].read()) ' - + 'if _uri else json.loads(os.environ["AGENT_PAYLOAD"])' - + '); ' + 'r = run_task_from_payload(p); ' + 'sys.exit(0 if r.get("status")=="success" else 1)', ]; + const overrides = { + containerOverrides: [{ + name: ECS_CONTAINER_NAME, + environment: containerEnv, + command: bootCommand, + }], + }; + if (Buffer.byteLength(JSON.stringify(overrides), 'utf8') > ECS_OVERRIDES_LIMIT_BYTES) { + throw new Error('PAYLOAD_BOOTSTRAP_TOO_LARGE: ECS container overrides exceed 8192 bytes'); + } const command = new RunTaskCommand({ cluster: ECS_CLUSTER_ARN, taskDefinition, @@ -288,21 +220,17 @@ export class EcsComputeStrategy implements ComputeStrategy { assignPublicIp: 'DISABLED', }, }, - overrides: { - containerOverrides: [{ - name: ECS_CONTAINER_NAME, - environment: containerEnv, - command: bootCommand, - }], - }, + overrides, }); - const result = await getClient().send(command); + const result = await getClient().send(command).catch((error: unknown) => { + throw safeLaunchError(error); + }); const ecsTask = result.tasks?.[0]; if (!ecsTask?.taskArn) { const failures = result.failures?.map(f => `${f.arn}: ${f.reason}`).join('; ') ?? 'unknown'; - throw new Error(`ECS RunTask returned no task: ${failures}`); + throw new Error(`ECS RunTask returned no task: ${redactPayloadUrls(failures)}`); } logger.info('ECS Fargate task started', { diff --git a/cdk/src/handlers/shared/strategies/lambda-microvm-strategy.ts b/cdk/src/handlers/shared/strategies/lambda-microvm-strategy.ts index b6ce0f5d4..537cbac79 100644 --- a/cdk/src/handlers/shared/strategies/lambda-microvm-strategy.ts +++ b/cdk/src/handlers/shared/strategies/lambda-microvm-strategy.ts @@ -27,7 +27,6 @@ import { SuspendMicrovmCommand, ResumeMicrovmCommand, } from '@aws-sdk/client-lambda-microvms'; -import { DeleteObjectCommand, PutObjectCommand, S3Client } from '@aws-sdk/client-s3'; // Cross-language contract (S9): `microvm_platform_config` is read by BOTH this // producer and `agent/src/server.py`'s `/run` consumer. Imported (not copied) so // `tsc` fails on a renamed field — see `contracts/constants.md`. @@ -41,17 +40,10 @@ import { readMicrovmImageMetadata, verifyMicrovmImageLifecycle, } from '../microvm/image-capability'; import { claimMicrovmStart, microvmStartRequestHash, saveMicrovmStartHandle, saveMicrovmImageCapability } from '../microvm/start'; +import { deletePayloadReference, preparePayloadReference, redactPayloadUrls } from '../payload-bootstrap'; import type { BlueprintConfig } from '../repo-config'; import { makeClient } from '../ua'; -let sharedS3Client: S3Client | undefined; -function getS3Client(): S3Client { - if (!sharedS3Client) { - sharedS3Client = makeClient(S3Client); - } - return sharedS3Client; -} - let sharedClient: LambdaMicrovmsClient | undefined; function getClient(): LambdaMicrovmsClient { if (!sharedClient) { @@ -359,8 +351,10 @@ export const MICROVM_ERROR_MARKER = 'MicroVM'; * marker first, which is the order the classifier patterns document. */ function wrapMicrovmError(operation: string, err: unknown): Error { - const name = err instanceof Error ? err.name : undefined; - const message = err instanceof Error ? err.message : String(err); + // SDK errors and their nested causes can contain signed payload URLs, so both + // the message and the retained cause are redacted copies (#1002). + const name = err instanceof Error ? redactPayloadUrls(err.name) : undefined; + const message = redactPayloadUrls(err instanceof Error ? err.message : String(err)); const detail = name && name !== 'Error' && !message.includes(name) ? `${name}: ${message}` : message; @@ -371,70 +365,12 @@ function wrapMicrovmError(operation: string, err: unknown): Error { return new Error(`${MICROVM_ERROR_MARKER} ${operation} failed: ${detail}`, { cause: safeCause }); } -/** - * S3 object key for a task's MicroVM ``/run`` payload. Same key shape as the - * ECS payload bucket (``ecsPayloadKey``): one object per task under its own - * task-id prefix, deleted by the orchestrator at finalize (see - * {@link deleteMicrovmPayload}), with the payload bucket's lifecycle-expiry rule - * (ADR-021 sub-decision 3, ``MICROVM_PAYLOAD_TTL_DAYS``) as the backstop. - */ -export function microvmPayloadKey(taskId: string): string { - return `${taskId}/payload.json`; -} - -/** - * Delete a task's MicroVM ``/run`` payload object. Best-effort: a failed delete - * must never fail the task — the bucket's 1-day lifecycle rule reaps it - * regardless. Called from the orchestrator's ``finalize`` step once the task is - * terminal. No-ops when the payload bucket isn't configured. - * - * WHY this exists rather than leaning on the TTL alone (ECS parity, and a real - * exposure delta): the execution role's payload-bucket grant is - * ``grantRead`` on the WHOLE bucket — it cannot be per-task scoped, because the - * MicroVM has to read its own object before any tenant identity is installed. - * The key shape is ``/payload.json``, so any running MicroVM that knows - * (or guesses) another task's id can read that task's HYDRATED PROMPT — issue - * body, comment thread, repo context. The MicroVM also runs untrusted repo code. - * Relying only on ``MICROVM_PAYLOAD_TTL_DAYS = 1`` left that window open for up - * to ~24 h; deleting at finalize closes it to the task's own lifetime, which is - * exactly the posture ``deleteEcsPayload`` already gives the ECS backend. - * - * ISSUED UNCONDITIONALLY, including for a task whose payload went INLINE (under - * the {@link RUN_HOOK_PAYLOAD_LIMIT_BYTES} cap, so no object was ever written). - * That is on purpose: ``DeleteObject`` on a missing key succeeds, so the call is - * harmless and idempotent, whereas *deciding* to skip it would mean trusting a - * per-task record of the delivery mode — and if that record were ever wrong or - * absent, the skip would leave a real payload behind for the full TTL. Attempting - * always is the fail-safe direction. - * - * The consequence is that a successful call proves a delete was ISSUED, never that - * an object existed — S3 returns nothing that distinguishes the two on an - * unversioned bucket. The log line below says exactly that and no more; an earlier - * "Deleted MicroVM payload object" asserted a deletion that never happened on - * every inline task. +/** Remove task instructions and their saved download capability after finalization. + * Best-effort; bucket lifecycle reaps leftovers. Deployment manifests are shared. */ export async function deleteMicrovmPayload(taskId: string): Promise { if (!MICROVM_PAYLOAD_BUCKET) return; - const key = microvmPayloadKey(taskId); - try { - await getS3Client().send(new DeleteObjectCommand({ - Bucket: MICROVM_PAYLOAD_BUCKET, - Key: key, - })); - // "issued", not "deleted": see the docstring. An inline-delivered task has no - // object here and the call still succeeds. - logger.info('MicroVM payload delete issued', { - task_id: taskId, - bucket: MICROVM_PAYLOAD_BUCKET, - key, - }); - } catch (err) { - // Non-fatal — the lifecycle rule is the backstop. - logger.warn('Failed to delete MicroVM payload object (non-fatal)', { - task_id: taskId, - error: err instanceof Error ? err.message : String(err), - }); - } + await deletePayloadReference(MICROVM_PAYLOAD_BUCKET, taskId); } /** Split a comma-separated env-var list into trimmed, non-empty entries. */ @@ -514,89 +450,28 @@ function assertImageArn(identifier: string): void { * requires compatible image hooks and enabled static/live rollout settings. */ /** - * Deliver the task payload to the `/run` hook (ADR-021 sub-decision 3). The - * `runHookPayload` is capped at 4 KB, so the S3-pointer path (mirroring ECS - * #502) is the dominant one and the inline envelope is the exception: - * { "agent_payload": {...}, "platform_config": {...} } — inline - * { "agent_payload_s3_uri": "…", "platform_config": {...} } — pointer - * `platform_config` rides in both forms and is merged into the S3 object too. - * Runs after the start receipt is claimed, so a replayed start rewrites the same - * object rather than racing another invocation. + * Deliver the task payload to the `/run` hook (ADR-021 sub-decision 3), whose + * request body is capped at 4 KB. Payload bootstrap v2 (#700, #1002): the hook + * body carries only a small, task-scoped launch reference. The worker reads the + * deployment manifest with IAM (no deployment identifiers live in the image + * snapshot) and downloads its own task payload through a short-lived signed + * one-object URL, so it cannot read other tasks' payloads. Runs after the start + * receipt is claimed, so a replayed start rewrites the same objects rather than + * racing another invocation. */ async function deliverRunHookPayload( taskId: string, payload: Record, platformConfig: MicrovmPlatformConfig, ): Promise { - const inlineEnvelope = JSON.stringify({ agent_payload: payload, platform_config: platformConfig }); - // Measure the SERIALIZED envelope, not the bare payload: the envelope is - // what the service counts against the 4 KB cap, and `platform_config` is part - // of it — which is precisely why nearly everything lands on the S3 path. - // Byte length (not String.length) because a multi-byte prompt/diff makes - // chars an undercount. - const inlineBytes = Buffer.byteLength(inlineEnvelope, 'utf8'); - - let runHookPayload: string; - let payloadS3Uri: string | undefined; - // EXACT boundary: `<= limit` inlines, `> limit` uploads. The service accepts - // 4 096 bytes and rejects 4 097 (measured), so 4 096 must still go inline. - if (inlineBytes <= RUN_HOOK_PAYLOAD_LIMIT_BYTES) { - runHookPayload = inlineEnvelope; - } else { - const key = microvmPayloadKey(taskId); - const uri = `s3://${MICROVM_PAYLOAD_BUCKET}/${key}`; - const pointerEnvelope = JSON.stringify({ - agent_payload_s3_uri: uri, - platform_config: platformConfig, - }); - // The pointer envelope is the LAST RESORT — there is no smaller shape to - // fall back to — so check it BEFORE the upload (an upload followed by a - // throw would leave an orphan object for the lifecycle rule to reap) and - // name the one thing an operator can actually act on. Unreachable in - // practice: the pointer plus all thirteen identifiers is well under 4 KB. - const pointerBytes = Buffer.byteLength(pointerEnvelope, 'utf8'); - if (pointerBytes > RUN_HOOK_PAYLOAD_LIMIT_BYTES) { - throw new Error( - `The MicroVM /run pointer envelope is ${pointerBytes} bytes, over the service's ` - + `${RUN_HOOK_PAYLOAD_LIMIT_BYTES}-byte runHookPayload cap, with the payload already moved ` - + 'to S3. The remaining size is the S3 URI plus the platform_config identifiers, so a ' - + 'pathologically long table/bucket/ARN name is the only possible cause — shorten the ' - + 'stack name (physical resource names derive from it) and redeploy.', - ); - } - // The S3 object carries the payload with `platform_config` merged in at the - // top level, so an agent that fetches the object gets the config with it. - // Platform config wins on a key collision — the payload has no - // `platform_config` key today, and if one ever appeared the platform's - // value is the authoritative one. - const payloadJson = JSON.stringify({ ...payload, platform_config: platformConfig }); - try { - await getS3Client().send(new PutObjectCommand({ - Bucket: MICROVM_PAYLOAD_BUCKET, - Key: key, - Body: payloadJson, - ContentType: 'application/json', - })); - } catch (err) { - // Marked so the classifier attributes an upload failure to this backend - // rather than letting a bare S3 exception name fall through to UNKNOWN. - throw wrapMicrovmError('payload upload', err); - } - payloadS3Uri = uri; - runHookPayload = pointerEnvelope; - logger.info('Wrote MicroVM run-hook payload to S3', { - task_id: taskId, - bytes: Buffer.byteLength(payloadJson, 'utf8'), - inline_bytes: inlineBytes, - inline_limit_bytes: RUN_HOOK_PAYLOAD_LIMIT_BYTES, - uri: payloadS3Uri, - }); + const reference = await preparePayloadReference({ + bucket: MICROVM_PAYLOAD_BUCKET!, taskId, backend: 'lambda-microvm', payload, platformConfig, + }).catch((error: unknown) => { throw wrapMicrovmError('payload bootstrap', error); }); + const runHookPayload = JSON.stringify(reference); + if (Buffer.byteLength(runHookPayload, 'utf8') > RUN_HOOK_PAYLOAD_LIMIT_BYTES) { + throw new Error('PAYLOAD_BOOTSTRAP_TOO_LARGE: launch reference exceeds the MicroVM hook limit'); } return runHookPayload; } -function runHookPayloadDelivery(runHookPayload: string): 'inline' | 's3_pointer' { - return runHookPayload.includes('"agent_payload_s3_uri"') ? 's3_pointer' : 'inline'; -} - type MicrovmSessionHandle = Extract; /** @@ -822,7 +697,7 @@ export class LambdaMicrovmComputeStrategy implements ComputeStrategy { image_version: handle.imageVersion ?? null, lifecycle_protocol: handle.lifecycleProtocol ?? 'unverified', maximum_duration_seconds: MICROVM_MAX_DURATION_SECONDS, - payload_delivery: runHookPayloadDelivery(runHookPayload), + payload_delivery: 'bootstrap_v2', // KEY NAMES only, never values: this is the one operator-visible record of // which optional platform identifiers a given session actually received, and // "the agent said ARTIFACTS_BUCKET_NAME is not configured" is otherwise a diff --git a/cdk/src/stacks/agent.ts b/cdk/src/stacks/agent.ts index d4e80b237..b4014c05d 100644 --- a/cdk/src/stacks/agent.ts +++ b/cdk/src/stacks/agent.ts @@ -1152,10 +1152,10 @@ export class AgentStack extends Stack { // includes ecs or the legacy `compute_type=ecs` context is used. Default // synthesis remains AgentCore-only. The backend list is resolved near the // top of this constructor so TaskApi can apply the same cancellation gates. - // Ephemeral bucket for ECS task payloads — the orchestrator writes the - // payload here (it exceeds the 8 KB RunTask containerOverrides limit) and - // passes only an S3 URI pointer; the container fetches it on boot, the - // orchestrator deletes it at finalize. Only synthesized under the ecs gate. + // ECS v2 bootstrap storage: deployment manifests, task instructions and + // private launch references. Workers read manifests with IAM and download + // their task through a signed one-object URL. Finalize deletes task objects; + // the one-day lifecycle reaps leftovers. Synthesized only under the ECS gate. const ecsPayloadBucket = ecsEnabled ? new EcsPayloadBucket(this, 'EcsPayloadBucket') : undefined; @@ -1163,7 +1163,7 @@ export class AgentStack extends Stack { NagSuppressions.addResourceSuppressions(ecsPayloadBucket.bucket, [ { id: 'AwsSolutions-S1', - reason: 'Ephemeral per-task payloads with a 1-day TTL; writes confined to the orchestrator IAM role by grantPut, reads to the ECS task role by grantRead, both scoped to this bucket. Object deleted at finalize. Object-level audit intentionally omitted — CloudTrail data events / a log bucket are not justified for transient boot payloads.', + reason: 'Ephemeral bootstrap storage with a 1-day TTL. The coordinator writes manifests and task objects, signs task reads and deletes task objects at finalize. Workers read only bootstrap/* with IAM and use single-object signed URLs for payloads; other object reads and bucket listing are explicitly denied. Object-level audit intentionally omitted — CloudTrail data events / a log bucket are not justified for transient boot payloads.', }, ]); } diff --git a/cdk/test/constructs/ecs-agent-cluster.test.ts b/cdk/test/constructs/ecs-agent-cluster.test.ts index 500546337..347893d32 100644 --- a/cdk/test/constructs/ecs-agent-cluster.test.ts +++ b/cdk/test/constructs/ecs-agent-cluster.test.ts @@ -955,7 +955,7 @@ describe('EcsAgentCluster payload bucket (#502)', () => { }); }); - test('grants the task role READ on the payload bucket, never write/delete', () => { + test('allows only bootstrap reads and explicitly denies other objects and listing', () => { const template = createWithPayloadBucket(); const policies = template.findResources('AWS::IAM::Policy'); const s3Actions = new Set(); @@ -967,7 +967,13 @@ describe('EcsAgentCluster payload bucket (#502)', () => { } } } - // Read actions present... + const statements = Object.values(policies).flatMap(p => p.Properties.PolicyDocument.Statement); + const allow = statements.find(s => s.Effect === 'Allow' && s.Action === 's3:GetObject'); + expect(JSON.stringify(allow.Resource)).toContain('/bootstrap/*'); + expect(statements).toEqual(expect.arrayContaining([ + expect.objectContaining({ Effect: 'Deny', Action: 's3:GetObject*', NotResource: allow.Resource }), + expect.objectContaining({ Effect: 'Deny', Action: 's3:List*' }), + ])); expect([...s3Actions].some(a => a === 's3:GetObject' || a === 's3:GetObject*')).toBe(true); // ...and NO write/delete on the payload bucket from the task role. expect(s3Actions.has('s3:PutObject')).toBe(false); diff --git a/cdk/test/constructs/lambda-microvm-compute.test.ts b/cdk/test/constructs/lambda-microvm-compute.test.ts index 057ff0fb0..ec32bdb77 100644 --- a/cdk/test/constructs/lambda-microvm-compute.test.ts +++ b/cdk/test/constructs/lambda-microvm-compute.test.ts @@ -782,19 +782,23 @@ describe('LambdaMicrovmCompute — image provisioned from a managed base image', ]); }); - test('execution role gets READ-ONLY on the payload bucket and no write/delete', () => { + test('execution role gets only bootstrap reads, explicit payload/list denies and no writes', () => { const policies = Object.entries(template.findResources('AWS::IAM::Policy')) .filter(([id]) => id.includes('LambdaMicrovmComputeExecutionRole')); const statements = policies.flatMap(([, p]) => p.Properties.PolicyDocument.Statement); const actions: string[] = statements.flatMap((s: { Action: string | string[] }) => Array.isArray(s.Action) ? s.Action : [s.Action]); - // CDK's grantRead renders the Get*/List* read set. - expect(actions).toContain('s3:GetObject*'); + const allowed = statements.filter((s: { Effect: string; Action?: string | string[] }) => s.Effect === 'Allow' && s.Action === 's3:GetObject'); + expect(allowed).toHaveLength(1); + expect(JSON.stringify(allowed[0].Resource)).toContain('/bootstrap/*'); + const denied = statements.find((s: { NotResource?: unknown }) => s.NotResource); + expect(denied.Effect).toBe('Deny'); + expect(denied.NotResource).toEqual(allowed[0].Resource); // The MicroVM runs untrusted repo code — it must not be able to clobber // another task's payload, so nothing mutating may appear. const s3Actions = actions.filter(a => a.startsWith('s3:')); - expect(s3Actions).toEqual(['s3:GetObject*', 's3:GetBucket*', 's3:List*']); + expect(s3Actions).toEqual(['s3:GetObject', 's3:GetObject*', 's3:List*']); for (const action of s3Actions) { expect(action).not.toMatch(/Put|Delete|Abort|Write|^s3:\*$/); } @@ -994,7 +998,7 @@ describe('LambdaMicrovmCompute — image provisioned from a managed base image', const s3Resources = executionRoleStatements() .flatMap(st => (Array.isArray(st.Action) ? st.Action : [st.Action])) .filter(action => action.startsWith('s3:')); - expect(s3Resources).toEqual(['s3:GetObject*', 's3:GetBucket*', 's3:List*']); + expect(s3Resources).toEqual(['s3:GetObject', 's3:GetObject*', 's3:List*']); const rendered = JSON.stringify( executionRoleStatements().filter((st) => { const actions = Array.isArray(st.Action) ? st.Action : [st.Action]; diff --git a/cdk/test/constructs/payload-bootstrap-permissions.test.ts b/cdk/test/constructs/payload-bootstrap-permissions.test.ts new file mode 100644 index 000000000..20bfddfba --- /dev/null +++ b/cdk/test/constructs/payload-bootstrap-permissions.test.ts @@ -0,0 +1,67 @@ +/** + * MIT No Attribution + * + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +import { App, Stack } from 'aws-cdk-lib'; +import { Template } from 'aws-cdk-lib/assertions'; +import * as iam from 'aws-cdk-lib/aws-iam'; +import * as s3 from 'aws-cdk-lib/aws-s3'; +import { grantCoordinatorPayloads, grantWorkerBootstrap } from '../../src/constructs/payload-bootstrap-permissions'; + +describe('payload bootstrap permission boundary', () => { + let template: Template; + beforeAll(() => { + const stack = new Stack(new App(), 'PayloadPermissions'); + const bucket = new s3.Bucket(stack, 'Payloads'); + const worker = new iam.Role(stack, 'Worker', { assumedBy: new iam.ServicePrincipal('lambda.amazonaws.com') }); + const coordinator = new iam.Role(stack, 'Coordinator', { assumedBy: new iam.ServicePrincipal('lambda.amazonaws.com') }); + grantWorkerBootstrap(bucket, worker); + grantCoordinatorPayloads(bucket, coordinator); + template = Template.fromStack(stack); + }); + + test('worker can read only deployment manifests, including against another public bucket', () => { + const policy = Object.entries(template.findResources('AWS::IAM::Policy')) + .find(([id]) => id.startsWith('Worker'))![1].Properties.PolicyDocument.Statement; + expect(policy).toHaveLength(3); + const allow = policy.find((s: { Effect: string }) => s.Effect === 'Allow'); + expect(allow.Action).toBe('s3:GetObject'); + expect(JSON.stringify(allow.Resource)).toContain('/bootstrap/*'); + const deny = policy.find((s: { NotResource?: unknown }) => s.NotResource); + expect(deny.Effect).toBe('Deny'); + expect(deny.Action).toBe('s3:GetObject*'); + expect(deny.NotResource).toEqual(allow.Resource); + expect(policy.find((s: { Action: string }) => s.Action === 's3:List*').Effect).toBe('Deny'); + expect(JSON.stringify(policy)).not.toContain('s3:Put'); + expect(JSON.stringify(policy)).not.toContain('s3:Delete'); + }); + + test('coordinator publishes manifests and privately persists, signs and deletes task references', () => { + const policy = Object.entries(template.findResources('AWS::IAM::Policy')) + .find(([id]) => id.startsWith('Coordinator'))![1].Properties.PolicyDocument.Statement; + const writes = policy.find((s: { Action: string }) => s.Action === 's3:PutObject'); + expect(JSON.stringify(writes.Resource)).toContain('/bootstrap/*'); + const reads = policy.find((s: { Action: string[] }) => Array.isArray(s.Action) && s.Action.includes('s3:GetObject')); + expect(reads.Action).toEqual(['s3:GetObject', 's3:DeleteObject']); + expect(JSON.stringify(reads.Resource)).toContain('*/payload.json'); + expect(JSON.stringify(reads.Resource)).toContain('*/launch.json'); + expect(JSON.stringify(reads.Resource)).not.toContain('/bootstrap/*'); + const list = policy.find((s: { Action: string }) => s.Action === 's3:ListBucket'); + expect(list.Resource).toEqual({ 'Fn::GetAtt': [expect.stringMatching(/^Payloads/), 'Arn'] }); + }); +}); diff --git a/cdk/test/constructs/task-orchestrator.test.ts b/cdk/test/constructs/task-orchestrator.test.ts index 7edede99e..7ad42d860 100644 --- a/cdk/test/constructs/task-orchestrator.test.ts +++ b/cdk/test/constructs/task-orchestrator.test.ts @@ -854,9 +854,18 @@ describe('TaskOrchestrator with the Lambda MicroVMs backend (ADR-021)', () => { .filter(s => JSON.stringify(s.Resource).includes('MicrovmPayloadBucket')); const actions = payloadStatements.flatMap(s => Array.isArray(s.Action) ? s.Action : [s.Action]); expect(actions).toContain('s3:PutObject'); - expect(actions.some(action => action.startsWith('s3:DeleteObject'))).toBe(true); - // The MicroVM execution role is the only reader of a task's payload. - expect(actions.some(action => action.startsWith('s3:GetObject'))).toBe(false); + expect(actions).toContain('s3:DeleteObject'); + expect(actions).toContain('s3:GetObject'); + expect(actions.filter(action => action.startsWith('s3:List'))).toEqual(['s3:ListBucket']); + const list = payloadStatements.find(s => s.Action === 's3:ListBucket'); + expect(list!.Resource).toEqual({ 'Fn::GetAtt': [expect.stringMatching(/^MicrovmPayloadBucket/), 'Arn'] }); + const deletes = payloadStatements.filter(s => + (Array.isArray(s.Action) ? s.Action : [s.Action]).some(action => action.startsWith('s3:Delete'))); + expect(deletes).toHaveLength(1); + expect(deletes[0]!.Action).toEqual(['s3:GetObject', 's3:DeleteObject']); + expect(JSON.stringify(deletes[0]!.Resource)).toContain('/*/payload.json'); + expect(JSON.stringify(deletes[0]!.Resource)).toContain('/*/launch.json'); + expect(JSON.stringify(deletes[0]!.Resource)).not.toContain('/bootstrap/*'); }); test('adds no MicroVM statements when microvmConfig is omitted', () => { diff --git a/cdk/test/handlers/orchestrate-task-microvm.test.ts b/cdk/test/handlers/orchestrate-task-microvm.test.ts index 0ac2ae685..ca9b2af07 100644 --- a/cdk/test/handlers/orchestrate-task-microvm.test.ts +++ b/cdk/test/handlers/orchestrate-task-microvm.test.ts @@ -375,7 +375,7 @@ describe('orchestrate-task for a lambda-microvm task', () => { expect(commandsOfType('TerminateMicrovm')).toHaveLength(1); }); - test('registry assets alone exceed the hook cap and survive real hydration and S3-pointer delivery (#818)', async () => { + test('registry assets alone exceed the hook cap and survive real hydration and v2 bootstrap delivery (#818, #1002)', async () => { const runtime = { transport: 'http', url: 'https://mcp.example.com/tools', @@ -397,19 +397,17 @@ describe('orchestrate-task for a lambda-microvm task', () => { expect(mockResolveAsset).toHaveBeenCalledTimes(1); const upload = s3CommandsOfType('PutObject').find(c => c.input.Key === 'TASK001/payload.json'); - const document = JSON.parse(upload.input.Body); + const document = JSON.parse(upload.input.Body).agent_payload; expect(document.resolved_assets).toEqual([asset]); - const { resolved_assets: assets, platform_config: _config, ...basePayload } = document; + const { resolved_assets: assets, ...basePayload } = document; expect(Buffer.byteLength(JSON.stringify(basePayload))).toBeLessThan(MICROVM_RUN_HOOK_PAYLOAD_LIMIT_BYTES); expect(Buffer.byteLength(JSON.stringify(assets))).toBeGreaterThan(MICROVM_RUN_HOOK_PAYLOAD_LIMIT_BYTES); const run = commandsOfType('RunMicrovm'); expect(run).toHaveLength(1); const wire = run[0].input.runHookPayload; expect(Buffer.byteLength(wire)).toBeLessThanOrEqual(MICROVM_RUN_HOOK_PAYLOAD_LIMIT_BYTES); - expect(JSON.parse(wire)).toMatchObject({ - agent_payload_s3_uri: 's3://test-microvm-payload-bucket/TASK001/payload.json', - platform_config: expect.any(Object), - }); + // The hook body is only the signed, task-scoped reference; the assets ride in the task object. + expect(JSON.parse(wire)).toMatchObject({ version: 2, task_id: 'TASK001', payload_url: expect.any(String) }); expect(wire).not.toContain('X-Registry-Context'); const audit = mockDdbSend.mock.calls.find(([c]) => c.input.ExpressionAttributeValues?.[':ra']); expect(audit![0].input.ExpressionAttributeValues[':ra']).toEqual([ @@ -723,19 +721,23 @@ describe('orchestrate-task for a lambda-microvm task', () => { // --- finalize-time payload delete (review NB3) --- - test('deletes its own payload object on finalize', async () => { - // The execution role can read the whole payload bucket, so finalize deletes - // this task's prompt instead of leaving it to the one-day lifecycle rule. + test('deletes its own payload and saved capability on finalize', async () => { + // Revoke the signed payload link and remove its private replay record. + // The one-day lifecycle remains a cleanup backstop. runMicrovmOk(); await handler({ task_id: 'TASK001' }, fakeContext().ctx as never); const deletes = s3CommandsOfType('DeleteObject'); - expect(deletes).toHaveLength(1); + expect(deletes).toHaveLength(2); expect(deletes[0].input).toEqual({ Bucket: 'test-microvm-payload-bucket', Key: 'TASK001/payload.json', }); + expect(deletes[1].input).toEqual({ + Bucket: 'test-microvm-payload-bucket', + Key: 'TASK001/launch.json', + }); // ...and it did not reach for the ECS deleter. expect(mockDeleteEcsPayload).not.toHaveBeenCalled(); }); diff --git a/cdk/test/handlers/shared/payload-bootstrap.test.ts b/cdk/test/handlers/shared/payload-bootstrap.test.ts new file mode 100644 index 000000000..091c58f07 --- /dev/null +++ b/cdk/test/handlers/shared/payload-bootstrap.test.ts @@ -0,0 +1,160 @@ +/** + * MIT No Attribution + * + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +import { createHash } from 'node:crypto'; + +const mockSend = jest.fn(); +const mockSign = jest.fn(); +const mockCredentials = jest.fn(); +jest.mock('@aws-sdk/client-s3', () => ({ + S3Client: jest.fn(() => ({ send: mockSend, config: { credentials: mockCredentials } })), + PutObjectCommand: jest.fn(input => ({ kind: 'put', input })), + GetObjectCommand: jest.fn(input => ({ kind: 'get', input })), + DeleteObjectCommand: jest.fn(input => ({ kind: 'delete', input })), +})); +jest.mock('@aws-sdk/s3-request-presigner', () => ({ + getSignedUrl: (...args: unknown[]) => mockSign(...args), +})); + +import { deletePayloadReference, PAYLOAD_BOOTSTRAP, preparePayloadReference, redactPayloadUrls } from '../../../src/handlers/shared/payload-bootstrap'; + +const objects = new Map(); +const input = { + bucket: 'payload-bucket', + taskId: 'task-1', + backend: 'lambda-microvm' as const, + payload: { task_id: 'task-1', prompt: 'hello' }, + platformConfig: { github_token_secret_arn: 'arn:aws:secretsmanager:us-west-2:123456789012:secret:github' }, +}; +let loseReplyFor: string | undefined; + +beforeEach(() => { + jest.clearAllMocks(); + objects.clear(); + loseReplyFor = undefined; + mockCredentials.mockResolvedValue({ accessKeyId: 'EXAMPLE', secretAccessKey: 'unused' }); + mockSign.mockImplementation(async () => `https://payload-bucket.s3.us-east-1.amazonaws.com/task-1/payload.json?X-Amz-Security-Token=secret&X-Amz-Signature=${mockSign.mock.calls.length}`); + mockSend.mockImplementation(async ({ kind, input: request }) => { + if (kind === 'get') { + if (!objects.has(request.Key)) throw Object.assign(new Error('missing'), { name: 'NoSuchKey' }); + return { Body: { transformToString: async () => objects.get(request.Key)! } }; + } + if (kind === 'delete') { objects.delete(request.Key); return {}; } + if (request.IfNoneMatch === '*' && objects.has(request.Key)) { + throw Object.assign(new Error('exists'), { name: 'PreconditionFailed' }); + } + objects.set(request.Key, request.Body); + if (loseReplyFor === request.Key) { + loseReplyFor = undefined; + throw new Error('lost committed reply'); + } + return {}; + }); +}); + +test('separates public manifest from private payload and saved capability', async () => { + const ref = await preparePayloadReference(input); + const key = ref.bootstrap_s3_uri.split('/').slice(3).join('/'); + const manifest = objects.get(key)!; + expect(key).toBe(`bootstrap/${createHash('sha256').update(manifest).digest('hex')}.json`); + expect(JSON.parse(manifest)).toEqual({ + version: 2, backend: 'lambda-microvm', platform_config: input.platformConfig, + }); + expect(manifest).not.toContain('hello'); + expect(manifest).not.toContain('X-Amz'); + expect(JSON.parse(objects.get('task-1/payload.json')!).agent_payload).toEqual(input.payload); + expect(JSON.parse(objects.get('task-1/launch.json')!).reference).toEqual(ref); + expect(mockSign).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({ + input: { Bucket: input.bucket, Key: 'task-1/payload.json' }, + }), { expiresIn: 900 }); +}); + +test('replay and concurrent preparation return identical launch bytes without resigning on replay', async () => { + const first = await preparePayloadReference(input); + const replay = await preparePayloadReference({ ...input, payload: { prompt: 'hello', task_id: 'task-1' } }); + expect(JSON.stringify(replay)).toBe(JSON.stringify(first)); + expect(mockSign).toHaveBeenCalledTimes(1); + // Fixed pair, covering conditional object publication by competing callers. + objects.clear(); + // eslint-disable-next-line @cdklabs/promiseall-no-unbounded-parallelism + const [a, b] = await Promise.all([preparePayloadReference(input), preparePayloadReference(input)]); + expect(JSON.stringify(a)).toBe(JSON.stringify(b)); +}); + +test.each(['task-1/payload.json', 'task-1/launch.json'])('recovers a lost committed response for %s', async key => { + loseReplyFor = key; + const first = await preparePayloadReference(input); + expect(await preparePayloadReference(input)).toEqual(first); +}); + +test('changed instructions cannot overwrite an existing payload or launch reference', async () => { + await preparePayloadReference(input); + const before = objects.get('task-1/payload.json'); + await expect(preparePayloadReference({ ...input, payload: { ...input.payload, prompt: 'changed' } })) + .rejects.toThrow('PAYLOAD_BOOTSTRAP_CONFLICT'); + expect(objects.get('task-1/payload.json')).toBe(before); +}); + +test('orphaned payload after a crash cannot be overwritten with changed instructions', async () => { + await preparePayloadReference(input); + objects.delete('task-1/launch.json'); + await expect(preparePayloadReference({ ...input, payload: { ...input.payload, prompt: 'changed' } })) + .rejects.toThrow('PAYLOAD_BOOTSTRAP_CONFLICT'); + expect(JSON.parse(objects.get('task-1/payload.json')!).agent_payload.prompt).toBe('hello'); +}); + +test('expired references fail closed without signing a replacement', async () => { + await preparePayloadReference(input); + const record = JSON.parse(objects.get('task-1/launch.json')!); + record.reference.expires_at = Date.now() - 1; + objects.set('task-1/launch.json', JSON.stringify(record)); + await expect(preparePayloadReference(input)).rejects.toThrow('PAYLOAD_BOOTSTRAP_EXPIRED'); + expect(mockSign).toHaveBeenCalledTimes(1); +}); + +test('credential lifetime bounds the link and refuses credentials expiring too soon', async () => { + mockCredentials.mockResolvedValue({ expiration: new Date(Date.now() + 20_000) }); + await expect(preparePayloadReference(input)).rejects.toThrow('CREDENTIALS_EXPIRING'); + expect(mockSign).not.toHaveBeenCalled(); +}); + +test.each(['../bootstrap', 'task/other', ''])('invalid task key %s performs no S3 writes', async taskId => { + await expect(preparePayloadReference({ ...input, taskId })).rejects.toThrow('identity'); + expect(mockSend).not.toHaveBeenCalled(); +}); + +test('oversized payload fails before uploading or signing', async () => { + await expect(preparePayloadReference({ + ...input, payload: { ...input.payload, prompt: 'x'.repeat(PAYLOAD_BOOTSTRAP.max_payload_bytes) }, + })).rejects.toThrow('TOO_LARGE'); + expect(mockSend).not.toHaveBeenCalled(); +}); + +test('cleanup removes the capability and payload, preserving shared configuration', async () => { + const ref = await preparePayloadReference(input); + await deletePayloadReference(input.bucket, input.taskId); + expect(objects.has('task-1/payload.json')).toBe(false); + expect(objects.has('task-1/launch.json')).toBe(false); + expect(objects.has(ref.bootstrap_s3_uri.split('/').slice(3).join('/'))).toBe(true); +}); + +test('error redaction removes the whole signed URL including the session token', () => { + expect(redactPayloadUrls('failed https://b.s3.us-east-1.amazonaws.com/key?X-Amz-Security-Token=secret&X-Amz-Signature=abc end')) + .toBe('failed [redacted payload URL] end'); +}); diff --git a/cdk/test/handlers/shared/strategies/ecs-strategy.test.ts b/cdk/test/handlers/shared/strategies/ecs-strategy.test.ts index b02458e17..10eaa820a 100644 --- a/cdk/test/handlers/shared/strategies/ecs-strategy.test.ts +++ b/cdk/test/handlers/shared/strategies/ecs-strategy.test.ts @@ -27,13 +27,9 @@ process.env.ECS_TASK_DEFINITION_ARN = TASK_DEF_ARN; process.env.ECS_SUBNETS = 'subnet-aaa,subnet-bbb'; process.env.ECS_SECURITY_GROUP = 'sg-12345'; process.env.ECS_CONTAINER_NAME = 'AgentContainer'; -// The top-of-file import's inline-fallback / no-op tests assume these OPTIONAL -// vars are ABSENT at load time. They are unset in a dev shell but the real ECS -// agent container HAS ECS_PAYLOAD_BUCKET set (#502) — so leaving this to ambient -// env made the build pass locally yet FAIL on ECS ("works local, dies on ECS"). -// The #502 / #299 describe blocks below set these via isolateModules; delete them -// here so the top-of-file import is hermetic regardless of the runner's env. -delete process.env.ECS_PAYLOAD_BUCKET; +// Pin the payload bucket and optional planning definition at import time so the +// test runner's own deployment environment cannot change these expectations. +process.env.ECS_PAYLOAD_BUCKET = 'payload-bucket'; delete process.env.ECS_PLANNING_TASK_DEFINITION_ARN; const mockSend = jest.fn(); @@ -44,17 +40,20 @@ jest.mock('@aws-sdk/client-ecs', () => ({ StopTaskCommand: jest.fn((input: unknown) => ({ _type: 'StopTask', input })), })); -const mockS3Send = jest.fn(); -jest.mock('@aws-sdk/client-s3', () => ({ - S3Client: jest.fn(() => ({ send: mockS3Send })), - PutObjectCommand: jest.fn((input: unknown) => ({ _type: 'PutObject', input })), - DeleteObjectCommand: jest.fn((input: unknown) => ({ _type: 'DeleteObject', input })), +const mockPrepare = jest.fn(); +const mockDelete = jest.fn(); +jest.mock('../../../../src/handlers/shared/payload-bootstrap', () => ({ + ...jest.requireActual('../../../../src/handlers/shared/payload-bootstrap'), + preparePayloadReference: (...args: unknown[]) => mockPrepare(...args), + deletePayloadReference: (...args: unknown[]) => mockDelete(...args), })); import { EcsComputeStrategy } from '../../../../src/handlers/shared/strategies/ecs-strategy'; beforeEach(() => { jest.clearAllMocks(); + mockPrepare.mockReset().mockImplementation(async ({ taskId }: { taskId: string }) => ({ version: 2, task_id: taskId, bootstrap_s3_uri: 's3://b/bootstrap/example.json', payload_url: 'https://signed.example/task', expires_at: Date.now()+900000 })); + mockDelete.mockResolvedValue(undefined); }); describe('EcsComputeStrategy', () => { @@ -103,21 +102,14 @@ describe('EcsComputeStrategy', () => { expect(envVars).toEqual(expect.arrayContaining([ { name: 'TASK_ID', value: 'TASK001' }, { name: 'REPO_URL', value: 'org/repo' }, - { name: 'TASK_DESCRIPTION', value: 'Fix the bug' }, { name: 'ISSUE_NUMBER', value: '42' }, { name: 'MAX_TURNS', value: '50' }, { name: 'CLAUDE_CODE_USE_BEDROCK', value: '1' }, ])); - // No ECS_PAYLOAD_BUCKET in this module's env → inline fallback (#502): the - // full payload rides in AGENT_PAYLOAD and nothing is written to S3. - const agentPayload = envVars.find((e: { name: string }) => e.name === 'AGENT_PAYLOAD'); - expect(agentPayload).toBeDefined(); - const parsed = JSON.parse(agentPayload.value); - expect(parsed.repo_url).toBe('org/repo'); - expect(parsed.prompt).toBe('Fix the bug'); - expect(envVars.find((e: { name: string }) => e.name === 'AGENT_PAYLOAD_S3_URI')).toBeUndefined(); - expect(mockS3Send).not.toHaveBeenCalled(); + const reference = envVars.find((e: { name: string }) => e.name === 'AGENT_PAYLOAD_REF'); + expect(JSON.parse(reference.value).task_id).toBe('TASK001'); + expect(mockPrepare).toHaveBeenCalledWith(expect.objectContaining({ payload: expect.objectContaining({ repo_url: 'org/repo', prompt: 'Fix the bug' }) })); // Container command override — runs Python directly instead of uvicorn expect(override.command).toBeDefined(); @@ -377,111 +369,47 @@ describe('EcsComputeStrategy', () => { }); }); -// #502: the S3-pointer path requires ECS_PAYLOAD_BUCKET to be set BEFORE the -// module is imported (it's a module-level constant). Re-import under -// jest.isolateModules with the env var set so these tests don't perturb the -// inline-fallback tests above. -describe('EcsComputeStrategy with ECS_PAYLOAD_BUCKET (S3-pointer path, #502)', () => { - const PAYLOAD_BUCKET = 'test-ecs-payload-bucket'; - - function loadStrategyWithBucket(): { - EcsComputeStrategy: typeof import('../../../../src/handlers/shared/strategies/ecs-strategy').EcsComputeStrategy; - deleteEcsPayload: typeof import('../../../../src/handlers/shared/strategies/ecs-strategy').deleteEcsPayload; - } { - let mod!: ReturnType; - jest.isolateModules(() => { - process.env.ECS_PAYLOAD_BUCKET = PAYLOAD_BUCKET; - process.env.ECS_CLUSTER_ARN = CLUSTER_ARN; - process.env.ECS_TASK_DEFINITION_ARN = TASK_DEF_ARN; - process.env.ECS_SUBNETS = 'subnet-aaa,subnet-bbb'; - process.env.ECS_SECURITY_GROUP = 'sg-12345'; - process.env.ECS_CONTAINER_NAME = 'AgentContainer'; - // eslint-disable-next-line @typescript-eslint/no-require-imports - mod = require('../../../../src/handlers/shared/strategies/ecs-strategy'); - }); - return mod; - } - - afterEach(() => { - delete process.env.ECS_PAYLOAD_BUCKET; - }); - - test('writes payload to S3 and passes AGENT_PAYLOAD_S3_URI, not the inline blob', async () => { - mockS3Send.mockResolvedValueOnce({}); +describe('ECS v2 bootstrap integration', () => { + test('passes the prepared capability and consumes it before entering the pipeline', async () => { mockSend.mockResolvedValueOnce({ tasks: [{ taskArn: TASK_ARN }] }); + await new EcsComputeStrategy().startSession({ taskId: 'TASK001', userId: 'u1', payload: { task_id: 'TASK001', prompt: 'x'.repeat(10000) }, blueprintConfig: { compute_type: 'ecs', runtime_arn: '' } }); + expect(mockPrepare).toHaveBeenCalledWith(expect.objectContaining({ backend: 'ecs', taskId: 'TASK001', bucket: 'payload-bucket' })); + const override=mockSend.mock.calls[0][0].input.overrides.containerOverrides[0]; + expect(override.environment.some((e: { name: string }) => ['AGENT_PAYLOAD', 'AGENT_PAYLOAD_S3_URI', 'TASK_DESCRIPTION'].includes(e.name))).toBe(false); + const source=override.command[2]; + expect(source).toContain('load_ecs_payload()'); + expect(source.indexOf('load_ecs_payload()')).toBeLessThan(source.indexOf('from entrypoint')); + }); + test('delegates deletion of the payload and private launch capability', async () => { + const { deleteEcsPayload }=await import('../../../../src/handlers/shared/strategies/ecs-strategy'); + await deleteEcsPayload('TASK001'); + expect(mockDelete).toHaveBeenCalledWith('payload-bucket', 'TASK001'); + }); - const { EcsComputeStrategy: Strategy } = loadStrategyWithBucket(); - const strategy = new Strategy(); - await strategy.startSession({ + test('rejects oversized UTF-8 overrides before RunTask', async () => { + await expect(new EcsComputeStrategy().startSession({ taskId: 'TASK001', - userId: 'cognito-test', - payload: { repo_url: 'org/repo', prompt: 'Fix the bug', hydrated_context: { big: 'x'.repeat(10000) } }, - blueprintConfig: { compute_type: 'ecs', runtime_arn: '' }, - }); - - // PutObject to the payload bucket at /payload.json - expect(mockS3Send).toHaveBeenCalledTimes(1); - const put = mockS3Send.mock.calls[0][0]; - expect(put._type).toBe('PutObject'); - expect(put.input.Bucket).toBe(PAYLOAD_BUCKET); - expect(put.input.Key).toBe('TASK001/payload.json'); - expect(JSON.parse(put.input.Body).repo_url).toBe('org/repo'); - - // Override carries the URI pointer, NOT the inline payload - const envVars = mockSend.mock.calls[0][0].input.overrides.containerOverrides[0].environment; - const uri = envVars.find((e: { name: string }) => e.name === 'AGENT_PAYLOAD_S3_URI'); - expect(uri.value).toBe(`s3://${PAYLOAD_BUCKET}/TASK001/payload.json`); - expect(envVars.find((e: { name: string }) => e.name === 'AGENT_PAYLOAD')).toBeUndefined(); + userId: 'u1', + payload: { task_id: 'TASK001' }, + blueprintConfig: { compute_type: 'ecs', runtime_arn: '', system_prompt_overrides: '🌍'.repeat(2100) }, + })).rejects.toThrow('ECS container overrides exceed 8192 bytes'); + expect(mockSend).not.toHaveBeenCalled(); }); - test('boot command loads payload from S3 when the URI is set, else inline', async () => { - mockS3Send.mockResolvedValueOnce({}); - mockSend.mockResolvedValueOnce({ tasks: [{ taskArn: TASK_ARN }] }); - - const { EcsComputeStrategy: Strategy } = loadStrategyWithBucket(); - await new Strategy().startSession({ + test('redacts a capability even when preparation fails before RunTask', async () => { + mockPrepare.mockRejectedValueOnce(new Error('failed https://bucket.example/key?X-Amz-Signature=BEARER-SECRET')); + await expect(new EcsComputeStrategy().startSession({ taskId: 'TASK001', - userId: 'cognito-test', - payload: { repo_url: 'org/repo' }, + userId: 'u1', + payload: { task_id: 'TASK001' }, blueprintConfig: { compute_type: 'ecs', runtime_arn: '' }, - }); - - const cmd = mockSend.mock.calls[0][0].input.overrides.containerOverrides[0].command; - const src = cmd[2]; - // Reads the URI, fetches via boto3 S3 when set, falls back to inline env. - expect(src).toContain('AGENT_PAYLOAD_S3_URI'); - expect(src).toContain('get_object'); - expect(src).toContain('AGENT_PAYLOAD'); - // ABCA-487: the boot command maps the WHOLE payload via - // run_task_from_payload (not a hand-listed kwarg subset that dropped - // channel_source/channel_metadata → no Linear reactions on ECS). Assert we - // call the mapper and no longer hand-pick the old prompt/model_id kwargs. - expect(src).toContain('run_task_from_payload(p)'); - expect(src).not.toContain('task_description=p.get'); - expect(src).not.toContain('channel_source'); // never hand-listed; the mapper forwards it - }); - - test('deleteEcsPayload deletes the task payload object', async () => { - mockS3Send.mockResolvedValueOnce({}); - const { deleteEcsPayload } = loadStrategyWithBucket(); - await deleteEcsPayload('TASK001'); - expect(mockS3Send).toHaveBeenCalledTimes(1); - const del = mockS3Send.mock.calls[0][0]; - expect(del._type).toBe('DeleteObject'); - expect(del.input.Bucket).toBe(PAYLOAD_BUCKET); - expect(del.input.Key).toBe('TASK001/payload.json'); - }); - - test('deleteEcsPayload swallows S3 errors (best-effort — lifecycle is the backstop)', async () => { - mockS3Send.mockRejectedValueOnce(new Error('AccessDenied')); - const { deleteEcsPayload } = loadStrategyWithBucket(); - await expect(deleteEcsPayload('TASK001')).resolves.toBeUndefined(); + })).rejects.toThrow('failed [redacted payload URL]'); + expect(mockSend).not.toHaveBeenCalled(); }); }); // #299 ECS_RIGHTSIZED_PLANNING: the planning task def ARN is a module-level -// constant, so set it BEFORE import via isolateModules (mirrors the #502 bucket -// pattern above) — this keeps it out of the inline tests at the top. +// constant, so set it BEFORE import via isolateModules. describe('EcsComputeStrategy read-only planning-def selection (#299 ECS_RIGHTSIZED_PLANNING)', () => { const PLANNING_DEF_ARN = 'arn:aws:ecs:us-east-1:123456789012:task-definition/agent-planning:1'; @@ -544,12 +472,34 @@ describe('EcsComputeStrategy read-only planning-def selection (#299 ECS_RIGHTSIZ }); }); -describe('deleteEcsPayload without ECS_PAYLOAD_BUCKET', () => { +describe('ECS without ECS_PAYLOAD_BUCKET', () => { + let isolated: typeof import('../../../../src/handlers/shared/strategies/ecs-strategy'); + beforeEach(() => { + const bucket = process.env.ECS_PAYLOAD_BUCKET; + delete process.env.ECS_PAYLOAD_BUCKET; + try { + jest.isolateModules(() => { + // eslint-disable-next-line @typescript-eslint/no-require-imports + isolated = require('../../../../src/handlers/shared/strategies/ecs-strategy'); + }); + } finally { + process.env.ECS_PAYLOAD_BUCKET = bucket; + } + }); + test('no-ops when no payload bucket is configured', async () => { - // The top-of-file import has no ECS_PAYLOAD_BUCKET set. - // eslint-disable-next-line @typescript-eslint/no-require-imports - const { deleteEcsPayload } = require('../../../../src/handlers/shared/strategies/ecs-strategy'); - await expect(deleteEcsPayload('TASK001')).resolves.toBeUndefined(); - expect(mockS3Send).not.toHaveBeenCalled(); + await expect(isolated.deleteEcsPayload('TASK001')).resolves.toBeUndefined(); + expect(mockDelete).not.toHaveBeenCalled(); + }); + + test('rejects a launch before preparing or running anything', async () => { + await expect(new isolated.EcsComputeStrategy().startSession({ + taskId: 'TASK001', + userId: 'u1', + payload: { task_id: 'TASK001' }, + blueprintConfig: { compute_type: 'ecs', runtime_arn: '' }, + })).rejects.toThrow('ECS_PAYLOAD_BUCKET is required'); + expect(mockPrepare).not.toHaveBeenCalled(); + expect(mockSend).not.toHaveBeenCalled(); }); }); diff --git a/cdk/test/handlers/shared/strategies/lambda-microvm-strategy.test.ts b/cdk/test/handlers/shared/strategies/lambda-microvm-strategy.test.ts index 42e8b35d8..3cedbe717 100644 --- a/cdk/test/handlers/shared/strategies/lambda-microvm-strategy.test.ts +++ b/cdk/test/handlers/shared/strategies/lambda-microvm-strategy.test.ts @@ -106,11 +106,12 @@ jest.mock('@aws-sdk/client-lambda-microvms', () => ({ }, })); -const mockS3Send = jest.fn(); -jest.mock('@aws-sdk/client-s3', () => ({ - S3Client: jest.fn(() => ({ send: mockS3Send })), - PutObjectCommand: jest.fn((input: unknown) => ({ _type: 'PutObject', input })), - DeleteObjectCommand: jest.fn((input: unknown) => ({ _type: 'DeleteObject', input })), +const mockPrepare = jest.fn(); +const mockDelete = jest.fn(); +jest.mock('../../../../src/handlers/shared/payload-bootstrap', () => ({ + ...jest.requireActual('../../../../src/handlers/shared/payload-bootstrap'), + preparePayloadReference: (...args: unknown[]) => mockPrepare(...args), + deletePayloadReference: (...args: unknown[]) => mockDelete(...args), })); // The real logger writes JSON to process.stdout/stderr, so level assertions need @@ -134,7 +135,6 @@ import { buildMicrovmPlatformConfig, deleteMicrovmPayload, microvmNoIngressConnectorArnForRegion, - microvmPayloadKey, } from '../../../../src/handlers/shared/strategies/lambda-microvm-strategy'; const BLUEPRINT: BlueprintConfig = { compute_type: 'lambda-microvm', runtime_arn: '' }; @@ -151,31 +151,6 @@ const EXPECTED_PLATFORM_CONFIG = { agent_session_role_arn: AGENT_SESSION_ROLE_ARN, }; -/** - * Build a payload whose serialized `{"agent_payload": …, "platform_config": …}` - * envelope is EXACTLY `targetBytes` long, so the 4 KB boundary can be probed on - * both sides. - * - * `platform_config` is part of the counted envelope (ADR-021 P2), so its bytes are - * subtracted from the payload's budget here. Asserts its own arithmetic — if the - * envelope shape or the platform block ever changes, this fails loudly rather than - * silently testing the wrong boundary. - */ -function payloadWithEnvelopeBytes(targetBytes: number): Record { - const overhead = Buffer.byteLength( - JSON.stringify({ agent_payload: { p: '' }, platform_config: EXPECTED_PLATFORM_CONFIG }), - 'utf8', - ); - const payload = { p: 'x'.repeat(targetBytes - overhead) }; - expect( - Buffer.byteLength( - JSON.stringify({ agent_payload: payload, platform_config: EXPECTED_PLATFORM_CONFIG }), - 'utf8', - ), - ).toBe(targetBytes); - return payload; -} - function runMicrovmOk() { mockSend.mockResolvedValueOnce({ microvmId: MICROVM_ID, @@ -263,27 +238,14 @@ async function withoutEnvAsync(keys: string[], body: () => Promise): Promi } } -/** {@link withoutEnvAsync}'s inverse: run `body` with extra env vars SET. */ -async function withEnvAsync(env: Record, body: () => Promise): Promise { - const saved = Object.fromEntries(Object.keys(env).map(key => [key, process.env[key]])); - try { - Object.assign(process.env, env); - await body(); - } finally { - for (const [key, value] of Object.entries(saved)) { - if (value === undefined) delete process.env[key]; - else process.env[key] = value; - } - } -} - beforeEach(() => { jest.clearAllMocks(); mockSend.mockReset(); - mockS3Send.mockReset().mockResolvedValue({}); mockClaimStart.mockReset().mockImplementation(async (taskId: string) => ({ clientToken: taskId, closed: false })); mockSaveHandle.mockReset().mockResolvedValue(undefined); mockSaveCapability.mockReset().mockResolvedValue(undefined); + mockPrepare.mockReset().mockImplementation(async ({ taskId }: { taskId: string }) => ({ version: 2, task_id: taskId, bootstrap_s3_uri: 's3://b/bootstrap/example.json', payload_url: 'https://signed.example/task', expires_at: Date.now()+900000 })); + mockDelete.mockResolvedValue(undefined); }); describe('per-worker image capability', () => { @@ -514,142 +476,17 @@ describe('LambdaMicrovmComputeStrategy', () => { ]); }); - test('inlines a small payload in runHookPayload and never touches S3', async () => { - runMicrovmOk(); - - await new LambdaMicrovmComputeStrategy().startSession({ - taskId: 'TASK001', - userId: 'cognito-test', - payload: { repo_url: 'org/repo', prompt: 'Fix the bug', max_turns: 50 }, - blueprintConfig: BLUEPRINT, - }); - - expect(mockS3Send).not.toHaveBeenCalled(); - const envelope = JSON.parse(mockSend.mock.calls[0][0].input.runHookPayload); - expect(envelope.agent_payload).toEqual({ repo_url: 'org/repo', prompt: 'Fix the bug', max_turns: 50 }); - expect(envelope.agent_payload_s3_uri).toBeUndefined(); - // The MicroVM's substitute for the env block the other two backends get at - // deploy time — a snapshot must not bake it in (ADR-021 sub-decision 3), so - // it rides the envelope alongside the payload. - expect(envelope.platform_config).toEqual(EXPECTED_PLATFORM_CONFIG); - }); - - test('uploads an oversized payload to S3 and inlines only the pointer', async () => { - mockS3Send.mockResolvedValueOnce({}); - runMicrovmOk(); - - const big = { repo_url: 'org/repo', hydrated_context: { blob: 'x'.repeat(20_000) } }; - await new LambdaMicrovmComputeStrategy().startSession({ - taskId: 'TASK001', - userId: 'cognito-test', - payload: big, - blueprintConfig: BLUEPRINT, - }); - - // Same key shape as the ECS payload bucket: /payload.json - expect(mockS3Send).toHaveBeenCalledTimes(1); - const put = mockS3Send.mock.calls[0][0]; - expect(put._type).toBe('PutObject'); - expect(put.input.Bucket).toBe(PAYLOAD_BUCKET); - expect(put.input.Key).toBe('TASK001/payload.json'); - expect(put.input.ContentType).toBe('application/json'); - // The S3 object carries the payload with platform_config merged in at the top - // level, so an agent that resolves the pointer gets the config with it. - expect(JSON.parse(put.input.Body)).toEqual({ ...big, platform_config: EXPECTED_PLATFORM_CONFIG }); - - const runHookPayload = mockSend.mock.calls[0][0].input.runHookPayload; - const envelope = JSON.parse(runHookPayload); - expect(envelope.agent_payload_s3_uri).toBe(`s3://${PAYLOAD_BUCKET}/TASK001/payload.json`); - expect(envelope.agent_payload).toBeUndefined(); - // ...and ALSO inline on the pointer envelope, deliberately duplicated: the - // agent must be able to read its platform configuration whether it takes it - // off the hook body before fetching S3 or out of the fetched object. - expect(envelope.platform_config).toEqual(EXPECTED_PLATFORM_CONFIG); - // The whole point: the hook body must sit far under the 4 KB cap. - expect(Buffer.byteLength(runHookPayload, 'utf8')).toBeLessThan(MICROVM_RUN_HOOK_PAYLOAD_LIMIT_BYTES); - }); - - test('the inline/S3 branch point IS the 4096-byte service cap, with no headroom', () => { - // Live-measured, NOT read off the SDK docs (which say 16,384): the service - // rejects 4097 with "Member must have length less than or equal to 4096". - // Unlike ECS (whose 8192-byte cap is shared with env vars + command, so it - // needs a margin), runHookPayload is the entire counted string. - expect(MICROVM_RUN_HOOK_PAYLOAD_LIMIT_BYTES).toBe(4_096); - }); - - test('a payload whose envelope is EXACTLY 4096 bytes stays inline', async () => { - runMicrovmOk(); - - await new LambdaMicrovmComputeStrategy().startSession({ - taskId: 'TASK001', - userId: 'cognito-test', - payload: payloadWithEnvelopeBytes(4_096), - blueprintConfig: BLUEPRINT, - }); - - // Boundary is `<=`: 4096 passed the service's length validation live. - expect(mockS3Send).not.toHaveBeenCalled(); - const runHookPayload = mockSend.mock.calls[0][0].input.runHookPayload; - expect(Buffer.byteLength(runHookPayload, 'utf8')).toBe(4_096); - expect(JSON.parse(runHookPayload).agent_payload).toBeDefined(); - }); - - test('a payload whose envelope is 4097 bytes — one over — goes to S3', async () => { - mockS3Send.mockResolvedValueOnce({}); - runMicrovmOk(); - - await new LambdaMicrovmComputeStrategy().startSession({ - taskId: 'TASK001', - userId: 'cognito-test', - payload: payloadWithEnvelopeBytes(4_097), - blueprintConfig: BLUEPRINT, - }); - - expect(mockS3Send).toHaveBeenCalledTimes(1); - const envelope = JSON.parse(mockSend.mock.calls[0][0].input.runHookPayload); - expect(envelope.agent_payload_s3_uri).toBe(`s3://${PAYLOAD_BUCKET}/TASK001/payload.json`); - expect(envelope.agent_payload).toBeUndefined(); - }); - - test('a mid-sized envelope the SDK-documented 16KB cap would have inlined goes to S3', async () => { - mockS3Send.mockResolvedValueOnce({}); - runMicrovmOk(); - - // Regression guard for the live-verification fix: anything from 4,097 to - // 16,384 bytes used to be inlined and would be REJECTED by the service. - await new LambdaMicrovmComputeStrategy().startSession({ - taskId: 'TASK001', - userId: 'cognito-test', - payload: payloadWithEnvelopeBytes(13_000), - blueprintConfig: BLUEPRINT, - }); - - expect(mockS3Send).toHaveBeenCalledTimes(1); - const envelope = JSON.parse(mockSend.mock.calls[0][0].input.runHookPayload); - expect(envelope.agent_payload_s3_uri).toBeDefined(); + test.each(['small', 'x'.repeat(20000)])('delivers a persisted v2 reference for every payload size', async prompt => { + mockSend.mockResolvedValueOnce({ microvmId: MICROVM_ID, endpoint: ENDPOINT }); + await new LambdaMicrovmComputeStrategy().startSession({ taskId: 'TASK001', userId: 'u1', payload: { prompt }, blueprintConfig: BLUEPRINT }); + expect(mockPrepare).toHaveBeenCalledWith(expect.objectContaining({ bucket: PAYLOAD_BUCKET, backend: 'lambda-microvm', platformConfig: EXPECTED_PLATFORM_CONFIG, payload: { prompt } })); + const envelope=JSON.parse(mockSend.mock.calls[0][0].input.runHookPayload); + expect(envelope.version).toBe(2); + expect(envelope.task_id).toBe('TASK001'); + expect(envelope.platform_config).toBeUndefined(); expect(envelope.agent_payload).toBeUndefined(); }); - test('measures the serialized envelope in BYTES, so a multi-byte payload still goes to S3', async () => { - mockS3Send.mockResolvedValueOnce({}); - runMicrovmOk(); - - // 3-byte UTF-8 characters: 2000 chars is ~6 KB of bytes but only 2 KB of - // chars, so measuring String.length would have wrongly inlined this. - const payload = { prompt: '\u4f60'.repeat(2_000) }; - expect(JSON.stringify({ agent_payload: payload, platform_config: EXPECTED_PLATFORM_CONFIG }).length) - .toBeLessThan(MICROVM_RUN_HOOK_PAYLOAD_LIMIT_BYTES); - await new LambdaMicrovmComputeStrategy().startSession({ - taskId: 'TASK001', - userId: 'cognito-test', - payload, - blueprintConfig: BLUEPRINT, - }); - - expect(mockS3Send).toHaveBeenCalledTimes(1); - expect(JSON.parse(mockSend.mock.calls[0][0].input.runHookPayload).agent_payload_s3_uri).toBeDefined(); - }); - test('throws when RunMicrovm returns no microvmId', async () => { mockSend.mockResolvedValueOnce({ endpoint: ENDPOINT, state: 'PENDING' }); @@ -694,59 +531,6 @@ describe('LambdaMicrovmComputeStrategy', () => { ); }); - test('platform_config COUNTS toward the 4 KB boundary — an otherwise-inlineable payload goes to S3', async () => { - // The regression this locks: measuring `{agent_payload}` alone and then - // sending `{agent_payload, platform_config}` would inline an envelope the - // service rejects outright. So the branch decision has to be made on the - // FULL envelope. This payload is exactly 4 096 bytes WITHOUT the platform - // block — i.e. the old code would have inlined it — and must now upload. - mockS3Send.mockResolvedValueOnce({}); - runMicrovmOk(); - - const overheadWithoutConfig = Buffer.byteLength(JSON.stringify({ agent_payload: { p: '' } }), 'utf8'); - const payload = { p: 'x'.repeat(MICROVM_RUN_HOOK_PAYLOAD_LIMIT_BYTES - overheadWithoutConfig) }; - expect(Buffer.byteLength(JSON.stringify({ agent_payload: payload }), 'utf8')) - .toBe(MICROVM_RUN_HOOK_PAYLOAD_LIMIT_BYTES); - - await new LambdaMicrovmComputeStrategy().startSession({ - taskId: 'TASK001', - userId: 'cognito-test', - payload, - blueprintConfig: BLUEPRINT, - }); - - expect(mockS3Send).toHaveBeenCalledTimes(1); - const runHookPayload = mockSend.mock.calls[0][0].input.runHookPayload; - expect(JSON.parse(runHookPayload).agent_payload_s3_uri).toBeDefined(); - expect(Buffer.byteLength(runHookPayload, 'utf8')) - .toBeLessThanOrEqual(MICROVM_RUN_HOOK_PAYLOAD_LIMIT_BYTES); - }); - - test('fails BEFORE the upload when even the POINTER envelope cannot fit (no orphan object)', async () => { - // The one shape with no smaller fallback: the payload has already been moved - // to S3, so if `{pointer + platform_config}` still exceeds 4 096 bytes there - // is nothing left to shed. Only a pathological identifier length can cause it - // — hence the check, and hence its placement BEFORE the PutObject so a - // misconfiguration cannot leave objects behind for the lifecycle rule to reap. - await withEnvAsync({ LOG_GROUP_NAME: `/aws/${'x'.repeat(5_000)}` }, async () => { - const start = new LambdaMicrovmComputeStrategy().startSession({ - taskId: 'TASK001', - userId: 'cognito-test', - payload: payloadWithEnvelopeBytes(20_000), - blueprintConfig: BLUEPRINT, - }); - - await expect(start).rejects.toThrow(/pointer envelope is \d+ bytes/); - await expect(start).rejects.toThrow(/shorten the stack name/); - expect(mockS3Send).not.toHaveBeenCalled(); - expect(mockSend).not.toHaveBeenCalled(); - }); - }); - - test('microvmPayloadKey matches the ECS payload key shape', () => { - expect(microvmPayloadKey('TASK001')).toBe('TASK001/payload.json'); - }); - test('REAPS the MicroVM when the response carries an id but no endpoint', async () => { // The one orphan window the orchestrator cannot cover: startSession never // returns a handle, so nothing downstream knows the id. A MicroVM is already @@ -817,7 +601,7 @@ describe('LambdaMicrovmComputeStrategy', () => { await expect(start).rejects.toThrow(new RegExp(`${key} <- ${envVar}`)); await expect(start).rejects.toThrow(/redeploy the stack/); expect(mockSend).not.toHaveBeenCalled(); - expect(mockS3Send).not.toHaveBeenCalled(); + expect(mockPrepare).not.toHaveBeenCalled(); }); }, ); @@ -839,45 +623,48 @@ describe('LambdaMicrovmComputeStrategy', () => { // ARN. Nothing resembling a value may appear on the log line. expect(JSON.stringify(started[1])).not.toContain(GITHUB_TOKEN_SECRET_ARN); }); - }); - // --- finalize-time payload delete (review NB3 / ayushtr nit 2) --- - // - // Finalize revokes the single-object link and removes its private replay - // record; worker credentials already deny direct task-object reads. - describe('deleteMicrovmPayload — closes the cross-task payload-read window', () => { - test('deletes the task\'s own object from the payload bucket', async () => { - await deleteMicrovmPayload('TASK001'); + test('rejects a saved reference exceeding the service cap before RunMicrovm', async () => { + mockPrepare.mockResolvedValueOnce({ version: 2, task_id: 'TASK001', payload_url: 'x'.repeat(MICROVM_RUN_HOOK_PAYLOAD_LIMIT_BYTES + 1) }); + await expect(new LambdaMicrovmComputeStrategy().startSession({ taskId: 'TASK001', userId: 'u1', payload: {}, blueprintConfig: BLUEPRINT })).rejects.toThrow('hook limit'); + expect(mockSend).not.toHaveBeenCalled(); + }); - expect(mockS3Send).toHaveBeenCalledTimes(1); - const call = mockS3Send.mock.calls[0][0]; - expect(call._type).toBe('DeleteObject'); - expect(call.input).toEqual({ - Bucket: PAYLOAD_BUCKET, - Key: microvmPayloadKey('TASK001'), + test.each(['bootstrap', 'run'])('redacts signed URLs throughout the %s error chain', async stage => { + const { inspect } = await import('node:util'); + const original = new Error('request failed https://bucket.example/key?X-Amz-Signature=BEARER-SECRET', { + cause: new Error('nested BEARER-SECRET'), }); + if (stage === 'bootstrap') mockPrepare.mockRejectedValueOnce(original); + else mockSend.mockRejectedValueOnce(original); + await new LambdaMicrovmComputeStrategy().startSession({ + taskId: 'TASK001', userId: 'u1', payload: {}, blueprintConfig: BLUEPRINT, + }).catch(error => { + expect(inspect(error, { depth: null })).not.toContain('BEARER-SECRET'); + }); + expect.assertions(1); }); - test('is best-effort — a failed delete never throws', async () => { - mockS3Send.mockRejectedValueOnce(new Error('AccessDenied')); - - await expect(deleteMicrovmPayload('TASK001')).resolves.toBeUndefined(); - // Not silent: the lifecycle rule is the backstop, but an operator must be - // able to see the delete is failing. - expect(mockLogger.warn).toHaveBeenCalledWith( - 'Failed to delete MicroVM payload object (non-fatal)', - expect.objectContaining({ task_id: 'TASK001', error: 'AccessDenied' }), - ); + test('keeps the capability out of ordinary logs', async () => { + mockPrepare.mockResolvedValueOnce({ version: 2, task_id: 'TASK001', payload_url: 'BEARER-SECRET' }); + runMicrovmOk(); + await new LambdaMicrovmComputeStrategy().startSession({ + taskId: 'TASK001', userId: 'u1', payload: {}, blueprintConfig: BLUEPRINT, + }); + expect(JSON.stringify([ + mockLogger.info.mock.calls, mockLogger.warn.mock.calls, mockLogger.error.mock.calls, + ])).not.toContain('BEARER-SECRET'); }); + }); - test('deletes ONLY the given task\'s key — never a prefix or the bucket', async () => { - // The delete must not become a cleanup that can reach another task's object. + // --- finalize-time payload delete (review NB3 / ayushtr nit 2) --- + // + // Finalize revokes the single-object link and removes its private replay + // record; worker credentials already deny direct task-object reads. + describe('deleteMicrovmPayload', () => { + test('delegates cleanup of payload and private launch record', async () => { await deleteMicrovmPayload('TASK001'); - - const { input } = mockS3Send.mock.calls[0][0]; - expect(input.Key).toBe('TASK001/payload.json'); - expect(input.Key).not.toContain('*'); - expect(input).not.toHaveProperty('Prefix'); + expect(mockDelete).toHaveBeenCalledWith(PAYLOAD_BUCKET, 'TASK001'); }); }); @@ -1136,7 +923,7 @@ describe('LambdaMicrovmComputeStrategy', () => { test('marks a payload-upload failure so an S3 fault is attributed to this backend', async () => { const err = new Error('Access Denied'); err.name = 'AccessDenied'; - mockS3Send.mockRejectedValueOnce(err); + mockPrepare.mockRejectedValueOnce(err); const start = new LambdaMicrovmComputeStrategy().startSession({ taskId: 'TASK001', @@ -1145,7 +932,7 @@ describe('LambdaMicrovmComputeStrategy', () => { blueprintConfig: BLUEPRINT, }); - await expect(start).rejects.toThrow('MicroVM payload upload failed: AccessDenied: Access Denied'); + await expect(start).rejects.toThrow('MicroVM payload bootstrap failed: AccessDenied: Access Denied'); // Never reaches RunMicrovm — no half-started MicroVM on an upload fault. expect(mockSend).not.toHaveBeenCalled(); }); @@ -1213,7 +1000,7 @@ describe('LambdaMicrovmComputeStrategy without the MicroVM substrate deployed', await expect(start).rejects.toThrow(new RegExp(envVar)); // Fails BEFORE any AWS call — no half-started MicroVM, no orphan S3 object. expect(mockSend).not.toHaveBeenCalled(); - expect(mockS3Send).not.toHaveBeenCalled(); + expect(mockPrepare).not.toHaveBeenCalled(); }); test('MICROVM_IMAGE_VERSION is optional — the field is omitted so the service picks the default', async () => { @@ -1317,7 +1104,7 @@ describe('LambdaMicrovmComputeStrategy image-identifier validation', () => { // ...and the remedy. await expect(start).rejects.toThrow(/--context compute_type=lambda-microvm/); expect(mockSend).not.toHaveBeenCalled(); - expect(mockS3Send).not.toHaveBeenCalled(); + expect(mockPrepare).not.toHaveBeenCalled(); }); test('accepts a full image ARN', async () => { @@ -1371,9 +1158,18 @@ describe('buildMicrovmPlatformConfig — the MicroVM substitute for a deploy-tim .toEqual(Object.keys(sharedConstants.microvm_platform_config.env_by_key)); expect([...MICROVM_PLATFORM_CONFIG_REQUIRED_KEYS]) .toEqual(sharedConstants.microvm_platform_config.required); + expect(Object.keys(sharedConstants.microvm_platform_config).sort()) + .toEqual(['account_anchor_key', 'arn_keys', 'env_by_key', 'required']); + expect(sharedConstants.microvm_platform_config.arn_keys).toEqual([ + 'github_token_secret_arn', + 'linear_oauth_secret_arn', + 'jira_oauth_secret_arn', + 'agent_session_role_arn', + ]); + expect(sharedConstants.microvm_platform_config.account_anchor_key).toBe('agent_session_role_arn'); - // Order is part of the contract: it is the serialization order, which the 4 KB - // inline/S3 branch decision is computed against. + // Keep the reviewed key inventory explicit. Payload/bootstrap hashing uses + // canonical JSON, so insertion order does not alter retry identity. expect([...MICROVM_PLATFORM_CONFIG_KEYS]).toEqual([ 'task_table_name', 'task_events_table_name', @@ -1592,18 +1388,6 @@ describe('buildMicrovmPlatformConfig — the MicroVM substitute for a deploy-tim const config = buildMicrovmPlatformConfig(); expect(config).toEqual(EXPECTED_PLATFORM_CONFIG); }); - - test('the full thirteen-key block fits the pointer envelope inside the 4 KB cap', () => { - // The one shape with no smaller fallback: if the pointer envelope itself - // exceeded 4 096 bytes there would be nothing left to move to S3. This asserts - // the design has real headroom rather than relying on the guard. - const pointerEnvelope = JSON.stringify({ - agent_payload_s3_uri: `s3://${PAYLOAD_BUCKET}/TASK001/payload.json`, - platform_config: buildMicrovmPlatformConfig(FULL_ENV), - }); - expect(Buffer.byteLength(pointerEnvelope, 'utf8')) - .toBeLessThan(MICROVM_RUN_HOOK_PAYLOAD_LIMIT_BYTES / 2); - }); }); describe('LambdaMicrovmComputeStrategy with the FULL platform_config environment', () => { @@ -1628,21 +1412,9 @@ describe('LambdaMicrovmComputeStrategy with the FULL platform_config environment for (const key of Object.keys(OPTIONAL_ENV)) delete process.env[key]; }); - test('delivers every configured identifier on the wire, in both envelope halves', async () => { - mockS3Send.mockResolvedValueOnce({}); - runMicrovmOk(); - - await new LambdaMicrovmComputeStrategy().startSession({ - taskId: 'TASK001', - userId: 'cognito-test', - payload: { repo_url: 'org/repo', hydrated_context: { blob: 'x'.repeat(10_000) } }, - blueprintConfig: BLUEPRINT, - }); - - const expected = { ...EXPECTED_PLATFORM_CONFIG, ...buildMicrovmPlatformConfig() }; - const envelope = JSON.parse(mockSend.mock.calls[0][0].input.runHookPayload); - expect(envelope.platform_config).toEqual(expected); - expect(Object.keys(envelope.platform_config)).toHaveLength(14); - expect(JSON.parse(mockS3Send.mock.calls[0][0].input.Body).platform_config).toEqual(expected); + test('passes every configured identifier to the authenticated manifest producer', async () => { + mockSend.mockResolvedValueOnce({ microvmId: MICROVM_ID, endpoint: ENDPOINT }); + await new LambdaMicrovmComputeStrategy().startSession({ taskId: 'TASK001', userId: 'u1', payload: {}, blueprintConfig: BLUEPRINT }); + expect(mockPrepare.mock.calls[0][0].platformConfig).toEqual(buildMicrovmPlatformConfig()); }); }); diff --git a/cdk/test/handlers/start-session-composition.test.ts b/cdk/test/handlers/start-session-composition.test.ts index 7e9a2e71d..c8c8db27e 100644 --- a/cdk/test/handlers/start-session-composition.test.ts +++ b/cdk/test/handlers/start-session-composition.test.ts @@ -57,10 +57,17 @@ jest.mock('@aws-sdk/client-lambda-microvms', () => ({ }, })); -jest.mock('@aws-sdk/client-s3', () => ({ - S3Client: jest.fn(() => ({ send: jest.fn().mockResolvedValue({}) })), - PutObjectCommand: jest.fn((input: unknown) => ({ _type: 'PutObject', input })), - DeleteObjectCommand: jest.fn((input: unknown) => ({ _type: 'DeleteObject', input })), +// This suite checks strategy/metadata composition. Real bootstrap replay is +// covered by microvm-start-recovery and orchestrate-task-microvm. +jest.mock('../../src/handlers/shared/payload-bootstrap', () => ({ + ...jest.requireActual('../../src/handlers/shared/payload-bootstrap'), + preparePayloadReference: jest.fn(async ({ taskId }: { taskId: string }) => ({ + version: 2, + task_id: taskId, + bootstrap_s3_uri: 's3://bucket/bootstrap/example.json', + payload_url: 'https://signed.example/task', + expires_at: Date.now() + 900000, + })), })); jest.mock('../../src/handlers/shared/repo-config', () => ({ diff --git a/cdk/test/scripts/check-constants-sync.test.ts b/cdk/test/scripts/check-constants-sync.test.ts index 1e5340be1..1e504b9dd 100644 --- a/cdk/test/scripts/check-constants-sync.test.ts +++ b/cdk/test/scripts/check-constants-sync.test.ts @@ -60,6 +60,7 @@ const PARITY_TEST_REL = 'agent/tests/test_constants_parity.py'; const FIXTURE_FILES = [ SCRIPT_REL, 'contracts/constants.json', + 'cdk/src/handlers/shared/payload-bootstrap.ts', 'cdk/src/constructs/lambda-microvm-compute.ts', 'cdk/src/handlers/shared/microvm/image-capability.ts', 'cdk/src/handlers/shared/strategies/lambda-microvm-strategy.ts', @@ -162,6 +163,30 @@ describe('check-constants-sync', () => { }); }); + describe('payload bootstrap contract', () => { + test.each([ + ['max_payload_bytes', 0], + ['minimum_url_lifetime_seconds', 901], + ['manifest_prefix', '../'], + ['launch_filename', 'payload.json'], + ])('rejects unsafe %s', (key, value) => { + const result = runInMutatedRepo(root => patchContract(root, json => { + json.payload_bootstrap[key] = value; + })); + expect(result.status).toBe(1); + expect(result.stderr).toContain('payload_bootstrap'); + }); + + test.each([ + ['agent/src/payload_bootstrap.py', 'CONTRACT = {}'], + ['cdk/src/handlers/shared/payload-bootstrap.ts', 'export const PAYLOAD_BOOTSTRAP = {};'], + ])('rejects a consumer with its own copy: %s', (file, source) => { + const result = runInMutatedRepo(root => write(root, file, source)); + expect(result.status).toBe(1); + expect(result.stderr).toContain('consumers must read the shared contract'); + }); + }); + describe('the real repository', () => { test('passes, and says what it actually checked', () => { const result = runInMutatedRepo(() => {}); diff --git a/cdk/test/stacks/agent.test.ts b/cdk/test/stacks/agent.test.ts index 91f839696..e75ee7073 100644 --- a/cdk/test/stacks/agent.test.ts +++ b/cdk/test/stacks/agent.test.ts @@ -1246,6 +1246,7 @@ describe('AgentStack', () => { }).toEqual({ 'root': Array(9).fill(notifiesTopic), 'TestAgentStack/AgentRegistryStack': [], + 'TestAgentStack/ApprovalRequests': [], 'TestAgentStack/RegistryApi': [], 'TestAgentStack/ConcurrencyMaintenance': Array(2).fill(notifiesTopic), }); @@ -1617,8 +1618,17 @@ describe('AgentStack with the Lambda MicroVMs substrate gate (--context compute_ JSON.stringify(s.Resource).includes('ComputePayloadBucket')); const actions = payloadStatements.flatMap(s => Array.isArray(s.Action) ? s.Action : [s.Action]); expect(actions).toContain('s3:PutObject'); - expect(actions.some(action => action.startsWith('s3:DeleteObject'))).toBe(true); - expect(actions.some(action => action.startsWith('s3:GetObject'))).toBe(false); + expect(actions).toContain('s3:DeleteObject'); + expect(actions).toContain('s3:GetObject'); + expect(actions).toContain('s3:ListBucket'); + const deletion = payloadStatements.find(s => Array.isArray(s.Action) && s.Action.includes('s3:DeleteObject')); + // The payload bucket lives in the MicroVM nested stack, so its ARN arrives as that stack's output. + expect(deletion!.Resource).toEqual(['payload.json', 'launch.json'].map(filename => ({ + 'Fn::Join': ['', [ + { 'Fn::GetAtt': [expect.stringMatching(/^MicrovmNestedStack/), expect.stringMatching(/ComputePayloadBucket.*Arn$/)] }, + `/*/${filename}`, + ]], + }))); }); test('cancel Lambda may terminate a MicroVM (and only terminate), image-scoped', () => { @@ -1925,8 +1935,9 @@ describe('AgentStack solution attribution (#319): AWS_SDK_UA_APP_ID via stack-le // unnoticed; the exact count fails if a Lambda is dropped OR if a new one // is added without being attributed below. // 48 existing handlers (5 scheduled maintenance jobs nested) + 2 registry - // provisioning handlers + 4 registry API handlers in nested stacks. - expect(abcaLambdas.length).toBe(54); + // provisioning handlers + 4 registry API handlers in nested stacks + the + // trusted approval writer (#1000) in its own nested stack. + expect(abcaLambdas.length).toBe(55); // Every ABCA-authored Lambda must carry the canonical `#` app-id. Collect // any offenders so a failure names the exact logical id(s) that are naked. const unattributed = abcaLambdas diff --git a/contracts/constants.json b/contracts/constants.json index 0ff962ad2..78faf1778 100644 --- a/contracts/constants.json +++ b/contracts/constants.json @@ -72,6 +72,15 @@ ], "account_anchor_key": "agent_session_role_arn" }, + "payload_bootstrap": { + "version": 2, + "manifest_prefix": "bootstrap/", + "launch_filename": "launch.json", + "max_manifest_bytes": 16384, + "max_payload_bytes": 8388608, + "url_ttl_seconds": 900, + "minimum_url_lifetime_seconds": 300 + }, "microvm_hook_budgets": { "ready_hook_timeout_seconds": 300, "warmup_total_budget_seconds": 240, diff --git a/contracts/constants.md b/contracts/constants.md index 8ec8e0c78..3f07e83e3 100644 --- a/contracts/constants.md +++ b/contracts/constants.md @@ -21,6 +21,8 @@ the contract. This is the neutral location both runtimes read. |---|---|---| | `agent/src/shared_constants.py` | `/app/contracts/constants.json` | import-time | | `agent/src/policy.py`, `agent/src/jira_reactions.py` | `SHARED_CONSTANTS` | import-time | +| `agent/src/payload_bootstrap.py` | `SHARED_CONSTANTS["payload_bootstrap"]` | import-time | +| `cdk/src/handlers/shared/payload-bootstrap.ts`, `cdk/src/constructs/payload-bootstrap-permissions.ts` | `payload_bootstrap` | import-time | | `agent/src/server.py` | `SHARED_CONSTANTS["microvm_platform_config"]`, `SHARED_CONSTANTS["microvm_hook_budgets"]` | import-time | | `cdk/src/handlers/shared/types.ts`, `jira-app-actor.ts` | `../../../../contracts/constants.json` | synth-time `import` | | `cdk/src/handlers/shared/strategies/lambda-microvm-strategy.ts` | `microvm_platform_config` | synth-time `import`, read per session start | @@ -80,6 +82,15 @@ JSON at TypeScript compile time via `resolveJsonModule`. "jira_oauth_secret_arn", "agent_session_role_arn"], "account_anchor_key": "agent_session_role_arn" }, + "payload_bootstrap": { + "version": 2, + "manifest_prefix": "bootstrap/", + "launch_filename": "launch.json", + "max_manifest_bytes": 16384, + "max_payload_bytes": 8388608, + "url_ttl_seconds": 900, + "minimum_url_lifetime_seconds": 300 + }, "microvm_hook_budgets": { "ready_hook_timeout_seconds": 300, "warmup_total_budget_seconds": 240, @@ -124,7 +135,7 @@ JSON at TypeScript compile time via `resolveJsonModule`. variable the agent installs it as (UPPER_SNAKE). This block is unlike the others — it is a **security allowlist**, not a tuning bound. The MicroVM image is a snapshot whose env is frozen at build time, so the agent's non-secret - platform env arrives in the `/run` hook payload instead; the values land in + platform env arrives through an authenticated v2 manifest and task payload instead; the values land in `os.environ`, which makes an unrecognised key an env-injection attempt. The consumer (`agent/src/server.py`) therefore **rejects** any `platform_config` carrying a key that is not in this map. Values are non-secret identifiers @@ -141,15 +152,15 @@ JSON at TypeScript compile time via `resolveJsonModule`. that disagrees with the anchor below on partition or account, is rejected (HTTP 400 `MICROVM_RUN_PLATFORM_CONFIG_INVALID`). This is **fail-fast plus defence in depth, not an ownership proof** — the account-scoped IAM grants are - what actually deny a foreign read, and an in-account redirect is deliberately - *not* covered (see `MICROVM_PLATFORM_CONFIG_ARN_KEYS` in - `agent/src/server.py` for the full statement of what this does and does not buy). + what actually deny a foreign read, and this ARN check alone does not cover an in-account redirect. The v2 bootstrap + authenticates a deployment manifest with IAM and requires the downloaded config + to match it; that separate check rejects same-account workspace substitutions. - **`microvm_platform_config.account_anchor_key`** — which `arn_keys` entry supplies the expected partition + account. Must be `agent_session_role_arn`-shaped: a payload key rather than `os.environ` or an `sts:GetCallerIdentity`, because the environment is empty by construction on this backend (the snapshot bakes nothing) - and this check runs on the path that must make zero AWS calls beyond the S3 - payload fetch. Two invariants follow and both are enforced: the anchor must be in + and the ARN consistency check itself makes no AWS calls. The v2 bootstrap + manifest read and signed task download precede it. Two invariants follow and both are enforced: the anchor must be in `arn_keys`, **and** it must be in `required` — an optional anchor would let a payload disarm the whole check by simply omitting it. @@ -162,6 +173,18 @@ duplication is deliberate: a malformed entry here would silently **widen** what agent accepts from a network payload, so neither side is trusted to be the only gate. +- **`payload_bootstrap`** — the shared ECS/MicroVM v2 transport. `version` is + required on references, manifests and task documents. `manifest_prefix` and + `launch_filename` define the authenticated settings directory and private retry + record. Byte limits bound manifest and task downloads; URL lifetime is at most + `url_ttl_seconds`, shortened by known signer credential expiry, with initial + creation requiring `minimum_url_lifetime_seconds`. The constants checker + rejects nonpositive/noninteger bounds, unsafe/colliding paths, a minimum above + its maximum, and consumers that stop reading the shared block. Changing the + protocol requires matching coordinator, worker images and policies; old unsigned + transports are rejected. See repository runbook + `docs/verification/645-payload-bootstrap.md` for rollout and live checks. + - **`microvm_hook_budgets.ready_hook_timeout_seconds`** — the `/ready` build-hook budget the CDK construct declares to `CreateMicrovmImage` (`READY_HOOK_TIMEOUT_SECONDS` in `cdk/src/constructs/lambda-microvm-compute.ts`). diff --git a/docs/decisions/ADR-021-lambda-microvms-compute-backend.md b/docs/decisions/ADR-021-lambda-microvms-compute-backend.md index 3da49c7fa..5355594d6 100644 --- a/docs/decisions/ADR-021-lambda-microvms-compute-backend.md +++ b/docs/decisions/ADR-021-lambda-microvms-compute-backend.md @@ -199,25 +199,28 @@ The binary was fine — in the identical image, locally, `claude --version` answ Both halves of the fix are kept, because they answer different questions. `/ready` now **exec's the heavyweight binaries before returning 200** (`claude` required, `git`/`node` best-effort), which is the only mechanism that can make the shipped snapshot warm — and its own budget rises to 300 s, well inside the 3600 s build-hook window, because it now does work whose duration is a cold `exec`. Two structural rules keep that honest, because **per-command timeouts do not compose**: the required command runs FIRST with its own budget so no best-effort warm-up can starve the one that decides whether the snapshot is usable, and the best-effort ones then SHARE the remainder of a total warm-up ceiling that sits inside the hook budget with margin (240 s against 300 s). Without them, three commands at 120 s each would be 360 s — a fix for a runtime failure that produces a build failure instead — and a single hung optional command could hold up a 200 that the required warm-up had already earned. Separately, the version probe's timeout goes from 10 s to 60 s: a probe that exists to print a version string into a log line gains nothing from a tight bound and loses the whole task when it trips. The general rule this generalises to, and the reason it belongs in the ADR rather than only in a comment: **on this backend, a first-touch cost that other substrates pay during container start is deferred to the first task instead**, so anything large and lazily-loaded is a turn-0 hazard unless it is touched in `/ready`. -**Payload delivery** reuses the ECS strategy's S3-pointer pattern, adapted to `runHookPayload` (**≤ 4 KB** — measured, see below): payloads that fit ride inline; the rest are uploaded by the strategy to a platform payload bucket (the ECS payload bucket pattern in `ecs-agent-cluster.ts`: orchestrator write access, compute-role read-only scoped to the bucket, lifecycle expiry on objects) with the S3 URI in `runHookPayload` in place of the payload itself — the MicroVM **execution role** holds the read grant, exactly as the ECS task role does today. Since P2 the hook body also carries `platform_config` in both branches, so `runHookPayload` is never *only* the URI (see the canonical shapes below). +**Payload delivery — v2 amendment (2026-09-13, #817/#700).** The local implementation now shares an authenticated bootstrap protocol between ECS and MicroVM. This replaces the original inline/S3-pointer protocol and broad worker payload-bucket read grant. The historical P1/P2 runs below predate this amendment; AWS authorization, networking, expiry and coordinated deployment validation remain pending. The repository runbook is `docs/verification/645-payload-bootstrap.md`. -The cap is **4 096 bytes**, not the 16 384 the SDK documents. Measured exactly: 4 096 passes, 4 097 is rejected with *"Value at 'runHookPayload' failed to satisfy constraint: Member must have length less than or equal to 4096"*. Two consequences follow. First, the original threshold would have inlined every envelope between 4 097 and 16 384 bytes and had the service reject all of them. Second, and more structurally: **the S3-pointer path is now the dominant one, and inline is the exception.** A hydrated task payload (prompt + issue thread + repo context) essentially always exceeds 4 KB, so "small payloads ride inline" describes tiny repo-less prompts rather than the common case. The payload bucket is therefore not a rarely-exercised overflow valve but a required part of every normal task, which raises its lifecycle rule (`MICROVM_PAYLOAD_TTL_DAYS`) and the execution role's read grant from edge-case plumbing to load-bearing. +Every task uses S3. The coordinator publishes a non-secret deployment manifest at `bootstrap/.json`, conditionally creates `/payload.json`, and sends a short-lived signed URL for that one task object. The worker reads the manifest with its own AWS role, whose policy explicitly denies object reads outside its deployment's `bootstrap/*` and denies payload-bucket listing. The explicit deny also prevents a foreign public bucket from authenticating a forged manifest. The task document must name the reference's task ID and contain the exact manifest configuration before the MicroVM installs any of it. -**Canonical wire shapes.** Three, and the producer (`lambda-microvm-strategy.ts`) emits exactly these: +The `runHookPayload` cap remains **4,096 bytes**, measured against the service despite the SDK's documented 16,384. It now applies to the serialized reference rather than choosing an inline branch. Payloads are capped at 8 MiB and manifests at 16 KiB; the bounds and version are shared in `contracts/constants.json`. -| Where | Exact shape | +| Location | v2 shape | |---|---| -| `runHookPayload`, inline branch | `{"agent_payload": {…}, "platform_config": {…}}` | -| `runHookPayload`, pointer branch | `{"agent_payload_s3_uri": "s3://…", "platform_config": {…}}` | -| the object at that S3 URI | `{…agent_payload fields…, "platform_config": {…}}` — the payload's own fields at the TOP level, with the config merged in beside them | +| `runHookPayload` string / ECS `AGENT_PAYLOAD_REF` | `{version:2, task_id, bootstrap_s3_uri, payload_url, expires_at}` | +| `bootstrap/.json` | `{version:2, backend, platform_config}` | +| `/payload.json` | `{version:2, task_id, agent_payload, platform_config}` | +| Private `/launch.json` | `{fingerprint, reference}`; coordinator-readable only, never on the agent-readable task row | -Two asymmetries are deliberate and must not be "tidied" without changing both sides. First, **the S3 object is not the envelope**: the payload's fields sit at the top level (that is what P1 uploaded, before `platform_config` existed) rather than nested under an `agent_payload` key. Second, **`platform_config` is duplicated** on the pointer path — once beside the pointer, once inside the uploaded object. It costs a few hundred bytes and buys the property that the config is reachable whichever end of the fetch a reader looks at, which matters because it is the agent's only substitute for an env block. +The coordinator saves the exact reference for replay: re-signing would change a Run request with the same client token. Task objects use conditional creation and read-back recovery after a lost committed write. URL lifetime is at most 900 seconds, bounded by known credential expiry, and initial creation requires at least 300 seconds. Expired saved references fail without re-signing. The coordinator needs bucket-scoped `ListBucket` so an absent launch record returns `NoSuchKey` rather than `AccessDenied`. It deletes both task objects at finalization; one-day lifecycle expiry is the backstop. Manifests are refreshed with identical bytes at preparation and may coexist across configuration revisions until lifecycle cleanup. -The agent's reader is deliberately more permissive than this contract: it also accepts an S3 object shaped like the envelope (`agent_payload` nested), and `platform_config` present in only one of the two places (the fetched object wins, the hook body is the fallback). Those are **defensive compatibility** for the independent deploy cadences of a snapshot image and the orchestrator Lambda — a tolerant reader, not an alternative contract. A producer must emit the three shapes above. +The image accepts only v2. The old inline/pointer forms and baked-environment fallback are rejected. A coordinated drain and switch of coordinator, images and application IAM is required; there is no new KMS/SSM resource or bootstrap bundle version. Signed URLs are bearer capabilities and must never appear in task rows, ordinary logs or repository subprocess environments. ECS consumes/removes its reference before importing the task pipeline. The URL consumer restricts requests to the exact task object on regional S3 HTTPS, disables redirects/proxies and bounds response bytes. AWS verifies signatures and actual expiration. -**Platform configuration delivery (P2): payload-sourced, allowlisted, fail-closed.** The other two backends hand the agent its non-secret platform env at launch — AgentCore Runtime env vars, ECS container overrides — and there is no equivalent on this substrate: a MicroVM starts from a **snapshot**, so its process environment is whatever was frozen at *image build* time and is then replayed by every MicroVM launched from that image version. Baking the deployment's identifiers into the snapshot would make them **version-frozen**: a redeploy that renames a table, adds a bucket or rotates the session role would leave every existing image version describing a deployment that no longer exists, and the drift would surface as a task-time `ResourceNotFound` rather than a deploy-time error. So the values travel with the task instead: `platform_config` is a SIBLING of the payload — beside `agent_payload` in the inline branch, beside `agent_payload_s3_uri` in the pointer branch, and merged in beside the payload's own fields inside the S3 object (the canonical shapes above give each one exactly) — whose snake_case keys the agent installs into `os.environ` as their UPPER_SNAKE equivalents. A payload value therefore **wins** over any pre-existing/image value — the orchestrator is describing the live deployment, the snapshot is describing a past one. `platform_config` carries **non-secret identifiers only** (table and bucket names, secret ARNs, the session-role ARN); secrets are still fetched at `/run` time from Secrets Manager using those ARNs, so the snapshot-must-stay-secret-free requirement above is untouched. Per-task fields — `memory_id` and friends — stay inside `agent_payload`: `platform_config` configures the *process*, `agent_payload` describes the *task*. +**Platform configuration delivery (P2, strengthened by v2).** A MicroVM restores a snapshot, including its process environment, so current deployment identifiers must arrive at task launch. The authenticated manifest and downloaded document both contain `platform_config`: non-secret table/bucket names, secret ARNs and session-role ARN. Per-task fields such as `memory_id` remain in `agent_payload`. ECS's manifest config is empty because ECS already receives deployment settings through its task definition and coordinator overrides. -Two rules make it safe. First, **the allowlist fails closed**: the agent installs a fixed set of keys and *rejects the entire run* (HTTP 400, nothing spawned, not one key installed) if the block carries anything else. These values become environment variables of the process that spawns the agent's tool subprocesses, so an unrecognised key is an attempt to set an arbitrary variable in the agent (`AWS_ENDPOINT_URL`, `LD_PRELOAD`, `PATH`, …) — an injection attempt, not a forward-compatibility gap, which is why unknown keys are refused rather than filtered out. Second, **installation happens before any credential or pipeline initialisation** on the hook path: the very next step reads `GITHUB_TOKEN_SECRET_ARN` to resolve the GitHub token and `AGENT_SESSION_ROLE_ARN` to scope the task's credentials, so installing later would silently resolve the whole task against the snapshot's frozen env. The one call that must precede installation is the S3 payload fetch (the config is *inside* the fetched object), which therefore runs on the ambient compute role via the attributed platform client — and it is the ONLY one: the same rule covers **logging**, so every `/run` log line before the install is stdout-only. The CloudWatch writer would otherwise resolve credentials and pin them in a boto3 default session (credentials only; clients still re-resolve the region) off whatever a snapshot happened to bake, which is the build-hook defect one phase later. Nothing is lost — in the intended deployment there is no baked `LOG_GROUP_NAME`, so those lines would have gone to stdout anyway, and the reason for every pre-install rejection also travels in the structured 4xx/5xx body the service surfaces. A **required subset** (task table, task-events table, GitHub token secret ARN, session-role ARN) is rejected as `…_INCOMPLETE` when missing or blank — a distinct wire code from the `…_INVALID` allowlist rejection, because the remedies differ (deployment wiring vs. producer bug). A `/run` envelope with *no* `platform_config` at all is still accepted, loudly warned: the image snapshot and the orchestrator Lambda deploy on independent cadences, and a new image must not require a same-instant orchestrator. The key set is a cross-package contract in `contracts/constants.json` (`microvm_platform_config`), consumed by the agent's `/run` hook and produced by the orchestrator, with shape and required-subset invariants enforced by `scripts/check-constants-sync.ts`. +MicroVM installs only allowlisted keys and rejects unknown keys before installing any. Required identifiers must be nonblank; malformed/control-character values and inconsistent ARN partitions/accounts are rejected. Legitimate cross-region secrets remain allowed when present in the trusted manifest. Account agreement alone cannot authenticate a sibling ARN; v2's manifest/config comparison supplies the provenance check. No-config envelopes are rejected regardless of the image's existing environment. + +Manifest read and signed payload download precede configuration installation. Secrets, task-scoped credential setup, CloudWatch initialization and the pipeline follow installation; pre-install diagnostics use stdout without unsafe exception chains. Build hooks remain AWS-silent. The settings allowlist and bootstrap bounds are cross-language contracts with drift checks. These source guarantees do not establish complete hostile-worker isolation: roles still retain other platform grants and choose session tags, and a stolen signed URL remains usable until expiry or revocation. **No orchestrator→agent HTTP path exists in P1–P3**: payload arrives through the `/run` hook, all agent work is outbound, and therefore **no JWE auth tokens are minted at all** — token minting (and its ≤ 60 min TTL refresh problem) is deferred until a real consumer exists (e.g. operator shell access, [#391](https://github.com/aws-samples/sample-autonomous-cloud-coding-agents/issues/391)). The `endpoint` stays in the `SessionHandle` because it is genuinely per-session state that becomes load-bearing the day such a consumer appears. But note the service does not agree by default: omitting `ingressNetworkConnectors` on `RunMicrovm` attaches a **public** `HTTP_INGRESS` connector, so the strategy passes the Lambda-managed `NO_INGRESS` connector explicitly on every launch (see sub-decision 4's security table). @@ -226,12 +229,12 @@ Two rules make it safe. First, **the allowlist fails closed**: the agent install Normative requirements (EARS). **Each requirement's own `(Pn)` tag is authoritative**; there is no blanket phase for the list. The tags are per-requirement because the original list *was* split P1/P2 on the assumption that a hook could be declared in one phase and served in a later one — which the service does not permit (see the phasing table above), so the hook-serving requirements collapsed into P1 while the P2 items below arrived with the P2 hooks and `platform_config`: - (P1) The image build shall not embed secrets, tokens, or per-task identity in the snapshot. -- (P1) If the task payload exceeds the 4 KB `runHookPayload` limit, then the strategy shall upload the payload to the platform payload bucket and pass its S3 URI in `runHookPayload` in place of the payload (from P2, alongside `platform_config`). -- (P1) The MicroVM execution role shall hold read-only access to the payload bucket, scoped to that bucket. +- (P1, amended by v2) Every task shall use the authenticated manifest and single-object signed payload reference; the serialized hook reference shall not exceed 4,096 bytes. +- (P1, amended by v2) The worker role shall read only deployment bootstrap manifests with ambient credentials; other object reads and payload-bucket listing shall be explicitly denied. The coordinator shall own task-object writes, signing, replay and deletion. - (P1) Where no ingress is configured for a deployment, the strategy shall pass the Lambda-managed `NO_INGRESS` network connector on every `RunMicrovm` call (the field shall not be omitted). - (P1) Where the image enables any MicroVM lifecycle hook, the image shall also enable the `/ready` hook and the agent shall serve it. - (P1) When the `/run` hook receives the task payload, the agent shall validate it, start the pipeline asynchronously, and return HTTP 200 within the hook budget. -- (P1) If the `/run` hook payload cannot be resolved to a task payload, then the agent shall reject the hook with a client error and shall not start a pipeline. +- (P1, clarified) Invalid hook references shall return a structured client error; unreadable manifest/payload bytes shall return a structured server error. Neither path shall install configuration or start a pipeline. - (P1) The agent shall not execute the clone→verify→PR pipeline on the hook path. - (P1) The agent shall resolve credentials at `/run` time. - (P1) Where a deployment configures a MicroVM image before smoke parity is verified, the platform shall warn that the backend has no smoke-parity guarantee. @@ -408,8 +411,8 @@ P3 implements sub-decisions 1 and 2 as written: mandatory `suspendSession`/`resu **P1 (start/poll/stop — no suspend):** -- Unit tests for the strategy: start/poll/stop mapping (including `SessionStatus` `'suspended'` reported mechanically, without task-state interpretation), payload-size branching (inline vs S3 pointer, at the exact 4 096/4 097-byte boundary), the image-identifier-must-be-an-ARN guard, the explicit `NO_INGRESS` argument (including the blank-env-var fallback, which must never omit the field), error classification (`ServiceQuotaExceededException`, `ThrottlingException`, `ResourceNotFoundException`, regional-unavailability), the omit-`idlePolicy` invariant, and `maximumDurationInSeconds` fixed at 28 800. -- Agent tests: `/ready` returns 200 once the server is up and starts nothing; `/run` accepts both envelope shapes (inline and S3 pointer), starts the pipeline asynchronously through the same mapper `/invocations` uses, returns before the pipeline finishes, and rejects every unusable envelope with a named code before spawning; `/suspend` and `/resume` are NOT served (`/validate` and `/terminate` joined the served set in P2). +- Unit tests for the strategy: start/poll/stop mapping (including `SessionStatus` `'suspended'` reported mechanically, without task-state interpretation), v2 reference-size bounds (4,096 bytes), immutable signed-reference replay and scoped payload transport, the image-identifier-must-be-an-ARN guard, the explicit `NO_INGRESS` argument (including the blank-env-var fallback, which must never omit the field), error classification (`ServiceQuotaExceededException`, `ThrottlingException`, `ResourceNotFoundException`, regional-unavailability), the omit-`idlePolicy` invariant, and `maximumDurationInSeconds` fixed at 28 800. +- Agent tests: `/ready` returns 200 after required local warm-up succeeds, without starting a task or calling AWS; `/run` accepts authenticated v2 references and rejects old unsigned envelopes, starts the pipeline asynchronously through the same mapper `/invocations` uses, returns before the pipeline finishes, and rejects every unusable envelope with a named code before spawning; `/suspend` and `/resume` are NOT served (`/validate` and `/terminate` joined the served set in P2). - Orchestrator tests: substrate-terminal + non-terminal task status → failed classification; `suspended` + non-`AWAITING_APPROVAL` status → anomaly event, no fail-fast; `compute_metadata` persisted with `microvmId`/`endpoint` after `startSession`. - CDK assertions: MicroVM resources present only when `ComputeTypes` includes the backend; synth failure for unsupported regions (plus the context-flag escape hatch); memory size validated against the accepted list at synth; the connector operator role and its trust; two connectors with the build-only one carrying port 80 and the runtime one not; the `/ready` + `/run` hook declaration and the absence of the others; IAM actions scoped as specified (orchestrator lifecycle set; no `CreateMicrovmAuthToken` anywhere); payload-bucket grants (execution role read-only); backend cost-allocation tags; types-sync check covers the widened `ComputeType`. - CLI tests: onboarding rejection with remedy when the availability probe fails; doctor check present when a blueprint selects the backend. diff --git a/docs/design/COMPUTE.md b/docs/design/COMPUTE.md index 79a8c6797..71ae20773 100644 --- a/docs/design/COMPUTE.md +++ b/docs/design/COMPUTE.md @@ -117,7 +117,7 @@ See [ORCHESTRATOR.md](./ORCHESTRATOR.md) for how the orchestrator handles these Lambda MicroVMs are an opt-in third backend. Include `lambda-microvm` in `compute_types`; repositories inherit the first listed backend or choose a deployed backend through an override. Legacy `compute_type=lambda-microvm` deploys AgentCore and MicroVM, with AgentCore as the default. Image configuration has three states: a managed base-image ARN and version creates the snapshot image in CDK; an external image identifier uses a snapshot built out of band; and supplying neither provisions only the roles, buckets, and connectors needed for the bootstrap deploy. `cdk/scripts/package-microvm-artifact.sh` packages the agent as zip + Dockerfile, uploads it to the artifact bucket, and can create the external image. Lambda MicroVMs are available in five launch regions (us-east-1, us-east-2, us-west-2, eu-west-1, ap-northeast-1) and will expand; the platform enforces regional availability in layers via a synth-time constant, onboarding live probes, and orchestration-time classification. -Because a snapshot freezes its build-time environment, deployment-specific, non-secret identifiers travel in the `/run` hook's `platform_config` block instead. The strategy sends the canonical inline envelope or, when that envelope exceeds the verified 4,096-byte `runHookPayload` limit, an S3-pointer envelope with the configuration also merged into the uploaded payload. The agent accepts only allowlisted keys and installs them before pipeline initialization; [ADR-021 §3](../decisions/ADR-021-lambda-microvms-compute-backend.md#3-packaging-same-agent-image-source-new-build-path) defines the exact wire shapes and validation rules. +Because a snapshot freezes its build-time environment, current deployment identifiers arrive through the v2 payload bootstrap. The coordinator publishes a non-secret deployment manifest and sends a single-object signed download URL for the task. The worker reads only its deployment's `bootstrap/*` with ambient credentials; other object reads and payload-bucket listing are explicitly denied. The downloaded task identity and configuration must match the authenticated manifest before configuration installation. The serialized reference fits the verified 4,096-byte hook limit; all payload sizes use S3. ECS shares this transport through `AGENT_PAYLOAD_REF`. [ADR-021 §3](../decisions/ADR-021-lambda-microvms-compute-backend.md#3-packaging-same-agent-image-source-new-build-path) defines the wire format, compatibility change and pending live gates. Networking separates image build from execution: the build-only connector permits TCP 80 and 443 because the Dockerfile uses `apt-get`, while running MicroVMs retain 443-only egress through the platform VPC. Every launch explicitly passes the Lambda-managed `NO_INGRESS` connector; omission would select the service's public-ingress default. The P2 image declares and serves `/ready` and `/validate` at build time and `/run` and `/terminate` at runtime. The P3 image also serves `/suspend` and `/resume`. diff --git a/docs/design/SECURITY.md b/docs/design/SECURITY.md index fafc9f840..be177fe8c 100644 --- a/docs/design/SECURITY.md +++ b/docs/design/SECURITY.md @@ -48,7 +48,10 @@ The compute role retains only non-tenant access (Bedrock model invocation — al **Lambda MicroVMs credentials after sleep (P3)** - A resumed MicroVM must not sign with keys cached before the freeze. `/resume` refreshes the task-scoped SessionRole and ambient credentials before releasing coding, and the Claude CLI reads credentials from a loopback container-credential broker that renews them synchronously instead of the export helper's stale cache. Suspension changes no IAM scope. -**Lambda MicroVMs compute-role delta** - On this backend the compute role additionally holds prefix-scoped `secretsmanager:GetSecretValue` on the per-workspace channel-OAuth secrets (`bgagent-linear-oauth-*`, `bgagent-jira-oauth-*`), read access to the `/run` payload bucket (the task payload arrives as an S3 object, not as environment), and `ec2:DescribeAvailabilityZones` (`Resource: *`, read-only — EC2 describe actions have no resource-level scoping) for a CDK repo's own synth gate. It is also **the only compute role in the platform whose trust policy carries no confused-deputy condition**: the Lambda MicroVMs service populates no `aws:SourceAccount` or `aws:SourceArn` when it assumes the role, so a trust policy carrying one is unassumable — verified live, not assumed (connector creation failed deterministically, and `RunMicrovm` surfaced the same root cause as a misleading caller-side `iam:PassRole` denial). The compensating controls are that each of the three MicroVM roles can be passed to `lambda.amazonaws.com` only by a named principal — the orchestrator, via an `iam:PassRole` scoped to the execution role's exact ARN, and the CloudFormation deployment role for the build and connector-operator roles — that every other resource they reach is account-scoped by ARN apart from two justified `Resource: *` read/create-time statements, and that none of them holds `iam:*`, cross-account trust, or any `sts:AssumeRole` beyond the execution role's scoped hop to the per-task SessionRole. Full evidence, the two-arm PassRole experiment, and the alternatives considered are in [ADR-021 §4](../decisions/ADR-021-lambda-microvms-compute-backend.md#4-infra-and-iam-conditional-resources-behind-bootstrap-computetypes). +**Lambda MicroVMs compute-role delta** - On this backend the compute role additionally holds prefix-scoped `secretsmanager:GetSecretValue` on the per-workspace channel-OAuth secrets (`bgagent-linear-oauth-*`, `bgagent-jira-oauth-*`), read access only to its payload bucket's `bootstrap/*` manifests (other object reads and payload-bucket listing are explicitly denied), and `ec2:DescribeAvailabilityZones` (`Resource: *`, read-only — EC2 describe actions have no resource-level scoping) for a CDK repo's own synth gate. It is also **the only compute role in the platform whose trust policy carries no confused-deputy condition**: the Lambda MicroVMs service populates no `aws:SourceAccount` or `aws:SourceArn` when it assumes the role, so a trust policy carrying one is unassumable — verified live, not assumed (connector creation failed deterministically, and `RunMicrovm` surfaced the same root cause as a misleading caller-side `iam:PassRole` denial). The compensating controls are that each of the three MicroVM roles can be passed to `lambda.amazonaws.com` only by a named principal — the orchestrator, via an `iam:PassRole` scoped to the execution role's exact ARN, and the CloudFormation deployment role for the build and connector-operator roles — that every other resource they reach is account-scoped by ARN apart from two justified `Resource: *` read/create-time statements, and that none of them holds `iam:*`, cross-account trust, or any `sts:AssumeRole` beyond the execution role's scoped hop to the per-task SessionRole. Full evidence, the two-arm PassRole experiment, and the alternatives considered are in [ADR-021 §4](../decisions/ADR-021-lambda-microvms-compute-backend.md#4-infra-and-iam-conditional-resources-behind-bootstrap-computetypes). + +**ECS/MicroVM task bootstrap (v2)** — The coordinator publishes non-secret deployment manifests and supplies a short-lived signed URL for exactly one task's payload. The worker reads the manifest with its ambient role, whose explicit deny outside its own `bootstrap/*` prevents a foreign public bucket from authorizing fake configuration. It verifies downloaded task identity and exact manifest/config agreement before installing MicroVM settings. The coordinator privately persists the URL outside TaskTable for retry and deletes both task objects at finalization. Worker roles cannot read/list task objects using their ambient credentials. A signed URL is a bearer capability: redact it in errors and keep it out of task rows and repository subprocess environments. Existing session-tag trust and other platform grants remain separate limitations. This protocol is implemented locally; real IAM/network/expiry gates and the coordinated image/coordinator/policy rollout are documented in the repository's `docs/verification/645-payload-bootstrap.md`. + > Out of scope for this control and tracked separately as GitHub issues: replacing the shared GitHub PAT (GitHub App / Token Vault), binding credentials to the MicroVM via attestation, and scoping AgentCore Memory (namespace isolation by `actorId`/`sessionId` remains its boundary). diff --git a/docs/src/content/docs/architecture/Compute.md b/docs/src/content/docs/architecture/Compute.md index 62296be74..3d96c7592 100644 --- a/docs/src/content/docs/architecture/Compute.md +++ b/docs/src/content/docs/architecture/Compute.md @@ -119,7 +119,7 @@ See [ORCHESTRATOR.md](/sample-autonomous-cloud-coding-agents/architecture/orches Lambda MicroVMs are an opt-in third backend. Include `lambda-microvm` in `compute_types`; repositories inherit the first listed backend or choose a deployed backend through an override. Legacy `compute_type=lambda-microvm` deploys AgentCore and MicroVM, with AgentCore as the default. Image configuration has three states: a managed base-image ARN and version creates the snapshot image in CDK; an external image identifier uses a snapshot built out of band; and supplying neither provisions only the roles, buckets, and connectors needed for the bootstrap deploy. `cdk/scripts/package-microvm-artifact.sh` packages the agent as zip + Dockerfile, uploads it to the artifact bucket, and can create the external image. Lambda MicroVMs are available in five launch regions (us-east-1, us-east-2, us-west-2, eu-west-1, ap-northeast-1) and will expand; the platform enforces regional availability in layers via a synth-time constant, onboarding live probes, and orchestration-time classification. -Because a snapshot freezes its build-time environment, deployment-specific, non-secret identifiers travel in the `/run` hook's `platform_config` block instead. The strategy sends the canonical inline envelope or, when that envelope exceeds the verified 4,096-byte `runHookPayload` limit, an S3-pointer envelope with the configuration also merged into the uploaded payload. The agent accepts only allowlisted keys and installs them before pipeline initialization; [ADR-021 §3](/sample-autonomous-cloud-coding-agents/decisions/adr-021-lambda-microvms-compute-backend#3-packaging-same-agent-image-source-new-build-path) defines the exact wire shapes and validation rules. +Because a snapshot freezes its build-time environment, current deployment identifiers arrive through the v2 payload bootstrap. The coordinator publishes a non-secret deployment manifest and sends a single-object signed download URL for the task. The worker reads only its deployment's `bootstrap/*` with ambient credentials; other object reads and payload-bucket listing are explicitly denied. The downloaded task identity and configuration must match the authenticated manifest before configuration installation. The serialized reference fits the verified 4,096-byte hook limit; all payload sizes use S3. ECS shares this transport through `AGENT_PAYLOAD_REF`. [ADR-021 §3](/sample-autonomous-cloud-coding-agents/decisions/adr-021-lambda-microvms-compute-backend#3-packaging-same-agent-image-source-new-build-path) defines the wire format, compatibility change and pending live gates. Networking separates image build from execution: the build-only connector permits TCP 80 and 443 because the Dockerfile uses `apt-get`, while running MicroVMs retain 443-only egress through the platform VPC. Every launch explicitly passes the Lambda-managed `NO_INGRESS` connector; omission would select the service's public-ingress default. The P2 image declares and serves `/ready` and `/validate` at build time and `/run` and `/terminate` at runtime. The P3 image also serves `/suspend` and `/resume`. diff --git a/docs/src/content/docs/architecture/Security.md b/docs/src/content/docs/architecture/Security.md index f7f178c44..41f36907a 100644 --- a/docs/src/content/docs/architecture/Security.md +++ b/docs/src/content/docs/architecture/Security.md @@ -50,7 +50,10 @@ The compute role retains only non-tenant access (Bedrock model invocation — al **Lambda MicroVMs credentials after sleep (P3)** - A resumed MicroVM must not sign with keys cached before the freeze. `/resume` refreshes the task-scoped SessionRole and ambient credentials before releasing coding, and the Claude CLI reads credentials from a loopback container-credential broker that renews them synchronously instead of the export helper's stale cache. Suspension changes no IAM scope. -**Lambda MicroVMs compute-role delta** - On this backend the compute role additionally holds prefix-scoped `secretsmanager:GetSecretValue` on the per-workspace channel-OAuth secrets (`bgagent-linear-oauth-*`, `bgagent-jira-oauth-*`), read access to the `/run` payload bucket (the task payload arrives as an S3 object, not as environment), and `ec2:DescribeAvailabilityZones` (`Resource: *`, read-only — EC2 describe actions have no resource-level scoping) for a CDK repo's own synth gate. It is also **the only compute role in the platform whose trust policy carries no confused-deputy condition**: the Lambda MicroVMs service populates no `aws:SourceAccount` or `aws:SourceArn` when it assumes the role, so a trust policy carrying one is unassumable — verified live, not assumed (connector creation failed deterministically, and `RunMicrovm` surfaced the same root cause as a misleading caller-side `iam:PassRole` denial). The compensating controls are that each of the three MicroVM roles can be passed to `lambda.amazonaws.com` only by a named principal — the orchestrator, via an `iam:PassRole` scoped to the execution role's exact ARN, and the CloudFormation deployment role for the build and connector-operator roles — that every other resource they reach is account-scoped by ARN apart from two justified `Resource: *` read/create-time statements, and that none of them holds `iam:*`, cross-account trust, or any `sts:AssumeRole` beyond the execution role's scoped hop to the per-task SessionRole. Full evidence, the two-arm PassRole experiment, and the alternatives considered are in [ADR-021 §4](/sample-autonomous-cloud-coding-agents/decisions/adr-021-lambda-microvms-compute-backend#4-infra-and-iam-conditional-resources-behind-bootstrap-computetypes). +**Lambda MicroVMs compute-role delta** - On this backend the compute role additionally holds prefix-scoped `secretsmanager:GetSecretValue` on the per-workspace channel-OAuth secrets (`bgagent-linear-oauth-*`, `bgagent-jira-oauth-*`), read access only to its payload bucket's `bootstrap/*` manifests (other object reads and payload-bucket listing are explicitly denied), and `ec2:DescribeAvailabilityZones` (`Resource: *`, read-only — EC2 describe actions have no resource-level scoping) for a CDK repo's own synth gate. It is also **the only compute role in the platform whose trust policy carries no confused-deputy condition**: the Lambda MicroVMs service populates no `aws:SourceAccount` or `aws:SourceArn` when it assumes the role, so a trust policy carrying one is unassumable — verified live, not assumed (connector creation failed deterministically, and `RunMicrovm` surfaced the same root cause as a misleading caller-side `iam:PassRole` denial). The compensating controls are that each of the three MicroVM roles can be passed to `lambda.amazonaws.com` only by a named principal — the orchestrator, via an `iam:PassRole` scoped to the execution role's exact ARN, and the CloudFormation deployment role for the build and connector-operator roles — that every other resource they reach is account-scoped by ARN apart from two justified `Resource: *` read/create-time statements, and that none of them holds `iam:*`, cross-account trust, or any `sts:AssumeRole` beyond the execution role's scoped hop to the per-task SessionRole. Full evidence, the two-arm PassRole experiment, and the alternatives considered are in [ADR-021 §4](/sample-autonomous-cloud-coding-agents/decisions/adr-021-lambda-microvms-compute-backend#4-infra-and-iam-conditional-resources-behind-bootstrap-computetypes). + +**ECS/MicroVM task bootstrap (v2)** — The coordinator publishes non-secret deployment manifests and supplies a short-lived signed URL for exactly one task's payload. The worker reads the manifest with its ambient role, whose explicit deny outside its own `bootstrap/*` prevents a foreign public bucket from authorizing fake configuration. It verifies downloaded task identity and exact manifest/config agreement before installing MicroVM settings. The coordinator privately persists the URL outside TaskTable for retry and deletes both task objects at finalization. Worker roles cannot read/list task objects using their ambient credentials. A signed URL is a bearer capability: redact it in errors and keep it out of task rows and repository subprocess environments. Existing session-tag trust and other platform grants remain separate limitations. This protocol is implemented locally; real IAM/network/expiry gates and the coordinated image/coordinator/policy rollout are documented in the repository's `docs/verification/645-payload-bootstrap.md`. + > Out of scope for this control and tracked separately as GitHub issues: replacing the shared GitHub PAT (GitHub App / Token Vault), binding credentials to the MicroVM via attestation, and scoping AgentCore Memory (namespace isolation by `actorId`/`sessionId` remains its boundary). diff --git a/docs/src/content/docs/decisions/Adr-021-lambda-microvms-compute-backend.md b/docs/src/content/docs/decisions/Adr-021-lambda-microvms-compute-backend.md index 6cc6368c0..4a01eb7a4 100644 --- a/docs/src/content/docs/decisions/Adr-021-lambda-microvms-compute-backend.md +++ b/docs/src/content/docs/decisions/Adr-021-lambda-microvms-compute-backend.md @@ -201,25 +201,28 @@ The binary was fine — in the identical image, locally, `claude --version` answ Both halves of the fix are kept, because they answer different questions. `/ready` now **exec's the heavyweight binaries before returning 200** (`claude` required, `git`/`node` best-effort), which is the only mechanism that can make the shipped snapshot warm — and its own budget rises to 300 s, well inside the 3600 s build-hook window, because it now does work whose duration is a cold `exec`. Two structural rules keep that honest, because **per-command timeouts do not compose**: the required command runs FIRST with its own budget so no best-effort warm-up can starve the one that decides whether the snapshot is usable, and the best-effort ones then SHARE the remainder of a total warm-up ceiling that sits inside the hook budget with margin (240 s against 300 s). Without them, three commands at 120 s each would be 360 s — a fix for a runtime failure that produces a build failure instead — and a single hung optional command could hold up a 200 that the required warm-up had already earned. Separately, the version probe's timeout goes from 10 s to 60 s: a probe that exists to print a version string into a log line gains nothing from a tight bound and loses the whole task when it trips. The general rule this generalises to, and the reason it belongs in the ADR rather than only in a comment: **on this backend, a first-touch cost that other substrates pay during container start is deferred to the first task instead**, so anything large and lazily-loaded is a turn-0 hazard unless it is touched in `/ready`. -**Payload delivery** reuses the ECS strategy's S3-pointer pattern, adapted to `runHookPayload` (**≤ 4 KB** — measured, see below): payloads that fit ride inline; the rest are uploaded by the strategy to a platform payload bucket (the ECS payload bucket pattern in `ecs-agent-cluster.ts`: orchestrator write access, compute-role read-only scoped to the bucket, lifecycle expiry on objects) with the S3 URI in `runHookPayload` in place of the payload itself — the MicroVM **execution role** holds the read grant, exactly as the ECS task role does today. Since P2 the hook body also carries `platform_config` in both branches, so `runHookPayload` is never *only* the URI (see the canonical shapes below). +**Payload delivery — v2 amendment (2026-09-13, #817/#700).** The local implementation now shares an authenticated bootstrap protocol between ECS and MicroVM. This replaces the original inline/S3-pointer protocol and broad worker payload-bucket read grant. The historical P1/P2 runs below predate this amendment; AWS authorization, networking, expiry and coordinated deployment validation remain pending. The repository runbook is `docs/verification/645-payload-bootstrap.md`. -The cap is **4 096 bytes**, not the 16 384 the SDK documents. Measured exactly: 4 096 passes, 4 097 is rejected with *"Value at 'runHookPayload' failed to satisfy constraint: Member must have length less than or equal to 4096"*. Two consequences follow. First, the original threshold would have inlined every envelope between 4 097 and 16 384 bytes and had the service reject all of them. Second, and more structurally: **the S3-pointer path is now the dominant one, and inline is the exception.** A hydrated task payload (prompt + issue thread + repo context) essentially always exceeds 4 KB, so "small payloads ride inline" describes tiny repo-less prompts rather than the common case. The payload bucket is therefore not a rarely-exercised overflow valve but a required part of every normal task, which raises its lifecycle rule (`MICROVM_PAYLOAD_TTL_DAYS`) and the execution role's read grant from edge-case plumbing to load-bearing. +Every task uses S3. The coordinator publishes a non-secret deployment manifest at `bootstrap/.json`, conditionally creates `/payload.json`, and sends a short-lived signed URL for that one task object. The worker reads the manifest with its own AWS role, whose policy explicitly denies object reads outside its deployment's `bootstrap/*` and denies payload-bucket listing. The explicit deny also prevents a foreign public bucket from authenticating a forged manifest. The task document must name the reference's task ID and contain the exact manifest configuration before the MicroVM installs any of it. -**Canonical wire shapes.** Three, and the producer (`lambda-microvm-strategy.ts`) emits exactly these: +The `runHookPayload` cap remains **4,096 bytes**, measured against the service despite the SDK's documented 16,384. It now applies to the serialized reference rather than choosing an inline branch. Payloads are capped at 8 MiB and manifests at 16 KiB; the bounds and version are shared in `contracts/constants.json`. -| Where | Exact shape | +| Location | v2 shape | |---|---| -| `runHookPayload`, inline branch | `{"agent_payload": {…}, "platform_config": {…}}` | -| `runHookPayload`, pointer branch | `{"agent_payload_s3_uri": "s3://…", "platform_config": {…}}` | -| the object at that S3 URI | `{…agent_payload fields…, "platform_config": {…}}` — the payload's own fields at the TOP level, with the config merged in beside them | +| `runHookPayload` string / ECS `AGENT_PAYLOAD_REF` | `{version:2, task_id, bootstrap_s3_uri, payload_url, expires_at}` | +| `bootstrap/.json` | `{version:2, backend, platform_config}` | +| `/payload.json` | `{version:2, task_id, agent_payload, platform_config}` | +| Private `/launch.json` | `{fingerprint, reference}`; coordinator-readable only, never on the agent-readable task row | -Two asymmetries are deliberate and must not be "tidied" without changing both sides. First, **the S3 object is not the envelope**: the payload's fields sit at the top level (that is what P1 uploaded, before `platform_config` existed) rather than nested under an `agent_payload` key. Second, **`platform_config` is duplicated** on the pointer path — once beside the pointer, once inside the uploaded object. It costs a few hundred bytes and buys the property that the config is reachable whichever end of the fetch a reader looks at, which matters because it is the agent's only substitute for an env block. +The coordinator saves the exact reference for replay: re-signing would change a Run request with the same client token. Task objects use conditional creation and read-back recovery after a lost committed write. URL lifetime is at most 900 seconds, bounded by known credential expiry, and initial creation requires at least 300 seconds. Expired saved references fail without re-signing. The coordinator needs bucket-scoped `ListBucket` so an absent launch record returns `NoSuchKey` rather than `AccessDenied`. It deletes both task objects at finalization; one-day lifecycle expiry is the backstop. Manifests are refreshed with identical bytes at preparation and may coexist across configuration revisions until lifecycle cleanup. -The agent's reader is deliberately more permissive than this contract: it also accepts an S3 object shaped like the envelope (`agent_payload` nested), and `platform_config` present in only one of the two places (the fetched object wins, the hook body is the fallback). Those are **defensive compatibility** for the independent deploy cadences of a snapshot image and the orchestrator Lambda — a tolerant reader, not an alternative contract. A producer must emit the three shapes above. +The image accepts only v2. The old inline/pointer forms and baked-environment fallback are rejected. A coordinated drain and switch of coordinator, images and application IAM is required; there is no new KMS/SSM resource or bootstrap bundle version. Signed URLs are bearer capabilities and must never appear in task rows, ordinary logs or repository subprocess environments. ECS consumes/removes its reference before importing the task pipeline. The URL consumer restricts requests to the exact task object on regional S3 HTTPS, disables redirects/proxies and bounds response bytes. AWS verifies signatures and actual expiration. -**Platform configuration delivery (P2): payload-sourced, allowlisted, fail-closed.** The other two backends hand the agent its non-secret platform env at launch — AgentCore Runtime env vars, ECS container overrides — and there is no equivalent on this substrate: a MicroVM starts from a **snapshot**, so its process environment is whatever was frozen at *image build* time and is then replayed by every MicroVM launched from that image version. Baking the deployment's identifiers into the snapshot would make them **version-frozen**: a redeploy that renames a table, adds a bucket or rotates the session role would leave every existing image version describing a deployment that no longer exists, and the drift would surface as a task-time `ResourceNotFound` rather than a deploy-time error. So the values travel with the task instead: `platform_config` is a SIBLING of the payload — beside `agent_payload` in the inline branch, beside `agent_payload_s3_uri` in the pointer branch, and merged in beside the payload's own fields inside the S3 object (the canonical shapes above give each one exactly) — whose snake_case keys the agent installs into `os.environ` as their UPPER_SNAKE equivalents. A payload value therefore **wins** over any pre-existing/image value — the orchestrator is describing the live deployment, the snapshot is describing a past one. `platform_config` carries **non-secret identifiers only** (table and bucket names, secret ARNs, the session-role ARN); secrets are still fetched at `/run` time from Secrets Manager using those ARNs, so the snapshot-must-stay-secret-free requirement above is untouched. Per-task fields — `memory_id` and friends — stay inside `agent_payload`: `platform_config` configures the *process*, `agent_payload` describes the *task*. +**Platform configuration delivery (P2, strengthened by v2).** A MicroVM restores a snapshot, including its process environment, so current deployment identifiers must arrive at task launch. The authenticated manifest and downloaded document both contain `platform_config`: non-secret table/bucket names, secret ARNs and session-role ARN. Per-task fields such as `memory_id` remain in `agent_payload`. ECS's manifest config is empty because ECS already receives deployment settings through its task definition and coordinator overrides. -Two rules make it safe. First, **the allowlist fails closed**: the agent installs a fixed set of keys and *rejects the entire run* (HTTP 400, nothing spawned, not one key installed) if the block carries anything else. These values become environment variables of the process that spawns the agent's tool subprocesses, so an unrecognised key is an attempt to set an arbitrary variable in the agent (`AWS_ENDPOINT_URL`, `LD_PRELOAD`, `PATH`, …) — an injection attempt, not a forward-compatibility gap, which is why unknown keys are refused rather than filtered out. Second, **installation happens before any credential or pipeline initialisation** on the hook path: the very next step reads `GITHUB_TOKEN_SECRET_ARN` to resolve the GitHub token and `AGENT_SESSION_ROLE_ARN` to scope the task's credentials, so installing later would silently resolve the whole task against the snapshot's frozen env. The one call that must precede installation is the S3 payload fetch (the config is *inside* the fetched object), which therefore runs on the ambient compute role via the attributed platform client — and it is the ONLY one: the same rule covers **logging**, so every `/run` log line before the install is stdout-only. The CloudWatch writer would otherwise resolve credentials and pin them in a boto3 default session (credentials only; clients still re-resolve the region) off whatever a snapshot happened to bake, which is the build-hook defect one phase later. Nothing is lost — in the intended deployment there is no baked `LOG_GROUP_NAME`, so those lines would have gone to stdout anyway, and the reason for every pre-install rejection also travels in the structured 4xx/5xx body the service surfaces. A **required subset** (task table, task-events table, GitHub token secret ARN, session-role ARN) is rejected as `…_INCOMPLETE` when missing or blank — a distinct wire code from the `…_INVALID` allowlist rejection, because the remedies differ (deployment wiring vs. producer bug). A `/run` envelope with *no* `platform_config` at all is still accepted, loudly warned: the image snapshot and the orchestrator Lambda deploy on independent cadences, and a new image must not require a same-instant orchestrator. The key set is a cross-package contract in `contracts/constants.json` (`microvm_platform_config`), consumed by the agent's `/run` hook and produced by the orchestrator, with shape and required-subset invariants enforced by `scripts/check-constants-sync.ts`. +MicroVM installs only allowlisted keys and rejects unknown keys before installing any. Required identifiers must be nonblank; malformed/control-character values and inconsistent ARN partitions/accounts are rejected. Legitimate cross-region secrets remain allowed when present in the trusted manifest. Account agreement alone cannot authenticate a sibling ARN; v2's manifest/config comparison supplies the provenance check. No-config envelopes are rejected regardless of the image's existing environment. + +Manifest read and signed payload download precede configuration installation. Secrets, task-scoped credential setup, CloudWatch initialization and the pipeline follow installation; pre-install diagnostics use stdout without unsafe exception chains. Build hooks remain AWS-silent. The settings allowlist and bootstrap bounds are cross-language contracts with drift checks. These source guarantees do not establish complete hostile-worker isolation: roles still retain other platform grants and choose session tags, and a stolen signed URL remains usable until expiry or revocation. **No orchestrator→agent HTTP path exists in P1–P3**: payload arrives through the `/run` hook, all agent work is outbound, and therefore **no JWE auth tokens are minted at all** — token minting (and its ≤ 60 min TTL refresh problem) is deferred until a real consumer exists (e.g. operator shell access, [#391](https://github.com/aws-samples/sample-autonomous-cloud-coding-agents/issues/391)). The `endpoint` stays in the `SessionHandle` because it is genuinely per-session state that becomes load-bearing the day such a consumer appears. But note the service does not agree by default: omitting `ingressNetworkConnectors` on `RunMicrovm` attaches a **public** `HTTP_INGRESS` connector, so the strategy passes the Lambda-managed `NO_INGRESS` connector explicitly on every launch (see sub-decision 4's security table). @@ -228,12 +231,12 @@ Two rules make it safe. First, **the allowlist fails closed**: the agent install Normative requirements (EARS). **Each requirement's own `(Pn)` tag is authoritative**; there is no blanket phase for the list. The tags are per-requirement because the original list *was* split P1/P2 on the assumption that a hook could be declared in one phase and served in a later one — which the service does not permit (see the phasing table above), so the hook-serving requirements collapsed into P1 while the P2 items below arrived with the P2 hooks and `platform_config`: - (P1) The image build shall not embed secrets, tokens, or per-task identity in the snapshot. -- (P1) If the task payload exceeds the 4 KB `runHookPayload` limit, then the strategy shall upload the payload to the platform payload bucket and pass its S3 URI in `runHookPayload` in place of the payload (from P2, alongside `platform_config`). -- (P1) The MicroVM execution role shall hold read-only access to the payload bucket, scoped to that bucket. +- (P1, amended by v2) Every task shall use the authenticated manifest and single-object signed payload reference; the serialized hook reference shall not exceed 4,096 bytes. +- (P1, amended by v2) The worker role shall read only deployment bootstrap manifests with ambient credentials; other object reads and payload-bucket listing shall be explicitly denied. The coordinator shall own task-object writes, signing, replay and deletion. - (P1) Where no ingress is configured for a deployment, the strategy shall pass the Lambda-managed `NO_INGRESS` network connector on every `RunMicrovm` call (the field shall not be omitted). - (P1) Where the image enables any MicroVM lifecycle hook, the image shall also enable the `/ready` hook and the agent shall serve it. - (P1) When the `/run` hook receives the task payload, the agent shall validate it, start the pipeline asynchronously, and return HTTP 200 within the hook budget. -- (P1) If the `/run` hook payload cannot be resolved to a task payload, then the agent shall reject the hook with a client error and shall not start a pipeline. +- (P1, clarified) Invalid hook references shall return a structured client error; unreadable manifest/payload bytes shall return a structured server error. Neither path shall install configuration or start a pipeline. - (P1) The agent shall not execute the clone→verify→PR pipeline on the hook path. - (P1) The agent shall resolve credentials at `/run` time. - (P1) Where a deployment configures a MicroVM image before smoke parity is verified, the platform shall warn that the backend has no smoke-parity guarantee. @@ -410,8 +413,8 @@ P3 implements sub-decisions 1 and 2 as written: mandatory `suspendSession`/`resu **P1 (start/poll/stop — no suspend):** -- Unit tests for the strategy: start/poll/stop mapping (including `SessionStatus` `'suspended'` reported mechanically, without task-state interpretation), payload-size branching (inline vs S3 pointer, at the exact 4 096/4 097-byte boundary), the image-identifier-must-be-an-ARN guard, the explicit `NO_INGRESS` argument (including the blank-env-var fallback, which must never omit the field), error classification (`ServiceQuotaExceededException`, `ThrottlingException`, `ResourceNotFoundException`, regional-unavailability), the omit-`idlePolicy` invariant, and `maximumDurationInSeconds` fixed at 28 800. -- Agent tests: `/ready` returns 200 once the server is up and starts nothing; `/run` accepts both envelope shapes (inline and S3 pointer), starts the pipeline asynchronously through the same mapper `/invocations` uses, returns before the pipeline finishes, and rejects every unusable envelope with a named code before spawning; `/suspend` and `/resume` are NOT served (`/validate` and `/terminate` joined the served set in P2). +- Unit tests for the strategy: start/poll/stop mapping (including `SessionStatus` `'suspended'` reported mechanically, without task-state interpretation), v2 reference-size bounds (4,096 bytes), immutable signed-reference replay and scoped payload transport, the image-identifier-must-be-an-ARN guard, the explicit `NO_INGRESS` argument (including the blank-env-var fallback, which must never omit the field), error classification (`ServiceQuotaExceededException`, `ThrottlingException`, `ResourceNotFoundException`, regional-unavailability), the omit-`idlePolicy` invariant, and `maximumDurationInSeconds` fixed at 28 800. +- Agent tests: `/ready` returns 200 after required local warm-up succeeds, without starting a task or calling AWS; `/run` accepts authenticated v2 references and rejects old unsigned envelopes, starts the pipeline asynchronously through the same mapper `/invocations` uses, returns before the pipeline finishes, and rejects every unusable envelope with a named code before spawning; `/suspend` and `/resume` are NOT served (`/validate` and `/terminate` joined the served set in P2). - Orchestrator tests: substrate-terminal + non-terminal task status → failed classification; `suspended` + non-`AWAITING_APPROVAL` status → anomaly event, no fail-fast; `compute_metadata` persisted with `microvmId`/`endpoint` after `startSession`. - CDK assertions: MicroVM resources present only when `ComputeTypes` includes the backend; synth failure for unsupported regions (plus the context-flag escape hatch); memory size validated against the accepted list at synth; the connector operator role and its trust; two connectors with the build-only one carrying port 80 and the runtime one not; the `/ready` + `/run` hook declaration and the absence of the others; IAM actions scoped as specified (orchestrator lifecycle set; no `CreateMicrovmAuthToken` anywhere); payload-bucket grants (execution role read-only); backend cost-allocation tags; types-sync check covers the widened `ComputeType`. - CLI tests: onboarding rejection with remedy when the availability probe fails; doctor check present when a blueprint selects the backend. diff --git a/docs/verification/645-payload-bootstrap.md b/docs/verification/645-payload-bootstrap.md new file mode 100644 index 000000000..f3b12f3bb --- /dev/null +++ b/docs/verification/645-payload-bootstrap.md @@ -0,0 +1,127 @@ +# #645: trusted task delivery for ECS and MicroVM + +Implementation date: 2026-09-13. Tracks the local prerequisites in #817 and #700. **Implemented locally; AWS authorization, networking, expiry and deployment checks below are still pending.** This does not implement P3 sleep/wake. + +## What changed, in plain language + +Think of S3 as a locked filing cabinet. A **bucket** is one cabinet and an **object** is one file. The **coordinator** is the supervisor that starts tasks. A **worker** is the ECS container or MicroVM that runs the coding agent. + +Previously, each worker's permission badge could read other tasks' instruction files. Also, checking that two AWS addresses named the same account did not prove either address belonged to this deployment. + +The new protocol gives the worker: + +1. A small **manifest**: a list of the deployment's non-secret settings. The worker reads this with its own AWS permission badge. Only this deployment's bootstrap directory is allowed. +2. A **presigned URL**: a temporary download ticket, created by the coordinator, for exactly one task's instruction file. AWS checks its signature. Possessing the ticket permits the read, so the complete URL must be treated like a password. + +The downloaded task must name the expected task ID and contain exactly the settings in the authenticated manifest. Changing a secret's address to another workspace in the same AWS account now fails this comparison. + +This bootstrap means “load the information needed to start a task.” It is distinct from the infrastructure bootstrap that installs deployment permissions. + +## Storage and wire contract + +Both backends use `contracts/constants.json` → `payload_bootstrap`, version 2. All task payloads use this path, including small tasks. + +| Location | Content / owner | +|---|---| +| `bootstrap/.json` | `{version:2, backend, platform_config}`. Coordinator writes; worker reads. The filename contains a SHA-256 digest: a fingerprint of the exact JSON bytes. | +| `/payload.json` | `{version:2, task_id, agent_payload, platform_config}`. Coordinator writes; worker downloads using the signed URL. | +| `/launch.json` | `{fingerprint, reference}`. Private coordinator replay record containing the signed URL. No worker read. | +| MicroVM `runHookPayload` / ECS `AGENT_PAYLOAD_REF` | JSON string containing the reference below. Never log it. | + +```json +{ + "version": 2, + "task_id": "TASK001", + "bootstrap_s3_uri": "s3://deployment-bucket/bootstrap/.json", + "payload_url": "", + "expires_at": 1789312500000 +} +``` + +The example is descriptive; the manifest digest and signed URL must be produced by the coordinator. `expires_at` is milliseconds since the Unix epoch. + +MicroVM manifests contain the allowlisted environment identifiers built from the coordinator's deployment environment. ECS manifests contain `{}` for `platform_config`: its platform settings already arrive through the trusted task definition and coordinator overrides. Task-specific fields remain in `agent_payload`. + +Manifest and payload limits are **16 KiB** and **8 MiB**, respectively. The serialized MicroVM reference must fit **4,096 bytes**. The entire ECS overrides object must fit **8,192 UTF-8 bytes**; the prompt is no longer duplicated in `TASK_DESCRIPTION`. + +The image rejects the old unsigned inline/S3 envelopes. There is no compatibility branch that accepts settings merely because an image already contains the required environment variables. + +## Permission boundary + +| Principal | Allowed | Denied / not granted | +|---|---|---| +| Worker ambient role | Exact `s3:GetObject` on its bucket's `bootstrap/*` | Explicit `Deny s3:GetObject*` outside that prefix, including other/public buckets; explicit `Deny s3:List*` on its payload bucket. No payload write/delete grant. | +| Trusted coordinator | `PutObject` on manifests and `*/payload.json`, `*/launch.json`; `GetObject`/`DeleteObject` on the two task paths; `ListBucket` on its payload bucket | No task-object version deletion or manifest deletion grant added by this helper. | + +The explicit denial outside `bootstrap/*` is essential. An allow-only policy would not authenticate configuration: an attacker-controlled public bucket could grant the worker access to a fake manifest. A successful read with the deployed deny policy establishes its permitted origin; the hash only detects different bytes, not authorship. + +The coordinator needs `ListBucket` because S3 returns **403 AccessDenied**, rather than **404 NoSuchKey**, for a missing object when the caller cannot list the bucket. The first launch probes for its saved record. Workers do not get this permission. + +AWS documents this in [GetObject permissions](https://docs.aws.amazon.com/AmazonS3/latest/API/API_GetObject.html). Its [conditional-write guide](https://docs.aws.amazon.com/AmazonS3/latest/userguide/conditional-writes.html) specifies that the first completed conditional write wins and later writes receive 412; a concurrent delete can produce 409. The [presigned-URL guide](https://docs.aws.amazon.com/AmazonS3/latest/userguide/using-presigned-url.html) confirms that temporary credential expiry can end a URL's validity before its requested expiry. These documents were checked during this review; deployed behavior remains a separate gate. + +The worker reads the manifest through the attributed `platform_client("s3")` before installing configuration. It then downloads the payload over HTTPS without adding worker credentials. Only the exact bucket/task key on a regional S3 host is accepted; redirects, environment proxies, alternate hosts, credentials in URLs, custom ports, duplicate query parameters and non-HTTPS URLs are rejected. AWS validates the actual signature and expiry; local URL checks are not a cryptographic verifier. + +The runtime still needs HTTPS/443 and DNS access to the selected S3 region. The source checks do not establish that the deployed connector permits it. Build hooks remain AWS-silent; before configuration installation, runtime bootstrap uses manifest-read and payload-download operations, and diagnostics go to stdout. + +## Retry, expiry and cleanup + +- The coordinator serializes JSON consistently and conditionally creates task objects with `IfNoneMatch: '*'`. A second writer cannot overwrite existing instructions. Read-back handles a write that committed but lost its reply. +- The saved launch record returns the **same URL** after a retry or coordinator restart. Generating a new URL would change the MicroVM Run request while reusing its client token. The private record is deliberately outside TaskTable because the agent can read its own task row. +- A URL is requested for at most **900 seconds**. If the SDK exposes an earlier credential expiry, that shortens the requested lifetime. Initial creation refuses a lifetime under **300 seconds**. AWS can still reject credentials earlier; the provider's actual expiration behavior needs live evidence. +- An expired saved reference fails explicitly; it is not silently re-signed. Recover any existing compute handle before deciding what to do. A timeout or expired ticket does not prove no worker started. MicroVM's saved-start receipt still governs its 120-second application replay window. +- The coordinator refreshes identical manifest bytes at each preparation so the bucket's one-day lifecycle does not remove an old manifest just before a new task reads it. Historical authorized manifests can coexist until lifecycle deletion; this is provenance authentication, not a “latest configuration only” policy. +- Finalization best-effort deletes both `payload.json` and `launch.json`. Deleting the current payload revokes its unversioned download link. Lifecycle deletion remains a backstop and is asynchronous, not an exact one-day alarm. +- ECS removes `AGENT_PAYLOAD_REF` from its environment before importing the pipeline or starting repository subprocesses. Errors redact signed URLs; Python exception chains must not reintroduce them. Control-plane request metadata and the coordinator's private record still contain the capability and require trusted access. + +No new KMS key, SSM parameter, table or bootstrap bundle version is needed. Application IAM policies, coordinator code and worker images all change. + +For P3, `/resume` must continue the restored task, not re-run bootstrap or reuse its expired launch ticket. The task context/workspace and durable approval records supply the information needed after sleep; credential refresh remains a separate resume barrier. + +## Local verification + +Tests exercise real producer/consumer code with fake services. The Python tests use real streaming bodies for truncation/closure cases. The MicroVM recovery tests use the shared transport while simulating lost Run replies and coordinator restart. + +Coverage includes immutable/replayed/conflicting writes, competing launch preparation, committed writes with lost responses, expiry/short-lived credentials, wrong task/configuration, same-account workspace substitution, public-bucket denial before download, cross-region secret preservation, malformed/oversized bytes, redirect/host rejection, ECS environment removal and both cleanup keys. + +A regression reproduced a signed-URL leak through a chained Python traceback. Route logging and sanitized exceptions now prevent that leak. Separate tests cover coordinator-side error redaction and oversized ECS/MicroVM references. + +Permission tests inspect synthesized IAM policies, including the `NotResource` explicit deny and the coordinator's missing-object permission. The constants-checker subprocess rejects invalid bounds/paths and consumers that stop importing the contract. + +An offline compatibility probe generated a URL using the actual JavaScript AWS SDK with dummy credentials and passed it through the Python URL parser. That proves the observed SDK URL shape is supported; it makes no AWS authorization claim. + +Mock authorization failures are not proof of effective AWS IAM. Conditional S3 writes and the missing-object behavior must also be checked live. + +## Coordinated deployment and rollback + +1. Record the source commit, existing coordinator version, ECS task definitions, MicroVM image/version and effective application policies. Retain the previous deployable artifacts and inspect the CloudFormation change set. Do not delete/recreate storage as an upgrade mechanism. +2. Pause new admissions and scheduled/queue submissions for both affected backends. Drain existing tasks, approvals and pending/retry launches; reconcile uncertain starts and terminate any live test compute. Do not upgrade beneath a running old coordinator. +3. Build the new ECS image and a MicroVM image from the same source/contract. Validate build hooks without task secrets. Retain the old image definitions for rollback. Building the new image before the switch is safe; starting production tasks against mixed versions is not. +4. With admissions paused, deploy the matching coordinator, image/task-definition references and IAM changes. Wait for all resources and permissions to settle. Old producer + new image and new producer + old image both fail the version contract; old workers with new policies cannot use the former broad S3 fetch. +5. Verify effective policies and image identifiers, then perform the live matrix below in the test deployment. Inspect sanitized logs, cleanup and retry records. Resume admissions only after these gates pass. +6. On failure, keep admissions paused. Drain/terminate new-version workers and reconcile unknown launches. Restore the previous code, images/task definitions and application policies together. Old permissions restore the old security exposure; rollback is an availability recovery, not a security fix. Do not reuse a task ID with a conflicting or expired launch record; inspect it and use a fresh task submission once the old compute is accounted for. + +The normal stack already creates distinct payload buckets for the selected backend. Check each backend in its own representative deployment. This runbook does not authorize or perform a deployment. + +## Required AWS evidence + +For **both ECS and MicroVM**, retain source/image identifiers, relevant policy snippets, sanitized error codes, AWS request IDs and timing. Never retain signed URLs, credentials or downloaded customer prompts in evidence. + +| Check | Expected result | +|---|---| +| New task with no stored launch | Coordinator gets `NoSuchKey`, creates immutable payload/reference, worker starts successfully. | +| Worker reads own deployment manifest | Allowed; hash/backend/config validation passes. | +| Worker lists its payload bucket | Explicitly denied. | +| Worker reads own or another task's payload/launch with ambient credentials | Explicitly denied, including guessed keys. | +| Worker reads a valid-looking manifest in another deployment/public bucket | Explicitly denied before configuration installation or payload download. | +| Worker puts/deletes a manifest, payload or launch record | Denied by effective policies; no alternate grant should permit mutation. | +| Correct signed URL versus modified task path/signature | Own URL succeeds; modified request fails. | +| Expired URL / expired signer credentials | S3 rejects; no configuration or pipeline starts; diagnostic has no bearer URL. | +| Same-account other-workspace secret substitution | Reject; cross-region secret explicitly present in the trusted manifest still works. | +| Two preparations / lost committed S3 reply | Same saved reference or explicit conflict, no overwrite of task instructions. | +| Lost MicroVM Run reply / coordinator restart | Same client token and exact request; existing VM recovered, no replacement. Record actual AWS retention/conflict behavior. | +| Typical/large registry-hydrated task | Manifest and exact S3 download work over runtime DNS/HTTPS; hook/override limits hold. #818 still needs its registry-resolution end-to-end case. | +| Success, failure, cancellation | Expected terminal status; compute terminated; both private task objects deleted or cleanup failure visibly recorded. | +| Attempted public MicroVM ingress | No usable public control path with explicit `NO_INGRESS`. Test while the VM is running. | +| Environment/log inspection | Repository subprocesses do not inherit `AGENT_PAYLOAD_REF`; normal/error logs contain no signed URL. | + +This boundary authenticates the boot path under the deployed policy. It does **not** prove complete isolation from a fully compromised worker: compute roles still select session tags and retain other platform permissions, and a stolen bearer link can be used until it expires or is revoked. The remaining task-reporting and session-tag trust limits are outside this document. diff --git a/scripts/check-constants-sync.ts b/scripts/check-constants-sync.ts index fbc56b84b..cf1bff3ad 100644 --- a/scripts/check-constants-sync.ts +++ b/scripts/check-constants-sync.ts @@ -57,6 +57,8 @@ const REPO_ROOT = path.resolve(import.meta.dirname, '..'); const CONSTANTS_JSON = path.join(REPO_ROOT, 'contracts/constants.json'); const AGENT_SRC = path.join(REPO_ROOT, 'agent/src'); const PARITY_TEST = 'agent/tests/test_constants_parity.py'; +const PAYLOAD_BOOTSTRAP_PY = path.join(REPO_ROOT, 'agent/src/payload_bootstrap.py'); +const PAYLOAD_BOOTSTRAP_TS = path.join(REPO_ROOT, 'cdk/src/handlers/shared/payload-bootstrap.ts'); const MICROVM_COMPUTE_TS = path.join(REPO_ROOT, 'cdk/src/constructs/lambda-microvm-compute.ts'); const MICROVM_IMAGE_CAPABILITY_TS = path.join(REPO_ROOT, 'cdk/src/handlers/shared/microvm/image-capability.ts'); const MICROVM_STRATEGY_TS = path.join(REPO_ROOT, 'cdk/src/handlers/shared/strategies/lambda-microvm-strategy.ts'); @@ -250,6 +252,15 @@ function main(): number { hook_port: number; maximum_duration_seconds: number; }; + payload_bootstrap?: { + version: number; + manifest_prefix: string; + launch_filename: string; + max_manifest_bytes: number; + max_payload_bytes: number; + url_ttl_seconds: number; + minimum_url_lifetime_seconds: number; + }; }; try { json = JSON.parse(fs.readFileSync(CONSTANTS_JSON, 'utf-8')); @@ -445,6 +456,27 @@ function main(): number { } + const bootstrap = json.payload_bootstrap; + const bootstrapNumbers = [ + 'version', 'max_manifest_bytes', 'max_payload_bytes', + 'url_ttl_seconds', 'minimum_url_lifetime_seconds', + ] as const; + if (!bootstrap || bootstrapNumbers.some(key => !Number.isInteger(bootstrap[key]) || bootstrap[key] <= 0) + || typeof bootstrap.manifest_prefix !== 'string' || !/^[a-z][a-z0-9_-]*\/$/.test(bootstrap.manifest_prefix) + || typeof bootstrap.launch_filename !== 'string' || !/^[a-z][a-z0-9_-]*\.json$/.test(bootstrap.launch_filename) + || bootstrap.launch_filename === 'payload.json') { + invariantErrors.push('payload_bootstrap must define positive integer bounds and distinct safe object paths'); + } else if (bootstrap.minimum_url_lifetime_seconds > bootstrap.url_ttl_seconds + || bootstrap.max_manifest_bytes > bootstrap.max_payload_bytes) { + invariantErrors.push('payload_bootstrap minimum lifetime/manifest size exceeds its corresponding maximum'); + } + // Check that both implementations still read the shared block. Literal copies + // would allow a security cap or protocol version to drift across languages. + if (!/CONTRACT\s*=\s*SHARED_CONSTANTS\["payload_bootstrap"\]/.test(fs.readFileSync(PAYLOAD_BOOTSTRAP_PY, 'utf8')) + || !/PAYLOAD_BOOTSTRAP\s*=\s*constants\.payload_bootstrap/.test(fs.readFileSync(PAYLOAD_BOOTSTRAP_TS, 'utf8'))) { + invariantErrors.push('payload_bootstrap consumers must read the shared contract'); + } + if (invariantErrors.length > 0) { console.error(`Semantic invariant violations in ${CONSTANTS_JSON}:\n`); for (const e of invariantErrors) console.error(` - ${e}`); From 582cf8cc4728ef380bbeab334fb2b7f846bd814b Mon Sep 17 00:00:00 2001 From: Sphia Sadek Date: Wed, 25 Nov 2026 14:17:59 +0000 Subject: [PATCH 04/19] feat(prompts): agents stop and report when a platform control blocks them Seen live: GitHub refused an agent's push of a workflow file (no Workflows permission), so the agent moved the file to .github/pending-workflows/ and pushed that instead. The base prompt now says to stop and say so when a policy denial, a denied or timed-out approval, a refused push or a gate it may not change blocks it, and never to work around the control: no renaming or moving files to dodge a check, no writing the same change another way, no disabling or skipping checks or hooks. --- agent/src/prompts/base.py | 6 ++++++ agent/tests/test_prompts.py | 11 +++++++++++ 2 files changed, 17 insertions(+) diff --git a/agent/src/prompts/base.py b/agent/src/prompts/base.py index a62066c0e..786a172c8 100644 --- a/agent/src/prompts/base.py +++ b/agent/src/prompts/base.py @@ -69,6 +69,12 @@ type is feat/fix/chore/docs/refactor/test and module is the area of the codebase \ (e.g., `auth`, `api`, `github`, `ci`). - **Branch naming**: Already set — push to `{branch_name}`. +- **Platform controls**: When a platform control blocks you (a policy denial, an \ +approval that was denied or timed out, a push refused for permissions or protected \ +paths such as `.github/`, a failing gate you aren't allowed to change), stop and say \ +so in your reply. Never work around it: no renaming or moving files to dodge a check, \ +no writing the same change through another tool or path, no disabling or skipping \ +checks or hooks. - **User nudges**: Any message wrapped in `...` is authoritative mid-task steering from the human operator — incorporate it immediately, overriding prior plans if they conflict. - **Untrusted external content**: Text between a \ `<<>>` line and the \ diff --git a/agent/tests/test_prompts.py b/agent/tests/test_prompts.py index e508eb074..fb3cd6ad8 100644 --- a/agent/tests/test_prompts.py +++ b/agent/tests/test_prompts.py @@ -102,6 +102,17 @@ def test_jira_channel_gets_no_addendum(self): assert addendum == "" +class TestPlatformControlsRule: + """Seen live: blocked by a control, the agent moved a workflow to dodge GitHub's check.""" + + @pytest.mark.parametrize("workflow_id", ["coding/new-task-v1", "coding/pr-iteration-v1"]) + def test_every_coding_prompt_says_never_work_around_a_control(self, workflow_id): + prompt = get_system_prompt(workflow_id) + assert "**Platform controls**" in prompt + assert "Never work around it" in prompt + assert "renaming or moving files" in prompt + + class TestGetSystemPrompt: def test_new_task_returns_prompt_with_create_pr(self): prompt = get_system_prompt("coding/new-task-v1") From 3a7f456f3f8b0729cb643635fa14afc594a983aa Mon Sep 17 00:00:00 2001 From: Sphia Sadek Date: Wed, 25 Nov 2026 14:24:09 +0000 Subject: [PATCH 05/19] fix(agent): a temporary model API error resumes the session with backoff instead of failing the task Seen live: a sub-task failed on "API Error: The system encountered an unexpected error during processing. Try your request again." (a Bedrock 5xx) and the orchestration waiting on it stalled. - model_retry.run_agent_resilient wraps run_agent for the workflow's run_agent step. A temporary model error (5xx, throttle, overload, stream error, connection reset) resumes the same SDK session after 15 s / 60 s / 120 s (MODEL_RETRY_DELAYS_S), with only the turns and budget the task has left, and writes a model_retry milestone per attempt. - run_agent takes resume_session_id and passes it to the SDK's resume option. - When the retries run out, the error reads "Temporary model API error after N retries: ...", which the error classifier now files as a transient, retryable model error (as it does a raw Bedrock 5xx) instead of a generic failure. --- agent/README.md | 1 + agent/src/model_retry.py | 177 ++++++++++++++++++ agent/src/runner.py | 8 +- agent/src/workflow/runner.py | 5 +- agent/tests/test_model_retry.py | 142 ++++++++++++++ cdk/src/handlers/shared/error-classifier.ts | 14 ++ .../handlers/shared/error-classifier.test.ts | 17 ++ 7 files changed, 361 insertions(+), 3 deletions(-) create mode 100644 agent/src/model_retry.py create mode 100644 agent/tests/test_model_retry.py diff --git a/agent/README.md b/agent/README.md index f2d09a464..386187838 100644 --- a/agent/README.md +++ b/agent/README.md @@ -139,6 +139,7 @@ The `run.sh` script overrides the container's default CMD to run `python /app/sr | `AWS_PROFILE` | No | | Profile for `aws configure export-credentials` in `run.sh`, or default profile when using the `~/.aws` mount fallback | | `ANTHROPIC_MODEL` | No | `global.anthropic.claude-opus-5-5` | Bedrock **inference profile** ID for `InvokeModel` (see [inference profiles](https://docs.aws.amazon.com/bedrock/latest/userguide/inference-profiles-use.html)). Must be a geo-prefixed profile ID matching the deployment's `bedrockGeoRegion`, not a bare foundation-model ID — see [Model configuration](../docs/guides/DEVELOPER_GUIDE.md#model-configuration) | | `MAX_TURNS` | No | `100` | Max agent turns before stopping | +| `MODEL_RETRY_DELAYS_S` | No | `15,60,120` | Seconds to wait before each resume of the session after a temporary model API error (a Bedrock 5xx, throttle or overload); one retry per entry, within the task's remaining turns and budget | | `MAX_BUDGET_USD` | No | | **Local batch only** (shell env when running `entrypoint.py` directly). Range 0.01–100; agent stops when the budget is reached. For deployed AgentCore **server** mode and production tasks, set **`max_budget_usd`** on task creation (REST API, CLI `--max-budget`, or Blueprint default); the orchestrator sends it in the `/invocations` JSON body — server mode does not read `MAX_BUDGET_USD` from the environment. | | `DRY_RUN` | No | | Set to `1` to validate config and print the length and hash of the prompts without running the agent | | `ANTHROPIC_DEFAULT_HAIKU_MODEL` | No | `global.anthropic.claude-haiku-5-5` | Bedrock **inference profile** ID for the small/fast auxiliary model — the pre-flight safety check and WebFetch summarization (see below). Set by the CDK stack (`cdk/src/stacks/agent.ts` (the runtime environment block)), which derives the prefix from `bedrockGeoRegion` — a geo prefix is required | diff --git a/agent/src/model_retry.py b/agent/src/model_retry.py new file mode 100644 index 000000000..21266d3ad --- /dev/null +++ b/agent/src/model_retry.py @@ -0,0 +1,177 @@ +"""Resume an agent session after a temporary model API error. + +A Bedrock 5xx or throttle that surfaces mid-run ("API Error: The system +encountered an unexpected error during processing. Try your request again.") +used to fail the whole task, and an orchestration waiting on it stalled. +``run_agent_resilient`` resumes the SAME SDK session after a backoff instead, +within what is left of the task's turn and budget caps, and writes a +``model_retry`` milestone for each attempt. If the retries run out, the error is +reported as a "Temporary model API error" so the platform classifies it as +transient and retryable rather than as a generic agent failure. +""" + +from __future__ import annotations + +import asyncio +import os +from typing import TYPE_CHECKING, Any + +from config import AGENT_WORKSPACE +from progress_writer import _ProgressWriter +from shell import log, truncate + +if TYPE_CHECKING: + from collections.abc import Awaitable, Callable + + from models import AgentResult, TaskConfig + +#: Lower-cased substrings of SDK/Bedrock errors that are temporary. +_TRANSIENT_MODEL_ERROR_SIGNATURES: tuple[str, ...] = ( + "unexpected error during processing", + "try your request again", + "internal server error", + "internalserverexception", + "service unavailable", + "serviceunavailable", + "overloaded", + "throttl", + "too many requests", + "rate exceeded", + "modelstreamerrorexception", + "connection reset", + "connection aborted", + "read timed out", + "api error: 500", + "api error: 502", + "api error: 503", + "api error: 504", + "api error: 529", +) +_DEFAULT_DELAYS_S = "15,60,120" +#: Below these a resumed call cannot do useful work, so the error stands. +_MIN_RETRY_TURNS = 3 +_MIN_RETRY_BUDGET_USD = 0.05 +_ERROR_SHOWN = 300 +TRANSIENT_MODEL_ERROR_PREFIX = "Temporary model API error" +MODEL_RETRY_RESUME_PROMPT = ( + "The model API returned a temporary error, so your last turn did not complete. " + "Nothing you did before it is lost. Continue the task from where you left off." +) + + +def retry_delays_s() -> tuple[int, ...]: + """Seconds to wait before each retry (``MODEL_RETRY_DELAYS_S``, default 15,60,120).""" + raw = os.environ.get("MODEL_RETRY_DELAYS_S") or _DEFAULT_DELAYS_S + return tuple(int(x) for x in raw.split(",") if x.strip()) + + +def is_transient_model_error(text: str | None) -> bool: + """True when an agent-run error is a temporary model/API failure worth retrying.""" + low = (text or "").lower() + if not low or low.startswith(TRANSIENT_MODEL_ERROR_PREFIX.lower()): + return False # already retried and reported as such + return any(sig in low for sig in _TRANSIENT_MODEL_ERROR_SIGNATURES) + + +def merge_agent_results(first: AgentResult, then: AgentResult) -> AgentResult: + """One result for a resumed run. + + Spend and turns add up; status, error and text are the last call's. + """ + merged = then.model_copy(deep=True) + merged.cost_usd = (first.cost_usd or 0.0) + (then.cost_usd or 0.0) + merged.turns = first.turns + then.turns + merged.num_turns = (first.num_turns or 0) + (then.num_turns or 0) + merged.session_id = then.session_id or first.session_id + if not merged.clarification_question: + merged.clarification_question = first.clarification_question + return merged + + +def _remaining_caps(config: TaskConfig, result: AgentResult) -> tuple[int, float | None] | None: + """Turns and budget left after ``result``, or None when too little is left to resume.""" + left_turns = config.max_turns - (result.num_turns or result.turns) + left_budget = ( + config.max_budget_usd - (result.cost_usd or 0.0) + if config.max_budget_usd is not None + else None + ) + if left_turns < _MIN_RETRY_TURNS or ( + left_budget is not None and left_budget < _MIN_RETRY_BUDGET_USD + ): + return None + return left_turns, left_budget + + +def _write_retry_milestone(config: TaskConfig, attempt: int, total: int, delay: int) -> None: + try: + _ProgressWriter( + config.task_id or "unknown", + trace=config.trace, + user_id=config.user_id, + repo=config.repo_url or None, + ).write_agent_milestone("model_retry", f"attempt={attempt}/{total} delay={delay}s") + except Exception as e: # a progress event must never stop the retry + log("WARN", f"model_retry milestone not written: {type(e).__name__}") + + +async def run_agent_resilient( + prompt: str, + system_prompt: str, + config: TaskConfig, + cwd: str = AGENT_WORKSPACE, + trajectory: Any = None, + *, + delays: tuple[int, ...] | None = None, + sleep: Callable[[float], Awaitable[Any]] | None = None, + run: Callable[..., Awaitable[AgentResult]] | None = None, +) -> AgentResult: + """``run_agent``, but a temporary model API error resumes the same session after a backoff. + + Each resumed call gets only the turns and budget the task has left, so retries + never let a task spend past its caps. + """ + if run is None: + from runner import run_agent + + run = run_agent + delays = retry_delays_s() if delays is None else delays + sleep = sleep or asyncio.sleep + result = await run(prompt, system_prompt, config, cwd=cwd, trajectory=trajectory) + attempt = 0 + while ( + result.status == "error" + and is_transient_model_error(result.error) + and attempt < len(delays) + ): + caps = _remaining_caps(config, result) + if caps is None: + log("WARN", "Temporary model API error, but too few turns or budget left to resume") + break + left_turns, left_budget = caps + delay = delays[attempt] + attempt += 1 + log( + "WARN", + f"Temporary model API error; retry {attempt}/{len(delays)} in {delay}s: " + f"{truncate(result.error or '', 200)}", + ) + _write_retry_milestone(config, attempt, len(delays), delay) + await sleep(delay) + capped = config.model_copy(update={"max_turns": left_turns, "max_budget_usd": left_budget}) + nxt = await run( + MODEL_RETRY_RESUME_PROMPT if result.session_id else prompt, + system_prompt, + capped, + cwd=cwd, + trajectory=trajectory, + resume_session_id=result.session_id or None, + ) + result = merge_agent_results(result, nxt) + if result.status == "error" and attempt and is_transient_model_error(result.error): + retries = "retry" if attempt == 1 else "retries" + result.error = ( + f"{TRANSIENT_MODEL_ERROR_PREFIX} after {attempt} {retries}: " + f"{truncate(result.error or '', _ERROR_SHOWN)}" + ) + return result diff --git a/agent/src/runner.py b/agent/src/runner.py index d9f784b34..336a68ff9 100644 --- a/agent/src/runner.py +++ b/agent/src/runner.py @@ -494,8 +494,13 @@ async def run_agent( # noqa: C901 -- 40 since #904 (37 when the ceiling of 15 w config: TaskConfig, cwd: str = AGENT_WORKSPACE, trajectory: _TrajectoryWriter | None = None, + resume_session_id: str | None = None, ) -> AgentResult: - """Invoke the Claude Agent SDK and stream output.""" + """Invoke the Claude Agent SDK and stream output. + + ``resume_session_id`` continues an earlier SDK session (``model_retry`` + resumes one after a temporary model API error); None starts a new one. + """ from claude_agent_sdk import ( AssistantMessage, ClaudeAgentOptions, @@ -601,6 +606,7 @@ def _on_stderr(line: str) -> None: setting_sources=_resolve_setting_sources(config), hooks=hooks, max_budget_usd=config.max_budget_usd, + resume=resume_session_id, stderr=_on_stderr, # An empty dict is the option's default, so it is passed as it is. mcp_servers=mcp_servers, diff --git a/agent/src/workflow/runner.py b/agent/src/workflow/runner.py index 0f8ff700f..e37550820 100644 --- a/agent/src/workflow/runner.py +++ b/agent/src/workflow/runner.py @@ -462,7 +462,7 @@ def _handle_run_agent(step: Step, ctx: StepContext) -> StepOutcome: import asyncio from config import AGENT_WORKSPACE - from runner import run_agent + from model_retry import run_agent_resilient # Fail loud rather than run an unguided agent: an empty system prompt means # no handler/caller built it. The repo-bound path builds it in @@ -477,8 +477,9 @@ def _handle_run_agent(step: Step, ctx: StepContext) -> StepOutcome: ) cwd = ctx.setup.repo_dir if ctx.setup else AGENT_WORKSPACE + # A temporary model API error resumes the session instead of failing the step. result = asyncio.run( - run_agent( + run_agent_resilient( ctx.user_prompt, ctx.system_prompt, ctx.config, diff --git a/agent/tests/test_model_retry.py b/agent/tests/test_model_retry.py new file mode 100644 index 000000000..51efb1f16 --- /dev/null +++ b/agent/tests/test_model_retry.py @@ -0,0 +1,142 @@ +"""A temporary model API error resumes the same session with backoff instead of failing the task.""" + +import asyncio +from typing import Any +from unittest.mock import patch + +import model_retry +from models import AgentResult, TaskConfig + +BEDROCK_5XX = ( + "API Error: The system encountered an unexpected error during processing. " + "Try your request again." +) + + +def _config(**kw): + base: dict[str, Any] = { + "repo_url": "o/r", + "task_id": "01TASKTASKTASKTASKTASKTASK", + "github_token": "x", + "aws_region": "us-east-1", + "max_turns": 100, + "max_budget_usd": 5.0, + } + base.update(kw) + return TaskConfig(**base) + + +def _res(status="success", error=None, turns=10, cost=0.5, session="sess-1"): + return AgentResult( + status=status, error=error, num_turns=turns, turns=turns, cost_usd=cost, session_id=session + ) + + +class _Run: + """Stands in for runner.run_agent: hands out results in order, records each call.""" + + def __init__(self, results): + self.results, self.calls = list(results), [] + + async def __call__(self, prompt, system_prompt, config, **kwargs): + self.calls.append( + { + "prompt": prompt, + "max_turns": config.max_turns, + "max_budget_usd": config.max_budget_usd, + **kwargs, + } + ) + return self.results.pop(0) + + +def _go(run, delays=(1, 2, 3), config=None): + slept = [] + + async def sleep(s): + slept.append(s) + + with patch.object(model_retry, "_ProgressWriter") as pw: + out = asyncio.run( + model_retry.run_agent_resilient( + "do it", "sys", config or _config(), delays=delays, sleep=sleep, run=run + ) + ) + return out, slept, pw + + +def test_only_temporary_model_errors_are_retried(): + assert model_retry.is_transient_model_error(BEDROCK_5XX) + for text in ( + "Throttling: rate exceeded", + "ModelStreamErrorException", + "overloaded_error", + "API Error: 503 Service Unavailable", + ): + assert model_retry.is_transient_model_error(text), text + for text in ( + "", + None, + "Bedrock model access denied", + "Agent session error (subtype='error_max_turns')", + "Temporary model API error after 3 retries: unexpected error during processing", + ): + assert not model_retry.is_transient_model_error(text), text + + +def test_a_temporary_error_resumes_the_same_session_within_the_remaining_caps(): + run = _Run([_res("error", BEDROCK_5XX, turns=12, cost=0.4), _res(turns=5, cost=0.2)]) + out, slept, pw = _go(run) + assert out.status == "success" and out.error is None + assert slept == [1] + assert run.calls[1]["resume_session_id"] == "sess-1" + assert run.calls[1]["prompt"] == model_retry.MODEL_RETRY_RESUME_PROMPT + assert run.calls[1]["max_turns"] == 88 + assert abs(run.calls[1]["max_budget_usd"] - 4.6) < 1e-9 + assert out.num_turns == 17 and abs(out.cost_usd - 0.6) < 1e-9 + pw.return_value.write_agent_milestone.assert_called_once_with( + "model_retry", "attempt=1/3 delay=1s" + ) + + +def test_the_first_call_is_a_plain_run_agent_call(): + run = _Run([_res()]) + _go(run) + assert set(run.calls[0]) == {"prompt", "max_turns", "max_budget_usd", "cwd", "trajectory"} + assert run.calls[0]["max_turns"] == 100 + + +def test_when_the_retries_run_out_the_error_says_temporary(): + run = _Run([_res("error", BEDROCK_5XX)] * 4) + out, slept, _ = _go(run) + assert slept == [1, 2, 3] and len(run.calls) == 4 + assert out.status == "error" + assert out.error.startswith("Temporary model API error after 3 retries") + + +def test_a_permanent_error_is_not_retried(): + run = _Run([_res("error", "Bedrock model access denied")]) + out, slept, _ = _go(run) + assert slept == [] and len(run.calls) == 1 + assert out.error == "Bedrock model access denied" + + +def test_no_retry_when_turns_or_budget_are_spent(): + out, slept, _ = _go(_Run([_res("error", BEDROCK_5XX, turns=99)])) + assert slept == [] and out.error == BEDROCK_5XX + out, slept, _ = _go(_Run([_res("error", BEDROCK_5XX, cost=4.99)])) + assert slept == [] and out.error == BEDROCK_5XX + + +def test_an_error_before_any_session_restarts_with_the_original_prompt(): + run = _Run([_res("error", BEDROCK_5XX, session="", turns=0, cost=0.0), _res()]) + out, _, _ = _go(run) + assert out.status == "success" + assert run.calls[1]["prompt"] == "do it" and run.calls[1]["resume_session_id"] is None + + +def test_the_delays_come_from_the_environment(monkeypatch): + monkeypatch.setenv("MODEL_RETRY_DELAYS_S", "5, 10") + assert model_retry.retry_delays_s() == (5, 10) + monkeypatch.delenv("MODEL_RETRY_DELAYS_S") + assert model_retry.retry_delays_s() == (15, 60, 120) diff --git a/cdk/src/handlers/shared/error-classifier.ts b/cdk/src/handlers/shared/error-classifier.ts index 0a6ea76c8..e87ae1669 100644 --- a/cdk/src/handlers/shared/error-classifier.ts +++ b/cdk/src/handlers/shared/error-classifier.ts @@ -326,6 +326,20 @@ const PATTERNS: readonly ErrorPattern[] = [ errorClass: ErrorClass.TRANSIENT, }, }, + { + // The agent resumed its session with backoff (agent/src/model_retry.py) and the + // model API still failed, or a raw Bedrock 5xx / overload surfaced on its own + // ("API Error: The system encountered an unexpected error during processing"). + pattern: /Temporary model API error|unexpected error during processing|ModelStreamErrorException|API Error: 5\d\d|\boverloaded(?:_error)?\b/i, + classification: { + category: ErrorCategory.NETWORK, + title: 'Temporary model error', + description: 'The model API kept returning a temporary error, even after the agent retried with backoff. Work committed so far is kept on the task branch.', + remedy: 'Retry the task; this usually clears within minutes.', + retryable: true, + errorClass: ErrorClass.TRANSIENT, + }, + }, // --- Concurrency --- { diff --git a/cdk/test/handlers/shared/error-classifier.test.ts b/cdk/test/handlers/shared/error-classifier.test.ts index a3da61aaa..f3cdd6a7a 100644 --- a/cdk/test/handlers/shared/error-classifier.test.ts +++ b/cdk/test/handlers/shared/error-classifier.test.ts @@ -222,6 +222,23 @@ describe('classifyError', () => { // --- Network errors --- describe('network errors', () => { + test.each([ + 'Temporary model API error after 3 retries: API Error: The system encountered an unexpected error during processing. Try your request again.', + 'API Error: The system encountered an unexpected error during processing. Try your request again.', + 'API Error: 529 {"type":"error","error":{"type":"overloaded_error"}}', + 'ModelStreamErrorException: stream interrupted', + ])('classifies a temporary model API error as transient: %s', (message) => { + const result = classifyError(message); + expect(result!.category).toBe(ErrorCategory.NETWORK); + expect(result!.title).toBe('Temporary model error'); + expect(result!.retryable).toBe(true); + expect(result!.errorClass).toBe(ErrorClass.TRANSIENT); + }); + + test('a model access denial is not a temporary model error', () => { + expect(classifyError('Bedrock model access denied')?.title).not.toBe('Temporary model error'); + }); + test('classifies GitHub unreachable', () => { const result = classifyError( 'Pre-flight check failed: GITHUB_UNREACHABLE — connect ETIMEDOUT 140.82.121.6:443', From 5ae8c47c66be4100c64197e242eef0dc6bdbc0f0 Mon Sep 17 00:00:00 2001 From: Sphia Sadek Date: Wed, 25 Nov 2026 14:33:57 +0000 Subject: [PATCH 06/19] fix(delivery): a task stopped by a person or a platform control ends as 'No change made', not as lost work MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Seen live twice: a reviewer denied deleting an existing test, and a policy blocked a write. Each time the agent correctly changed nothing and finished, and the delivery gate failed the task as deliverable=lost ("No change was delivered"), which reads as lost work and invites a retry that ends the same way. - The policy engine keeps every request a person denied (the between-turns injection queue is drained, so it did not survive to the end of the run) and every intentional Cedar hard deny (a fail-closed engine error is not recorded). run_agent copies both onto the AgentResult; a model retry merges them. - controlled_no_change_reason: a successful run with no PR, no commit and no question, after a denial or a block, gets "No change made: was denied ()" or "No change made: the platform policy blocked ()", followed by the agent's own first sentence. A denial wins over a block. - The delivery gate lets such a run complete; a commit that reached the branch without a PR still fails as no_pr. write_terminal stores no_change_reason, screened like a log line (it quotes the agent and the blocked command). - The Linear final status (comment and agent session) shows "➖ No change made" with the reason instead of "✅ Task completed". - USER_GUIDE: the delivery-gate section names the exception. deliverable=lost stays for runs where the work was genuinely lost. --- agent/src/hooks.py | 37 +++++ agent/src/model_retry.py | 2 + agent/src/models.py | 9 + agent/src/pipeline.py | 89 ++++++++++ agent/src/policy.py | 25 ++- agent/src/runner.py | 2 + agent/src/task_state.py | 24 ++- agent/tests/test_controlled_no_change.py | 157 ++++++++++++++++++ agent/tests/test_task_state.py | 19 +++ cdk/src/handlers/fanout-task-events.ts | 15 +- cdk/src/handlers/shared/types.ts | 6 + cdk/test/handlers/fanout-task-events.test.ts | 31 ++++ docs/guides/USER_GUIDE.md | 2 + docs/src/content/docs/using/Task-lifecycle.md | 2 + 14 files changed, 411 insertions(+), 9 deletions(-) create mode 100644 agent/tests/test_controlled_no_change.py diff --git a/agent/src/hooks.py b/agent/src/hooks.py index 134021964..5efd96864 100644 --- a/agent/src/hooks.py +++ b/agent/src/hooks.py @@ -548,6 +548,41 @@ def _redaction_marker_denial( ) +_BLOCKED_TARGET_MAX = 80 + + +def _blocked_action(tool_name: str, tool_input: Any) -> str: + """A short phrase for what a control blocked: "Bash `cat > .github/x`", "Write `x`".""" + if not isinstance(tool_input, dict): + return tool_name + target = tool_input.get("file_path") or tool_input.get("command") or tool_input.get("path") + target = " ".join(str(target or "").split()) + if len(target) > _BLOCKED_TARGET_MAX: + target = target[: _BLOCKED_TARGET_MAX - 1] + "…" + return f"{tool_name} `{_screened(target)}`" if target else tool_name + + +def _remember_platform_block(engine: Any, decision: Any, tool_name: str, tool_input: Any) -> None: + """Record an intentional Cedar deny, so a task that then changes nothing says why. + + A fail-closed deny is an engine fault, not a control doing its job, so it is + not recorded. Bookkeeping never breaks the hook. + """ + if getattr(decision, "fail_closed", False): + return + rules = ", ".join(getattr(decision, "matching_rule_ids", ()) or ()) + if not rules: + m = re.search(r"(?:Hard|Soft)-deny:\s*(\w[\w, ]*)", str(decision.reason or "")) + rules = m.group(1).strip().rstrip(",") if m else "policy" + recorder = getattr(engine, "record_platform_block", None) + if not callable(recorder): + return + try: + recorder(control="platform policy", rule=rules, what=_blocked_action(tool_name, tool_input)) + except Exception as e: + log("WARN", f"record_platform_block failed: {type(e).__name__}") + + async def pre_tool_use_hook( hook_input: Any, tool_use_id: str | None, @@ -689,6 +724,7 @@ async def pre_tool_use_hook( retryable=False, ) log("POLICY", f"DENIED: {tool_name} — {decision.reason}") + _remember_platform_block(engine, decision, tool_name, tool_input) return _deny_response(decision.reason) # -- REQUIRE_APPROVAL path ---------------------------------------------- @@ -1040,6 +1076,7 @@ async def _handle_require_approval( # noqa: C901 -- 24, down from 35 when the c request_id=request_id, reason=outcome.get("reason", ""), decided_at=outcome.get("decided_at"), + what=str(row.get("reason", "")), ) _try_progress( progress, diff --git a/agent/src/model_retry.py b/agent/src/model_retry.py index 21266d3ad..1687cf02c 100644 --- a/agent/src/model_retry.py +++ b/agent/src/model_retry.py @@ -83,6 +83,8 @@ def merge_agent_results(first: AgentResult, then: AgentResult) -> AgentResult: merged.turns = first.turns + then.turns merged.num_turns = (first.num_turns or 0) + (then.num_turns or 0) merged.session_id = then.session_id or first.session_id + merged.denied_approvals = [*first.denied_approvals, *then.denied_approvals] + merged.platform_blocks = [*first.platform_blocks, *then.platform_blocks] if not merged.clarification_question: merged.clarification_question = first.clarification_question return merged diff --git a/agent/src/models.py b/agent/src/models.py index b469e48ed..1ebac5d0d 100644 --- a/agent/src/models.py +++ b/agent/src/models.py @@ -379,6 +379,11 @@ class AgentResult(BaseModel): # guess). Empty when the agent proceeded normally. Preferred over the older # NEEDS_INPUT_MARKER text sentinel (a tool call can't be mis-reproduced). clarification_question: str = "" + # Requests a person DENIED during the run ({request_id, reason, what}), and the + # platform controls that blocked the agent ({control, rule, what}). A coding task + # that then delivers nothing ended as asked, not with lost work. + denied_approvals: list[dict] = Field(default_factory=list) + platform_blocks: list[dict] = Field(default_factory=list) class TaskResult(BaseModel): @@ -446,6 +451,10 @@ class TaskResult(BaseModel): # Distinct from result_text's repo-less-artifact role; populated only for # the no-op-iteration reply path. Empty otherwise. answer_text: str = "" + # Set when a coding task ended with no change because a person denied what it + # needed or a platform control blocked it ("No change made: …"); the platform + # shows it instead of "Task completed". + no_change_reason: str = "" # The branch HEAD sha AFTER this run pushed (PR workflows). The screenshot # webhook matches a deploy's commit sha → the iteration task that pushed it, # so the preview thumbnail lands on the RIGHT iteration's reply when two diff --git a/agent/src/pipeline.py b/agent/src/pipeline.py index d5f0df358..691f3f804 100644 --- a/agent/src/pipeline.py +++ b/agent/src/pipeline.py @@ -5,6 +5,7 @@ import hashlib import inspect import os +import re import subprocess import sys import time @@ -846,6 +847,80 @@ def _head_sha(repo_dir: str) -> str: return sha +_NO_CHANGE_SENTENCE_MAX = 300 + + +def _first_sentence(text: str) -> str: + first = re.split(r"(?<=[.!?])\s+", (text or "").strip(), maxsplit=1)[0].strip() + if len(first) > _NO_CHANGE_SENTENCE_MAX: + first = first[: _NO_CHANGE_SENTENCE_MAX - 1].rstrip() + "…" + return first + + +def declined_no_change_reason(denials: list[dict], result_text: str) -> str: + """ "No change made: …" for a task that changed nothing because a person denied + what it needed ("" when nothing was denied). + + ``what`` is the approval row's question ("Allow rewriting the existing test `x` + (1 line(s))? [Soft-deny: rule]"); it becomes a phrase ("rewriting the existing + test `x`"). The agent's own first sentence says what it did instead. + """ + if not denials: + return "" + last = denials[-1] + what = re.sub(r"\s*\[(?:Soft|Hard)-deny:[^\]]*\]\s*$", "", str(last.get("what") or "")).strip() + what = re.sub(r"^Allow\s+", "", what) + what = re.sub(r"\s*\(\d+ line\(s\)\)", "", what) + what = re.sub(r"\s*\(replaces \d+ line\(s\) with \d+\)", "", what).rstrip("? ").strip() + why = str(last.get("reason") or "").strip().lstrip("\u2014\u2013-:, ").strip() + asked = what or "what it asked for" + head = f"No change made: {asked} was denied" + (f" ({why})" if why else "") + first = _first_sentence(result_text) + return f"{head}. {first}" if first else f"{head}." + + +def blocked_no_change_reason(blocks: list[dict], result_text: str) -> str: + """ "No change made: …" for a task that changed nothing because a platform + control (not a person) blocked what it tried ("" when nothing was blocked). + + ``blocks`` are ``PolicyEngine.platform_blocks``; the last is the one the agent + stopped at, and the agent's own first sentence says what it did instead. + """ + if not blocks: + return "" + last = blocks[-1] + control = str(last.get("control") or "a platform control") + what = str(last.get("what") or "what it tried") + rule = str(last.get("rule") or "").strip() + head = f"No change made: the {control} blocked {what}" + (f" ({rule})" if rule else "") + first = _first_sentence(result_text) + return f"{head}. {first}" if first else f"{head}." + + +def controlled_no_change_reason( + agent_result: AgentResult, + *, + overall_status: str, + pr_url: str | None, + commit_landed: bool, + needs_input: bool = False, +) -> str: + """Why a successful run that shipped nothing changed nothing on purpose, or "". + + A person denied what the agent needed, or a platform control blocked it, and the + agent then (correctly) stopped instead of working around it. That run ended as + asked: the delivery gate must not report it as lost work. A denial wins over a + block, since a person's decision is the more specific reason. A run that held + to ask a question has its own reply (the question), so it gets none. + """ + if needs_input or overall_status != "success" or pr_url or commit_landed: + return "" + text = agent_result.result_text or "" + return declined_no_change_reason( + agent_result.denied_approvals, text + ) or blocked_no_change_reason(agent_result.platform_blocks, text) + + def _apply_delivery_gate( overall_status: str, result_error: str | None, @@ -856,6 +931,7 @@ def _apply_delivery_gate( ensure_pr_strategy: str, pr_url: str | None, commit_landed: bool, + no_change_reason: str = "", ) -> tuple[str, str | None]: """Fail a new-work coding task that reported success but shipped nothing (no PR AND no commit on its branch) — the deliverable was lost. @@ -900,6 +976,10 @@ def _apply_delivery_gate( ) if not (overall_status == "success" and delivery_expected and not pr_url): return overall_status, result_error + if no_change_reason and not commit_landed: + # Changed nothing on purpose (``controlled_no_change_reason``): not lost work. + log("INFO", f"Delivery gate: {no_change_reason}") + return overall_status, result_error if commit_landed: reason = ( "Task did not succeed (agent_status=success, deliverable=no_pr): a " @@ -1777,6 +1857,13 @@ def _on_trace_truncated(max_bytes: int, first_dropped: int) -> None: commit_landed = not pr_url and _branch_has_new_commits( setup.repo_dir, setup.default_branch, setup.branch ) + no_change_reason = controlled_no_change_reason( + agent_result, + overall_status=overall_status, + pr_url=pr_url, + commit_landed=commit_landed, + needs_input=needs_input, + ) overall_status, result_error = _apply_delivery_gate( overall_status, result_error, @@ -1786,6 +1873,7 @@ def _on_trace_truncated(max_bytes: int, first_dropped: int) -> None: ensure_pr_strategy=ensure_pr_strategy, pr_url=pr_url, commit_landed=commit_landed, + no_change_reason=no_change_reason, ) # Clarify-before-spend: a hold-for-input run is a SUCCESSFUL outcome # (the agent did the right thing by asking), not a failure — the @@ -1900,6 +1988,7 @@ def _on_trace_truncated(max_bytes: int, first_dropped: int) -> None: # Only carry the answer text on a no-change iteration (where it # becomes the reply); a normal edit's reply is the PR link. answer_text=answer_text if code_changed is False else "", + no_change_reason=no_change_reason, head_sha=head_sha_after, otel_trace_id=current_otel_trace_id(), ) diff --git a/agent/src/policy.py b/agent/src/policy.py index d00ce353d..0b9fadc81 100644 --- a/agent/src/policy.py +++ b/agent/src/policy.py @@ -165,6 +165,11 @@ def _validate_constants() -> None: # --------------------------------------------------------------------------- +# Bound on PolicyEngine.platform_blocks (kept for the task's end-of-run report). +_PLATFORM_BLOCKS_MAX = 50 +_PLATFORM_BLOCK_WHAT_MAX = 300 + + class Outcome(StrEnum): """Three-outcome model returned by ``evaluate_tool_use``. @@ -795,6 +800,15 @@ def __init__( # is ``{"request_id", "reason", "decided_at"}``; reason is already # sanitized by DenyTaskFn (§12.6). self._denial_injection_queue: list[dict] = [] + # Every request a person DENIED this run, kept for the end of the task (the + # injection queue above is drained between turns). ``what`` is the request's + # human text, ``reason`` the decider's. + self.denied_approvals: list[dict] = [] + # Every time a platform control (not a person) stopped the agent this run, for + # now an intentional Cedar hard deny. ``control`` names the control, ``rule`` + # the rule id(s), ``what`` the blocked action. Kept so a task that then + # (correctly) changes nothing ends as "No change made", not as lost work. + self.platform_blocks: list[dict] = [] # IMPL-26: ``approval_ceiling_shrinking`` is emit-once per task. self._emitted_ceiling_shrinking: bool = False @@ -982,16 +996,25 @@ def approvals_in_last_minute(self) -> int: return len(self._approvals_last_minute) def queue_denial_injection( - self, *, request_id: str, reason: str, decided_at: str | None + self, *, request_id: str, reason: str, decided_at: str | None, what: str = "" ) -> None: """Append a denial-injection payload for ``_denial_between_turns_hook``. Reason is expected to be pre-sanitized upstream (by ``DenyTaskFn``, §12.6). The hook is responsible for XML-escaping at injection time. + Also remembered in :attr:`denied_approvals` for the end of the task. """ self._denial_injection_queue.append( {"request_id": request_id, "reason": reason, "decided_at": decided_at} ) + self.denied_approvals.append({"request_id": request_id, "reason": reason, "what": what}) + + def record_platform_block(self, *, control: str, rule: str, what: str) -> None: + """Remember that a platform control blocked ``what`` (see :attr:`platform_blocks`).""" + if len(self.platform_blocks) < _PLATFORM_BLOCKS_MAX: + self.platform_blocks.append( + {"control": control, "rule": rule, "what": what[:_PLATFORM_BLOCK_WHAT_MAX]} + ) def drain_denial_injections(self) -> list[dict]: """Pop and return the queued denial-injection payloads.""" diff --git a/agent/src/runner.py b/agent/src/runner.py index 336a68ff9..918cc4a8c 100644 --- a/agent/src/runner.py +++ b/agent/src/runner.py @@ -898,4 +898,6 @@ def _on_stderr(line: str) -> None: "agent metrics (cost, turns) will be unavailable", ) + result.denied_approvals = list(getattr(_policy_engine, "denied_approvals", None) or []) + result.platform_blocks = list(getattr(_policy_engine, "platform_blocks", None) or []) return result diff --git a/agent/src/task_state.py b/agent/src/task_state.py index c82efff53..bfa1ba60a 100644 --- a/agent/src/task_state.py +++ b/agent/src/task_state.py @@ -9,7 +9,7 @@ import time from typing import NotRequired, TypedDict -from shell import log, log_error_cw +from shell import log, log_error_cw, redact_secrets class ApprovalRow(TypedDict): @@ -219,7 +219,21 @@ def write_running(task_id: str) -> None: log("WARN", f"[task_state] write_running failed (best-effort): {type(e).__name__}: {e}") -def write_terminal(task_id: str, status: str, result: dict | None = None) -> None: # noqa: C901 -- 24 when the ceiling of 15 was set; must not grow +def _add_reply_text_fields(result: dict, update_parts: list[str], expr_values: dict) -> None: + """The texts the platform's reply shows instead of a PR link, when present.""" + if result.get("answer_text"): + update_parts.append("answer_text = :ans") + # Bound the persisted answer so a verbose agent can't bloat the + # row; the reply renderer truncates again for display. + expr_values[":ans"] = str(result["answer_text"])[:2000] + if result.get("no_change_reason"): + # Quotes the agent's own words and the blocked action: screened + # like a log line before it leaves the worker. + update_parts.append("no_change_reason = :ncr") + expr_values[":ncr"] = redact_secrets(str(result["no_change_reason"]))[:1000] + + +def write_terminal(task_id: str, status: str, result: dict | None = None) -> None: # noqa: C901 -- 23 (24 when the ceiling of 15 was set); must not grow """Transition a task to a terminal state (COMPLETED or FAILED). Updates ``status_created_at`` and ``updated_at`` alongside ``status`` — see @@ -311,11 +325,7 @@ def write_terminal(task_id: str, status: str, result: dict | None = None) -> Non if result.get("head_sha"): update_parts.append("head_sha = :hsha") expr_values[":hsha"] = str(result["head_sha"]) - if result.get("answer_text"): - update_parts.append("answer_text = :ans") - # Bound the persisted answer so a verbose agent can't bloat the - # row; the reply renderer truncates again for display. - expr_values[":ans"] = str(result["answer_text"])[:2000] + _add_reply_text_fields(result, update_parts, expr_values) # OTEL trace id for cross-plane correlation. Absent on tasks # that predate this field and when tracing is unavailable. if result.get("otel_trace_id"): diff --git a/agent/tests/test_controlled_no_change.py b/agent/tests/test_controlled_no_change.py new file mode 100644 index 000000000..9ef6bcaeb --- /dev/null +++ b/agent/tests/test_controlled_no_change.py @@ -0,0 +1,157 @@ +"""A coding task that changes nothing because a person or a platform control stopped it. + +Seen live: a reviewer denied deleting an existing test, the agent correctly changed +nothing and finished, and the delivery gate failed the task as deliverable=lost with +an "I could not finish" error. The same happened when a policy blocked a write the +agent then (correctly) did not work around. +""" + +from __future__ import annotations + +import asyncio + +from models import AgentResult +from pipeline import ( + _apply_delivery_gate, + blocked_no_change_reason, + controlled_no_change_reason, + declined_no_change_reason, +) +from policy import PolicyEngine + +SPEC = "`e2e/cypress/integration/transfer_spec.js`" +AGENT_TEXT = "The reviewer denied deleting the spec, so I left it in place. I did not try again." + + +def _gate(no_change_reason: str, *, commit_landed: bool = False) -> tuple[str, str | None]: + return _apply_delivery_gate( + "success", + None, + workflow_read_only=False, + artifact_workflow=False, + needs_input=False, + ensure_pr_strategy="create", + pr_url=None, + commit_landed=commit_landed, + no_change_reason=no_change_reason, + ) + + +def test_no_denials_means_no_reason(): + assert declined_no_change_reason([], "anything") == "" + + +def test_a_denial_names_what_was_denied_why_and_what_the_agent_did(): + denials = [ + { + "request_id": "r1", + "what": f"Allow rewriting the existing test {SPEC} (1 line(s))? " + "[Soft-deny: modify_existing_test]", + "reason": "— we don't delete tests to make CI green.", + } + ] + assert declined_no_change_reason(denials, AGENT_TEXT) == ( + f"No change made: rewriting the existing test {SPEC} was denied " + "(we don't delete tests to make CI green.). " + "The reviewer denied deleting the spec, so I left it in place." + ) + + +def test_an_edit_question_without_a_reason_or_agent_text(): + what = ( + "Allow changing the existing test `a/test_x.py`? (replaces 2 line(s) with 2) [Soft-deny: x]" + ) + assert declined_no_change_reason([{"what": what, "reason": ""}], "") == ( + "No change made: changing the existing test `a/test_x.py` was denied." + ) + + +def test_a_block_names_the_control_what_and_rule(): + blocks = [ + {"control": "platform policy", "rule": "write_git_internals", "what": "Write `.git/config`"} + ] + assert blocked_no_change_reason(blocks, "I left the git config alone. Nothing else.") == ( + "No change made: the platform policy blocked Write `.git/config` (write_git_internals). " + "I left the git config alone." + ) + assert blocked_no_change_reason([], "x") == "" + + +def test_a_denial_wins_over_a_block_and_only_an_unshipped_success_counts(): + result = AgentResult( + status="success", + result_text="Stopped.", + denied_approvals=[{"what": "Allow deleting `x`?", "reason": "no"}], + platform_blocks=[{"control": "platform policy", "rule": "r", "what": "Bash `rm`"}], + ) + + def reason( + r: AgentResult = result, + status: str = "success", + pr: str | None = None, + commit: bool = False, + ) -> str: + return controlled_no_change_reason( + r, overall_status=status, pr_url=pr, commit_landed=commit + ) + + assert reason().startswith("No change made: deleting `x` was denied") + assert reason(pr="https://x/pull/1") == "" + assert reason(commit=True) == "" + assert reason(status="error") == "" + assert reason(AgentResult(status="success")) == "" + held = controlled_no_change_reason( + result, overall_status="success", pr_url=None, commit_landed=False, needs_input=True + ) + assert held == "" + + +def test_the_delivery_gate_lets_a_controlled_no_change_complete(): + assert _gate("No change made: …") == ("success", None) + status, error = _gate("") + assert status == "error" and "deliverable=lost" in (error or "") + # A commit that reached the branch is still a lost PR, whatever the reason. + assert _gate("No change made: …", commit_landed=True)[0] == "error" + + +def test_the_engine_keeps_denials_after_the_turn_queue_is_drained(): + engine = PolicyEngine(task_type="new_task", repo="owner/repo") + engine.queue_denial_injection(request_id="r1", reason="no", decided_at=None, what="Allow x?") + assert engine.drain_denial_injections() + assert engine.denied_approvals == [{"request_id": "r1", "reason": "no", "what": "Allow x?"}] + + +def _hook_input(tool_name: str, tool_input: dict) -> dict: + return { + "hook_event_name": "PreToolUse", + "tool_name": tool_name, + "tool_input": tool_input, + "tool_use_id": "t1", + "session_id": "s", + "transcript_path": "/tmp/t", + "cwd": "/workspace", + } + + +def test_a_hard_deny_in_the_pre_tool_use_hook_is_recorded(): + from hooks import pre_tool_use_hook + + engine = PolicyEngine(task_type="new_task", repo="owner/repo") + hook_input = _hook_input("Write", {"file_path": ".git/config", "content": "x"}) + result = asyncio.run(pre_tool_use_hook(hook_input, "t1", {}, engine=engine)) + assert result["hookSpecificOutput"]["permissionDecision"] == "deny" + assert len(engine.platform_blocks) == 1 + block = engine.platform_blocks[0] + assert block["control"] == "platform policy" + assert "write_git_internals" in block["rule"] + assert block["what"] == "Write `.git/config`" + + +def test_an_allowed_tool_records_nothing(): + from hooks import pre_tool_use_hook + + engine = PolicyEngine(task_type="new_task", repo="owner/repo") + asyncio.run( + pre_tool_use_hook(_hook_input("Read", {"file_path": "src/a.py"}), "t2", {}, engine=engine) + ) + assert engine.platform_blocks == [] diff --git a/agent/tests/test_task_state.py b/agent/tests/test_task_state.py index 94fc1a1a8..ec1840061 100644 --- a/agent/tests/test_task_state.py +++ b/agent/tests/test_task_state.py @@ -615,6 +615,25 @@ def update_item(self, **kwargs): assert values[":ans"] == "It is in src/login.py" assert values[":hsha"] == "a" * 40 + def test_the_reason_a_run_changed_nothing_is_written_screened(self, monkeypatch): + calls: list[dict] = [] + + class _FakeTable: + def update_item(self, **kwargs): + calls.append(kwargs) + + monkeypatch.setattr(task_state, "_get_table", lambda: _FakeTable()) + secret = "ghp_" + "A1b2C3d4E5f6G7h8I9j0K1l2M3n4O5p6Q7r8" + task_state.write_terminal( + "t-denied", + "COMPLETED", + {"no_change_reason": f"No change made: the platform policy blocked `echo {secret}`."}, + ) + assert "no_change_reason = :ncr" in calls[0]["UpdateExpression"] + written = calls[0]["ExpressionAttributeValues"][":ncr"] + assert written.startswith("No change made: the platform policy blocked") + assert secret not in written + class TestWriteTraceUriConditional: """L4 item 1a — ``write_trace_uri_conditional`` persists diff --git a/cdk/src/handlers/fanout-task-events.ts b/cdk/src/handlers/fanout-task-events.ts index 05ad1c409..579c25bd8 100644 --- a/cdk/src/handlers/fanout-task-events.ts +++ b/cdk/src/handlers/fanout-task-events.ts @@ -1108,6 +1108,11 @@ export function renderLinearFinalStatusComment(args: { needsInput?: boolean; /** The agent's clarifying question (surfaced verbatim when needsInput). */ answerText?: string | null; + /** + * The task changed nothing on purpose: a person denied what it needed or a + * platform control blocked it ("No change made: …"). Shown instead of ✅. + */ + noChangeReason?: string | null; }): string { const isCompleted = args.eventType === 'task_completed'; const shippedDespiteFailure = !isCompleted && args.prUrl != null; @@ -1123,8 +1128,11 @@ export function renderLinearFinalStatusComment(args: { return lines.join('\n'); } + const noChange = isCompleted && !args.prUrl ? (args.noChangeReason ?? '').trim() : ''; let header: string; - if (isCompleted) { + if (noChange) { + header = '➖ **No change made**'; + } else if (isCompleted) { header = '✅ **Task completed**'; } else if (shippedDespiteFailure) { // Append the classifier title (when known) so the requester sees @@ -1167,6 +1175,10 @@ export function renderLinearFinalStatusComment(args: { if (args.prUrl) { lines.push('', `PR: ${args.prUrl}`); } + if (noChange) { + // The header already says it; the reason names who or what stopped the work. + lines.push('', noChange.replace(/^No change made:\s*/, '')); + } lines.push('', `_task ${args.taskId}_`); return lines.join('\n'); } @@ -1681,6 +1693,7 @@ function linearFinalStatusArgs( // "done" when nothing shipped). Only the no-PR + code_changed===false shape. needsInput: task.code_changed === false && !task.pr_url, answerText: typeof task.answer_text === 'string' ? task.answer_text : null, + noChangeReason: typeof task.no_change_reason === 'string' ? task.no_change_reason : null, // DDB returns numeric attributes as strings at the Document-client // boundary; coerce so toFixed/comparisons work. Same pattern the // GitHub dispatcher uses. diff --git a/cdk/src/handlers/shared/types.ts b/cdk/src/handlers/shared/types.ts index b0d810d3a..6153a091b 100644 --- a/cdk/src/handlers/shared/types.ts +++ b/cdk/src/handlers/shared/types.ts @@ -240,6 +240,12 @@ export interface TaskRecord { readonly code_changed?: boolean; /** A6/#299: the agent's answer, surfaced on a no-change iteration reply. */ readonly answer_text?: string; + /** + * Why a coding task completed without changing anything on purpose: a person + * denied what it needed, or a platform control blocked it ("No change made: …"). + * Shown instead of "Task completed"; absent for every other run. + */ + readonly no_change_reason?: string; /** * The branch HEAD sha this iteration pushed. The screenshot webhook matches a * deploy's commit sha → the iteration task that pushed it, so the preview diff --git a/cdk/test/handlers/fanout-task-events.test.ts b/cdk/test/handlers/fanout-task-events.test.ts index 6c6c7033a..56c66f653 100644 --- a/cdk/test/handlers/fanout-task-events.test.ts +++ b/cdk/test/handlers/fanout-task-events.test.ts @@ -2256,6 +2256,37 @@ describe('fanout-task-events: Linear dispatcher', () => { // --------------------------------------------------------------------------- describe('renderLinearFinalStatusComment', () => { + describe('a task that changed nothing on purpose', () => { + const base = { + eventType: 'task_completed', + prUrl: null, + costUsd: 0.12, + turns: 4, + maxTurns: 100, + durationS: 42, + taskId: 't-nc', + errorTitle: null, + }; + const reason = 'No change made: the platform policy blocked Write `.git/config` (write_git_internals). I left it alone.'; + + test('says No change made, with who or what stopped it, instead of ✅', () => { + const body = renderLinearFinalStatusComment({ ...base, noChangeReason: reason }); + expect(body.split('\n')[0]).toBe('➖ **No change made**'); + expect(body).not.toContain('✅'); + expect(body).toContain('the platform policy blocked Write `.git/config` (write_git_internals). I left it alone.'); + expect(body).not.toContain('No change made: the platform'); + expect(body).toContain('cost: $0.12 • turns: 4 / 100'); + }); + + test('a pull request or a failure keeps its usual header', () => { + expect(renderLinearFinalStatusComment({ ...base, prUrl: 'https://github.com/o/r/pull/1', noChangeReason: reason })) + .toMatch(/^✅ \*\*Task completed\*\*/); + expect(renderLinearFinalStatusComment({ ...base, eventType: 'task_failed', noChangeReason: reason })) + .toMatch(/^❌/); + expect(renderLinearFinalStatusComment({ ...base, noChangeReason: ' ' })).toMatch(/^✅/); + }); + }); + // The dispatcher tests above exercise the renderer indirectly through // the full handler stack. These tests call the exported renderer // directly to cover edge cases the integration fixtures don't: diff --git a/docs/guides/USER_GUIDE.md b/docs/guides/USER_GUIDE.md index 678168d05..e1dd76589 100644 --- a/docs/guides/USER_GUIDE.md +++ b/docs/guides/USER_GUIDE.md @@ -1177,6 +1177,8 @@ A task that is expected to open a new pull request ends as `FAILED`, not `COMPLE The error is "No change was delivered" (`deliverable=lost` in the `error_message`). Either the agent made no change, for example because the repository already had what you asked for, or its changes were lost before they reached the branch. The platform cannot tell which. Check the repository before you retry. If it has what you asked for, a retry ends the same way. [#751](https://github.com/aws-samples/sample-autonomous-cloud-coding-agents/issues/751) tracks a way for the agent to report that no change was needed. +There is one exception: a task that changed nothing because someone stopped it. If you denied an approval the agent needed, or a Cedar hard-deny rule blocked what it tried, and the agent then stopped instead of working around it, the task ends `COMPLETED`. Its final comment reads **No change made**, names what was denied or blocked and the rule, and quotes the agent's own first sentence (`no_change_reason` on the task record). + Terminal states: `COMPLETED`, `FAILED`, `CANCELLED`, `TIMED_OUT`. `AWAITING_APPROVAL` is not terminal — a decision (or an approval-timeout) always flips it back to `RUNNING` or onto a terminal state. Task records in terminal states are automatically deleted after 90 days (configurable via `taskRetentionDays`). diff --git a/docs/src/content/docs/using/Task-lifecycle.md b/docs/src/content/docs/using/Task-lifecycle.md index 38f770953..b6dd048bf 100644 --- a/docs/src/content/docs/using/Task-lifecycle.md +++ b/docs/src/content/docs/using/Task-lifecycle.md @@ -43,6 +43,8 @@ A task that is expected to open a new pull request ends as `FAILED`, not `COMPLE The error is "No change was delivered" (`deliverable=lost` in the `error_message`). Either the agent made no change, for example because the repository already had what you asked for, or its changes were lost before they reached the branch. The platform cannot tell which. Check the repository before you retry. If it has what you asked for, a retry ends the same way. [#751](https://github.com/aws-samples/sample-autonomous-cloud-coding-agents/issues/751) tracks a way for the agent to report that no change was needed. +There is one exception: a task that changed nothing because someone stopped it. If you denied an approval the agent needed, or a Cedar hard-deny rule blocked what it tried, and the agent then stopped instead of working around it, the task ends `COMPLETED`. Its final comment reads **No change made**, names what was denied or blocked and the rule, and quotes the agent's own first sentence (`no_change_reason` on the task record). + Terminal states: `COMPLETED`, `FAILED`, `CANCELLED`, `TIMED_OUT`. `AWAITING_APPROVAL` is not terminal — a decision (or an approval-timeout) always flips it back to `RUNNING` or onto a terminal state. Task records in terminal states are automatically deleted after 90 days (configurable via `taskRetentionDays`). From 2376a9b754583fb9eb2189b43da57e4fd75c4b9f Mon Sep 17 00:00:00 2001 From: Sphia Sadek Date: Wed, 25 Nov 2026 14:56:39 +0000 Subject: [PATCH 07/19] fix(cli): show the approval writer's stack under Orchestration in setup progress #1000 adds the ApprovalRequests nested stack at the top level of AgentStack; without a component it would show as a platform helper. --- cli/src/setup-ui.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cli/src/setup-ui.ts b/cli/src/setup-ui.ts index 3b81e380c..bfba9a0f0 100644 --- a/cli/src/setup-ui.ts +++ b/cli/src/setup-ui.ts @@ -62,7 +62,7 @@ const COMPONENTS: ReadonlyArray = [ ]], ['Orchestration', [ 'TaskOrchestrator', 'ConcurrencyMaintenance', 'OrchestrationReconciler', 'StrandedOrchestrationReconciler', - 'IterationHeartbeat', 'FanOutConsumer', 'ApprovalMetricsPublisherConsumer', + 'IterationHeartbeat', 'FanOutConsumer', 'ApprovalMetricsPublisherConsumer', 'ApprovalRequests', ]], ['Monitoring & alerts', ['TaskDashboard', 'OperationalAlerts', 'BudgetAlerts', 'ModelInvocationLogGroup', 'BedrockLoggingRole', 'ModelInvocationLogging']], ['Slack', ['SlackIntegration']], From 6dc5d3db4ac8db157f23f95a63e4ed72ee3b51e7 Mon Sep 17 00:00:00 2001 From: Sphia Sadek Date: Wed, 25 Nov 2026 15:52:17 +0000 Subject: [PATCH 08/19] fix(policy): file rules also apply to paths a Bash command writes Found in live testing: every Cedar file rule (write_file with context.file_path: .env and credentials files, the .git hard-deny rules, and any a blueprint adds) saw only the Write and Edit tools. A shell command that wrote the same file was evaluated as execute_bash alone, so no file rule applied to it. - bash_writes.bash_written_paths reads the paths a command writes: redirects, tee, the destination of cp / mv / install / ln, dd of=, in-place sed -i / perl -i, truncate and touch, across ; && || | and parentheses, with quoted paths, sudo / env prefixes, bash -c scripts, cd DIR and .. segments. A heuristic over the command text: a target built at run time ("$F", $(...)) and files other programs write are not recognised. - The engine evaluates each path as a write_file request at the same tier as the execute_bash request and keeps every match: a hard file rule denies, a soft one requires approval with the annotations merged as for any multi-match. Nothing here can turn a deny into an allow; the approval request shows the real command. - CEDAR_HITL_GATES.md says what the file rules now cover. --- agent/src/bash_writes.py | 217 ++++++++++++++++++ agent/src/policy.py | 36 ++- agent/tests/test_bash_writes.py | 93 ++++++++ docs/design/CEDAR_HITL_GATES.md | 2 + .../docs/architecture/Cedar-hitl-gates.md | 2 + 5 files changed, 341 insertions(+), 9 deletions(-) create mode 100644 agent/src/bash_writes.py create mode 100644 agent/tests/test_bash_writes.py diff --git a/agent/src/bash_writes.py b/agent/src/bash_writes.py new file mode 100644 index 000000000..f8b3453db --- /dev/null +++ b/agent/src/bash_writes.py @@ -0,0 +1,217 @@ +"""Paths a Bash command writes, for the policy engine's file rules. + +Every Cedar file rule (``write_file`` with ``context.file_path``: ``.env`` and +credentials files, ``.git`` internals) used to see only the Write and Edit +tools. A shell command that wrote the same file (a redirect, ``tee``, ``cp``) +was evaluated as ``execute_bash`` alone, so no file rule applied to it. +``bash_written_paths`` lists the paths a command writes so the engine can put +each one through the same file rules. + +This is a heuristic over the command text, not a sandbox: + +- Covered: redirects (``>``, ``>>``, ``>|``, ``&>``, ``N>``), ``tee``, the + destination of ``cp`` / ``mv`` / ``install`` / ``ln`` (``-t DIR`` too), + ``dd of=``, in-place ``sed -i`` / ``perl -i``, ``truncate`` and ``touch``; + commands joined with ``;``, ``&&``, ``||``, ``|``, ``&``, newlines or + parentheses; quoted paths; ``sudo`` / ``env`` / ``command`` / ``nohup`` / + ``time`` prefixes and leading ``VAR=value`` assignments; ``bash -c`` / + ``sh -c`` scripts; ``cd DIR`` before a relative path; ``..`` segments. +- Not covered: a target built at run time (``> "$F"``, ``$(...)``, backticks) + is not guessed at, and neither are writes by other programs (an editor, a + script, ``git``, a package manager). Unbalanced quotes yield no paths: bash + would refuse to run the command anyway. +""" + +from __future__ import annotations + +import os +import shlex + +_SEPARATORS = frozenset({";", "&&", "||", "|", "&", "|&", "(", ")", ";;"}) +_WRITE_REDIRECTS = frozenset({">", ">>", ">|", "&>", "&>>"}) +_PREFIX_COMMANDS = frozenset({"sudo", "env", "command", "nohup", "time", "exec", "builtin"}) +_SHELLS = frozenset({"bash", "sh", "zsh", "dash"}) +_COPY_COMMANDS = frozenset({"cp", "mv", "install", "ln"}) +# Options of these commands that take a value (the next token is not a path). +_VALUE_OPTIONS = { + "sed": frozenset({"-e", "--expression", "-f", "--file", "-l", "--line-length"}), + "perl": frozenset({"-e", "-E", "-I", "-M", "-m"}), + "truncate": frozenset({"-s", "--size", "-r", "--reference"}), + "touch": frozenset({"-d", "--date", "-t", "-r", "--reference"}), + "cp": frozenset({"-t", "--target-directory", "-S", "--suffix"}), + "mv": frozenset({"-t", "--target-directory", "-S", "--suffix"}), + "install": frozenset( + { + "-t", + "--target-directory", + "-m", + "--mode", + "-o", + "--owner", + "-g", + "--group", + "-S", + "--suffix", + } + ), + "ln": frozenset({"-t", "--target-directory", "-S", "--suffix"}), + "tee": frozenset(), +} +_MAX_SHELL_DEPTH = 3 +# A copy needs a source and a destination; `cd` takes one directory. +_COPY_MIN_OPERANDS = 2 +_CD_ARGV_LEN = 2 + + +def _dynamic(token: str) -> bool: + """A token whose value is only known when the shell runs it.""" + return "$" in token or "`" in token + + +def _tokens(command: str) -> list[str] | None: + lexer = shlex.shlex(command.replace("\n", " ; "), posix=True, punctuation_chars=True) + lexer.whitespace_split = True + try: + return list(lexer) + except ValueError: + return None + + +def _segments(tokens: list[str]) -> list[tuple[list[str], list[str]]]: + """Split into simple commands: each command's words and its redirect targets.""" + segments: list[tuple[list[str], list[str]]] = [([], [])] + i = 0 + while i < len(tokens): + tok = tokens[i] + words, redirects = segments[-1] + if tok in _SEPARATORS: + segments.append(([], [])) + elif tok in _WRITE_REDIRECTS or tok in ("<", ">&") or tok.endswith(">&"): + target = tokens[i + 1] if i + 1 < len(tokens) else "" + # `2>/dev/null`: the fd number lexes as an argument of its own. + if words and words[-1].isdigit(): + words.pop() + if tok in _WRITE_REDIRECTS and target and target not in _SEPARATORS: + redirects.append(target) + i += 1 # the target (or the fd of `2>&1`) is consumed + else: + words.append(tok) + i += 1 + return [seg for seg in segments if seg[0] or seg[1]] + + +def _strip_prefixes(argv: list[str]) -> list[str]: + while argv and ( + "=" in argv[0] and not argv[0].startswith("-") and argv[0].split("=", 1)[0].isidentifier() + ): + argv = argv[1:] + while argv and os.path.basename(argv[0]) in _PREFIX_COMMANDS: + argv = argv[1:] + while argv and argv[0].startswith("-"): + argv = argv[1:] + while argv and "=" in argv[0] and argv[0].split("=", 1)[0].isidentifier(): + argv = argv[1:] + return argv + + +def _operands(name: str, args: list[str]) -> tuple[list[str], dict[str, str]]: + """Non-option arguments, and the values of options that take one.""" + takes_value = _VALUE_OPTIONS.get(name, frozenset()) + operands: list[str] = [] + values: dict[str, str] = {} + i = 0 + while i < len(args): + arg = args[i] + if arg == "--": + operands.extend(args[i + 1 :]) + break + if arg.startswith("--") and "=" in arg: + key, value = arg.split("=", 1) + values[key] = value + elif arg in takes_value: + values[arg] = args[i + 1] if i + 1 < len(args) else "" + i += 1 + elif not arg.startswith("-") or arg == "-": + operands.append(arg) + i += 1 + return operands, values + + +def _copy_targets(name: str, args: list[str]) -> list[str]: + operands, values = _operands(name, args) + target_dir = values.get("-t") or values.get("--target-directory") + if target_dir: + return [target_dir, *(os.path.join(target_dir, os.path.basename(s)) for s in operands)] + if len(operands) < _COPY_MIN_OPERANDS: + return [] + *sources, dest = operands + if dest.endswith("/") or len(sources) > 1: + return [dest, *(os.path.join(dest, os.path.basename(s)) for s in sources)] + return [dest] + + +def _in_place_targets(name: str, args: list[str]) -> list[str]: + in_place = any( + a == "--in-place" + or a.startswith("--in-place=") + or (a.startswith("-") and not a.startswith("--") and "i" in a[1:]) + for a in args + ) + if not in_place: + return [] + operands, values = _operands(name, args) + has_script_option = any(k in values for k in ("-e", "--expression", "-f", "--file", "-E")) + return operands if has_script_option else operands[1:] + + +def _command_targets(argv: list[str], depth: int) -> list[str]: + name = os.path.basename(argv[0]) + args = argv[1:] + if name in _SHELLS and "-c" in args: + idx = args.index("-c") + script = args[idx + 1] if idx + 1 < len(args) else "" + return _written(script, depth + 1) if depth < _MAX_SHELL_DEPTH else [] + if name == "tee": + return _operands(name, args)[0] + if name in _COPY_COMMANDS: + return _copy_targets(name, args) + if name == "dd": + return [a.split("=", 1)[1] for a in args if a.startswith("of=")] + if name in ("sed", "perl"): + return _in_place_targets(name, args) + if name in ("truncate", "touch"): + return _operands(name, args)[0] + return [] + + +def _written(command: str, depth: int) -> list[str]: + tokens = _tokens(command) + if tokens is None: + return [] + found: list[str] = [] + cwd = "" + for raw, redirects in _segments(tokens): + argv = _strip_prefixes(raw) + if argv and argv[0] == "cd" and len(argv) == _CD_ARGV_LEN and not _dynamic(argv[1]): + cwd = argv[1] if argv[1].startswith("/") else os.path.join(cwd, argv[1]) + continue + targets = (_command_targets(argv, depth) if argv else []) + redirects + found.extend(os.path.join(cwd, t) if cwd and not t.startswith("/") else t for t in targets) + return found + + +def bash_written_paths(command: str) -> list[str]: + """Paths ``command`` writes, normalized (``a/../.git/x`` -> ``.git/x``), in order, deduplicated. + + Paths built at run time (``$VAR``, ``$(...)``, backticks) are left out. + """ + out: list[str] = [] + for path in _written(command, 0): + if not path or _dynamic(path) or path in ("/dev/null", "-"): + continue + norm = os.path.normpath(path) + if path.endswith("/") and not norm.endswith("/"): + norm += "/" + if norm not in out: + out.append(norm) + return out diff --git a/agent/src/policy.py b/agent/src/policy.py index 0b9fadc81..4f7ce5a26 100644 --- a/agent/src/policy.py +++ b/agent/src/policy.py @@ -66,6 +66,7 @@ from pathlib import Path from typing import TYPE_CHECKING +from bash_writes import bash_written_paths from shared_constants import SHARED_CONSTANTS from shell import log @@ -1353,21 +1354,38 @@ def _run(action: str, resource_type: str, resource_id: str, ctx: dict): if write_decision == "deny": return ("deny", write_reasons) - # Bash: evaluate execute_bash with command in context. + # Bash: evaluate execute_bash with command in context, then every path + # the command writes as a write_file, so the file rules (.env and + # credentials files, .git internals) apply to a redirect, `tee` or `cp` + # as they do to the Write tool. All matches at this tier are kept, so a + # soft-deny merges their annotations; nothing here can turn a deny back + # into an allow. See bash_writes.py for what is and is not recognised. if tool_name == "Bash": command = tool_input.get("command", "") if command: - bash_decision, bash_reasons = _run( - "execute_bash", - "Agent::BashCommand", - "command", - {**base_context, "command": command}, - ) - if bash_decision == "deny": - return ("deny", bash_reasons) + return self._eval_bash(_run, command, base_context) return None + @staticmethod + def _eval_bash(run, command: str, base_context: dict) -> tuple[str, list[str]] | None: + reasons: list[str] = [] + bash_decision, bash_reasons = run( + "execute_bash", + "Agent::BashCommand", + "command", + {**base_context, "command": command}, + ) + if bash_decision == "deny": + reasons.extend(bash_reasons) + for path in bash_written_paths(command): + write_decision, write_reasons = run( + "write_file", "Agent::File", "file", {**base_context, "file_path": path} + ) + if write_decision == "deny": + reasons.extend(r for r in write_reasons if r not in reasons) + return ("deny", reasons) if reasons else None + def _matching_rule_ids( rules: list[_ParsedRule], diff --git a/agent/tests/test_bash_writes.py b/agent/tests/test_bash_writes.py new file mode 100644 index 000000000..9ac5e3a20 --- /dev/null +++ b/agent/tests/test_bash_writes.py @@ -0,0 +1,93 @@ +"""File rules also apply to the paths a Bash command writes (bash_writes.py). + +Found in live testing: a Bash redirect wrote a ``.env`` file with no approval, +because every file rule saw only the Write and Edit tools. +""" + +import pytest + +from bash_writes import bash_written_paths +from policy import Outcome, PolicyEngine + + +@pytest.mark.parametrize( + ("command", "expected"), + [ + ("printf 'A=1\\n' > config/site.env", ["config/site.env"]), + ("echo x >> .env.local", [".env.local"]), + ("cmd &> logs/run.env", ["logs/run.env"]), + ("tee -a creds/credentials.json", ["creds/credentials.json"]), + ("cp x .git/hooks/pre-commit", [".git/hooks/pre-commit"]), + ("cp a.env b.env backup/", ["backup/", "backup/a.env", "backup/b.env"]), + ("mv -t .git/hooks x", [".git/hooks", ".git/hooks/x"]), + ("dd if=/dev/zero of=db.env bs=1 count=1", ["db.env"]), + ("sed -i 's/a/b/' app.env", ["app.env"]), + ("perl -pi -e 's/a/b/' y.env", ["y.env"]), + ("truncate -s 0 old.env", ["old.env"]), + ("echo hi > 'my dir/a b.env'", ["my dir/a b.env"]), + ("ls; npm test && echo done > out/.env", ["out/.env"]), + ("cd .git && echo x > config", [".git/config"]), + ("echo x > a/../.git/HEAD", [".git/HEAD"]), + ("bash -c 'echo x > .env'", [".env"]), + ("FOO=1 sudo tee .env", [".env"]), + ], +) +def test_paths_a_command_writes(command, expected): + assert bash_written_paths(command) == expected + + +@pytest.mark.parametrize( + "command", + [ + "cat .env", + "grep KEY .env", + "npm test 2>&1 | tail -5", + "cmd 2>/dev/null", + 'git commit -m "write x > y.env"', + 'echo x > "$F"', + "echo x > $(mktemp)", + "echo 'unbalanced", + ], +) +def test_reads_quoted_text_and_runtime_targets_write_nothing_known(command): + assert bash_written_paths(command) == [] + + +@pytest.fixture(scope="module") +def engine(): + return PolicyEngine(task_type="new_task", repo="o/r") + + +def _bash(engine, command): + return engine.evaluate_tool_use("Bash", {"command": command}) + + +def test_a_redirect_to_an_env_file_needs_approval_like_the_write_tool(engine): + via_shell = _bash(engine, "mkdir -p config && printf 'A=1' > config/site.env") + via_tool = engine.evaluate_tool_use("Write", {"file_path": "config/site.env", "content": "A=1"}) + assert via_shell.outcome == via_tool.outcome == Outcome.REQUIRE_APPROVAL + assert via_shell.matching_rule_ids == via_tool.matching_rule_ids == ("write_env_files",) + + +@pytest.mark.parametrize("command", ["cp hook.sh .git/hooks/pre-commit", "echo > .git/config"]) +def test_writing_git_internals_from_the_shell_is_a_hard_deny(engine, command): + decision = _bash(engine, command) + assert decision.outcome == Outcome.DENY + assert "write_git_internals" in decision.reason + + +def test_tee_into_a_credentials_file_needs_approval(engine): + decision = _bash(engine, "echo '{}' | tee -a creds/credentials.json") + assert decision.outcome == Outcome.REQUIRE_APPROVAL + assert decision.matching_rule_ids == ("write_credentials",) + + +@pytest.mark.parametrize("command", ["cat .env", "grep foo src > out.txt", 'echo x > "$F"']) +def test_reads_and_ordinary_writes_stay_allowed(engine, command): + assert _bash(engine, command).outcome == Outcome.ALLOW + + +def test_a_command_rule_and_a_file_rule_both_count(engine): + decision = _bash(engine, "git push --force origin feature > push.env") + assert decision.outcome == Outcome.REQUIRE_APPROVAL + assert decision.matching_rule_ids == ("force_push_any", "write_env_files") diff --git a/docs/design/CEDAR_HITL_GATES.md b/docs/design/CEDAR_HITL_GATES.md index 7c75fbe5d..cd56726d0 100644 --- a/docs/design/CEDAR_HITL_GATES.md +++ b/docs/design/CEDAR_HITL_GATES.md @@ -503,6 +503,8 @@ forbid (principal, action == Agent::Action::"write_file", resource) when { context.file_path like "*credentials*" }; ``` +**File rules cover shell writes too.** A `write_file` rule (these two, the `.git` hard-deny rules, and any a blueprint adds) applies to the Write and Edit tools and also to every path a Bash command writes: redirects (`>`, `>>`, `&>`), `tee`, the destination of `cp` / `mv` / `install` / `ln`, `dd of=`, in-place `sed -i` / `perl -i`, `truncate` and `touch`, including after `cd DIR` and inside `bash -c`. Each path is evaluated as its own `write_file` request at the same tier, and every match counts (a soft-deny merges their annotations). This reads the command text (`agent/src/bash_writes.py`), so it is a heuristic: a target built at run time (`"$F"`, `$(...)`) and files that other programs write are not recognised. + **Optional patterns (not shipped by default — copy into your blueprint if your repo needs them):** ```cedar // Gate writes under a conventional infrastructure/ directory. Not in the diff --git a/docs/src/content/docs/architecture/Cedar-hitl-gates.md b/docs/src/content/docs/architecture/Cedar-hitl-gates.md index be074348d..c4266d081 100644 --- a/docs/src/content/docs/architecture/Cedar-hitl-gates.md +++ b/docs/src/content/docs/architecture/Cedar-hitl-gates.md @@ -505,6 +505,8 @@ forbid (principal, action == Agent::Action::"write_file", resource) when { context.file_path like "*credentials*" }; ``` +**File rules cover shell writes too.** A `write_file` rule (these two, the `.git` hard-deny rules, and any a blueprint adds) applies to the Write and Edit tools and also to every path a Bash command writes: redirects (`>`, `>>`, `&>`), `tee`, the destination of `cp` / `mv` / `install` / `ln`, `dd of=`, in-place `sed -i` / `perl -i`, `truncate` and `touch`, including after `cd DIR` and inside `bash -c`. Each path is evaluated as its own `write_file` request at the same tier, and every match counts (a soft-deny merges their annotations). This reads the command text (`agent/src/bash_writes.py`), so it is a heuristic: a target built at run time (`"$F"`, `$(...)`) and files that other programs write are not recognised. + **Optional patterns (not shipped by default — copy into your blueprint if your repo needs them):** ```cedar // Gate writes under a conventional infrastructure/ directory. Not in the From 5ac702e87966c43192b302490c64a28a5ca0f710 Mon Sep 17 00:00:00 2001 From: Sphia Sadek Date: Wed, 25 Nov 2026 20:51:15 +0000 Subject: [PATCH 09/19] chore: no change (re-sync the pull request head) From 92930e6ec090c49da151885ad635602d4ac9c878 Mon Sep 17 00:00:00 2001 From: Sphia Sadek Date: Thu, 26 Nov 2026 01:02:08 +0000 Subject: [PATCH 10/19] fix(policy): a command shlex cannot split is not a command that writes nothing Bash runs commands that shlex rejects, such as ANSI-C quoting ($'it\'s'). The extractor returned no paths for them, so `echo $'it\'s' > .env` passed every file rule. Such a command's rough words now come back as possible targets, so the file rules still see .env or .git/. The worst case is an extra approval on a rare unsplittable command, never a missed one. The SAST range scan had flagged the swallowed parse error. --- agent/src/bash_writes.py | 23 +++++++++++++++++------ agent/tests/test_bash_writes.py | 18 ++++++++++++++++-- 2 files changed, 33 insertions(+), 8 deletions(-) diff --git a/agent/src/bash_writes.py b/agent/src/bash_writes.py index f8b3453db..6ab1e4898 100644 --- a/agent/src/bash_writes.py +++ b/agent/src/bash_writes.py @@ -25,6 +25,7 @@ from __future__ import annotations import os +import re import shlex _SEPARATORS = frozenset({";", "&&", "||", "|", "&", "|&", "(", ")", ";;"}) @@ -68,13 +69,23 @@ def _dynamic(token: str) -> bool: return "$" in token or "`" in token -def _tokens(command: str) -> list[str] | None: +_ROUGH_SPLIT = re.compile(r"[\s;&|()<>]+") + + +def _tokens(command: str) -> tuple[list[str], bool]: + """The command's tokens, and whether shlex read them exactly. + + Bash accepts commands shlex rejects (ANSI-C quoting such as ``$'it\\'s'``). + Such a command must not read as writing nothing, so its rough words come back + unparsed and the caller treats every one as a possible target. + """ lexer = shlex.shlex(command.replace("\n", " ; "), posix=True, punctuation_chars=True) lexer.whitespace_split = True try: - return list(lexer) + return list(lexer), True except ValueError: - return None + words = (w.strip("'\"$") for w in _ROUGH_SPLIT.split(command)) + return [w for w in words if w], False def _segments(tokens: list[str]) -> list[tuple[list[str], list[str]]]: @@ -185,9 +196,9 @@ def _command_targets(argv: list[str], depth: int) -> list[str]: def _written(command: str, depth: int) -> list[str]: - tokens = _tokens(command) - if tokens is None: - return [] + tokens, exact = _tokens(command) + if not exact: + return tokens found: list[str] = [] cwd = "" for raw, redirects in _segments(tokens): diff --git a/agent/tests/test_bash_writes.py b/agent/tests/test_bash_writes.py index 9ac5e3a20..92ed9cd44 100644 --- a/agent/tests/test_bash_writes.py +++ b/agent/tests/test_bash_writes.py @@ -46,7 +46,6 @@ def test_paths_a_command_writes(command, expected): 'git commit -m "write x > y.env"', 'echo x > "$F"', "echo x > $(mktemp)", - "echo 'unbalanced", ], ) def test_reads_quoted_text_and_runtime_targets_write_nothing_known(command): @@ -69,13 +68,28 @@ def test_a_redirect_to_an_env_file_needs_approval_like_the_write_tool(engine): assert via_shell.matching_rule_ids == via_tool.matching_rule_ids == ("write_env_files",) -@pytest.mark.parametrize("command", ["cp hook.sh .git/hooks/pre-commit", "echo > .git/config"]) +@pytest.mark.parametrize( + "command", + ["cp hook.sh .git/hooks/pre-commit", "echo > .git/config", "echo $'x\\'y' > .git/config"], +) def test_writing_git_internals_from_the_shell_is_a_hard_deny(engine, command): decision = _bash(engine, command) assert decision.outcome == Outcome.DENY assert "write_git_internals" in decision.reason +def test_a_command_shlex_cannot_split_treats_every_word_as_a_target(): + # Bash runs ANSI-C quoting that shlex rejects; such a command must not read as writing nothing. + assert ".env" in bash_written_paths("echo $'it\\'s' > .env") + assert bash_written_paths("echo 'unbalanced") == ["echo", "unbalanced"] + + +def test_an_unsplittable_write_to_an_env_file_still_needs_approval(engine): + decision = _bash(engine, "printf %s $'a\\'b' > .env") + assert decision.outcome == Outcome.REQUIRE_APPROVAL + assert decision.matching_rule_ids == ("write_env_files",) + + def test_tee_into_a_credentials_file_needs_approval(engine): decision = _bash(engine, "echo '{}' | tee -a creds/credentials.json") assert decision.outcome == Outcome.REQUIRE_APPROVAL From 24871670dfb0f2d205e943ea9e675f659564dfbf Mon Sep 17 00:00:00 2001 From: Sphia Sadek Date: Thu, 26 Nov 2026 01:02:48 +0000 Subject: [PATCH 11/19] test(emulator): the seat defects fixed by #1003 pass, so they are plain tests The replayed-finalize double release and the reconciler that dropped the seat of a task awaiting approval were test.failing witnesses until this fix. The leaked-seat test now writes the leak to the counter directly: admission ties every seat to a task record. --- .../emulator/concurrency-seats.emulator.ts | 21 +++++++++++-------- 1 file changed, 12 insertions(+), 9 deletions(-) diff --git a/cdk/test/emulator/concurrency-seats.emulator.ts b/cdk/test/emulator/concurrency-seats.emulator.ts index da4ac59dc..fcb874987 100644 --- a/cdk/test/emulator/concurrency-seats.emulator.ts +++ b/cdk/test/emulator/concurrency-seats.emulator.ts @@ -138,7 +138,14 @@ describe('concurrency seats against the AWS Emulator', () => { const user = newUser(); await running(user); // A seat with no live task behind it, as a finalize step that never ran leaves. - expect(await admissionControl({ user_id: user } as TaskRecord)).toBe(true); + // Admission ties every seat to a task record (#1003), so the leak is written + // to the counter directly. + await ddb.send(new UpdateCommand({ + TableName: process.env.USER_CONCURRENCY_TABLE_NAME, + Key: { user_id: user }, + UpdateExpression: 'ADD active_count :one', + ExpressionAttributeValues: { ':one': 1 }, + })); expect(await seats(user)).toBe(2); await reconcileConcurrency(); @@ -146,13 +153,9 @@ describe('concurrency seats against the AWS Emulator', () => { expect(await seats(user)).toBe(1); }); - // KNOWN FAILURES: executable witnesses for two seat defects on main, reproduced - // here with real conditional writes rather than mocked `send` calls. Kept as - // `test.failing` so the suite stays green and flags the day the fix lands (open - // PR #1009 addresses both). Each was run once as a plain `test` to confirm it - // fails on its last assertion and not on setup; the passing tests above cover - // the same setup. - test.failing('#1003: a replayed finalize step does not release a second seat', async () => { + // Two seat defects of earlier releases, reproduced with real conditional writes + // rather than mocked `send` calls. Both were `test.failing` until #1003's fix. + test('#1003: a replayed finalize step does not release a second seat', async () => { const user = newUser(); const done = await running(user); await running(user); @@ -168,7 +171,7 @@ describe('concurrency seats against the AWS Emulator', () => { // No issue reports this one: reconcile-concurrency counts four hard-coded // statuses, while the design and ACTIVE_STATUSES say a task awaiting approval // holds its seat. - test.failing('the concurrency reconciler keeps the seat of a task awaiting approval', async () => { + test('the concurrency reconciler keeps the seat of a task awaiting approval', async () => { const user = newUser(); const paused = await running(user); // The Python agent is the only writer of this status; this writes the status From b9cee449d04b02ebeae029ca584b86b8feed0f91 Mon Sep 17 00:00:00 2001 From: Sphia Sadek Date: Thu, 26 Nov 2026 01:09:23 +0000 Subject: [PATCH 12/19] fix(delivery): work left in the clone is not "No change made" controlled_no_change_reason took "no PR and no commit on the remote branch" as "changed nothing". After a denial or a block, a run whose push failed, whose safety-net commit was refused, or whose only work was new untracked files completed as "No change made" instead of failing as deliverable=lost. The reason now also requires the clone to match its base: no local commit and a clean working tree. --- agent/src/pipeline.py | 38 +++++++++++++++++++++--- agent/tests/test_controlled_no_change.py | 34 +++++++++++++++++---- 2 files changed, 62 insertions(+), 10 deletions(-) diff --git a/agent/src/pipeline.py b/agent/src/pipeline.py index 691f3f804..2dc8678db 100644 --- a/agent/src/pipeline.py +++ b/agent/src/pipeline.py @@ -897,12 +897,39 @@ def blocked_no_change_reason(blocks: list[dict], result_text: str) -> str: return f"{head}. {first}" if first else f"{head}." +def _workspace_changed(repo_dir: str, base_branch: str) -> bool: + """True when the clone differs from ``origin/``: a local commit, or + a tracked or untracked change. A git failure counts as a change.""" + try: + ahead = subprocess.run( + ["git", "rev-list", "--count", f"origin/{base_branch}..HEAD"], + cwd=repo_dir, + capture_output=True, + text=True, + timeout=60, + ) + status = subprocess.run( + ["git", "status", "--porcelain"], + cwd=repo_dir, + capture_output=True, + timeout=60, + ) + except (OSError, subprocess.SubprocessError): + return True + return ( + ahead.returncode != 0 + or ahead.stdout.strip() != "0" + or status.returncode != 0 + or bool(status.stdout.strip()) + ) + + def controlled_no_change_reason( agent_result: AgentResult, *, overall_status: str, pr_url: str | None, - commit_landed: bool, + changed: bool, needs_input: bool = False, ) -> str: """Why a successful run that shipped nothing changed nothing on purpose, or "". @@ -911,9 +938,11 @@ def controlled_no_change_reason( agent then (correctly) stopped instead of working around it. That run ended as asked: the delivery gate must not report it as lost work. A denial wins over a block, since a person's decision is the more specific reason. A run that held - to ask a question has its own reply (the question), so it gets none. + to ask a question has its own reply (the question), so it gets none. ``changed`` + is True when a commit landed or the clone holds work that did not: that work + was lost, whatever stopped the agent. """ - if needs_input or overall_status != "success" or pr_url or commit_landed: + if needs_input or overall_status != "success" or pr_url or changed: return "" text = agent_result.result_text or "" return declined_no_change_reason( @@ -1861,7 +1890,8 @@ def _on_trace_truncated(max_bytes: int, first_dropped: int) -> None: agent_result, overall_status=overall_status, pr_url=pr_url, - commit_landed=commit_landed, + changed=commit_landed + or (not pr_url and _workspace_changed(setup.repo_dir, setup.default_branch)), needs_input=needs_input, ) overall_status, result_error = _apply_delivery_gate( diff --git a/agent/tests/test_controlled_no_change.py b/agent/tests/test_controlled_no_change.py index 9ef6bcaeb..9359d7ca9 100644 --- a/agent/tests/test_controlled_no_change.py +++ b/agent/tests/test_controlled_no_change.py @@ -9,10 +9,12 @@ from __future__ import annotations import asyncio +import subprocess from models import AgentResult from pipeline import ( _apply_delivery_gate, + _workspace_changed, blocked_no_change_reason, controlled_no_change_reason, declined_no_change_reason, @@ -89,19 +91,17 @@ def reason( r: AgentResult = result, status: str = "success", pr: str | None = None, - commit: bool = False, + changed: bool = False, ) -> str: - return controlled_no_change_reason( - r, overall_status=status, pr_url=pr, commit_landed=commit - ) + return controlled_no_change_reason(r, overall_status=status, pr_url=pr, changed=changed) assert reason().startswith("No change made: deleting `x` was denied") assert reason(pr="https://x/pull/1") == "" - assert reason(commit=True) == "" + assert reason(changed=True) == "" assert reason(status="error") == "" assert reason(AgentResult(status="success")) == "" held = controlled_no_change_reason( - result, overall_status="success", pr_url=None, commit_landed=False, needs_input=True + result, overall_status="success", pr_url=None, changed=False, needs_input=True ) assert held == "" @@ -114,6 +114,28 @@ def test_the_delivery_gate_lets_a_controlled_no_change_complete(): assert _gate("No change made: …", commit_landed=True)[0] == "error" +def _git(repo, *args: str) -> None: + identity = ["-c", "user.name=t", "-c", "user.email=t@e"] + subprocess.run(["git", *identity, *args], cwd=repo, check=True, capture_output=True) + + +def test_work_left_in_the_clone_is_a_change(tmp_path): + origin, repo = tmp_path / "origin.git", tmp_path / "repo" + _git(tmp_path, "init", "-q", "--bare", "-b", "main", str(origin)) + _git(tmp_path, "clone", "-q", str(origin), str(repo)) + _git(repo, "commit", "-q", "--allow-empty", "-m", "b") + _git(repo, "push", "-q", "origin", "main") + _git(repo, "checkout", "-qb", "bgagent/t") + assert not _workspace_changed(str(repo), "main") + (repo / "new.py").write_text("x") + assert _workspace_changed(str(repo), "main") + _git(repo, "add", "new.py") + _git(repo, "commit", "-q", "-m", "work") + # Committed but never pushed: the work exists only in this container. + assert _workspace_changed(str(repo), "main") + assert _workspace_changed(str(tmp_path / "missing"), "main") + + def test_the_engine_keeps_denials_after_the_turn_queue_is_drained(): engine = PolicyEngine(task_type="new_task", repo="owner/repo") engine.queue_denial_injection(request_id="r1", reason="no", decided_at=None, what="Allow x?") From c79f216bfe2745f60518f298d07480a26fee1be5 Mon Sep 17 00:00:00 2001 From: Sphia Sadek Date: Thu, 26 Nov 2026 01:10:39 +0000 Subject: [PATCH 13/19] fix(agent): a resumed run keeps the approval gates the task already opened run_agent builds a new policy engine for every call and seeds its approval gate count from the task config. A model-retry resume reused the original config, so each resume restarted the count and a task could open up to four times the per-task approval gate cap. The result now carries the engine's count and the resumed call is seeded with it. --- agent/src/model_retry.py | 8 +++++++- agent/src/models.py | 2 ++ agent/src/runner.py | 1 + agent/tests/test_model_retry.py | 14 ++++++++++++++ 4 files changed, 24 insertions(+), 1 deletion(-) diff --git a/agent/src/model_retry.py b/agent/src/model_retry.py index 1687cf02c..6633b4bbc 100644 --- a/agent/src/model_retry.py +++ b/agent/src/model_retry.py @@ -160,7 +160,13 @@ async def run_agent_resilient( ) _write_retry_milestone(config, attempt, len(delays), delay) await sleep(delay) - capped = config.model_copy(update={"max_turns": left_turns, "max_budget_usd": left_budget}) + capped = config.model_copy( + update={ + "max_turns": left_turns, + "max_budget_usd": left_budget, + "initial_approval_gate_count": result.approval_gate_count, + } + ) nxt = await run( MODEL_RETRY_RESUME_PROMPT if result.session_id else prompt, system_prompt, diff --git a/agent/src/models.py b/agent/src/models.py index 1ebac5d0d..74db2bb74 100644 --- a/agent/src/models.py +++ b/agent/src/models.py @@ -384,6 +384,8 @@ class AgentResult(BaseModel): # that then delivers nothing ended as asked, not with lost work. denied_approvals: list[dict] = Field(default_factory=list) platform_blocks: list[dict] = Field(default_factory=list) + # Approval gates opened so far this task, which seed a resumed run's engine. + approval_gate_count: int = 0 class TaskResult(BaseModel): diff --git a/agent/src/runner.py b/agent/src/runner.py index 918cc4a8c..5428b94b2 100644 --- a/agent/src/runner.py +++ b/agent/src/runner.py @@ -900,4 +900,5 @@ def _on_stderr(line: str) -> None: result.denied_approvals = list(getattr(_policy_engine, "denied_approvals", None) or []) result.platform_blocks = list(getattr(_policy_engine, "platform_blocks", None) or []) + result.approval_gate_count = getattr(_policy_engine, "approval_gate_count", 0) return result diff --git a/agent/tests/test_model_retry.py b/agent/tests/test_model_retry.py index 51efb1f16..10ab997ce 100644 --- a/agent/tests/test_model_retry.py +++ b/agent/tests/test_model_retry.py @@ -140,3 +140,17 @@ def test_the_delays_come_from_the_environment(monkeypatch): assert model_retry.retry_delays_s() == (5, 10) monkeypatch.delenv("MODEL_RETRY_DELAYS_S") assert model_retry.retry_delays_s() == (15, 60, 120) + + +def test_a_resumed_run_keeps_the_approval_gates_already_opened(): + first = _res(status="error", error=BEDROCK_5XX) + first.approval_gate_count = 7 + run = _Run([first, _res()]) + seeded = [] + + async def recording(prompt, system_prompt, config, **kwargs): + seeded.append(config.initial_approval_gate_count) + return await run(prompt, system_prompt, config, **kwargs) + + _go(recording, config=_config(initial_approval_gate_count=2)) + assert seeded == [2, 7] From 83922e7ed38717e2511303512f67575ff582e9b7 Mon Sep 17 00:00:00 2001 From: Sphia Sadek Date: Thu, 26 Nov 2026 01:12:28 +0000 Subject: [PATCH 14/19] fix(policy): a heredoc body is input, not shell commands bash_written_paths read every heredoc body line as a command. A body that mentioned a protected path as text (a document written with `cat > file < "$F"``, ``$(...)``, backticks) is not guessed at, and neither are writes by other programs (an editor, a script, ``git``, a package manager). Unbalanced quotes yield no paths: bash @@ -70,6 +71,40 @@ def _dynamic(token: str) -> bool: _ROUGH_SPLIT = re.compile(r"[\s;&|()<>]+") +_HEREDOC = re.compile(r"(? tuple[str, list[str]]: + """The command without its heredoc bodies, and the bodies a shell reads as a script. + + A body is the command's input, not commands. A body without its closing line is + kept as commands. + """ + lines = command.split("\n") + kept: list[str] = [] + scripts: list[str] = [] + i = 0 + while i < len(lines): + line = lines[i] + kept.append(line) + i += 1 + for match in _HEREDOC.finditer(line): + dash, _, delimiter = match.groups() + end = next( + ( + j + for j in range(i, len(lines)) + if (lines[j].lstrip("\t") if dash else lines[j]) == delimiter + ), + None, + ) + if end is None: + break + reader = _strip_prefixes(re.split(r"[;&|()]", line[: match.start()])[-1].split()) + if reader and os.path.basename(reader[0]) in _SHELLS: + scripts.append("\n".join(lines[i:end])) + i = end + 1 + return "\n".join(kept), scripts def _tokens(command: str) -> tuple[list[str], bool]: @@ -196,10 +231,11 @@ def _command_targets(argv: list[str], depth: int) -> list[str]: def _written(command: str, depth: int) -> list[str]: + command, scripts = _split_heredocs(command) + found = [p for script in scripts for p in _written(script, depth + 1)] tokens, exact = _tokens(command) if not exact: - return tokens - found: list[str] = [] + return found + tokens cwd = "" for raw, redirects in _segments(tokens): argv = _strip_prefixes(raw) diff --git a/agent/tests/test_bash_writes.py b/agent/tests/test_bash_writes.py index 92ed9cd44..dc8151c30 100644 --- a/agent/tests/test_bash_writes.py +++ b/agent/tests/test_bash_writes.py @@ -101,6 +101,25 @@ def test_reads_and_ordinary_writes_stay_allowed(engine, command): assert _bash(engine, command).outcome == Outcome.ALLOW +@pytest.mark.parametrize( + "command", + [ + "cat > docs/hooks.md <<'EOF'\nThe hook goes to .git/hooks/pre-commit. Don't edit it.\nEOF", + "cat > docs/setup.md < .git/config\nEOF\necho done > out.txt") + assert decision.outcome == Outcome.DENY + assert bash_written_paths("sudo sh -s < .env\nEOF") == [".env"] + assert bash_written_paths("cat > a.md < .env") == ["a.md", ".env"] + + def test_a_command_rule_and_a_file_rule_both_count(engine): decision = _bash(engine, "git push --force origin feature > push.env") assert decision.outcome == Outcome.REQUIRE_APPROVAL From 05e517768892192a9842c928487c3f7f311fcc01 Mon Sep 17 00:00:00 2001 From: Sphia Sadek Date: Thu, 26 Nov 2026 01:13:49 +0000 Subject: [PATCH 15/19] fix(policy): read prefix option values and copies into a directory Two forms the module says it covers were missed. A prefix option that takes a value (`sudo -u USER`, `env -u NAME`) left the value as the command name, so the real command was never read. A copy, move or link with one source and a destination without a trailing slash listed only the destination, though an existing directory receives the source by name inside it. Prefix options with a value now consume it, and every copy lists the in-directory path as well. --- agent/src/bash_writes.py | 18 ++++++++++++++---- agent/tests/test_bash_writes.py | 6 +++++- 2 files changed, 19 insertions(+), 5 deletions(-) diff --git a/agent/src/bash_writes.py b/agent/src/bash_writes.py index 96aa996c5..268ed7e75 100644 --- a/agent/src/bash_writes.py +++ b/agent/src/bash_writes.py @@ -32,6 +32,16 @@ _SEPARATORS = frozenset({";", "&&", "||", "|", "&", "|&", "(", ")", ";;"}) _WRITE_REDIRECTS = frozenset({">", ">>", ">|", "&>", "&>>"}) _PREFIX_COMMANDS = frozenset({"sudo", "env", "command", "nohup", "time", "exec", "builtin"}) +# Options of the prefix commands that take a value (the next token is not the command). +_PREFIX_VALUE_OPTIONS = { + "sudo": frozenset( + {"-u", "--user", "-g", "--group", "-C", "-D", "--chdir", "-h", "--host", "-p"} + | {"--prompt", "-r", "--role", "-t", "--type", "-U", "--other-user", "-T"} + ), + "env": frozenset({"-u", "--unset", "-C", "--chdir", "-S", "--split-string"}), + "time": frozenset({"-f", "--format", "-o", "--output"}), + "exec": frozenset({"-a"}), +} _SHELLS = frozenset({"bash", "sh", "zsh", "dash"}) _COPY_COMMANDS = frozenset({"cp", "mv", "install", "ln"}) # Options of these commands that take a value (the next token is not a path). @@ -152,9 +162,10 @@ def _strip_prefixes(argv: list[str]) -> list[str]: ): argv = argv[1:] while argv and os.path.basename(argv[0]) in _PREFIX_COMMANDS: + takes_value = _PREFIX_VALUE_OPTIONS.get(os.path.basename(argv[0]), frozenset()) argv = argv[1:] while argv and argv[0].startswith("-"): - argv = argv[1:] + argv = argv[2:] if argv[0] in takes_value else argv[1:] while argv and "=" in argv[0] and argv[0].split("=", 1)[0].isidentifier(): argv = argv[1:] return argv @@ -190,10 +201,9 @@ def _copy_targets(name: str, args: list[str]) -> list[str]: return [target_dir, *(os.path.join(target_dir, os.path.basename(s)) for s in operands)] if len(operands) < _COPY_MIN_OPERANDS: return [] + # The destination may be an existing directory, which the copy writes into. *sources, dest = operands - if dest.endswith("/") or len(sources) > 1: - return [dest, *(os.path.join(dest, os.path.basename(s)) for s in sources)] - return [dest] + return [dest, *(os.path.join(dest, os.path.basename(s)) for s in sources)] def _in_place_targets(name: str, args: list[str]) -> list[str]: diff --git a/agent/tests/test_bash_writes.py b/agent/tests/test_bash_writes.py index dc8151c30..0f09c9287 100644 --- a/agent/tests/test_bash_writes.py +++ b/agent/tests/test_bash_writes.py @@ -17,7 +17,7 @@ ("echo x >> .env.local", [".env.local"]), ("cmd &> logs/run.env", ["logs/run.env"]), ("tee -a creds/credentials.json", ["creds/credentials.json"]), - ("cp x .git/hooks/pre-commit", [".git/hooks/pre-commit"]), + ("cp x .git/hooks/pre-commit", [".git/hooks/pre-commit", ".git/hooks/pre-commit/x"]), ("cp a.env b.env backup/", ["backup/", "backup/a.env", "backup/b.env"]), ("mv -t .git/hooks x", [".git/hooks", ".git/hooks/x"]), ("dd if=/dev/zero of=db.env bs=1 count=1", ["db.env"]), @@ -30,6 +30,10 @@ ("echo x > a/../.git/HEAD", [".git/HEAD"]), ("bash -c 'echo x > .env'", [".env"]), ("FOO=1 sudo tee .env", [".env"]), + ("sudo -u app tee .env", [".env"]), + ("env -u HOME tee .env", [".env"]), + ("time -p tee .env", [".env"]), + ("cp -r hooks .git", [".git", ".git/hooks"]), ], ) def test_paths_a_command_writes(command, expected): From 167ee665a8b9b8b9df8529da561b06c216e021ec Mon Sep 17 00:00:00 2001 From: Sphia Sadek Date: Thu, 26 Nov 2026 01:15:45 +0000 Subject: [PATCH 16/19] refactor: drop speculative guards and narrating comments added by this change The platform-block recorder no longer checks that the engine has the method it always has, nor swallows its own errors. An orphaned doc comment on the approval writer, a history note in finalization and a restating comment on the Bash evaluation are removed. --- agent/src/hooks.py | 16 ++++++---------- agent/src/policy.py | 7 +------ cdk/src/constructs/approval-request-service.ts | 1 - cdk/src/handlers/shared/orchestrator.ts | 4 +--- 4 files changed, 8 insertions(+), 20 deletions(-) diff --git a/agent/src/hooks.py b/agent/src/hooks.py index 5efd96864..c58ea1d98 100644 --- a/agent/src/hooks.py +++ b/agent/src/hooks.py @@ -566,21 +566,17 @@ def _remember_platform_block(engine: Any, decision: Any, tool_name: str, tool_in """Record an intentional Cedar deny, so a task that then changes nothing says why. A fail-closed deny is an engine fault, not a control doing its job, so it is - not recorded. Bookkeeping never breaks the hook. + not recorded. """ if getattr(decision, "fail_closed", False): return - rules = ", ".join(getattr(decision, "matching_rule_ids", ()) or ()) + rules = ", ".join(decision.matching_rule_ids) if not rules: - m = re.search(r"(?:Hard|Soft)-deny:\s*(\w[\w, ]*)", str(decision.reason or "")) + m = re.search(r"(?:Hard|Soft)-deny:\s*(\w[\w, ]*)", decision.reason) rules = m.group(1).strip().rstrip(",") if m else "policy" - recorder = getattr(engine, "record_platform_block", None) - if not callable(recorder): - return - try: - recorder(control="platform policy", rule=rules, what=_blocked_action(tool_name, tool_input)) - except Exception as e: - log("WARN", f"record_platform_block failed: {type(e).__name__}") + engine.record_platform_block( + control="platform policy", rule=rules, what=_blocked_action(tool_name, tool_input) + ) async def pre_tool_use_hook( diff --git a/agent/src/policy.py b/agent/src/policy.py index 4f7ce5a26..7fea9146b 100644 --- a/agent/src/policy.py +++ b/agent/src/policy.py @@ -1354,12 +1354,7 @@ def _run(action: str, resource_type: str, resource_id: str, ctx: dict): if write_decision == "deny": return ("deny", write_reasons) - # Bash: evaluate execute_bash with command in context, then every path - # the command writes as a write_file, so the file rules (.env and - # credentials files, .git internals) apply to a redirect, `tee` or `cp` - # as they do to the Write tool. All matches at this tier are kept, so a - # soft-deny merges their annotations; nothing here can turn a deny back - # into an allow. See bash_writes.py for what is and is not recognised. + # Bash: execute_bash, then each path the command writes as a write_file. if tool_name == "Bash": command = tool_input.get("command", "") if command: diff --git a/cdk/src/constructs/approval-request-service.ts b/cdk/src/constructs/approval-request-service.ts index 66470c85e..26e810296 100644 --- a/cdk/src/constructs/approval-request-service.ts +++ b/cdk/src/constructs/approval-request-service.ts @@ -92,7 +92,6 @@ export class ApprovalRequestService extends NestedStack { ], true); } - /** No wildcard task path on production session credentials. */ /** * Deploy after the parent API's regional API Gateway logging account, which this * API reuses instead of creating its own (it is one per Region). diff --git a/cdk/src/handlers/shared/orchestrator.ts b/cdk/src/handlers/shared/orchestrator.ts index 51d6fda11..89fafdb08 100644 --- a/cdk/src/handlers/shared/orchestrator.ts +++ b/cdk/src/handlers/shared/orchestrator.ts @@ -1214,9 +1214,7 @@ async function finalizeTaskOutcome(taskId: string, pollState: PollState, task: T // If still RUNNING / FINALIZING / AWAITING_APPROVAL after the poll window // closes, terminate through an allowed transition: AWAITING_APPROVAL permits - // FAILED, not TIMED_OUT. The previous TIMED_OUT attempt for an approval wait - // was rejected by VALID_TRANSITIONS, left the task active, and still freed - // its seat. + // FAILED, not TIMED_OUT. if ( currentStatus === TaskStatus.RUNNING || currentStatus === TaskStatus.FINALIZING From 19c92ac34dcdccd23c44c2c93ad12534360bacac Mon Sep 17 00:00:00 2001 From: Sphia Sadek Date: Thu, 26 Nov 2026 02:14:59 +0000 Subject: [PATCH 17/19] fix(security): repeat of a committed approval create reports its success The writer commits the PENDING approval row and the task's move to AWAITING_APPROVAL in one transaction. When the worker lost the response to a committed create, a repeat with the same request id was cancelled, because the row exists and the task is no longer RUNNING, so the worker could never learn that the task was waiting on it. A cancelled create now reads the row and the task with ConsistentRead and returns the first create's success when the row is for the same task, user and tool input and the task still awaits that request id. Any other state stays a failure; the transaction conditions are unchanged. --- cdk/src/handlers/request-approval.ts | 23 +++++++++- .../handlers/request-approval-local.test.ts | 17 ++++++++ cdk/test/handlers/request-approval.test.ts | 43 +++++++++++++++++++ 3 files changed, 82 insertions(+), 1 deletion(-) diff --git a/cdk/src/handlers/request-approval.ts b/cdk/src/handlers/request-approval.ts index a5222858e..508edd3c1 100644 --- a/cdk/src/handlers/request-approval.ts +++ b/cdk/src/handlers/request-approval.ts @@ -91,6 +91,24 @@ export function approvalRowTtl(createdAt: string, timeoutS: number): number { : computeTtlEpoch(Number(process.env.TASK_RETENTION_DAYS ?? DEFAULT_RETENTION_DAYS)); } +/** + * A worker that lost the response to a committed create repeats it with the same + * request id. Report the first create's success to that repeat, and only to it: + * the row exists for this task, user and tool input, and the task still waits on it. + */ +async function createCommitted(input: RequestInput, userId: string, error: unknown): Promise { + if ((error as { name?: string }).name !== 'TransactionCanceledException') return false; + const request = await ddb.send(new GetCommand({ + TableName: APPROVALS, Key: { task_id: input.task_id, request_id: input.request_id }, ConsistentRead: true, + })); + const task = await ddb.send(new GetCommand({ TableName: TASKS, Key: { task_id: input.task_id }, ConsistentRead: true })); + return request.Item?.user_id === userId + && request.Item.tool_input_sha256 === input.approval?.tool_input_sha256 + && task.Item?.user_id === userId + && task.Item.status === TaskStatus.AWAITING_APPROVAL + && task.Item.awaiting_approval_request_id === input.request_id; +} + /** * Worker-callable writer: creates pending requests or records a non-human timeout. * Human decisions remain exclusively in approve/deny handlers. Workers have no @@ -133,7 +151,10 @@ export async function recordWorkerRequest(input: RequestInput): Promise { + // A repeat of a create whose response the worker lost. + if (!await createCommitted(input, task.user_id, error)) throw error; + }); } else { // A worker may fail closed after a deadline or polling failure; it cannot // turn either into human DENIED/APPROVED or replace an existing decision. diff --git a/cdk/test/handlers/request-approval-local.test.ts b/cdk/test/handlers/request-approval-local.test.ts index 16c44abd1..e96c7bda0 100644 --- a/cdk/test/handlers/request-approval-local.test.ts +++ b/cdk/test/handlers/request-approval-local.test.ts @@ -157,6 +157,23 @@ local('Trusted approval writer against DynamoDB Local', () => { expect(result.cancellation_reasons).toEqual([{ Code: 'None' }, { Code: 'ConditionalCheckFailed' }]); expect(await read(approvals)).toEqual(before); }); + test('repeating a committed create succeeds and changes nothing', async () => { + const first = row(); + const again = () => recordWorkerRequest({ operation: 'create', task_id: taskId, request_id: gate, approval: first }); + expect(await again()).toEqual({ ok: true }); + const [request, task] = [await read(approvals), await read(tasks)]; + expect(await again()).toEqual({ ok: true }); + expect(await read(approvals)).toEqual(request); + expect(await read(tasks)).toEqual(task); + }); + test.each([ + ['resumed', 'RUNNING'], ['cancelled', 'CANCELLED'], + ])('repeating a create after the task %s still fails', async (_name, status) => { + await create(); + await change(tasks, 'status', status); + expect(await create()).toMatchObject({ ok: false, code: 'TransactionCanceledException' }); + expect(await read(tasks)).toMatchObject({ status }); + }); test('a second request cannot replace the first while the task waits', async () => { await create(); const result = await recordWorkerRequest({ diff --git a/cdk/test/handlers/request-approval.test.ts b/cdk/test/handlers/request-approval.test.ts index d876c59d7..a083d5429 100644 --- a/cdk/test/handlers/request-approval.test.ts +++ b/cdk/test/handlers/request-approval.test.ts @@ -106,6 +106,49 @@ test('preserves cancellation reasons without returning request contents', async }); }); +describe('repeat create of the same request (the worker lost the first response)', () => { + const cancelled = { name: 'TransactionCanceledException', CancellationReasons: [{ Code: 'ConditionalCheckFailed' }, { Code: 'ConditionalCheckFailed' }] }; + let stored: Record | undefined; + beforeEach(() => { + task = { ...task, status: 'AWAITING_APPROVAL', awaiting_approval_request_id: 'gate' }; + stored = { ...approval }; + send.mockImplementation(async command => { + if (command.constructor.name === 'TransactWriteCommand') throw cancelled; + return { Item: command.input.Key.request_id === undefined ? task : stored }; + }); + }); + + test('returns the success the committed create returned, from consistent reads', async () => { + expect(await recordWorkerRequest(input)).toEqual({ ok: true }); + const reads = send.mock.calls.slice(2).map(([command]) => command.input); + expect(reads).toEqual(expect.arrayContaining([ + expect.objectContaining({ Key: { task_id: 'task', request_id: 'gate' }, ConsistentRead: true }), + expect.objectContaining({ Key: { task_id: 'task' }, ConsistentRead: true }), + ])); + }); + + test.each([ + ['the task awaits another request', () => { task.awaiting_approval_request_id = 'other'; }], + ['the task no longer awaits approval', () => { task.status = 'RUNNING'; }], + ['the task was cancelled', () => { task.status = 'CANCELLED'; }], + ['no request row exists', () => { stored = undefined; }], + ['the row belongs to another user', () => { stored = { ...approval, user_id: 'other' }; }], + ['the row is for another tool input', () => { stored = { ...approval, tool_input_sha256: 'b'.repeat(64) }; }], + ])('still fails when %s', async (_name, arrange) => { + arrange(); + expect(await recordWorkerRequest(input)).toEqual({ + ok: false, + code: 'TransactionCanceledException', + cancellation_reasons: [{ Code: 'ConditionalCheckFailed' }, { Code: 'ConditionalCheckFailed' }], + }); + }); + + test('a different request id for the waiting task still fails', async () => { + const other = { ...input, request_id: 'other', approval: { ...approval, request_id: 'other' } }; + expect(await recordWorkerRequest(other)).toMatchObject({ ok: false, code: 'TransactionCanceledException' }); + }); +}); + test('requires IAM caller identity and refuses body/path task substitution', async () => { const event = { body: JSON.stringify(input), From 143850e47713178ccda538197ba71c172a0b734c Mon Sep 17 00:00:00 2001 From: Sphia Sadek Date: Thu, 26 Nov 2026 02:15:48 +0000 Subject: [PATCH 18/19] fix(agent): repeat an unanswered approval create and never leave the task waiting A create whose response was lost (timeout, connection error, 5xx) denied the tool call and returned while the writer might have committed the request, so the task stayed AWAITING_APPROVAL with a PENDING row and the agent carried on. The worker now repeats such a create up to two more times with the same request id, which the writer answers with the first create's success. A rejected or cancelled create is not repeated. A create that stays unconfirmed gets the timeout and resume that follow an unanswered gate, both conditioned on the task awaiting that request, and the call is denied as before. --- agent/src/hooks.py | 24 +++++++ agent/src/task_state.py | 47 +++++++++---- agent/tests/test_hooks.py | 144 +++++++++++++++++++++++++++++++++++++- 3 files changed, 201 insertions(+), 14 deletions(-) diff --git a/agent/src/hooks.py b/agent/src/hooks.py index c58ea1d98..2e63a72eb 100644 --- a/agent/src/hooks.py +++ b/agent/src/hooks.py @@ -737,6 +737,29 @@ async def pre_tool_use_hook( ) +async def _close_unconfirmed_request(ts: Any, task_id: str, request_id: str) -> None: + """Leave no task waiting on a request the writer may have committed unseen. + + The timeout and resume that follow an unanswered gate: both change nothing + unless the task waits on ``request_id``, so a create that did not commit is + left as it was. Best effort; the call is denied either way. + """ + try: + await asyncio.to_thread( + ts.best_effort_update_approval_status, + task_id, + request_id, + "TIMED_OUT", + reason="approval request was not confirmed", + ) + except Exception as exc: + log("WARN", f"approval TIMED_OUT write raised: {type(exc).__name__}: {exc}") + try: + await asyncio.to_thread(ts.transact_resume_from_approval, task_id, request_id) + except Exception as exc: + log("WARN", f"approval resume raised: {type(exc).__name__}: {exc}") + + async def _handle_require_approval( # noqa: C901 -- 24, down from 35 when the ceiling of 15 was set; must not grow *, decision: Any, @@ -904,6 +927,7 @@ async def _handle_require_approval( # noqa: C901 -- 24, down from 35 when the c request_id=request_id, error=f"{type(exc).__name__}: {exc}", ) + await _close_unconfirmed_request(ts, task_id, request_id) return _deny_response("approval system unavailable") # Step 8 — ``approval_requested`` milestone so the user's stream diff --git a/agent/src/task_state.py b/agent/src/task_state.py index bfa1ba60a..d235708ae 100644 --- a/agent/src/task_state.py +++ b/agent/src/task_state.py @@ -7,8 +7,11 @@ import os import time +from http import HTTPStatus from typing import NotRequired, TypedDict +import requests + from shell import log, log_error_cw, redact_secrets @@ -656,6 +659,20 @@ def _ddb_attr_to_py(attr): return attr +# Waits before the second and third attempt of a create whose answer was lost. +_CREATE_RETRY_DELAYS_S = (0.5, 1.0) + + +def _answer_lost(exc: BaseException) -> bool: + """The writer may have committed: no answer arrived, or the service failed.""" + if isinstance(exc, (requests.Timeout, requests.ConnectionError)): + return True + response = getattr(exc, "response", None) + metadata = response.get("ResponseMetadata") if isinstance(response, dict) else None + status = metadata.get("HTTPStatusCode") if isinstance(metadata, dict) else None + return isinstance(status, int) and status >= HTTPStatus.INTERNAL_SERVER_ERROR + + def transact_write_approval_request( task_id: str, request_id: str, @@ -687,18 +704,24 @@ def transact_write_approval_request( import approval_requests if approval_requests.configured(): - try: - approval_requests.record_request( - "create", task_id, request_id, approval=dict(approval_row) - ) - return - except Exception as exc: - if _extract_error_code(exc) == "TransactionCanceledException": - reasons = _extract_cancellation_reasons(exc) - raise ApprovalWriteError( - f"approval write cancelled: reasons={reasons}", cancellation_reasons=reasons - ) from exc - raise + # The writer reports a repeat of a committed create as its success, so a + # create whose answer was lost is repeated with the same request id. + for retry_delay_s in (*_CREATE_RETRY_DELAYS_S, None): + try: + approval_requests.record_request( + "create", task_id, request_id, approval=dict(approval_row) + ) + return + except Exception as exc: + if _extract_error_code(exc) == "TransactionCanceledException": + reasons = _extract_cancellation_reasons(exc) + raise ApprovalWriteError( + f"approval write cancelled: reasons={reasons}", cancellation_reasons=reasons + ) from exc + if retry_delay_s is None or not _answer_lost(exc): + raise + log("WARN", f"approval request {request_id} unconfirmed, repeating: {exc}") + time.sleep(retry_delay_s) # Compatibility with unscoped legacy/local deployments. configured() rejects # a missing service URL for cloud workers that use the session role. task_table, approvals_table = _require_tables() diff --git a/agent/tests/test_hooks.py b/agent/tests/test_hooks.py index 8e9cc3dba..4ea796925 100644 --- a/agent/tests/test_hooks.py +++ b/agent/tests/test_hooks.py @@ -12,6 +12,8 @@ # These tests must then fail, not drop out of the run. import cedarpy # noqa: F401 import pytest +import requests +from botocore.exceptions import ClientError import hooks from hooks import ( @@ -3173,7 +3175,8 @@ def test_any_other_write_error_denies_and_is_not_waited_for( self, fake_task_state, progress, engine_with_soft_gate, monkeypatch ): # Throttling, the network: neither of the two errors the hook knows by - # name. No request was written, so there is no answer to wait for. + # name. The request may have been written without the hook hearing so: + # it is timed out and the task restored, and no answer is waited for. _fast_poll(monkeypatch) _prime_approval( fake_task_state, {"status": "APPROVED", "scope": "this_call", "decided_at": "t1"} @@ -3200,7 +3203,144 @@ def test_any_other_write_error_denies_and_is_not_waited_for( ) assert "write_approval_write_failed" in progress.milestones() assert fake_task_state.get_calls == [] - assert fake_task_state.resume_calls == [] + request_id = fake_task_state.write_calls[0][1] + assert [call[:3] for call in fake_task_state.update_calls] == [ + ("01KTASK", request_id, "TIMED_OUT") + ] + assert fake_task_state.resume_calls == [("01KTASK", request_id)] + + @staticmethod + def _writer(monkeypatch, fake_task_state, outcomes): + """Route the create through the real client-side write, to a scripted writer.""" + import approval_requests + import task_state + + calls = [] + + def record_request(operation, task_id, request_id, **_kwargs): + # The last scripted outcome repeats. + calls.append((operation, task_id, request_id)) + outcome = outcomes[min(len(calls), len(outcomes)) - 1] + if outcome is not None: + raise outcome + + monkeypatch.setattr(approval_requests, "configured", lambda: True) + monkeypatch.setattr(approval_requests, "record_request", record_request) + monkeypatch.setattr(task_state.time, "sleep", lambda _seconds: None) + + def write(task_id, request_id, approval_row, *, client=None): + fake_task_state.write_calls.append((task_id, request_id, approval_row)) + task_state.transact_write_approval_request(task_id, request_id, approval_row) + + fake_task_state.transact_write_approval_request = write + return calls + + @pytest.mark.parametrize( + "lost", + [ + requests.ReadTimeout("read timed out"), + requests.ConnectionError("connection reset by peer"), + ClientError( + { + "Error": {"Code": "ApprovalServiceUnavailable"}, + "ResponseMetadata": {"HTTPStatusCode": 504}, + }, + "RecordApprovalRequest", + ), + ], + ids=["timeout", "reset", "gateway-504"], + ) + def test_a_lost_create_response_is_retried_with_the_same_request( + self, fake_task_state, progress, engine_with_soft_gate, monkeypatch, lost + ): + _fast_poll(monkeypatch) + _prime_approval( + fake_task_state, {"status": "APPROVED", "scope": "this_call", "decided_at": "t1"} + ) + calls = self._writer(monkeypatch, fake_task_state, [lost, None]) + + result = _run( + pre_tool_use_hook( + _hook_input(), + "tu-1", + {}, + engine=engine_with_soft_gate, + task_id="01KTASK", + user_id="u-1", + progress=progress, + task_state_module=fake_task_state, + ) + ) + + assert result["hookSpecificOutput"]["permissionDecision"] == "allow" + request_id = fake_task_state.write_calls[0][1] + assert calls == [("create", "01KTASK", request_id)] * 2 + assert "write_approval_requested" in progress.milestones() + assert "write_approval_write_failed" not in progress.milestones() + assert {call[1] for call in fake_task_state.get_calls} == {request_id} + assert fake_task_state.update_calls == [] + assert fake_task_state.resume_calls == [("01KTASK", request_id)] + + def test_a_create_never_confirmed_is_timed_out_and_the_task_restored( + self, fake_task_state, progress, engine_with_soft_gate, monkeypatch + ): + _fast_poll(monkeypatch) + calls = self._writer(monkeypatch, fake_task_state, [requests.ConnectionError("reset")]) + + result = _run( + pre_tool_use_hook( + _hook_input(), + "tu-1", + {}, + engine=engine_with_soft_gate, + task_id="01KTASK", + user_id="u-1", + progress=progress, + task_state_module=fake_task_state, + ) + ) + + assert result["hookSpecificOutput"]["permissionDecision"] == "deny" + assert ( + result["hookSpecificOutput"]["permissionDecisionReason"] + == "approval system unavailable" + ) + request_id = fake_task_state.write_calls[0][1] + assert calls == [("create", "01KTASK", request_id)] * 3 + assert "write_approval_requested" not in progress.milestones() + assert fake_task_state.get_calls == [] + assert [call[:3] for call in fake_task_state.update_calls] == [ + ("01KTASK", request_id, "TIMED_OUT") + ] + assert fake_task_state.resume_calls == [("01KTASK", request_id)] + + def test_a_rejected_create_is_not_retried( + self, fake_task_state, progress, engine_with_soft_gate, monkeypatch + ): + rejected = ClientError( + { + "Error": {"Code": "APPROVAL_REQUEST_INVALID"}, + "ResponseMetadata": {"HTTPStatusCode": 400}, + }, + "RecordApprovalRequest", + ) + calls = self._writer(monkeypatch, fake_task_state, [rejected]) + + result = _run( + pre_tool_use_hook( + _hook_input(), + "tu-1", + {}, + engine=engine_with_soft_gate, + task_id="01KTASK", + user_id="u-1", + progress=progress, + task_state_module=fake_task_state, + ) + ) + + assert result["hookSpecificOutput"]["permissionDecision"] == "deny" + assert len(calls) == 1 def test_without_a_task_id_the_call_is_denied_and_nothing_is_written( self, fake_task_state, progress, engine_with_soft_gate, monkeypatch From 6a0d6ea5d4ee8c04420590f8093c943fac6ac359 Mon Sep 17 00:00:00 2001 From: Sphia Sadek Date: Thu, 26 Nov 2026 02:59:29 +0000 Subject: [PATCH 19/19] fix(agent): a resumed run keeps the scopes a person approved during the task A model-error retry builds a new policy engine seeded only from the task's initial approvals, so a scope granted at runtime (Approve for this task, or a rule scope approved from the CLI) was gone: the person was asked again, and the repeat prompts counted toward the gate cap. The allowlist records the scopes it installs, the run's result carries them as approval_scopes, and the resumed run is seeded with them, as it already is with the gate count. --- agent/src/model_retry.py | 2 ++ agent/src/models.py | 3 +++ agent/src/policy.py | 11 +++++++++++ agent/src/runner.py | 2 ++ agent/tests/test_model_retry.py | 14 ++++++++++++++ agent/tests/test_policy_three_outcome.py | 7 +++++++ 6 files changed, 39 insertions(+) diff --git a/agent/src/model_retry.py b/agent/src/model_retry.py index 6633b4bbc..2499b7e5f 100644 --- a/agent/src/model_retry.py +++ b/agent/src/model_retry.py @@ -165,6 +165,8 @@ async def run_agent_resilient( "max_turns": left_turns, "max_budget_usd": left_budget, "initial_approval_gate_count": result.approval_gate_count, + # Scopes granted during the run would be lost with the old engine. + "initial_approvals": result.approval_scopes or list(config.initial_approvals), } ) nxt = await run( diff --git a/agent/src/models.py b/agent/src/models.py index 74db2bb74..97e3f53a2 100644 --- a/agent/src/models.py +++ b/agent/src/models.py @@ -386,6 +386,9 @@ class AgentResult(BaseModel): platform_blocks: list[dict] = Field(default_factory=list) # Approval gates opened so far this task, which seed a resumed run's engine. approval_gate_count: int = 0 + # Approval scopes in force at the end of the run (pre-approvals plus scopes a + # person granted, such as "Approve for this task"), which seed a resumed run. + approval_scopes: list[str] = Field(default_factory=list) class TaskResult(BaseModel): diff --git a/agent/src/policy.py b/agent/src/policy.py index 7fea9146b..fbac019ad 100644 --- a/agent/src/policy.py +++ b/agent/src/policy.py @@ -300,6 +300,7 @@ def __init__(self, initial_scopes: list[str] | None = None) -> None: self._rule_ids: set[str] = set() self._bash_patterns: list[str] = [] self._write_path_patterns: list[str] = [] + self._scopes: list[str] = [] for scope in initial_scopes or []: self.add(scope) @@ -318,6 +319,16 @@ def add(self, scope: str) -> None: (§5.5 finding #15). """ normalized = scope.strip() + self._install(normalized, scope) + if normalized not in self._scopes: + self._scopes.append(normalized) + + @property + def scopes(self) -> tuple[str, ...]: + """Every scope installed so far (initial and granted at runtime), in order.""" + return tuple(self._scopes) + + def _install(self, normalized: str, scope: str) -> None: if normalized == "all_session": self._all_session = True return diff --git a/agent/src/runner.py b/agent/src/runner.py index 5428b94b2..3577e82e7 100644 --- a/agent/src/runner.py +++ b/agent/src/runner.py @@ -901,4 +901,6 @@ def _on_stderr(line: str) -> None: result.denied_approvals = list(getattr(_policy_engine, "denied_approvals", None) or []) result.platform_blocks = list(getattr(_policy_engine, "platform_blocks", None) or []) result.approval_gate_count = getattr(_policy_engine, "approval_gate_count", 0) + allowlist = getattr(_policy_engine, "allowlist", None) + result.approval_scopes = list(allowlist.scopes) if allowlist is not None else [] return result diff --git a/agent/tests/test_model_retry.py b/agent/tests/test_model_retry.py index 10ab997ce..8cbca742a 100644 --- a/agent/tests/test_model_retry.py +++ b/agent/tests/test_model_retry.py @@ -154,3 +154,17 @@ async def recording(prompt, system_prompt, config, **kwargs): _go(recording, config=_config(initial_approval_gate_count=2)) assert seeded == [2, 7] + + +def test_a_resumed_run_keeps_the_scopes_approved_during_the_task(): + first = _res(status="error", error=BEDROCK_5XX) + first.approval_scopes = ["tool_type:Read", "rule:write_env_files"] + run = _Run([first, _res()]) + seeded = [] + + async def recording(prompt, system_prompt, config, **kwargs): + seeded.append(list(config.initial_approvals)) + return await run(prompt, system_prompt, config, **kwargs) + + _go(recording, config=_config(initial_approvals=["tool_type:Read"])) + assert seeded == [["tool_type:Read"], ["tool_type:Read", "rule:write_env_files"]] diff --git a/agent/tests/test_policy_three_outcome.py b/agent/tests/test_policy_three_outcome.py index 0b5d80cba..05365d3cb 100644 --- a/agent/tests/test_policy_three_outcome.py +++ b/agent/tests/test_policy_three_outcome.py @@ -203,6 +203,13 @@ def test_hard_deny_is_not_fail_closed(self): class TestApprovalAllowlist: + def test_scopes_lists_initial_and_granted_scopes_once_each(self): + allowlist = ApprovalAllowlist(["tool_type:Read"]) + allowlist.add(" rule:write_env_files ") + allowlist.add("tool_type:Read") + assert allowlist.scopes == ("tool_type:Read", "rule:write_env_files") + assert ApprovalAllowlist(list(allowlist.scopes)).rule_ids == allowlist.rule_ids + def test_empty_allowlist_matches_nothing(self): al = ApprovalAllowlist() assert al.matches("Read", {"file_path": "a.py"}) is False