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 c9b290736..86c13933b 100644 --- a/containers/enclave/agent-entrypoint.py +++ b/containers/enclave/agent-entrypoint.py @@ -96,22 +96,11 @@ 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" + 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") @@ -124,6 +113,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() @@ -132,26 +139,46 @@ def file_operation(operation: str, action, *, fatal: bool = True): raise -def close_file(handle, operation: str, *, fatal: bool = True) -> None: +def chown_runtime_path(path: Path, operation: str) -> None: try: - handle.close() + os.chown(path, *agent_identity()) except OSError as error: - safe_os_error(error, operation, fatal=fatal) + safe_os_error(error, operation) + raise + + +@contextmanager +def managed_file(handle, operation: str, *, fatal: bool = True): + pending_error = False + try: + with handle: + try: + yield handle + except BaseException: + pending_error = True + raise + except OSError as error: + 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) + phase = f"{operation}-open" + pending_error = False 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: + with path.open(mode) as opened: + phase = f"{operation}-close" + try: + yield opened + except BaseException: + pending_error = True raise + except OSError as error: + if not pending_error: + safe_os_error(error, phase, fatal=fatal) + raise def read_file(path: Path, operation: str, *, limit: int = -1, fatal: bool = True) -> bytes: @@ -457,31 +484,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") @@ -767,7 +788,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") @@ -803,6 +826,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: + chown_runtime_path(GITHUB_MCP_CONFIG_PATH, "github-mcp-config-chown") def configure_scoped_github_mcp() -> None: @@ -833,6 +858,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: + chown_runtime_path(GITHUB_MCP_CONFIG_PATH, "github-mcp-config-chown") def configure_dynamic_github_mcp() -> None: @@ -865,6 +892,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: + chown_runtime_path(GITHUB_MCP_CONFIG_PATH, "github-mcp-config-chown") def append_engine_result(completed: subprocess.CompletedProcess) -> tuple[str, str]: @@ -909,6 +938,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 +956,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 +985,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 +1007,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 +1071,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: @@ -1037,10 +1089,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}": @@ -1167,6 +1219,8 @@ def main() -> int: for identifier, path in runtime_paths: try: path.mkdir(mode=0o700, exist_ok=True) + if os.geteuid() == 0: + 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"}) @@ -1223,6 +1277,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/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/enclave-runner-spec.js b/containers/enclave/agent-executor/enclave-runner-spec.js index 5d2c8ddd6..fd411a401 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. */ @@ -122,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. @@ -161,8 +166,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 +185,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/session-diagnostics.js b/containers/enclave/agent-executor/session-diagnostics.js index ca475fd70..1fb1ced1f 100644 --- a/containers/enclave/agent-executor/session-diagnostics.js +++ b/containers/enclave/agent-executor/session-diagnostics.js @@ -76,8 +76,6 @@ function projectEvent(value) { result.event = 'progress'; result.stage = value.stage; if (typeof value.valid === 'boolean') result.valid = value.valid; - if (value.stage === 'engine-completed' && integer(value.attempt) - && value.attempt > 0 && value.attempt <= 5) result.attempt = value.attempt; if (String(value.stage).startsWith('claude-')) { for (const key of ['shellAvailable', 'toolError', 'resultError', 'stdoutObserved', 'stderrObserved', 'captureTruncated']) { @@ -87,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', @@ -264,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/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 ae288559b..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 @@ -293,6 +300,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 a03252965..5688a230b 100644 --- a/scripts/ci/collect-enclave-smoke-debug.cjs +++ b/scripts/ci/collect-enclave-smoke-debug.cjs @@ -146,14 +146,13 @@ function projectSessionEvent(value) { result.event = value.event; result.stage = value.stage; if (typeof value.valid === 'boolean') result.valid = value.valid; - if (value.stage === 'engine-completed' && count(value.attempt) - && value.attempt > 0 && value.attempt <= 5) result.attempt = value.attempt; if (value.stage.startsWith('claude-')) { Object.assign(result, fields(value, { ...Object.fromEntries(['shellAvailable', 'toolError', 'resultError', 'stdoutObserved', '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') { @@ -211,6 +210,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 804073a1d..de2e15e9d 100644 --- a/scripts/ci/collect-enclave-smoke-debug.test.ts +++ b/scripts/ci/collect-enclave-smoke-debug.test.ts @@ -319,6 +319,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', @@ -347,7 +383,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/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/cloud-hypervisor/host-enclave-executor.test.ts b/src/cloud-hypervisor/host-enclave-executor.test.ts index 9a0aeb3fb..4e19fd46e 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 4624d2e93..45520a985 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,15 @@ 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_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): @@ -258,12 +276,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 +488,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 +665,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); @@ -676,6 +767,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 }); @@ -1111,6 +1204,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/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-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/agent-runner-spec.test.ts b/src/enclave/agent-runner-spec.test.ts index c15cbeaa1..9f765eab1 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 { @@ -98,12 +100,27 @@ 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', '--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 +131,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 +397,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..606f393a2 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,28 @@ 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('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 ffc10c301..d23eb66ae 100644 --- a/src/enclave/claude-unattended.test.ts +++ b/src/enclave/claude-unattended.test.ts @@ -33,6 +33,50 @@ 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); + 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 }); + } +}); + +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 @@ -44,13 +88,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" @@ -59,22 +105,35 @@ 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 = [] +output_failure = os.environ.get("OUTPUT_FAILURE") == "true" class Provider(http.server.BaseHTTPRequestHandler): def log_message(self, *args): pass @@ -87,14 +146,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 = { @@ -128,12 +191,10 @@ 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("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: @@ -160,10 +221,14 @@ 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 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,38 +247,44 @@ 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'); 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 }); 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,NODE_BIN', 'unshare', '--net', '--mount', '--pid', '--fork', '--kill-child', '--mount-proc', '/bin/sh', '-c', '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!, ALLOW_TOOLS: String(approved), + 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)) }, encoding: 'utf8', timeout: 20_000, }); @@ -228,15 +299,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]); } 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/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, }); 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) {