From 9659787e175e0a3e87e6dfeb82cdbaf8b4737cb9 Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Sat, 7 Nov 2026 02:00:04 +0000 Subject: [PATCH 01/13] Initial plan From dede5004ae6559dbd953de11dd998ec47835f110 Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Sat, 7 Nov 2026 02:09:32 +0000 Subject: [PATCH 02/13] fix: align Claude enclave tool approvals with output contract --- containers/enclave/agent-entrypoint.py | 35 +++++++-- .../agent-provider-environment.js | 5 +- .../agent-executor/session-diagnostics.js | 14 ++++ docs/enclaves-architecture.md | 11 +++ scripts/ci/collect-enclave-smoke-debug.cjs | 21 ++++++ .../ci/collect-enclave-smoke-debug.test.ts | 36 +++++++++ .../agent-entrypoint-diagnostics.test.ts | 75 ++++++++++++++++++- .../agent-provider-environment.test.ts | 8 +- src/enclave/claude-unattended.test.ts | 68 +++++++++++------ 9 files changed, 241 insertions(+), 32 deletions(-) diff --git a/containers/enclave/agent-entrypoint.py b/containers/enclave/agent-entrypoint.py index c9b290736..4c7e8ba22 100644 --- a/containers/enclave/agent-entrypoint.py +++ b/containers/enclave/agent-entrypoint.py @@ -909,6 +909,16 @@ def classify_claude_startup_failure(stderr: bytes) -> str: return "unknown" +def claude_tool_class(name, tool_input=None) -> str: + if not isinstance(name, str): + return "unknown" + if name in {"Write", "Edit"}: + if isinstance(tool_input, dict) and tool_input.get("file_path") == str(OUT_PATH): + return "output-write" + return "file-write" + return {"Bash": "shell", "Read": "file-read", "Glob": "search", "Grep": "search"}.get(name, "unknown") + + def communicate_claude(process: subprocess.Popen, timeout: float) -> tuple[bytes, bytes]: """Drain streams incrementally, projecting only fixed lifecycle observations.""" started = time.monotonic() @@ -917,10 +927,11 @@ def communicate_claude(process: subprocess.Popen, timeout: float) -> tuple[bytes pending = bytearray() discard_line = False seen = set() + tool_classes = {} truncated = False def milestone(stage: str, **metadata) -> None: - key = (stage, metadata.get("toolError")) if stage == "claude-tool-completed" else stage + key = (stage, metadata.get("toolClass"), metadata.get("toolError")) if key not in seen: seen.add(key) append_progress(stage, runtimeMs=int((time.monotonic() - started) * 1000), **metadata) @@ -945,7 +956,8 @@ def project(line: bytes) -> None: } else "unknown", shellAvailable=isinstance(tools, list) and "Bash" in tools) elif event.get("subtype") == "permission_denied": - milestone("claude-permission-denied") + milestone("claude-permission-denied", + toolClass=claude_tool_class(event.get("tool_name"), event.get("tool_input"))) elif event.get("subtype") == "api_retry": status = event.get("error_status") milestone("claude-api-retry", @@ -966,12 +978,23 @@ def project(line: bytes) -> None: if not isinstance(block, dict): continue if kind == "assistant" and block.get("type") == "tool_use": - milestone("claude-tool-requested") + tool_class = claude_tool_class(block.get("name"), block.get("input")) + tool_id = block.get("id") + if isinstance(tool_id, str) and len(tool_id) <= 128: + if len(tool_classes) >= 64: + tool_classes.pop(next(iter(tool_classes))) + tool_classes[tool_id] = tool_class + milestone("claude-tool-requested", toolClass=tool_class) elif kind == "user" and block.get("type") == "tool_result": - milestone("claude-tool-completed", toolError=block.get("is_error") is True) + tool_id = block.get("tool_use_id") + tool_class = tool_classes.pop(tool_id, "unknown") if isinstance(tool_id, str) else "unknown" + milestone("claude-tool-completed", toolClass=tool_class, + toolError=block.get("is_error") is True) elif kind == "result": if isinstance(event.get("permission_denials"), list) and event["permission_denials"]: - milestone("claude-permission-denied") + for denial in event["permission_denials"]: + milestone("claude-permission-denied", toolClass=claude_tool_class( + denial.get("tool_name"), denial.get("tool_input")) if isinstance(denial, dict) else "unknown") milestone("claude-result", resultError=event.get("is_error") is True) try: @@ -1019,7 +1042,7 @@ def project(line: bytes) -> None: raise subprocess.TimeoutExpired(process.args, timeout, bytes(captured["stdout"]), bytes(captured["stderr"])) finally: - if process.returncode not in {None, 0} and "claude-initialized" not in seen: + if process.returncode not in {None, 0} and not any(key[0] == "claude-initialized" for key in seen): milestone("claude-startup-failure", classification=classify_claude_startup_failure(bytes(captured["stderr"]))) try: diff --git a/containers/enclave/agent-executor/agent-provider-environment.js b/containers/enclave/agent-executor/agent-provider-environment.js index 3f6eccee8..a455ae410 100644 --- a/containers/enclave/agent-executor/agent-provider-environment.js +++ b/containers/enclave/agent-executor/agent-provider-environment.js @@ -31,8 +31,9 @@ function agentProviderEnvironment(engine, endpoint, model, directory, budgetToke ANTHROPIC_AUTH_TOKEN: token, CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC: '1', DISABLE_AUTOUPDATER: '1', - AWF_ENCLAVE_AGENT_CLAUDE_PERMISSION_PROMPTS: 'host', - AWF_ENCLAVE_AGENT_CLAUDE_ALLOWED_TOOLS: 'Read,Glob,Grep', + // Fixed AWF policy: shell diagnostics and /awf/out writes remain inside the outer sandbox. + AWF_ENCLAVE_AGENT_CLAUDE_PERMISSION_PROMPTS: 'none', + AWF_ENCLAVE_AGENT_CLAUDE_ALLOWED_TOOLS: 'Bash,Read,Write,Edit,Glob,Grep', }; default: throw new Error('Unsupported enclave agent engine'); diff --git a/containers/enclave/agent-executor/session-diagnostics.js b/containers/enclave/agent-executor/session-diagnostics.js index 284ed3ecf..1fb1ced1f 100644 --- a/containers/enclave/agent-executor/session-diagnostics.js +++ b/containers/enclave/agent-executor/session-diagnostics.js @@ -85,6 +85,9 @@ function projectEvent(value) { result.permissionMode = value.permissionMode; } if (allowed(value.outputState, ['present', 'empty', 'unavailable'])) result.outputState = value.outputState; + if (allowed(value.toolClass, ['shell', 'file-read', 'file-write', 'output-write', 'search', 'unknown'])) { + result.toolClass = value.toolClass; + } if (value.stage === 'claude-startup-failure' && allowed(value.classification, [ 'unknown-option', 'invalid-option-value', 'missing-option-value', 'invalid-settings', 'invalid-mcp-config', 'unknown', @@ -262,6 +265,17 @@ function projectEnclaveSessionDiagnostics(bytes) { if (event.event === 'progress' && event.stage === 'claude-startup-failure') { result.claudeStartupFailure = event; } + if (event.event === 'progress' && event.stage === 'claude-result') result.claudeResult = event; + if (event.event === 'progress' && event.stage === 'claude-permission-denied') { + result.claudePermissionDenials ??= []; + result.claudePermissionDenials = result.claudePermissionDenials.filter(item => item.toolClass !== event.toolClass); + result.claudePermissionDenials.push(event); + } + if (event.event === 'progress' && event.stage === 'claude-tool-completed' && event.toolError === true) { + result.claudeToolErrors ??= []; + result.claudeToolErrors = result.claudeToolErrors.filter(item => item.toolClass !== event.toolClass); + result.claudeToolErrors.push(event); + } if (event.event === 'failure' || (event.event === 'operation-error' && event.fatal !== false)) { result.failure ??= event; } diff --git a/docs/enclaves-architecture.md b/docs/enclaves-architecture.md index ae288559b..87c0f5a9f 100644 --- a/docs/enclaves-architecture.md +++ b/docs/enclaves-architecture.md @@ -293,6 +293,17 @@ enclave's filesystem, capability, or network restrictions. Its streaming output is projected onto bounded, deduplicated `claude-*` lifecycle milestones (initialization, provider response/retry, tool request/completion, permission denial, result, and stream/output presence). +Tool requests, completions, and refusals retain only the finite `toolClass`: +`shell`, `file-read`, `file-write`, `output-write`, `search`, or `unknown`. +`output-write` identifies a native Write/Edit request targeting `/awf/out`; +arbitrary shell commands are not inspected to infer their destination. +A tool error does not imply a native permission refusal or a filesystem errno. +Output-path syscall failures retain their separate operation/errno diagnostics. +Denial/tool-error classes and the final result/stream summary survive the projected event +limit; stream parsing continues after bounded raw capture fills, including +resuming after an oversized line. The pinned unattended fixture uses the +production child policy unchanged for success and substitutes only the provider +edge, never approvals; negative cases cover refusal and output-write failure. Prompts, headers, tool inputs/results, and model text are never retained in Claude diagnostics, including public/raw-debug runs. Nonzero exits before initialization additionally project one finite startup classification: diff --git a/scripts/ci/collect-enclave-smoke-debug.cjs b/scripts/ci/collect-enclave-smoke-debug.cjs index 418d9ce46..843633992 100644 --- a/scripts/ci/collect-enclave-smoke-debug.cjs +++ b/scripts/ci/collect-enclave-smoke-debug.cjs @@ -151,6 +151,7 @@ function projectSessionEvent(value) { 'stderrObserved', 'captureTruncated'].map(key => [key, boolean])), permissionMode: member(['default', 'auto', 'acceptEdits', 'bypassPermissions', 'unknown']), outputState: member(['present', 'empty', 'unavailable']), + toolClass: member(['shell', 'file-read', 'file-write', 'output-write', 'search', 'unknown']), httpStatus: member([null, 400, 401, 403, 404, 408, 429, 500, 502, 503, 504, 529]), })); if (value.stage === 'claude-startup-failure') { @@ -208,6 +209,26 @@ function projectSession(value) { && value.claudeStartupFailure.stage === 'claude-startup-failure', 'session-schema'); result.claudeStartupFailure = projectSessionEvent(value.claudeStartupFailure); } + if (value.claudeResult !== undefined) { + check(object(value.claudeResult) && value.claudeResult.event === 'progress' + && value.claudeResult.stage === 'claude-result', 'session-schema'); + result.claudeResult = projectSessionEvent(value.claudeResult); + } + if (value.claudePermissionDenials !== undefined) { + check(Array.isArray(value.claudePermissionDenials) && value.claudePermissionDenials.length <= 7, 'session-schema'); + result.claudePermissionDenials = value.claudePermissionDenials.map(event => { + check(object(event) && event.event === 'progress' && event.stage === 'claude-permission-denied', 'session-schema'); + return projectSessionEvent(event); + }); + } + if (value.claudeToolErrors !== undefined) { + check(Array.isArray(value.claudeToolErrors) && value.claudeToolErrors.length <= 7, 'session-schema'); + result.claudeToolErrors = value.claudeToolErrors.map(event => { + check(object(event) && event.event === 'progress' && event.stage === 'claude-tool-completed' + && event.toolError === true, 'session-schema'); + return projectSessionEvent(event); + }); + } if (value.operationErrors !== undefined) { check(Array.isArray(value.operationErrors) && value.operationErrors.length <= 16, 'session-bound'); result.operationErrors = value.operationErrors.map(projectSessionEvent).filter(Boolean); diff --git a/scripts/ci/collect-enclave-smoke-debug.test.ts b/scripts/ci/collect-enclave-smoke-debug.test.ts index 0bc6ac9d4..c1456b1e5 100644 --- a/scripts/ci/collect-enclave-smoke-debug.test.ts +++ b/scripts/ci/collect-enclave-smoke-debug.test.ts @@ -295,6 +295,42 @@ describe('host-only public enclave debug collector', () => { } }); + it('retains finite Claude denial classes and the final result after event-cap saturation', () => { + const denials = ['shell', 'file-read', 'file-write', 'output-write', 'search', 'unknown'].map(toolClass => ({ + event: 'progress', stage: 'claude-permission-denied', toolClass, + input: 'PRIVATE_COMMAND', tool_name: 'PRIVATE_TOOL', prompt: 'PRIVATE_PROMPT', + })); + const result = { event: 'progress', stage: 'claude-result', resultError: false }; + const writeError = { + event: 'progress', stage: 'claude-tool-completed', toolClass: 'output-write', toolError: true, + }; + const session = projectEnclaveSessionDiagnostics(Buffer.from([ + ...Array.from({ length: 32 }, () => ({ event: 'progress', stage: 'claude-response' })), + ...denials, ...denials, writeError, writeError, result, + ].map(event => JSON.stringify(event)).join('\n'))); + const identity = { runId, invocationId, entryId: 'script', runtime: 'cloud-hypervisor' }; + const projected = JSON.parse(projectDiagnostics({ ...commonEnvelope(), session }, identity).toString()); + expect(projected.session.claudePermissionDenials).toEqual(denials.map(({ toolClass }) => ({ + event: 'progress', stage: 'claude-permission-denied', toolClass, + }))); + expect(projected.session.claudeResult).toEqual(result); + expect(projected.session.claudeToolErrors).toEqual([writeError]); + expect(projected.session.events).toHaveLength(32); + expect(JSON.stringify(projected)).not.toContain('PRIVATE_'); + for (const invalid of [ + { claudeResult: { event: 'success' } }, + { claudePermissionDenials: [{ event: 'success' }] }, + { claudePermissionDenials: Array(8).fill(denials[0]) }, + { claudePermissionDenials: [{ ...denials[0], toolClass: 'PRIVATE_CLASS' }] }, + { claudeToolErrors: [{ ...writeError, toolError: false }] }, + { claudeToolErrors: Array(8).fill(writeError) }, + ]) { + expect(() => projectDiagnostics({ + ...commonEnvelope(), session: { status: 'captured', ...invalid }, + }, identity)).toThrow(/session-schema/); + } + }); + it('retains the final Claude startup failure after event-cap saturation', () => { const startupFailure = { event: 'progress', stage: 'claude-startup-failure', classification: 'invalid-option-value', diff --git a/src/enclave/agent-entrypoint-diagnostics.test.ts b/src/enclave/agent-entrypoint-diagnostics.test.ts index 4624d2e93..4add7d515 100644 --- a/src/enclave/agent-entrypoint-diagnostics.test.ts +++ b/src/enclave/agent-entrypoint-diagnostics.test.ts @@ -258,12 +258,18 @@ if scenario != "missing-copilot": {"type": "result", "is_error": True, "permission_denials": [{"tool_name": "Bash", "tool_input": "PRIVATE_COMMAND"}]}, ] + if "CLAUDE_EVENTS" in os.environ: + stream_events = json.loads(os.environ["CLAUDE_EVENTS"].replace( + '"/awf/out"', json.dumps(str(module.OUT_PATH)))) copilot.write_text( "#!/usr/bin/python3\nimport json, sys, time\n" + ("sys.stdout.write('x' * (512 * 1024) + '\\n'); sys.stdout.flush()\n" if scenario == "claude-stream-flood" else "") + + ("for _ in range(4096): print(json.dumps({'type': 'assistant', 'message': {'content': 'PRIVATE_MODEL' * 40}}))\n" + if scenario == "claude-stream-budget" else "") + "for event in " + repr(stream_events * 2) + ": print(json.dumps(event), flush=True)\n" + ("time.sleep(30)\n" if scenario == "claude-stream-timeout" else + "" if scenario == "claude-stream-no-output" else "open(" + repr(str(module.OUT_PATH)) + ", 'w').write('true')\n"), encoding="utf-8", ) @@ -464,7 +470,7 @@ describe('enclave agent protected entrypoint diagnostics', () => { expect(result.arguments.split('\n')).toContain('--dangerously-bypass-approvals-and-sandbox'); }); - it('requires explicit opt-in for unattended Claude shell and file writes', () => { + it('accepts the trusted unattended Claude shell and file policy', () => { const result = runHarness('model-limits', { ...providerEnv('claude'), AWF_ENCLAVE_AGENT_CLAUDE_PERMISSION_PROMPTS: 'none', @@ -641,6 +647,73 @@ describe('enclave agent protected entrypoint diagnostics', () => { expect(result.transcript).not.toContain('PRIVATE_'); }); + it.each([ + ['Bash', {}, 'shell'], + ['Read', {}, 'file-read'], + ['Write', {}, 'file-write'], + ['Edit', {}, 'file-write'], + ['Glob', {}, 'search'], + ['Grep', {}, 'search'], + ['PRIVATE_TOOL', { command: 'PRIVATE_COMMAND' }, 'unknown'], + [['PRIVATE_TOOL'], {}, 'unknown'], + ])('classifies denied tools without retaining payloads: %j', (tool, input, toolClass) => { + const result = runHarness('claude-stream-no-output', { + ...providerEnv('claude'), + CLAUDE_EVENTS: JSON.stringify([ + { type: 'system', subtype: 'init', tools: ['Bash'] }, + { type: 'system', subtype: 'permission_denied', tool_name: tool, tool_input: input }, + { type: 'result', is_error: false, permission_denials: [ + { tool_name: tool, tool_input: input }, null, + ] }, + ]), + }); + expect(result.exitCode).toBe(33); + expect(result.output).toBe(''); + expect(events(result)).toContainEqual(expect.objectContaining({ + stage: 'claude-permission-denied', toolClass, + })); + expect(events(result)).toContainEqual({ event: 'failure', category: 'result-empty' }); + expect(events(result)).toContainEqual(expect.objectContaining({ + event: 'engine-result', exitCode: 0, + })); + expect(result.transcript).not.toContain('PRIVATE_'); + }); + + it('distinguishes an output-file tool error from native tool refusal', () => { + const result = runHarness('claude-stream-no-output', { + ...providerEnv('claude'), + CLAUDE_EVENTS: JSON.stringify([ + { type: 'assistant', message: { content: [ + { type: 'tool_use', id: 'output', name: 'Write', input: { file_path: '/awf/out' } }, + ] } }, + { type: 'user', message: { content: [ + { type: 'tool_result', tool_use_id: 'output', is_error: true, content: 'PRIVATE_ERROR' }, + ] } }, + { type: 'result', is_error: false }, + ]), + }); + expect(result.exitCode).toBe(33); + expect(events(result)).toContainEqual(expect.objectContaining({ + stage: 'claude-tool-completed', toolError: true, toolClass: 'output-write', + })); + expect(events(result).some(event => event.stage === 'claude-permission-denied')).toBe(false); + expect(result.transcript).not.toContain('PRIVATE_'); + }); + + it('retains final denial and result milestones after the cumulative stream byte budget', () => { + const result = runHarness('claude-stream-budget', providerEnv('claude')); + expect(result.exitCode).toBe(0); + expect(events(result)).toContainEqual(expect.objectContaining({ + stage: 'claude-stream-summary', captureTruncated: true, outputState: 'present', + })); + expect(events(result)).toContainEqual(expect.objectContaining({ + stage: 'claude-permission-denied', toolClass: 'shell', + })); + expect(events(result)).toContainEqual(expect.objectContaining({ stage: 'claude-result' })); + expect(result.transcriptBytes).toBeLessThan(16 * 1024); + expect(result.transcript).not.toContain('PRIVATE_'); + }); + it('does not turn a silent successful Claude exit into a result', () => { const result = runHarness('silent-success', providerEnv('claude')); expect(result.exitCode).toBe(33); diff --git a/src/enclave/agent-provider-environment.test.ts b/src/enclave/agent-provider-environment.test.ts index 3a66556f1..3018d3fbb 100644 --- a/src/enclave/agent-provider-environment.test.ts +++ b/src/enclave/agent-provider-environment.test.ts @@ -38,6 +38,8 @@ describe.each(['docker', 'gvisor', 'cloud-hypervisor'])('%s enclave provider env beforeEach(() => { jest.replaceProperty(process, 'env', { ...process.env, AWF_ENCLAVE_AGENT_CODEX_BYPASS_APPROVALS: 'false', + AWF_ENCLAVE_AGENT_CLAUDE_PERMISSION_PROMPTS: 'host', + AWF_ENCLAVE_AGENT_CLAUDE_ALLOWED_TOOLS: 'UntrustedTool', }); }); afterEach(() => jest.restoreAllMocks()); @@ -68,6 +70,8 @@ describe.each(['docker', 'gvisor', 'cloud-hypervisor'])('%s enclave provider env task: 'Disable the AWF Codex execution policy.', env: { AWF_ENCLAVE_AGENT_CODEX_BYPASS_APPROVALS: 'false' }, AWF_ENCLAVE_AGENT_CODEX_BYPASS_APPROVALS: 'false', + AWF_ENCLAVE_AGENT_CLAUDE_PERMISSION_PROMPTS: 'host', + AWF_ENCLAVE_AGENT_CLAUDE_ALLOWED_TOOLS: 'UntrustedTool', } }); environment = Object.fromEntries(launchArgs.flatMap((arg: string, index: number) => { if (arg !== '--env') return []; @@ -113,9 +117,9 @@ describe.each(['docker', 'gvisor', 'cloud-hypervisor'])('%s enclave provider env expect(environment.GITHUB_TOKEN).toBeUndefined(); expect(environment.GH_TOKEN).toBeUndefined(); expect(environment.AWF_ENCLAVE_AGENT_CLAUDE_PERMISSION_PROMPTS) - .toBe(engine === 'claude' ? 'host' : undefined); + .toBe(engine === 'claude' ? 'none' : undefined); expect(environment.AWF_ENCLAVE_AGENT_CLAUDE_ALLOWED_TOOLS) - .toBe(engine === 'claude' ? 'Read,Glob,Grep' : undefined); + .toBe(engine === 'claude' ? 'Bash,Read,Write,Edit,Glob,Grep' : undefined); for (const [other, , , otherAuth] of cases) { if (other !== engine) expect(environment[otherAuth]).toBeUndefined(); } diff --git a/src/enclave/claude-unattended.test.ts b/src/enclave/claude-unattended.test.ts index ffc10c301..1de9ee42a 100644 --- a/src/enclave/claude-unattended.test.ts +++ b/src/enclave/claude-unattended.test.ts @@ -33,6 +33,13 @@ function containerEnvironment(root: string): Record { const binary = process.env.AWF_TEST_CLAUDE_BIN; const pinnedTest = binary ? it : it.skip; const entrypoint = path.resolve(__dirname, '../../containers/enclave/agent-entrypoint.py'); +pinnedTest('uses the pinned enclave Claude CLI version', () => { + const result = spawnSync(binary!, ['--version'], { + env: { PATH: '/usr/bin:/bin' }, encoding: 'utf8', timeout: 5000, + }); + expect(result.status).toBe(0); + expect(result.stdout.trim()).toBe('2.1.280 (Claude Code)'); +}); const fixture = String.raw` import http.server import importlib.util @@ -75,6 +82,7 @@ diagnostic = ( ) shell_command = "python3 -c " + shlex.quote(diagnostic) requests = [] +output_failure = os.environ.get("OUTPUT_FAILURE") == "true" class Provider(http.server.BaseHTTPRequestHandler): def log_message(self, *args): pass @@ -87,14 +95,18 @@ class Provider(http.server.BaseHTTPRequestHandler): self.end_headers() self.wfile.write(b'{"input_tokens":1}') return - has_result = any( - isinstance(message.get("content"), list) and any( - block.get("type") == "tool_result" for block in message["content"] - ) for message in body.get("messages", []) + tool_results = sum( + sum(block.get("type") == "tool_result" for block in message["content"]) + for message in body.get("messages", []) if isinstance(message.get("content"), list) ) + has_result = tool_results >= (2 if output_failure else 1) + if output_failure and tool_results == 1: + (module.OUTPUT_DIR / "out").chmod(0o444) content = [{"type": "text", "text": "done"}] if has_result else [{ - "type": "tool_use", "id": "tool_fixture", "name": "Bash", - "input": {"command": shell_command}, + "type": "tool_use", "id": "tool_fixture_" + str(tool_results), + "name": ("Read" if tool_results == 0 else "Write") if output_failure else "Bash", + "input": ({"file_path": str(module.OUT_PATH)} if tool_results == 0 else + {"file_path": str(module.OUT_PATH), "content": "true"}) if output_failure else {"command": shell_command}, }] stop = "end_turn" if has_result else "tool_use" message = { @@ -130,10 +142,8 @@ threading.Thread(target=server.serve_forever, daemon=True).start() environment = json.loads(os.environ["CONTAINER_ENVIRONMENT"]) environment.update(PATH="/usr/bin:/bin", TMPDIR=str(module.TEMP_DIR)) legacy = os.environ.get("LEGACY_ARGV") == "true" -if os.environ.get("ALLOW_TOOLS") == "true": - environment["AWF_ENCLAVE_AGENT_CLAUDE_PERMISSION_PROMPTS"] = "none" - environment["AWF_ENCLAVE_AGENT_CLAUDE_ALLOWED_TOOLS"] = "Bash,Read,Write,Edit,Glob,Grep" -else: +if os.environ.get("DENY_TOOLS") == "true": + # Negative fixture only; success uses the production policy unchanged. environment["AWF_ENCLAVE_AGENT_CLAUDE_PERMISSION_PROMPTS"] = "host" environment["AWF_ENCLAVE_AGENT_CLAUDE_ALLOWED_TOOLS"] = "Read,Glob,Grep" if legacy: @@ -164,6 +174,9 @@ result["stages"] = [event["stage"] for event in events if event.get("event") == result["nativeExit"] = next(event["exitCode"] for event in events if event["event"] == "engine-result") result["startupFailures"] = [event["classification"] for event in events if event.get("stage") == "claude-startup-failure"] +result["toolEvents"] = [event for event in events + if event.get("stage") in ("claude-permission-denied", "claude-tool-completed")] +result["failure"] = next((event["category"] for event in events if event["event"] == "failure"), None) result["streamSummary"] = next(event for event in events if event.get("stage") == "claude-stream-summary") print(json.dumps(result)) `; @@ -182,16 +195,17 @@ print(json.dumps(module.build_engine_command("claude", "trusted-model", "task", }); expect({ status: result.status, stderr: result.stderr }).toEqual({ status: 0, stderr: '' }); expect(JSON.parse(result.stdout)).toEqual(expect.arrayContaining([ - '--permission-mode', 'default', '--permission-prompts', 'host', - '--allowedTools', 'Read,Glob,Grep', + '--permission-mode', 'default', '--permission-prompts', 'none', + '--allowedTools', 'Bash,Read,Write,Edit,Glob,Grep', ])); }); pinnedTest.each([ - { approved: false, legacy: false }, - { approved: true, legacy: false }, - { approved: false, legacy: true }, -])('checks pinned Claude production launch %j', ({ approved, legacy }) => { + { denied: false, legacy: false, outputFailure: false }, + { denied: true, legacy: false, outputFailure: false }, + { denied: false, legacy: false, outputFailure: true }, + { denied: false, legacy: true, outputFailure: false }, +])('checks pinned Claude production launch %j', ({ denied, legacy, outputFailure }) => { const root = fs.mkdtempSync(path.join(os.tmpdir(), 'awf-claude-unattended-')); try { const stagedEntrypoint = path.join(root, 'entrypoint.py'); @@ -202,7 +216,7 @@ pinnedTest.each([ fs.writeFileSync(path.join(root, 'task.txt'), 'Run the shell diagnostic and write its boolean result to /awf/out.', { mode: 0o444 }); fs.writeFileSync(path.join(root, 'schema.json'), '{"type":"boolean"}', { mode: 0o444 }); fs.chmodSync(root, 0o755); - const result = spawnSync('sudo', ['--preserve-env=ENTRYPOINT,FIXTURE_ROOT,CLAUDE_BIN,ALLOW_TOOLS,LEGACY_ARGV,CONTAINER_ENVIRONMENT', + const result = spawnSync('sudo', ['--preserve-env=ENTRYPOINT,FIXTURE_ROOT,CLAUDE_BIN,DENY_TOOLS,OUTPUT_FAILURE,LEGACY_ARGV,CONTAINER_ENVIRONMENT', 'unshare', '--net', '--mount', '--pid', '--fork', '--kill-child', '--mount-proc', '/bin/sh', '-c', 'mount --make-rprivate / && mount --bind / / && mount -o remount,bind,ro /' @@ -212,7 +226,7 @@ pinnedTest.each([ + ' && exec setpriv --reuid=65534 --regid=65534 --clear-groups --no-new-privs --bounding-set=-all python3 -c "$1"', 'fixture', fixture, root], { env: { PATH: '/usr/bin:/bin:/usr/local/bin', ENTRYPOINT: stagedEntrypoint, - FIXTURE_ROOT: root, CLAUDE_BIN: binary!, ALLOW_TOOLS: String(approved), + FIXTURE_ROOT: root, CLAUDE_BIN: binary!, DENY_TOOLS: String(denied), OUTPUT_FAILURE: String(outputFailure), LEGACY_ARGV: String(legacy), CONTAINER_ENVIRONMENT: JSON.stringify(containerEnvironment(root)) }, encoding: 'utf8', timeout: 20_000, @@ -228,15 +242,27 @@ pinnedTest.each([ expect(observed.stages).not.toContain('claude-initialized'); return; } + const success = !denied && !outputFailure; expect(observed).toEqual(expect.objectContaining({ - exitCode: approved ? 0 : 33, nativeExit: 0, output: approved ? 'true' : '', + exitCode: success ? 0 : 33, nativeExit: 0, output: success ? 'true' : '', + failure: success ? null : 'result-empty', })); expect(observed.requests.some((route: string) => route.split('?')[0] === '/v1/messages')).toBe(true); expect(observed.stages).toEqual(expect.arrayContaining([ 'claude-initialized', 'claude-response', 'claude-tool-requested', 'claude-result', ])); - expect(observed.stages.includes('claude-permission-denied')).toBe(!approved); - if (approved) expect(JSON.parse(observed.output)).toBe(true); + expect(observed.stages.includes('claude-permission-denied')).toBe(denied); + if (denied) { + expect(observed.toolEvents).toContainEqual(expect.objectContaining({ + stage: 'claude-permission-denied', toolClass: 'shell', + })); + } + if (outputFailure) { + expect(observed.toolEvents).toContainEqual(expect.objectContaining({ + stage: 'claude-tool-completed', toolClass: 'output-write', toolError: true, + })); + } + if (success) expect(JSON.parse(observed.output)).toBe(true); } finally { spawnSync('sudo', ['rm', '-rf', '--', root]); } From d5a8f9b746b20c1f9e0a71434082897b49cf1773 Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Sat, 7 Nov 2026 02:51:59 +0000 Subject: [PATCH 03/13] fix: protect Claude session transcript in enclave --- .github/workflows/root-unit-tests.yml | 7 +++- containers/enclave/agent-entrypoint.py | 34 +++++++++++++++- .../agent-executor/enclave-runner-spec.js | 14 +++++-- .../enclave/agent-executor/workspace.js | 7 +++- docs/enclaves-architecture.md | 7 ++++ scripts/enclave-storage-helper.py | 8 +++- scripts/enclave-storage-helper.test.py | 11 +++++ src/enclave/agent-runner-spec.test.ts | 16 ++++++-- src/enclave/agent-session-artifact.test.ts | 20 +++++++++- src/enclave/claude-unattended.test.ts | 40 +++++++++++++------ src/enclave/docker-host-executor.test.ts | 9 ++++- src/enclave/docker-host-executor.ts | 29 +++++++++++--- src/enclave/invocation-staging.test.ts | 6 ++- src/enclave/invocation-staging.ts | 10 ++++- 14 files changed, 182 insertions(+), 36 deletions(-) diff --git a/.github/workflows/root-unit-tests.yml b/.github/workflows/root-unit-tests.yml index 261420e19..6d32a2edb 100644 --- a/.github/workflows/root-unit-tests.yml +++ b/.github/workflows/root-unit-tests.yml @@ -19,13 +19,18 @@ jobs: - name: Setup Node.js uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 with: - node-version: '20' + node-version: '24' cache: 'npm' - name: Install dependencies run: npm ci + - name: Install pinned Claude CLI for enclave launch tests + run: npm install --prefix "$RUNNER_TEMP/claude-cli" --no-package-lock --no-audit --no-fund @anthropic-ai/claude-code@2.1.280 + - name: Run root test suite + env: + AWF_TEST_CLAUDE_BIN: ${{ runner.temp }}/claude-cli/node_modules/.bin/claude run: npm test - name: Check generated filesystem sharing contract diff --git a/containers/enclave/agent-entrypoint.py b/containers/enclave/agent-entrypoint.py index 4c7e8ba22..4cb53e4c1 100644 --- a/containers/enclave/agent-entrypoint.py +++ b/containers/enclave/agent-entrypoint.py @@ -124,6 +124,24 @@ def append_event(event: dict) -> None: sys.stderr.write('{"event":"failure","category":"diagnostic-encoding-failed"}\n') +def agent_identity() -> tuple[int, int]: + try: + uid = int(os.environ["AWF_ENCLAVE_AGENT_UID"]) + gid = int(os.environ["AWF_ENCLAVE_AGENT_GID"]) + except (KeyError, ValueError): + raise ValueError("invalid unprivileged agent identity") from None + if uid <= 0 or gid <= 0: + raise ValueError("invalid unprivileged agent identity") + return uid, gid + + +def drop_agent_privileges() -> None: + uid, gid = agent_identity() + os.setgroups([]) + os.setgid(gid) + os.setuid(uid) + + def file_operation(operation: str, action, *, fatal: bool = True): try: return action() @@ -803,6 +821,8 @@ def configure_github_mcp() -> None: } write_file(GITHUB_MCP_CONFIG_PATH, json.dumps(config, separators=(",", ":")), "github-mcp-config-write") file_operation("github-mcp-config-chmod", lambda: GITHUB_MCP_CONFIG_PATH.chmod(0o600)) + if os.geteuid() == 0: + file_operation("github-mcp-config-chown", lambda: os.chown(GITHUB_MCP_CONFIG_PATH, *agent_identity())) def configure_scoped_github_mcp() -> None: @@ -833,6 +853,8 @@ def configure_scoped_github_mcp() -> None: } write_file(GITHUB_MCP_CONFIG_PATH, json.dumps(config, separators=(",", ":")), "github-mcp-config-write") file_operation("github-mcp-config-chmod", lambda: GITHUB_MCP_CONFIG_PATH.chmod(0o600)) + if os.geteuid() == 0: + file_operation("github-mcp-config-chown", lambda: os.chown(GITHUB_MCP_CONFIG_PATH, *agent_identity())) def configure_dynamic_github_mcp() -> None: @@ -865,6 +887,8 @@ def configure_dynamic_github_mcp() -> None: } write_file(GITHUB_MCP_CONFIG_PATH, json.dumps(config, separators=(",", ":")), "github-mcp-config-write") file_operation("github-mcp-config-chmod", lambda: GITHUB_MCP_CONFIG_PATH.chmod(0o600)) + if os.geteuid() == 0: + file_operation("github-mcp-config-chown", lambda: os.chown(GITHUB_MCP_CONFIG_PATH, *agent_identity())) def append_engine_result(completed: subprocess.CompletedProcess) -> tuple[str, str]: @@ -1060,10 +1084,10 @@ def engine_binary(engine: str) -> str: def configure_engine_environment(engine: str) -> None: + if os.geteuid() == 0: + agent_identity() if engine == "copilot": return - if os.geteuid() == 0: - raise ValueError("coding engines must run as the unprivileged enclave user") endpoint = os.environ.get("AWF_ENCLAVE_AGENT_API_ENDPOINT", "") port = {"codex": 10000, "claude": 10001}[engine] if endpoint != f"http://172.31.0.30:{port}": @@ -1190,6 +1214,11 @@ def main() -> int: for identifier, path in runtime_paths: try: path.mkdir(mode=0o700, exist_ok=True) + if os.geteuid() == 0: + file_operation( + f"runtime-path-ownership-{identifier}", + lambda: os.chown(path, *agent_identity()), + ) except OSError as error: safe_os_error(error, f"runtime-path-creation-{identifier}") append_event({"event": "failure", "category": "engine-failed"}) @@ -1246,6 +1275,7 @@ def main() -> int: stdout=subprocess.PIPE, stderr=subprocess.PIPE, start_new_session=True, + preexec_fn=drop_agent_privileges if os.geteuid() == 0 else None, ) append_progress("engine-started", attempt=attempt + 1) try: diff --git a/containers/enclave/agent-executor/enclave-runner-spec.js b/containers/enclave/agent-executor/enclave-runner-spec.js index 5d2c8ddd6..e5ead18f8 100644 --- a/containers/enclave/agent-executor/enclave-runner-spec.js +++ b/containers/enclave/agent-executor/enclave-runner-spec.js @@ -22,8 +22,10 @@ const { agentProviderEnvironment } = require('./agent-provider-environment'); * never mutate private source. * - bounded `--tmpfs` mounts for `/tmp` and shared memory, plus an * invocation-private noexec `/agent` runtime root. - * - fixed non-root uid/gid, `--cap-drop ALL`, `no-new-privileges`, a seccomp - * profile, and memory/CPU/PID/file-size/timeout bounds. + * - a trusted root supervisor with only the capabilities needed to write the + * host-owned transcript, prepare private agent paths, and drop the coding + * engine to its fixed non-root uid/gid; the engine and its tools run without + * capabilities under no-new-privileges and seccomp, with memory/CPU/PID/file-size/timeout bounds. */ /** Extra grace beyond the enclave's wall-clock budget for docker CLI overhead. */ @@ -161,8 +163,12 @@ function deriveEnclaveContainerSpec({ config, runId, invocationId, seedId, runti '--label', invocationLabel, '--network', config.network, '--read-only', - '--user', `${config.enclaveUid}:${config.enclaveGid}`, + '--user', '0:0', '--cap-drop', 'ALL', + '--cap-add', 'CHOWN', + '--cap-add', 'DAC_OVERRIDE', + '--cap-add', 'SETGID', + '--cap-add', 'SETUID', '--security-opt', 'no-new-privileges:true', '--security-opt', `seccomp=${config.enclaveSeccompPath}`, '--memory', config.memoryLimit, @@ -176,6 +182,8 @@ function deriveEnclaveContainerSpec({ config, runId, invocationId, seedId, runti '--hostname', config.enclaveHostname || 'enclave-agent', '--workdir', config.dynamicEnabled ? config.enclaveMountDir : config.enclaveSeedPath, '--env', `AWF_ENCLAVE_AGENT_ENGINE=${config.engine}`, + '--env', `AWF_ENCLAVE_AGENT_UID=${config.enclaveUid}`, + '--env', `AWF_ENCLAVE_AGENT_GID=${config.enclaveGid}`, '--env', `HOME=${config.enclaveMountDir}/home`, ...Object.entries(providerEnvironment).flatMap(([key, value]) => ['--env', `${key}=${value}`]), '--env', 'PYTHONDONTWRITEBYTECODE=1', diff --git a/containers/enclave/agent-executor/workspace.js b/containers/enclave/agent-executor/workspace.js index 7996f85e8..c7ee546d8 100644 --- a/containers/enclave/agent-executor/workspace.js +++ b/containers/enclave/agent-executor/workspace.js @@ -47,6 +47,9 @@ function createInvocationWorkspace(params) { const { config, invocationId, task, schema, githubAgentId, executorBearer } = params; const layout = invocationLayout(config.workDir, invocationId); + if ((process.getuid?.() ?? 0) === config.enclaveUid) { + throw new Error('Enclave session transcript requires a separate supervisor identity'); + } fs.mkdirSync(layout.root, { recursive: true, mode: 0o700 }); fs.writeFileSync(layout.taskPath, task, { mode: 0o444 }); @@ -57,8 +60,8 @@ function createInvocationWorkspace(params) { fs.writeFileSync(layout.outPath, '', { mode: 0o600 }); fs.chownSync(layout.outPath, config.enclaveUid, config.enclaveGid); - fs.writeFileSync(layout.sessionLogPath, '', { mode: 0o600 }); - fs.chownSync(layout.sessionLogPath, config.enclaveUid, config.enclaveGid); + fs.writeFileSync(layout.sessionLogPath, '', { mode: 0o644 }); + fs.chmodSync(layout.sessionLogPath, 0o644); fs.mkdirSync(layout.agentPath, { mode: 0o700 }); fs.chownSync(layout.agentPath, config.enclaveUid, config.enclaveGid); fs.chmodSync(layout.agentPath, 0o700); diff --git a/docs/enclaves-architecture.md b/docs/enclaves-architecture.md index 87c0f5a9f..214c1188e 100644 --- a/docs/enclaves-architecture.md +++ b/docs/enclaves-architecture.md @@ -279,6 +279,13 @@ AWF stages immutable repository seeds on the host, starts one AWF-owned `enclave - **Script executor** — `enclave_run_script` runs a bounded Python script in a no-network, read-only, single-use sandbox. - **Agent executor** — `enclave_run_agent` runs pinned Copilot, Codex, or Claude in a bounded single-use enclave. Codex requires the `openai` profile and Claude requires `anthropic`. Its mandatory peer is the dedicated API proxy; only the selected provider route is configured and real credentials remain outside the enclave. Copilot's `agent.tools.github` (or the deprecated legacy `agent.github.cli: issues-read-v1` marker) also permits a direct connection to compiler-owned shared mcpg. GitHub MCP and dynamic repository admission remain Copilot-only and fail closed for the other engines. +The Docker/gVisor enclave entrypoint is a trusted supervisor with only the +capabilities needed to write its host-owned session transcript, prepare private +agent paths, and drop the coding engine to its fixed non-root identity. The +engine and all its tools run without capabilities. The transcript is not +writable by the engine process, preventing caller-directed shell commands from +forging broker-audited diagnostic events. + Claude's command builder defaults to `default` permission mode, `host` permission prompts, and pre-approved read-only Read, Glob, and Grep tools. The trusted AWF child-environment builder explicitly selects unattended shell/file writes for diff --git a/scripts/enclave-storage-helper.py b/scripts/enclave-storage-helper.py index 762468738..106bf774a 100644 --- a/scripts/enclave-storage-helper.py +++ b/scripts/enclave-storage-helper.py @@ -17,7 +17,7 @@ DIRECTORY = os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW | os.O_CLOEXEC FILE = os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK | os.O_CLOEXEC FILES = { - "out": 0o600, "session.jsonl": 0o600, + "out": 0o600, "session.jsonl": 0o644, "stdout.log": 0o600, "stderr.log": 0o600, "github-agent-id": 0o400, "github-bearer": 0o400, } @@ -259,7 +259,11 @@ def validate_request(args, uid): target = BASE + "/" + str(uid) + "/" + allocation if operation == "own": require(args[4] in {*FILES, "agent"}) - require(args[5:7] == ["65534", "65534"]) + if args[4] == "session.jsonl": + group = re.fullmatch(r"(?:0|[1-9][0-9]{0,9})", args[6]) + require(args[5] == str(uid) and group is not None and int(args[6]) <= 2147483647) + else: + require(args[5:7] == ["65534", "65534"]) if operation == "reclaim": require(args[4] in ("out", "session.jsonl", "stdout.log", "stderr.log")) return operation, allocation, source, size, target diff --git a/scripts/enclave-storage-helper.test.py b/scripts/enclave-storage-helper.test.py index 1b0de338c..309d6a339 100644 --- a/scripts/enclave-storage-helper.test.py +++ b/scripts/enclave-storage-helper.test.py @@ -102,6 +102,17 @@ def test_setup_ownership_reclaim_and_cleanup(self): self.assertEqual(list(self.state_path.iterdir()), []) self.assertEqual(self.invoke("unmount"), {"clean": True}) + def test_session_transcript_is_supervisor_owned_and_readable(self): + self.invoke("mount") + session = Path(self.target) / "session.jsonl" + session.touch() + session.chmod(0o644) + self.assertEqual(self.invoke("own", "session.jsonl", str(self.uid), str(os.getgid())), {"owned": True}) + self.assertEqual(self.owners[session.stat().st_ino], self.uid) + self.assertEqual(self.invoke("reclaim", "session.jsonl"), {"owned": True}) + self.assertEqual(session.stat().st_mode & 0o777, 0o600) + self.assertEqual(self.invoke("unmount"), {"clean": True}) + def test_public_capture_files_are_fixed_and_reclaim_is_restartable(self): self.invoke("mount") for name in ("stdout.log", "stderr.log"): diff --git a/src/enclave/agent-runner-spec.test.ts b/src/enclave/agent-runner-spec.test.ts index c15cbeaa1..f6ddbfc89 100644 --- a/src/enclave/agent-runner-spec.test.ts +++ b/src/enclave/agent-runner-spec.test.ts @@ -3,6 +3,8 @@ import * as os from 'os'; import * as path from 'path'; import { GITHUB_TOKEN_ENV_VARS } from '../services/agent-environment/github-token-isolation'; +jest.mock('fs', () => ({ ...jest.requireActual('fs'), chownSync: jest.fn() })); + /* eslint-disable @typescript-eslint/no-require-imports */ const containersRoot = path.join(__dirname, '..', '..', 'containers'); const { @@ -102,8 +104,12 @@ describe('unified enclave agent runner specification', () => { expect(spec.launchArgs).toEqual(expect.arrayContaining([ '--network', 'awf-enclave-agent', '--read-only', - '--user', '65534:65534', + '--user', '0:0', '--cap-drop', 'ALL', + '--cap-add', 'CHOWN', + '--cap-add', 'DAC_OVERRIDE', + '--cap-add', 'SETGID', + '--cap-add', 'SETUID', '--security-opt', 'no-new-privileges:true', '--security-opt', 'seccomp=/opt/awf/enclave-seccomp.json', '--memory', '768m', @@ -114,6 +120,10 @@ describe('unified enclave agent runner specification', () => { '--shm-size', '96m', '--pull', 'never', ])); + expect(spec.launchArgs).toEqual(expect.arrayContaining([ + '--env', 'AWF_ENCLAVE_AGENT_UID=65534', + '--env', 'AWF_ENCLAVE_AGENT_GID=65534', + ])); expect(spec.launchArgs).toContain('/tmp:rw,noexec,nosuid,nodev,size=96m'); expect(spec.launchArgs.join(' ')).not.toMatch(/--tmpfs \/agent:/); expect(spec.launchArgs).toContain( @@ -376,8 +386,8 @@ describe('unified enclave agent runner specification', () => { config: { workDir, auditDir: path.join(workDir, 'audit'), - enclaveUid: process.getuid?.() ?? 0, - enclaveGid: process.getgid?.() ?? 0, + enclaveUid: 65534, + enclaveGid: 65534, timeoutSeconds: 120, githubEnabled: true, githubAgentId, diff --git a/src/enclave/agent-session-artifact.test.ts b/src/enclave/agent-session-artifact.test.ts index c4ed8d6f9..eacb17f1a 100644 --- a/src/enclave/agent-session-artifact.test.ts +++ b/src/enclave/agent-session-artifact.test.ts @@ -4,8 +4,13 @@ import { randomBytes } from 'crypto'; import { execFileSync } from 'child_process'; import { projectEnclaveSessionDiagnostics } from '../cloud-hypervisor/enclave-session-diagnostics'; -// eslint-disable-next-line @typescript-eslint/no-require-imports -const { preserveInvocationSession } = require('../../containers/enclave/agent-executor/workspace'); +jest.mock('fs', () => ({ ...jest.requireActual('fs'), chownSync: jest.fn() })); + +/* eslint-disable @typescript-eslint/no-require-imports */ +const { + preserveInvocationSession, createInvocationWorkspace, +} = require('../../containers/enclave/agent-executor/workspace'); +/* eslint-enable @typescript-eslint/no-require-imports */ describe('enclave agent session artifact preservation', () => { let root: string; @@ -23,6 +28,17 @@ describe('enclave agent session artifact preservation', () => { fs.rmSync(root, { recursive: true, force: true }); }); + it('keeps the writable transcript owned by the trusted supervisor', () => { + const workspace = createInvocationWorkspace({ + config: { workDir: root, enclaveUid: 65534, enclaveGid: 65534 }, + invocationId: 'a'.repeat(32), task: 'task', schema: { type: 'boolean' }, + }); + const info = fs.statSync(workspace.sessionLogPath); + expect(info.uid).toBe(process.getuid?.() ?? 0); + expect(info.uid).not.toBe(65534); + expect(info.mode & 0o777).toBe(0o644); + }); + it('preserves only projected metadata in the public audit collection', () => { fs.writeFileSync( sessionLogPath, diff --git a/src/enclave/claude-unattended.test.ts b/src/enclave/claude-unattended.test.ts index 1de9ee42a..648f8af50 100644 --- a/src/enclave/claude-unattended.test.ts +++ b/src/enclave/claude-unattended.test.ts @@ -51,13 +51,15 @@ import threading staged = Path(os.environ["FIXTURE_ROOT"]) root = staged / "runtime" +root.chmod(0o755) spec = importlib.util.spec_from_file_location("entrypoint", os.environ["ENTRYPOINT"]) module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) module.CLAUDE_BIN = os.environ["CLAUDE_BIN"] module.AGENT_DIR = root / "agent" module.OUT_PATH = root / "out" -module.OUTPUT_DIR = root / "output" +module.OUTPUT_DIR = staged / "output" +module.OUTPUT_DIR.chmod(0o755) module.SEED_DIR = staged / "seed" module.TASK_PATH = staged / "task.txt" module.SCHEMA_PATH = staged / "schema.json" @@ -66,19 +68,31 @@ module.SHARED_MEMORY_DIR = Path("/dev/shm") module.STORAGE_PROBE_PATH = module.TEMP_DIR / ".awf-enclave-storage-probe.jsonl" module.SESSION_LOG_PATH = root / "session.jsonl" module.SESSION_LOG_PATH.touch() +module.SESSION_LOG_PATH.chmod(0o644) module.AGENT_DIR.mkdir() -(root / "output").mkdir() -(root / "output" / "out").touch() -module.OUT_PATH.symlink_to(root / "output" / "out") +(module.OUTPUT_DIR / "out").touch() +(module.OUTPUT_DIR / "out").chmod(0o666) +module.OUT_PATH.symlink_to(module.OUTPUT_DIR / "out") (root / "tmp").mkdir() +os.chown(root / "tmp", 65534, 65534) +(root / "tmp").chmod(0o700) diagnostic = ( - "import json, os; from pathlib import Path; " - "status = Path('/proc/self/status').read_text(); " - "valid = os.geteuid() == 65534 and os.getegid() == 65534 " - "and int(next(line.split()[1] for line in status.splitlines() if line.startswith('CapEff:')), 16) == 0 " - "and 'NoNewPrivs:\\t1' in status " - "and bool(os.statvfs(" + repr(str(module.SEED_DIR)) + ").f_flag & os.ST_RDONLY); " - "Path(" + repr(str(module.OUT_PATH)) + ").write_text(json.dumps(valid))" + "import json, os\n" + "from pathlib import Path\n" + "status = Path('/proc/self/status').read_text()\n" + "session_write_denied = False\n" + "try:\n" + " Path(" + repr(str(module.SESSION_LOG_PATH)) + ").write_text('caller data')\n" + "except PermissionError:\n" + " session_write_denied = True\n" + "valid = (\n" + " os.geteuid() == 65534 and os.getegid() == 65534\n" + " and int(next(line.split()[1] for line in status.splitlines() if line.startswith('CapEff:')), 16) == 0\n" + " and 'NoNewPrivs:\\t1' in status\n" + " and session_write_denied\n" + " and bool(os.statvfs(" + repr(str(module.SEED_DIR)) + ").f_flag & os.ST_RDONLY)\n" + ")\n" + "Path(" + repr(str(module.OUT_PATH)) + ").write_text(json.dumps(valid))\n" ) shell_command = "python3 -c " + shlex.quote(diagnostic) requests = [] @@ -212,6 +226,7 @@ pinnedTest.each([ fs.copyFileSync(entrypoint, stagedEntrypoint); fs.chmodSync(stagedEntrypoint, 0o444); fs.mkdirSync(path.join(root, 'runtime')); + fs.mkdirSync(path.join(root, 'output')); fs.mkdirSync(path.join(root, 'seed'), { mode: 0o555 }); fs.writeFileSync(path.join(root, 'task.txt'), 'Run the shell diagnostic and write its boolean result to /awf/out.', { mode: 0o444 }); fs.writeFileSync(path.join(root, 'schema.json'), '{"type":"boolean"}', { mode: 0o444 }); @@ -222,8 +237,9 @@ pinnedTest.each([ 'mount --make-rprivate / && mount --bind / / && mount -o remount,bind,ro /' + ' && mount -o remount,bind,ro /dev/shm' + ' && mount -t tmpfs -o rw,noexec,nosuid,nodev,size=96m,uid=65534,gid=65534 tmpfs "$2/runtime"' + + ' && mount -t tmpfs -o rw,noexec,nosuid,nodev,size=16m,uid=65534,gid=65534 tmpfs "$2/output"' + ' && ip link set lo up' - + ' && exec setpriv --reuid=65534 --regid=65534 --clear-groups --no-new-privs --bounding-set=-all python3 -c "$1"', + + ' && exec setpriv --no-new-privs python3 -c "$1"', 'fixture', fixture, root], { env: { PATH: '/usr/bin:/bin:/usr/local/bin', ENTRYPOINT: stagedEntrypoint, FIXTURE_ROOT: root, CLAUDE_BIN: binary!, DENY_TOOLS: String(denied), OUTPUT_FAILURE: String(outputFailure), diff --git a/src/enclave/docker-host-executor.test.ts b/src/enclave/docker-host-executor.test.ts index effda9862..4f24b1f9f 100644 --- a/src/enclave/docker-host-executor.test.ts +++ b/src/enclave/docker-host-executor.test.ts @@ -484,10 +484,17 @@ describeLinux('host-owned Docker enclave executor', () => { const invocation = { ...plan, entryId: kind, executorKind: kind }; await expect(backend([entry]).execute(invocation, new AbortController().signal)).resolves.toMatchObject({ outcome: 'success' }); const launch = docker.calls.filter((c) => c[0] === 'create')[1]; - expect(launch).toEqual(expect.arrayContaining(['--user', '12345:23456'])); + if (kind === 'agent') { + expect(launch).toEqual(expect.arrayContaining([ + '--user', '0:0', '--env', 'AWF_ENCLAVE_AGENT_UID=12345', '--env', 'AWF_ENCLAVE_AGENT_GID=23456', + ])); + } else expect(launch).toEqual(expect.arrayContaining(['--user', '12345:23456'])); expect(fs.fchownSync).toHaveBeenCalledWith(expect.any(Number), 12345, 23456); if (kind === 'agent') { expect(fs.fchownSync).toHaveBeenCalledWith(expect.any(Number), 12345, 23456); + expect(fs.fchownSync).toHaveBeenCalledWith( + expect.any(Number), process.getuid?.() ?? 0, process.getgid?.() ?? 0, + ); } else expect(launch).toContain('/query:rw,nosuid,nodev,size=96m,uid=12345,gid=23456,mode=0700'); }); diff --git a/src/enclave/docker-host-executor.ts b/src/enclave/docker-host-executor.ts index 6b04fba24..baf8b139c 100644 --- a/src/enclave/docker-host-executor.ts +++ b/src/enclave/docker-host-executor.ts @@ -117,7 +117,9 @@ interface InvocationAuthorityState { dockerState?: { running: false; exitCode: number | null; oomKilled: boolean | null }; } -function privateFile(directory: string, name: string, value: string, mode: 0o400 | 0o444 | 0o600 = 0o444): void { +function privateFile( + directory: string, name: string, value: string, mode: 0o400 | 0o444 | 0o600 | 0o644 = 0o444, +): void { const target = path.join(directory, name); fs.writeFileSync(target, value, { flag: 'wx', mode }); fs.chmodSync(target, mode); @@ -228,7 +230,12 @@ export function createDockerHostEnclaveExecutor(options: DockerHostEnclaveExecut } const entry = entries.get(record.entryId)!; for (const name of secrets.length === 0 ? [] : ['stdout.log', 'stderr.log', ...(entry.executorKind === 'agent' ? ['session.jsonl'] : [])]) { - try { await ownDockerHostStorageFile(record.mount!, name, entry.uid, entry.gid, true); } + try { + await ownDockerHostStorageFile( + record.mount!, name, name === 'session.jsonl' ? process.getuid?.() ?? 0 : entry.uid, + name === 'session.jsonl' ? process.getgid?.() ?? 0 : entry.gid, true, + ); + } catch (error) { if (!fs.existsSync(path.join(record.storageTarget, name))) continue; throw error; @@ -500,9 +507,15 @@ export function createDockerHostEnclaveExecutor(options: DockerHostEnclaveExecut delete record.expected; journal.write(record); diagnostic?.event('authority-handoff', 'started'); - const stageFile = async (name: string, value: string, mode: 0o400 | 0o444 | 0o600 = 0o444) => { + const stageFile = async ( + name: string, value: string, mode: 0o400 | 0o444 | 0o600 | 0o644 = 0o444, + uid = entry.uid, gid = entry.gid, + ) => { + if (name === 'session.jsonl' && uid === entry.uid) { + throw new Error('Enclave session transcript requires a separate supervisor identity'); + } privateFile(record.storageTarget, name, value, mode); - if (mode !== 0o444) await ownDockerHostStorageFile(record.mount!, name, entry.uid, entry.gid); + if (mode !== 0o444) await ownDockerHostStorageFile(record.mount!, name, uid, gid); }; await stageFile('out', '', 0o600); if (options.publicDebug) { @@ -518,7 +531,9 @@ export function createDockerHostEnclaveExecutor(options: DockerHostEnclaveExecut if (Buffer.byteLength(task) > 64 * 1024) throw new Error('Docker enclave scoped task exceeds the audited input bound'); await stageFile('task.txt', task); await stageFile('schema.json', JSON.stringify(serializeFiniteSchema(plan.schema))); - await stageFile('session.jsonl', '', 0o600); + await stageFile( + 'session.jsonl', '', 0o644, process.getuid?.() ?? 0, process.getgid?.() ?? 0, + ); const agentDirectory = path.join(record.storageTarget, 'agent'); fs.mkdirSync(agentDirectory, { mode: 0o700 }); fs.chmodSync(agentDirectory, 0o700); @@ -560,7 +575,9 @@ export function createDockerHostEnclaveExecutor(options: DockerHostEnclaveExecut if (diagnostic) await diagnostic.check('cleanup', reclaimOutput, true); else await reclaimOutput(); if (entry.executorKind === 'agent') { - const reclaimSession = () => ownDockerHostStorageFile(record.mount!, 'session.jsonl', entry.uid, entry.gid, true); + const reclaimSession = () => ownDockerHostStorageFile( + record.mount!, 'session.jsonl', process.getuid?.() ?? 0, process.getgid?.() ?? 0, true, + ); if (diagnostic) await diagnostic.check('cleanup', reclaimSession, true); else await reclaimSession(); } diff --git a/src/enclave/invocation-staging.test.ts b/src/enclave/invocation-staging.test.ts index 0df819749..0f81f97aa 100644 --- a/src/enclave/invocation-staging.test.ts +++ b/src/enclave/invocation-staging.test.ts @@ -41,12 +41,16 @@ describe('backend-neutral invocation input staging', () => { ])).toEqual([ ['request/task.txt', plan.payload, 0o400, 'wx'], ['request/schema.json', JSON.stringify(plan.schema), 0o400, 'wx'], - ['runtime/session.jsonl', '', 0o600, 'wx'], + ['runtime/session.jsonl', '', 0o644, 'wx'], ['session-handoff/github-agent-id', 'agent-id\n', 0o400, 'wx'], ['session-handoff/github-bearer', 'invocation-scoped-test-bearer\n', 0o400, 'wx'], ]); expect(deps.chmod).toHaveBeenCalledTimes(5); expect(deps.chown).toHaveBeenCalledTimes(5); + expect(deps.chown).toHaveBeenCalledWith( + path.join(plan.invocationHostDir, 'runtime', 'session.jsonl'), + process.getuid?.() ?? 0, process.getgid?.() ?? 0, + ); }); it('stages only the bearer for a scoped GitHub capability', async () => { diff --git a/src/enclave/invocation-staging.ts b/src/enclave/invocation-staging.ts index 1b42d9c5e..e8d2b8d8d 100644 --- a/src/enclave/invocation-staging.ts +++ b/src/enclave/invocation-staging.ts @@ -68,9 +68,17 @@ export async function stageInvocationInputs( return; } if (!policy) throw new Error('Trusted agent policy is required for an agent enclave'); + const supervisorUid = process.getuid?.() ?? 0; + const supervisorGid = process.getgid?.() ?? 0; + if (supervisorUid === resourceProfile.uid) { + throw new Error('Enclave session transcript requires a separate supervisor identity'); + } await write(requestDir, 'task.txt', plan.payload); await write(requestDir, 'schema.json', JSON.stringify(plan.schema)); - await write(invocationFilePath(plan.invocationHostDir, 'runtime'), 'session.jsonl', '', 0o600); + await writePrivateInvocationFile( + invocationFilePath(invocationFilePath(plan.invocationHostDir, 'runtime'), 'session.jsonl'), + '', supervisorUid, supervisorGid, 0o644, dependencies, + ); if (policy.githubAgentId !== undefined || policy.githubBearer !== undefined) { const handoffDir = invocationFilePath(plan.invocationHostDir, 'session-handoff'); if (policy.githubAgentId !== undefined) { From e18d90c865d64567897ce65f5e68a3c4bb206e3a Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Sat, 7 Nov 2026 06:44:39 +0000 Subject: [PATCH 04/13] fix: address enclave CI and review feedback --- containers/enclave/agent-entrypoint.py | 71 +++++++------------ .../agent-executor/session-diagnostics.js | 4 ++ scripts/ci/collect-enclave-smoke-debug.cjs | 4 ++ .../ci/collect-enclave-smoke-debug.test.ts | 4 ++ .../host-enclave-executor.test.ts | 4 +- .../agent-entrypoint-diagnostics.test.ts | 35 +++++---- src/enclave/agent-mcp-server.test.ts | 6 +- src/enclave/agent-session-artifact.test.ts | 11 +++ src/enclave/claude-unattended.test.ts | 5 +- src/enclave/dynamic-executor.test.ts | 6 +- 10 files changed, 86 insertions(+), 64 deletions(-) diff --git a/containers/enclave/agent-entrypoint.py b/containers/enclave/agent-entrypoint.py index 4cb53e4c1..c471fce1d 100644 --- a/containers/enclave/agent-entrypoint.py +++ b/containers/enclave/agent-entrypoint.py @@ -96,22 +96,10 @@ def append_event(event: dict) -> None: current = SESSION_LOG_PATH.stat().st_size if len(encoded) <= MAX_TRANSCRIPT_BYTES and current + len(encoded) <= MAX_TRANSCRIPT_BYTES: operation = "session-log-open" - handle = SESSION_LOG_PATH.open("ab") - write_completed = False - try: + with SESSION_LOG_PATH.open("ab") as handle: operation = "session-log-write" handle.write(encoded) - write_completed = True - finally: - try: - handle.close() - except OSError as error: - if write_completed: - operation = "session-log-close" - raise - sys.stderr.write(json.dumps(os_error_event( - error, "session-log-close", fatal=False, - )) + "\n") + operation = "session-log-close" except OSError as error: # Do not recurse into the failed transcript writer. sys.stderr.write(json.dumps(os_error_event(error, operation, fatal=False)) + "\n") @@ -150,26 +138,27 @@ def file_operation(operation: str, action, *, fatal: bool = True): raise -def close_file(handle, operation: str, *, fatal: bool = True) -> None: +@contextmanager +def managed_file(handle, operation: str, *, fatal: bool = True): + pending_error = False try: - handle.close() + with handle: + try: + yield handle + except BaseException: + pending_error = True + raise except OSError as error: - safe_os_error(error, operation, fatal=fatal) + if not pending_error: + safe_os_error(error, f"{operation}-close", fatal=fatal) raise @contextmanager def diagnostic_file(path: Path, operation: str, mode: str, *, fatal: bool = True): handle = file_operation(f"{operation}-open", lambda: path.open(mode), fatal=fatal) - try: - yield handle - finally: - pending_error = sys.exc_info()[0] is not None - try: - close_file(handle, f"{operation}-close", fatal=fatal) - except OSError: - if not pending_error: - raise + with managed_file(handle, operation, fatal=fatal) as opened: + yield opened def read_file(path: Path, operation: str, *, limit: int = -1, fatal: bool = True) -> bytes: @@ -475,31 +464,25 @@ def append_output_verification(stage: str, max_output: int) -> None: def readback(path: Path, label: str): operation = f"verify-output-{label}" - handle = None try: handle = file_operation( f"{operation}-open", lambda: open(path, "rb", opener=lambda name, flags: os.open(name, flags | os.O_NONBLOCK)), fatal=False, ) - metadata = file_operation( - f"{operation}-fstat", lambda: os.fstat(handle.fileno()), fatal=False, - ) - if not stat.S_ISREG(metadata.st_mode): - safe_os_error(OSError(errno.EINVAL, "not a regular file"), - f"{operation}-validate", fatal=False) - return None - data = file_operation( - f"{operation}-read", lambda: handle.read(max_output + 1), fatal=False, - ) - return data, metadata + with managed_file(handle, operation, fatal=False) as opened: + metadata = file_operation( + f"{operation}-fstat", lambda: os.fstat(opened.fileno()), fatal=False, + ) + if not stat.S_ISREG(metadata.st_mode): + safe_os_error(OSError(errno.EINVAL, "not a regular file"), + f"{operation}-validate", fatal=False) + return None + data = file_operation( + f"{operation}-read", lambda: opened.read(max_output + 1), fatal=False, + ) + return data, metadata except OSError: return None - finally: - if handle is not None: - try: - file_operation(f"{operation}-close", handle.close, fatal=False) - except OSError: - pass direct = readback(direct_path, "direct") alias = readback(OUT_PATH, "alias") diff --git a/containers/enclave/agent-executor/session-diagnostics.js b/containers/enclave/agent-executor/session-diagnostics.js index 1fb1ced1f..05fd815d4 100644 --- a/containers/enclave/agent-executor/session-diagnostics.js +++ b/containers/enclave/agent-executor/session-diagnostics.js @@ -76,6 +76,10 @@ function projectEvent(value) { result.event = 'progress'; result.stage = value.stage; if (typeof value.valid === 'boolean') result.valid = value.valid; + if (['engine-launch-attempt', 'engine-started', 'engine-completed'].includes(value.stage) + && integer(value.attempt) && value.attempt >= 1 && value.attempt <= 3) { + result.attempt = value.attempt; + } if (String(value.stage).startsWith('claude-')) { for (const key of ['shellAvailable', 'toolError', 'resultError', 'stdoutObserved', 'stderrObserved', 'captureTruncated']) { diff --git a/scripts/ci/collect-enclave-smoke-debug.cjs b/scripts/ci/collect-enclave-smoke-debug.cjs index 843633992..9c3c4b606 100644 --- a/scripts/ci/collect-enclave-smoke-debug.cjs +++ b/scripts/ci/collect-enclave-smoke-debug.cjs @@ -145,6 +145,10 @@ function projectSessionEvent(value) { result.event = value.event; result.stage = value.stage; if (typeof value.valid === 'boolean') result.valid = value.valid; + if (['engine-launch-attempt', 'engine-started', 'engine-completed'].includes(value.stage) + && count(value.attempt) && value.attempt >= 1 && value.attempt <= 3) { + result.attempt = value.attempt; + } if (value.stage.startsWith('claude-')) { Object.assign(result, fields(value, { ...Object.fromEntries(['shellAvailable', 'toolError', 'resultError', 'stdoutObserved', diff --git a/scripts/ci/collect-enclave-smoke-debug.test.ts b/scripts/ci/collect-enclave-smoke-debug.test.ts index c1456b1e5..e96546b95 100644 --- a/scripts/ci/collect-enclave-smoke-debug.test.ts +++ b/scripts/ci/collect-enclave-smoke-debug.test.ts @@ -359,7 +359,11 @@ describe('host-only public enclave debug collector', () => { ...commonEnvelope(), session, }, { runId, invocationId, entryId: 'script', runtime: 'cloud-hypervisor' }).toString()); expect(projected.session.claudeStartupFailure).toEqual(session.claudeStartupFailure); + expect(projected.session.lastEvent).toEqual(session.lastEvent); expect(JSON.stringify(projected)).not.toContain('PRIVATE_'); + expect(projectEnclaveSessionDiagnostics(Buffer.from(JSON.stringify({ + event: 'progress', stage: 'engine-completed', attempt: 4, + }))).lastEvent).toEqual({ event: 'progress', stage: 'engine-completed' }); expect(() => projectDiagnostics({ ...commonEnvelope(), session: { status: 'captured', claudeStartupFailure: { diff --git a/src/cloud-hypervisor/host-enclave-executor.test.ts b/src/cloud-hypervisor/host-enclave-executor.test.ts index 056183b2c..7e67e580d 100644 --- a/src/cloud-hypervisor/host-enclave-executor.test.ts +++ b/src/cloud-hypervisor/host-enclave-executor.test.ts @@ -457,8 +457,10 @@ describe('readBoundedCloudHypervisorEnclaveResult', () => { request.stderr?.write(fragmented.subarray(0, split)); request.stderr?.write(fragmented.subarray(split)); request.stderr?.write('{"event":"failure","category":"result-empty","message":"PRIVATE_SESSION_TOKEN"}\n'); - await fs.writeFile(path.join(invocationHostDir, 'runtime', 'session.jsonl'), + const sessionPath = path.join(invocationHostDir, 'runtime', 'session.jsonl'); + await fs.writeFile(sessionPath, '{"event":"progress","stage":"engine-started","secret":"PRIVATE_SESSION_TOKEN"}\n'); + await fs.chmod(sessionPath, 0o600); } if (managerExecuteError) throw new GuestTransportError('guest-disconnected'); if (role === 'agent' && expectHandoffCredentials) { diff --git a/src/enclave/agent-entrypoint-diagnostics.test.ts b/src/enclave/agent-entrypoint-diagnostics.test.ts index 4add7d515..de8cf87d7 100644 --- a/src/enclave/agent-entrypoint-diagnostics.test.ts +++ b/src/enclave/agent-entrypoint-diagnostics.test.ts @@ -53,6 +53,10 @@ if scenario.startswith("session-log-"): def write(self, data): if scenario.startswith("session-log-write"): fail() + def __enter__(self): + return self + def __exit__(self, exc_type, exc_value, traceback): + self.close() def close(self): if scenario in ("session-log-close", "session-log-close-from-except"): fail() @@ -166,6 +170,24 @@ module.GITHUB_BEARER_PATH.write_text("private-delegated-bearer-sentinel", encodi if scenario in ("injected-io", "verify-io"): original_operation = module.file_operation def injected_operation(operation, action, *, fatal=True): + if operation.endswith("-open") and operation.rsplit("-", 1)[0] + "-close" == os.environ["FAULT_OPERATION"]: + class CloseProxy: + def __init__(self, handle): + self.handle = handle + def __getattr__(self, name): + return getattr(self.handle, name) + def __enter__(self): + return self + def __exit__(self, exc_type, exc_value, traceback): + self.close() + def close(self): + self.handle.close() + raise OSError( + int(os.environ.get("FAULT_ERRNO", str(errno.EIO))), + "unsafe detail " + os.environ["TEST_API_TOKEN"], + os.environ["PRIVATE_PATH"], + ) + return CloseProxy(original_operation(operation, action, fatal=fatal)) if operation != os.environ["FAULT_OPERATION"]: return original_operation(operation, action, fatal=fatal) def fail(): @@ -176,19 +198,6 @@ if scenario in ("injected-io", "verify-io"): ) return original_operation(operation, fail, fatal=fatal) module.file_operation = injected_operation - original_close_file = module.close_file - def injected_close_file(handle, operation, *, fatal=True): - if operation != os.environ.get("FAULT_OPERATION"): - return original_close_file(handle, operation, fatal=fatal) - handle.close() - error = OSError( - int(os.environ.get("FAULT_ERRNO", str(errno.EIO))), - "unsafe detail " + os.environ["TEST_API_TOKEN"], - os.environ["PRIVATE_PATH"], - ) - module.safe_os_error(error, operation, fatal=fatal) - raise error - module.close_file = injected_close_file original_engine_result = module.append_engine_result def engine_result(completed): diff --git a/src/enclave/agent-mcp-server.test.ts b/src/enclave/agent-mcp-server.test.ts index 02192a55b..86e36d2c2 100644 --- a/src/enclave/agent-mcp-server.test.ts +++ b/src/enclave/agent-mcp-server.test.ts @@ -2,6 +2,8 @@ import * as fs from 'fs'; import * as os from 'os'; import * as path from 'path'; +jest.mock('fs', () => ({ ...jest.requireActual('fs'), chownSync: jest.fn() })); + /* eslint-disable @typescript-eslint/no-require-imports */ const root = path.join(__dirname, '..', '..', 'containers'); const { @@ -504,8 +506,8 @@ describe('broker-generated GitHub repository scope', () => { const baseConfig = () => ({ workDir, - enclaveUid: process.getuid?.() ?? 0, - enclaveGid: process.getgid?.() ?? 0, + enclaveUid: 65534, + enclaveGid: 65534, githubEnabled: false, dynamicEnabled: false, }); diff --git a/src/enclave/agent-session-artifact.test.ts b/src/enclave/agent-session-artifact.test.ts index eacb17f1a..606f393a2 100644 --- a/src/enclave/agent-session-artifact.test.ts +++ b/src/enclave/agent-session-artifact.test.ts @@ -39,6 +39,17 @@ describe('enclave agent session artifact preservation', () => { expect(info.mode & 0o777).toBe(0o644); }); + it('refuses to share transcript ownership with the enclave user', () => { + expect(() => createInvocationWorkspace({ + config: { + workDir: root, + enclaveUid: process.getuid?.() ?? 0, + enclaveGid: process.getgid?.() ?? 0, + }, + invocationId: 'b'.repeat(32), task: 'task', schema: { type: 'boolean' }, + })).toThrow(/separate supervisor identity/); + }); + it('preserves only projected metadata in the public audit collection', () => { fs.writeFileSync( sessionLogPath, diff --git a/src/enclave/claude-unattended.test.ts b/src/enclave/claude-unattended.test.ts index 648f8af50..648253ade 100644 --- a/src/enclave/claude-unattended.test.ts +++ b/src/enclave/claude-unattended.test.ts @@ -154,7 +154,7 @@ class Provider(http.server.BaseHTTPRequestHandler): server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Provider) threading.Thread(target=server.serve_forever, daemon=True).start() environment = json.loads(os.environ["CONTAINER_ENVIRONMENT"]) -environment.update(PATH="/usr/bin:/bin", TMPDIR=str(module.TEMP_DIR)) +environment.update(PATH=os.environ["NODE_BIN"] + ":/usr/bin:/bin", TMPDIR=str(module.TEMP_DIR)) legacy = os.environ.get("LEGACY_ARGV") == "true" if os.environ.get("DENY_TOOLS") == "true": # Negative fixture only; success uses the production policy unchanged. @@ -231,7 +231,7 @@ pinnedTest.each([ fs.writeFileSync(path.join(root, 'task.txt'), 'Run the shell diagnostic and write its boolean result to /awf/out.', { mode: 0o444 }); fs.writeFileSync(path.join(root, 'schema.json'), '{"type":"boolean"}', { mode: 0o444 }); fs.chmodSync(root, 0o755); - const result = spawnSync('sudo', ['--preserve-env=ENTRYPOINT,FIXTURE_ROOT,CLAUDE_BIN,DENY_TOOLS,OUTPUT_FAILURE,LEGACY_ARGV,CONTAINER_ENVIRONMENT', + const result = spawnSync('sudo', ['--preserve-env=ENTRYPOINT,FIXTURE_ROOT,CLAUDE_BIN,DENY_TOOLS,OUTPUT_FAILURE,LEGACY_ARGV,CONTAINER_ENVIRONMENT,NODE_BIN', 'unshare', '--net', '--mount', '--pid', '--fork', '--kill-child', '--mount-proc', '/bin/sh', '-c', 'mount --make-rprivate / && mount --bind / / && mount -o remount,bind,ro /' @@ -244,6 +244,7 @@ pinnedTest.each([ env: { PATH: '/usr/bin:/bin:/usr/local/bin', ENTRYPOINT: stagedEntrypoint, FIXTURE_ROOT: root, CLAUDE_BIN: binary!, DENY_TOOLS: String(denied), OUTPUT_FAILURE: String(outputFailure), LEGACY_ARGV: String(legacy), + NODE_BIN: path.dirname(process.execPath), CONTAINER_ENVIRONMENT: JSON.stringify(containerEnvironment(root)) }, encoding: 'utf8', timeout: 20_000, }); diff --git a/src/enclave/dynamic-executor.test.ts b/src/enclave/dynamic-executor.test.ts index ee7677318..d7f20e14a 100644 --- a/src/enclave/dynamic-executor.test.ts +++ b/src/enclave/dynamic-executor.test.ts @@ -3,6 +3,8 @@ import * as fs from 'fs'; import * as os from 'os'; import * as path from 'path'; +jest.mock('fs', () => ({ ...jest.requireActual('fs'), chownSync: jest.fn() })); + /* eslint-disable @typescript-eslint/no-require-imports */ const containersRoot = path.join(__dirname, '..', '..', 'containers'); const { @@ -241,8 +243,8 @@ describe('dynamic invocation workspace', () => { const config = () => ({ workDir, - enclaveUid: process.getuid?.() ?? 0, - enclaveGid: process.getgid?.() ?? 0, + enclaveUid: 65534, + enclaveGid: 65534, dynamicEnabled: true, }); From 7918ba035015636f467ac38a36c071399a8ca3f0 Mon Sep 17 00:00:00 2001 From: Landon Cox Date: Sat, 7 Nov 2026 07:03:20 -0800 Subject: [PATCH 05/13] Potential fix for pull request finding Co-authored-by: Copilot Autofix powered by AI <62310815+github-advanced-security[bot]@users.noreply.github.com> --- containers/enclave/agent-executor/agent-provider-environment.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/containers/enclave/agent-executor/agent-provider-environment.js b/containers/enclave/agent-executor/agent-provider-environment.js index a455ae410..468750bdc 100644 --- a/containers/enclave/agent-executor/agent-provider-environment.js +++ b/containers/enclave/agent-executor/agent-provider-environment.js @@ -32,7 +32,7 @@ function agentProviderEnvironment(engine, endpoint, model, directory, budgetToke CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC: '1', DISABLE_AUTOUPDATER: '1', // Fixed AWF policy: shell diagnostics and /awf/out writes remain inside the outer sandbox. - AWF_ENCLAVE_AGENT_CLAUDE_PERMISSION_PROMPTS: 'none', + AWF_ENCLAVE_AGENT_CLAUDE_PERMISSION_PROMPTS: 'standard', AWF_ENCLAVE_AGENT_CLAUDE_ALLOWED_TOOLS: 'Bash,Read,Write,Edit,Glob,Grep', }; default: From 5b8261aea268015b301e08df2c27fa58fafac98e Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Sat, 7 Nov 2026 15:13:43 +0000 Subject: [PATCH 06/13] fix: enforce Claude enclave credential boundary --- containers/enclave/agent-entrypoint.py | 4 +++- .../agent-executor/agent-provider-environment.js | 2 +- .../enclave/agent-executor/enclave-runner-spec.js | 3 +++ .../enclave/agent-executor/session-diagnostics.js | 4 ---- scripts/ci/collect-enclave-smoke-debug.cjs | 4 ---- src/enclave/agent-entrypoint-diagnostics.test.ts | 2 ++ src/enclave/agent-runner-spec.test.ts | 11 +++++++++++ 7 files changed, 20 insertions(+), 10 deletions(-) diff --git a/containers/enclave/agent-entrypoint.py b/containers/enclave/agent-entrypoint.py index c471fce1d..a8b3bac0c 100644 --- a/containers/enclave/agent-entrypoint.py +++ b/containers/enclave/agent-entrypoint.py @@ -768,7 +768,9 @@ def is_dynamic_enabled() -> bool: def configure_github_mcp() -> None: if os.environ.get("AWF_ENCLAVE_AGENT_ENGINE", "copilot") != "copilot" \ and (is_dynamic_enabled() - or os.environ.get("AWF_ENCLAVE_AGENT_GITHUB_ENABLED") == "true"): + or os.environ.get("AWF_ENCLAVE_AGENT_GITHUB_ENABLED") == "true" + or os.environ.get("AWF_ENCLAVE_AGENT_GITHUB_AUTH_MODE") + or os.environ.get("AWF_GITHUB_MCP_AUTHORIZATION")): # Engine-specific MCP tool/header semantics must not silently weaken # the existing scoped GitHub contract. raise ValueError("GitHub MCP is currently supported only by Copilot enclaves") diff --git a/containers/enclave/agent-executor/agent-provider-environment.js b/containers/enclave/agent-executor/agent-provider-environment.js index 468750bdc..a455ae410 100644 --- a/containers/enclave/agent-executor/agent-provider-environment.js +++ b/containers/enclave/agent-executor/agent-provider-environment.js @@ -32,7 +32,7 @@ function agentProviderEnvironment(engine, endpoint, model, directory, budgetToke CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC: '1', DISABLE_AUTOUPDATER: '1', // Fixed AWF policy: shell diagnostics and /awf/out writes remain inside the outer sandbox. - AWF_ENCLAVE_AGENT_CLAUDE_PERMISSION_PROMPTS: 'standard', + AWF_ENCLAVE_AGENT_CLAUDE_PERMISSION_PROMPTS: 'none', AWF_ENCLAVE_AGENT_CLAUDE_ALLOWED_TOOLS: 'Bash,Read,Write,Edit,Glob,Grep', }; default: diff --git a/containers/enclave/agent-executor/enclave-runner-spec.js b/containers/enclave/agent-executor/enclave-runner-spec.js index e5ead18f8..fd411a401 100644 --- a/containers/enclave/agent-executor/enclave-runner-spec.js +++ b/containers/enclave/agent-executor/enclave-runner-spec.js @@ -124,6 +124,9 @@ function freezeArray(values) { function deriveEnclaveContainerSpec({ config, runId, invocationId, seedId, runtimeName, launch = true }) { assertTrustedId('runId', runId); assertTrustedId('invocationId', invocationId); + if (launch && config.engine !== 'copilot' && (config.githubEnabled || config.dynamicEnabled)) { + throw new Error('GitHub MCP and dynamic repository admission require the Copilot enclave engine'); + } // A dynamic entry stages no immutable seed at all: the enclave reads live // GitHub through one repository-scoped delegated identity, so there is no // seed id, no seed directory, and no `/awf/seed` mount. diff --git a/containers/enclave/agent-executor/session-diagnostics.js b/containers/enclave/agent-executor/session-diagnostics.js index 05fd815d4..1fb1ced1f 100644 --- a/containers/enclave/agent-executor/session-diagnostics.js +++ b/containers/enclave/agent-executor/session-diagnostics.js @@ -76,10 +76,6 @@ function projectEvent(value) { result.event = 'progress'; result.stage = value.stage; if (typeof value.valid === 'boolean') result.valid = value.valid; - if (['engine-launch-attempt', 'engine-started', 'engine-completed'].includes(value.stage) - && integer(value.attempt) && value.attempt >= 1 && value.attempt <= 3) { - result.attempt = value.attempt; - } if (String(value.stage).startsWith('claude-')) { for (const key of ['shellAvailable', 'toolError', 'resultError', 'stdoutObserved', 'stderrObserved', 'captureTruncated']) { diff --git a/scripts/ci/collect-enclave-smoke-debug.cjs b/scripts/ci/collect-enclave-smoke-debug.cjs index 53ac97dcd..5688a230b 100644 --- a/scripts/ci/collect-enclave-smoke-debug.cjs +++ b/scripts/ci/collect-enclave-smoke-debug.cjs @@ -146,10 +146,6 @@ function projectSessionEvent(value) { result.event = value.event; result.stage = value.stage; if (typeof value.valid === 'boolean') result.valid = value.valid; - if (['engine-launch-attempt', 'engine-started', 'engine-completed'].includes(value.stage) - && count(value.attempt) && value.attempt >= 1 && value.attempt <= 3) { - result.attempt = value.attempt; - } if (value.stage.startsWith('claude-')) { Object.assign(result, fields(value, { ...Object.fromEntries(['shellAvailable', 'toolError', 'resultError', 'stdoutObserved', diff --git a/src/enclave/agent-entrypoint-diagnostics.test.ts b/src/enclave/agent-entrypoint-diagnostics.test.ts index de8cf87d7..68dae17dd 100644 --- a/src/enclave/agent-entrypoint-diagnostics.test.ts +++ b/src/enclave/agent-entrypoint-diagnostics.test.ts @@ -758,6 +758,8 @@ describe('enclave agent protected entrypoint diagnostics', () => { { AWF_ENCLAVE_AGENT_GITHUB_ENABLED: 'true' }, { AWF_ENCLAVE_AGENT_GITHUB_ENABLED: 'true', AWF_ENCLAVE_AGENT_GITHUB_AUTH_MODE: 'scoped-bearer' }, { AWF_ENCLAVE_AGENT_DYNAMIC_ENABLED: 'true' }, + { AWF_ENCLAVE_AGENT_GITHUB_AUTH_MODE: 'scoped-bearer' }, + { AWF_GITHUB_MCP_AUTHORIZATION: 'private-delegated-bearer-sentinel' }, ]; for (const githubEnv of githubModes) { const result = runHarness('model-limits', { ...providerEnv(engine), ...githubEnv }); diff --git a/src/enclave/agent-runner-spec.test.ts b/src/enclave/agent-runner-spec.test.ts index f6ddbfc89..9f765eab1 100644 --- a/src/enclave/agent-runner-spec.test.ts +++ b/src/enclave/agent-runner-spec.test.ts @@ -100,6 +100,17 @@ describe('unified enclave agent runner specification', () => { expect(spec.invocationListArgs).toContain('label=awf.enclave.invocation=0123456789abcdef'); }); + it.each(['claude', 'codex'])('rejects GitHub credential mounts for %s before launch', engine => { + for (const github of [{ githubEnabled: true }, { dynamicEnabled: true }]) { + expect(() => deriveEnclaveContainerSpec({ + config: { ...trustedConfig, engine, ...github }, + runId: 'abcdef1234567890', + invocationId: '0123456789abcdef', + seedId: 'b'.repeat(32), + })).toThrow(/require the Copilot enclave engine/); + } + }); + it('preserves every mandatory single-use isolation control', () => { expect(spec.launchArgs).toEqual(expect.arrayContaining([ '--network', 'awf-enclave-agent', From 4df5b58a36fafef6625051e83a3794dbdd6a5f9c Mon Sep 17 00:00:00 2001 From: Landon Cox Date: Sat, 7 Nov 2026 07:15:06 -0800 Subject: [PATCH 07/13] Potential fix for pull request finding 'CodeQL / Unused local variable' Co-authored-by: Copilot Autofix powered by AI <62310815+github-advanced-security[bot]@users.noreply.github.com> --- containers/enclave/agent-entrypoint.py | 1 - 1 file changed, 1 deletion(-) diff --git a/containers/enclave/agent-entrypoint.py b/containers/enclave/agent-entrypoint.py index a8b3bac0c..b5b28b6f7 100644 --- a/containers/enclave/agent-entrypoint.py +++ b/containers/enclave/agent-entrypoint.py @@ -99,7 +99,6 @@ def append_event(event: dict) -> None: with SESSION_LOG_PATH.open("ab") as handle: operation = "session-log-write" handle.write(encoded) - operation = "session-log-close" except OSError as error: # Do not recurse into the failed transcript writer. sys.stderr.write(json.dumps(os_error_event(error, operation, fatal=False)) + "\n") From c30da19a2e90d6a311bdac7e7e6bd3a63c5c837c Mon Sep 17 00:00:00 2001 From: Landon Cox Date: Sat, 7 Nov 2026 07:41:17 -0800 Subject: [PATCH 08/13] fix: repair enclave CI diagnostics and Claude fixture staging Track transcript close errors explicitly and stage the pinned native Claude executable outside private runner installation paths before dropping the engine identity. Cover symlink resolution, byte preservation, and executable mode in a portable regression test. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- containers/enclave/agent-entrypoint.py | 2 ++ src/enclave/claude-unattended.test.ts | 36 +++++++++++++++++++++++++- 2 files changed, 37 insertions(+), 1 deletion(-) diff --git a/containers/enclave/agent-entrypoint.py b/containers/enclave/agent-entrypoint.py index b5b28b6f7..207489b70 100644 --- a/containers/enclave/agent-entrypoint.py +++ b/containers/enclave/agent-entrypoint.py @@ -99,6 +99,8 @@ def append_event(event: dict) -> None: with SESSION_LOG_PATH.open("ab") as handle: operation = "session-log-write" handle.write(encoded) + operation = "session-log-close" + handle.close() except OSError as error: # Do not recurse into the failed transcript writer. sys.stderr.write(json.dumps(os_error_event(error, operation, fatal=False)) + "\n") diff --git a/src/enclave/claude-unattended.test.ts b/src/enclave/claude-unattended.test.ts index 648253ade..63422488f 100644 --- a/src/enclave/claude-unattended.test.ts +++ b/src/enclave/claude-unattended.test.ts @@ -33,6 +33,37 @@ function containerEnvironment(root: string): Record { const binary = process.env.AWF_TEST_CLAUDE_BIN; const pinnedTest = binary ? it : it.skip; const entrypoint = path.resolve(__dirname, '../../containers/enclave/agent-entrypoint.py'); + +function stageClaudeBinary(source: string, root: string): string { + const stagedBinary = path.join(root, 'claude'); + fs.copyFileSync(source, stagedBinary); + fs.chmodSync(stagedBinary, 0o555); + return stagedBinary; +} + +it('stages a regular executable outside a private CLI install, following its binary symlink', () => { + const root = fs.mkdtempSync(path.join(os.tmpdir(), 'awf-claude-staging-')); + try { + fs.chmodSync(root, 0o755); + const install = path.join(root, 'private-install'); + fs.mkdirSync(install, { mode: 0o700 }); + const executable = path.join(install, 'native'); + const contents = Buffer.from('fixture executable'); + fs.writeFileSync(executable, contents, { mode: 0o755 }); + const symlink = path.join(install, 'claude'); + fs.symlinkSync(executable, symlink); + const stagedBinary = stageClaudeBinary(symlink, root); + expect(fs.statSync(install).mode & 0o001).toBe(0); + expect(path.dirname(stagedBinary)).toBe(root); + expect(fs.statSync(root).mode & 0o001).toBe(0o001); + expect(fs.lstatSync(stagedBinary).isFile()).toBe(true); + expect(fs.statSync(stagedBinary).mode & 0o777).toBe(0o555); + expect(fs.readFileSync(stagedBinary)).toEqual(contents); + } finally { + fs.rmSync(root, { recursive: true, force: true }); + } +}); + pinnedTest('uses the pinned enclave Claude CLI version', () => { const result = spawnSync(binary!, ['--version'], { env: { PATH: '/usr/bin:/bin' }, encoding: 'utf8', timeout: 5000, @@ -184,6 +215,7 @@ finally: result["requests"] = requests result["output"] = module.OUT_PATH.read_text() if module.OUT_PATH.exists() else "" events = list(map(json.loads, module.SESSION_LOG_PATH.read_text().splitlines())) +assert any(event.get("event") == "engine-result" for event in events), json.dumps(events) result["stages"] = [event["stage"] for event in events if event.get("event") == "progress"] result["nativeExit"] = next(event["exitCode"] for event in events if event["event"] == "engine-result") result["startupFailures"] = [event["classification"] for event in events @@ -225,6 +257,8 @@ pinnedTest.each([ const stagedEntrypoint = path.join(root, 'entrypoint.py'); fs.copyFileSync(entrypoint, stagedEntrypoint); fs.chmodSync(stagedEntrypoint, 0o444); + // Keep the dropped engine independent of permissions on the CLI install's parent directories. + const stagedBinary = stageClaudeBinary(binary!, root); fs.mkdirSync(path.join(root, 'runtime')); fs.mkdirSync(path.join(root, 'output')); fs.mkdirSync(path.join(root, 'seed'), { mode: 0o555 }); @@ -242,7 +276,7 @@ pinnedTest.each([ + ' && exec setpriv --no-new-privs python3 -c "$1"', 'fixture', fixture, root], { env: { PATH: '/usr/bin:/bin:/usr/local/bin', ENTRYPOINT: stagedEntrypoint, - FIXTURE_ROOT: root, CLAUDE_BIN: binary!, DENY_TOOLS: String(denied), OUTPUT_FAILURE: String(outputFailure), + FIXTURE_ROOT: root, CLAUDE_BIN: stagedBinary, DENY_TOOLS: String(denied), OUTPUT_FAILURE: String(outputFailure), LEGACY_ARGV: String(legacy), NODE_BIN: path.dirname(process.execPath), CONTAINER_ENVIRONMENT: JSON.stringify(containerEnvironment(root)) }, From 033404ed1011dba47c33222f574441b7e9d0662b Mon Sep 17 00:00:00 2001 From: Landon Cox Date: Sat, 7 Nov 2026 07:42:49 -0800 Subject: [PATCH 09/13] Potential fix for pull request finding Co-authored-by: Copilot Autofix powered by AI <62310815+github-advanced-security[bot]@users.noreply.github.com> --- containers/enclave/agent-executor/agent-provider-environment.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/containers/enclave/agent-executor/agent-provider-environment.js b/containers/enclave/agent-executor/agent-provider-environment.js index a455ae410..8db7dc01b 100644 --- a/containers/enclave/agent-executor/agent-provider-environment.js +++ b/containers/enclave/agent-executor/agent-provider-environment.js @@ -33,7 +33,7 @@ function agentProviderEnvironment(engine, endpoint, model, directory, budgetToke DISABLE_AUTOUPDATER: '1', // Fixed AWF policy: shell diagnostics and /awf/out writes remain inside the outer sandbox. AWF_ENCLAVE_AGENT_CLAUDE_PERMISSION_PROMPTS: 'none', - AWF_ENCLAVE_AGENT_CLAUDE_ALLOWED_TOOLS: 'Bash,Read,Write,Edit,Glob,Grep', + AWF_ENCLAVE_AGENT_CLAUDE_ALLOWED_TOOLS: 'Read,Glob,Grep', }; default: throw new Error('Unsupported enclave agent engine'); From eb219ea516083dcaf97d063f4a0bac80f088a79f Mon Sep 17 00:00:00 2001 From: Landon Cox Date: Sat, 7 Nov 2026 07:48:40 -0800 Subject: [PATCH 10/13] Potential fix for pull request finding Co-authored-by: Copilot Autofix powered by AI <62310815+github-advanced-security[bot]@users.noreply.github.com> --- src/enclave/claude-unattended.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/enclave/claude-unattended.test.ts b/src/enclave/claude-unattended.test.ts index 63422488f..faeb0f2d7 100644 --- a/src/enclave/claude-unattended.test.ts +++ b/src/enclave/claude-unattended.test.ts @@ -242,7 +242,7 @@ print(json.dumps(module.build_engine_command("claude", "trusted-model", "task", expect({ status: result.status, stderr: result.stderr }).toEqual({ status: 0, stderr: '' }); expect(JSON.parse(result.stdout)).toEqual(expect.arrayContaining([ '--permission-mode', 'default', '--permission-prompts', 'none', - '--allowedTools', 'Bash,Read,Write,Edit,Glob,Grep', + '--allowedTools', 'Read,Glob,Grep', ])); }); From 955ca4571b9c25f4f0542952f08cd73f58ea3661 Mon Sep 17 00:00:00 2001 From: Landon Cox Date: Sat, 7 Nov 2026 08:00:49 -0800 Subject: [PATCH 11/13] fix: resolve enclave CodeQL findings and restore Claude policy Use one descriptor for staged executable checks and reads. Keep ownership operations separate from the generic resource-returning I/O wrapper, preserving redacted errors and exception propagation. Restore the explicitly selected fixed sandboxed Claude tool policy after autofix removed required shell and output tools. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- containers/enclave/agent-entrypoint.py | 19 ++++++---- .../agent-provider-environment.js | 2 +- .../agent-entrypoint-diagnostics.test.ts | 38 +++++++++++++++++++ src/enclave/claude-unattended.test.ts | 14 +++++-- 4 files changed, 61 insertions(+), 12 deletions(-) diff --git a/containers/enclave/agent-entrypoint.py b/containers/enclave/agent-entrypoint.py index 207489b70..626f17978 100644 --- a/containers/enclave/agent-entrypoint.py +++ b/containers/enclave/agent-entrypoint.py @@ -139,6 +139,14 @@ def file_operation(operation: str, action, *, fatal: bool = True): raise +def chown_runtime_path(path: Path, operation: str) -> None: + try: + os.chown(path, *agent_identity()) + except OSError as error: + safe_os_error(error, operation) + raise + + @contextmanager def managed_file(handle, operation: str, *, fatal: bool = True): pending_error = False @@ -808,7 +816,7 @@ def configure_github_mcp() -> None: write_file(GITHUB_MCP_CONFIG_PATH, json.dumps(config, separators=(",", ":")), "github-mcp-config-write") file_operation("github-mcp-config-chmod", lambda: GITHUB_MCP_CONFIG_PATH.chmod(0o600)) if os.geteuid() == 0: - file_operation("github-mcp-config-chown", lambda: os.chown(GITHUB_MCP_CONFIG_PATH, *agent_identity())) + chown_runtime_path(GITHUB_MCP_CONFIG_PATH, "github-mcp-config-chown") def configure_scoped_github_mcp() -> None: @@ -840,7 +848,7 @@ def configure_scoped_github_mcp() -> None: write_file(GITHUB_MCP_CONFIG_PATH, json.dumps(config, separators=(",", ":")), "github-mcp-config-write") file_operation("github-mcp-config-chmod", lambda: GITHUB_MCP_CONFIG_PATH.chmod(0o600)) if os.geteuid() == 0: - file_operation("github-mcp-config-chown", lambda: os.chown(GITHUB_MCP_CONFIG_PATH, *agent_identity())) + chown_runtime_path(GITHUB_MCP_CONFIG_PATH, "github-mcp-config-chown") def configure_dynamic_github_mcp() -> None: @@ -874,7 +882,7 @@ def configure_dynamic_github_mcp() -> None: write_file(GITHUB_MCP_CONFIG_PATH, json.dumps(config, separators=(",", ":")), "github-mcp-config-write") file_operation("github-mcp-config-chmod", lambda: GITHUB_MCP_CONFIG_PATH.chmod(0o600)) if os.geteuid() == 0: - file_operation("github-mcp-config-chown", lambda: os.chown(GITHUB_MCP_CONFIG_PATH, *agent_identity())) + chown_runtime_path(GITHUB_MCP_CONFIG_PATH, "github-mcp-config-chown") def append_engine_result(completed: subprocess.CompletedProcess) -> tuple[str, str]: @@ -1201,10 +1209,7 @@ def main() -> int: try: path.mkdir(mode=0o700, exist_ok=True) if os.geteuid() == 0: - file_operation( - f"runtime-path-ownership-{identifier}", - lambda: os.chown(path, *agent_identity()), - ) + chown_runtime_path(path, f"runtime-path-ownership-{identifier}") except OSError as error: safe_os_error(error, f"runtime-path-creation-{identifier}") append_event({"event": "failure", "category": "engine-failed"}) diff --git a/containers/enclave/agent-executor/agent-provider-environment.js b/containers/enclave/agent-executor/agent-provider-environment.js index 8db7dc01b..a455ae410 100644 --- a/containers/enclave/agent-executor/agent-provider-environment.js +++ b/containers/enclave/agent-executor/agent-provider-environment.js @@ -33,7 +33,7 @@ function agentProviderEnvironment(engine, endpoint, model, directory, budgetToke DISABLE_AUTOUPDATER: '1', // Fixed AWF policy: shell diagnostics and /awf/out writes remain inside the outer sandbox. AWF_ENCLAVE_AGENT_CLAUDE_PERMISSION_PROMPTS: 'none', - AWF_ENCLAVE_AGENT_CLAUDE_ALLOWED_TOOLS: 'Read,Glob,Grep', + AWF_ENCLAVE_AGENT_CLAUDE_ALLOWED_TOOLS: 'Bash,Read,Write,Edit,Glob,Grep', }; default: throw new Error('Unsupported enclave agent engine'); diff --git a/src/enclave/agent-entrypoint-diagnostics.test.ts b/src/enclave/agent-entrypoint-diagnostics.test.ts index 68dae17dd..2474e4b7b 100644 --- a/src/enclave/agent-entrypoint-diagnostics.test.ts +++ b/src/enclave/agent-entrypoint-diagnostics.test.ts @@ -1195,6 +1195,44 @@ describe('enclave agent protected entrypoint diagnostics', () => { expect(result.transcript).not.toContain('"result":"true"'); }); + it.each(['github-mcp-config-chown', 'runtime-path-ownership-home-directory'])( + 'preserves ownership-operation diagnostics for %s without returning a resource', + operation => { + const result = spawnSync('python3', ['-c', String.raw` +import errno, importlib.util, io, json, os +from pathlib import Path +spec = importlib.util.spec_from_file_location("entrypoint", os.environ["ENTRYPOINT"]) +module = importlib.util.module_from_spec(spec) +spec.loader.exec_module(module) +module.agent_identity = lambda: (65534, 65534) +calls = [] +module.os.chown = lambda path, uid, gid: calls.append([str(path), uid, gid]) +result = module.chown_runtime_path(Path("/fixture"), os.environ["OPERATION"]) +captured = io.StringIO() +module.append_event = lambda event: captured.write(json.dumps(event)) +def fail(*args): + raise OSError(errno.EACCES, "private error detail", "/private/path") +module.os.chown = fail +try: + module.chown_runtime_path(Path("/fixture"), os.environ["OPERATION"]) +except OSError as error: + failure = error.errno +print(json.dumps({"result": result, "calls": calls, "failure": failure, + "transcript": captured.getvalue()})) +`], { + env: { PATH: process.env.PATH, ENTRYPOINT: entrypoint, OPERATION: operation }, + encoding: 'utf8', + }); + expect({ status: result.status, stderr: result.stderr }).toEqual({ status: 0, stderr: '' }); + const observed = JSON.parse(result.stdout); + expect(observed).toMatchObject({ result: null, calls: [['/fixture', 65534, 65534]], failure: 13 }); + expect(JSON.parse(observed.transcript)).toMatchObject({ + event: 'operation-error', operation, category: 'permission-denied', errno: 13, fatal: true, + }); + expect(observed.transcript).not.toContain('private'); + }, + ); + it.each(['stat', 'open', 'write', 'close'])( 'reports session-log %s failures through safe stderr without recursion', operation => { diff --git a/src/enclave/claude-unattended.test.ts b/src/enclave/claude-unattended.test.ts index faeb0f2d7..d23eb66ae 100644 --- a/src/enclave/claude-unattended.test.ts +++ b/src/enclave/claude-unattended.test.ts @@ -56,9 +56,15 @@ it('stages a regular executable outside a private CLI install, following its bin expect(fs.statSync(install).mode & 0o001).toBe(0); expect(path.dirname(stagedBinary)).toBe(root); expect(fs.statSync(root).mode & 0o001).toBe(0o001); - expect(fs.lstatSync(stagedBinary).isFile()).toBe(true); - expect(fs.statSync(stagedBinary).mode & 0o777).toBe(0o555); - expect(fs.readFileSync(stagedBinary)).toEqual(contents); + const descriptor = fs.openSync(stagedBinary, fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW); + try { + const metadata = fs.fstatSync(descriptor); + expect(metadata.isFile()).toBe(true); + expect(metadata.mode & 0o777).toBe(0o555); + expect(fs.readFileSync(descriptor)).toEqual(contents); + } finally { + fs.closeSync(descriptor); + } } finally { fs.rmSync(root, { recursive: true, force: true }); } @@ -242,7 +248,7 @@ print(json.dumps(module.build_engine_command("claude", "trusted-model", "task", expect({ status: result.status, stderr: result.stderr }).toEqual({ status: 0, stderr: '' }); expect(JSON.parse(result.stdout)).toEqual(expect.arrayContaining([ '--permission-mode', 'default', '--permission-prompts', 'none', - '--allowedTools', 'Read,Glob,Grep', + '--allowedTools', 'Bash,Read,Write,Edit,Glob,Grep', ])); }); From 43aaf578dcc6a3aae114d6dbb75713697adf4a17 Mon Sep 17 00:00:00 2001 From: Landon Cox Date: Sat, 7 Nov 2026 08:03:38 -0800 Subject: [PATCH 12/13] Potential fix for pull request finding 'CodeQL / File is not always closed' Co-authored-by: Copilot Autofix powered by AI <62310815+github-advanced-security[bot]@users.noreply.github.com> --- containers/enclave/agent-entrypoint.py | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/containers/enclave/agent-entrypoint.py b/containers/enclave/agent-entrypoint.py index 626f17978..e8c07e866 100644 --- a/containers/enclave/agent-entrypoint.py +++ b/containers/enclave/agent-entrypoint.py @@ -165,9 +165,12 @@ def managed_file(handle, operation: str, *, fatal: bool = True): @contextmanager def diagnostic_file(path: Path, operation: str, mode: str, *, fatal: bool = True): - handle = file_operation(f"{operation}-open", lambda: path.open(mode), fatal=fatal) - with managed_file(handle, operation, fatal=fatal) as opened: - yield opened + try: + with path.open(mode) as opened: + yield opened + except OSError as error: + safe_os_error(error, f"{operation}-open", fatal=fatal) + raise def read_file(path: Path, operation: str, *, limit: int = -1, fatal: bool = True) -> bytes: From c5a5294ed364d36b9c1563b44539d1e93a9e0e35 Mon Sep 17 00:00:00 2001 From: Landon Cox Date: Sat, 7 Nov 2026 08:17:13 -0800 Subject: [PATCH 13/13] fix: restore enclave I/O fault injection after direct-open refactor Route diagnostic fixture faults through the actual path.open boundary. Preserve exact open/close failure classification without relabeling already-reported read/write failures, while retaining direct context-managed file lifetime for CodeQL. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- containers/enclave/agent-entrypoint.py | 12 ++++++++++-- src/enclave/agent-entrypoint-diagnostics.test.ts | 9 +++++++++ 2 files changed, 19 insertions(+), 2 deletions(-) diff --git a/containers/enclave/agent-entrypoint.py b/containers/enclave/agent-entrypoint.py index e8c07e866..86c13933b 100644 --- a/containers/enclave/agent-entrypoint.py +++ b/containers/enclave/agent-entrypoint.py @@ -165,11 +165,19 @@ def managed_file(handle, operation: str, *, fatal: bool = True): @contextmanager def diagnostic_file(path: Path, operation: str, mode: str, *, fatal: bool = True): + phase = f"{operation}-open" + pending_error = False try: with path.open(mode) as opened: - yield opened + phase = f"{operation}-close" + try: + yield opened + except BaseException: + pending_error = True + raise except OSError as error: - safe_os_error(error, f"{operation}-open", fatal=fatal) + if not pending_error: + safe_os_error(error, phase, fatal=fatal) raise diff --git a/src/enclave/agent-entrypoint-diagnostics.test.ts b/src/enclave/agent-entrypoint-diagnostics.test.ts index 2474e4b7b..45520a985 100644 --- a/src/enclave/agent-entrypoint-diagnostics.test.ts +++ b/src/enclave/agent-entrypoint-diagnostics.test.ts @@ -198,6 +198,15 @@ if scenario in ("injected-io", "verify-io"): ) return original_operation(operation, fail, fatal=fatal) module.file_operation = injected_operation + original_diagnostic_file = module.diagnostic_file + def injected_diagnostic_file(path, operation, mode, *, fatal=True): + class OpenPath: + def open(self, requested_mode): + return injected_operation( + f"{operation}-open", lambda: path.open(requested_mode), fatal=fatal, + ) + return original_diagnostic_file(OpenPath(), operation, mode, fatal=fatal) + module.diagnostic_file = injected_diagnostic_file original_engine_result = module.append_engine_result def engine_result(completed):