diff --git a/docs/hol-guard-before-tool.md b/docs/hol-guard-before-tool.md new file mode 100644 index 0000000..5f71d94 --- /dev/null +++ b/docs/hol-guard-before-tool.md @@ -0,0 +1,109 @@ +# HOL Guard `before_tool` adapter packet + +Status (updated October 28, 2026): HOL-authored adapter proposed for independent review in [Klaat Code PR #68](https://github.com/KlaatAI/klaatcode/pull/68). The PR is open, not merged or released. This document corrects the earlier pre-submission status; it does not claim third-party approval or adoption. + +## Why this maps cleanly + +Klaat Code sends a JSON object to `before_tool` hooks. For a `run_command` call, the relevant fields are: + +- `event`: `before_tool` +- `project_root`: current project root +- `tool_name`: `run_command` +- `tool_args`: the raw JSON argument string passed to the tool + +Klaat Code blocks a tool call when the hook exits with status `2` or writes a JSON object such as: + +```json +{"decision":"block","reason":"..."} +``` + +HOL Guard already has native pre-tool authority for command decisions. The supported native request is a versioned `PreToolUse` envelope whose `tool_input.command` contains the command string. The Rust runtime owns the security decision. The adapter transports and renders that result rather than reimplementing Guard policy in Klaat Code. + +## Proposed adapter behavior + +The proposed PR branch contains the JavaScript adapter `scripts/hol-guard-before-tool.mjs` and a POSIX fail-closed launcher `scripts/hol-guard-before-tool.sh`. For `tool_name == "run_command"` it: + +1. Parses `tool_args` as JSON. +2. Extracts the non-empty `command` string. Missing or malformed command input fails closed. +3. Constructs a Guard `PreToolUse` request with the current project as `cwd`. +4. Sends the complete request through `hol-guard hook --harness codex --json`, with the workspace when available, so Guard's native hook authority remains the decision owner. +5. Requires `hookSpecificOutput.hookEventName` to be `PreToolUse`, then allows an authoritative native `allow` decision or the explicit `native_policy_warning` allow-with-warning result. Missing or mismatched event binding fails closed. +6. Fails closed when native review is unavailable or not ready, including `native_pre_tool_unavailable`, `native_policy_not_ready`, worker/daemon availability failures, unmanaged-harness passthrough, unknown warning results, malformed output, timeout, missing Guard, review, reapproval, sandbox-required, or block. + +The adapter does not use `hol-guard command explain` as enforcement authority. The `--json` response must be one complete JSON object on stdout; a diagnostic prefix, suffix, or multiple verdicts fails closed instead of letting the adapter extract a possibly misleading allow result. + +## Validation completed + +The exact owned branch was downloaded into an independent Linux sandbox and validated with Node 20 and Bun 1.4.2. + +The following checks pass: + +- `node --check scripts/hol-guard-before-tool.mjs` +- `node --test scripts/hol-guard-before-tool.test.mjs`, 7/7 focused tests +- `node --test scripts/hol-guard-before-tool-wrapper.test.mjs`, 4/4 isolated POSIX launcher tests (October 28; not upstream CI) +- `bun install --frozen-lockfile` +- `bun run typecheck` +- `bun run build` + +The focused tests cover command extraction, unrelated hook pass-through, malformed `tool_args`, complete `PreToolUse` envelope construction, authoritative allow and policy-warning handling, unavailable native review, unknown warnings, review/block responses, and malformed/missing-reason responses. + +## Real HOL Guard 3.4.2 availability test + +A clean isolated Python environment installed the published `hol-guard==3.4.2` package successfully. + +With no resident native policy authority initialized, `hol-guard hook --harness codex --json` returned `policy_action: warn`, `permissionDecision: allow`, and `reason_code: native_pre_tool_unavailable` for both a benign command and a destructive command. That response means Guard could not complete the native decision. It is not execution proof. + +The first adapter version treated a generic `warn` plus `permissionDecision: allow` as sufficient and therefore would have allowed that unavailable state. The owned-fork adapter now rejects Guard availability and not-ready reason codes and rejects unknown warning results. Re-running the adapter against the same real 3.4.2 runtime now emits Klaat's block result for both test commands while Guard authority is unavailable. + +This closes the unavailable-runtime fail-open defect seen in the initial test. The [PR description](https://github.com/KlaatAI/klaatcode/pull/68) additionally reports a later isolated HOL Guard 3.4.2 native-runtime test with benign allows and a destructive-command block. That later assertion is a contributor report, not an independent maintainer acceptance or a raw test log reproduced in this document. + +## Independent review and real-runtime validation + +The implementation has already been submitted for independent upstream review in PR #68. A reviewer should reproduce these cases with an isolated managed Guard runtime rather than relying only on contributor-reported results: + +| Case | Expected result | +| --- | --- | +| `pwd` | Klaat Code command proceeds after authoritative Guard allow | +| `git status --short` | Klaat Code command proceeds after authoritative Guard allow | +| `rm -rf /` | Klaat Code command is blocked | +| `shred ~/.ssh/id_ed25519` | Klaat Code command is blocked | +| malformed `tool_args` | fail closed | +| Guard runtime unavailable | fail closed | + +The denial test must verify that the target command was not executed. The PR description reports a sentinel test; the exact runtime transcript is not reproduced in this document. + +An earlier isolated `hol-guard install codex` attempt did not establish authority because Guard rejected the sandbox interpreter as writable by another user. No real user installation was modified. The PR description reports a later successful managed-runtime test; that proof should be independently replayed before merge. + +## Candidate hook configuration + +This is an **unreleased, project-local proposal**, not a component shipped by Klaat Code or HOL Guard. Copy **both** `scripts/hol-guard-before-tool.sh` and `scripts/hol-guard-before-tool.mjs` from the reviewed PR branch into your project's `scripts/` directory. Do not assume these scripts are included in the npm package: Klaat's current `package.json` publishes only its built CLI, README, and license. + +```json +{ + "before_tool": [ + { + "matcher": "run_command", + "command": "sh ./scripts/hol-guard-before-tool.sh", + "timeout": 12 + } + ] +} +``` + +Klaat's current hook runner treats exit status **2** or an explicit JSON block as denial, but ignores other failed shell exits and timeouts. The POSIX launcher therefore converts missing Node, missing adapter, and unexpected adapter failures to exit **2** rather than silently allowing the command. The host timeout is set above the adapter's 9-second Guard deadline so the adapter can return its own block verdict first. + +**Limit:** This does not fix a missing `sh` interpreter, a missing *launcher itself*, or a host timeout before the launcher can report a verdict. Klaat currently fails open in those cases. A separate upstream hook-runner change to fail closed on every nonzero exit, start failure, and timeout would be needed before treating this as a general enforcement boundary. Do not represent the PR as a shipped security guarantee. + +The current upstream README example points at `./scripts/guard-shell.sh`, but that helper is not present in the repository. This PR supplies an opt-in adapter, not a replacement for Klaat's global hook-failure semantics. + +## Acceptance and release gates + +Before merge or release: + +- revalidate the current Klaat Code upstream head, hook payload, block semantics, contribution guidance, and queue ownership; +- revalidate HOL Guard's current native hook entry point; +- keep Klaat Code typecheck/build plus focused adapter tests green; +- prove one authoritative allow path and one authoritative deny path with the real Guard runtime, including target command non-execution on deny; +- get independent Klaat maintainer review and check the current PR branch against the upstream contribution rules. + +Until independent upstream approval/merge and a separate usable release, PR #68 remains a HOL-authored proposal. It is not an externally authored PR, a tagged extension release, or independently measured nonauthor adoption. diff --git a/scripts/hol-guard-before-tool-wrapper.test.mjs b/scripts/hol-guard-before-tool-wrapper.test.mjs new file mode 100644 index 0000000..ad735af --- /dev/null +++ b/scripts/hol-guard-before-tool-wrapper.test.mjs @@ -0,0 +1,56 @@ +import assert from 'node:assert/strict'; +import { spawnSync } from 'node:child_process'; +import { copyFileSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { dirname, join } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import test from 'node:test'; + +const wrapperPath = join(dirname(fileURLToPath(import.meta.url)), 'hol-guard-before-tool.sh'); + +function runWrapper(fakeAdapter) { + const directory = mkdtempSync(join(tmpdir(), 'klaat-guard-wrapper-')); + try { + const wrapper = join(directory, 'hol-guard-before-tool.sh'); + copyFileSync(wrapperPath, wrapper); + if (fakeAdapter !== null) { + writeFileSync(join(directory, 'hol-guard-before-tool.mjs'), fakeAdapter); + } + return spawnSync('sh', [wrapper], { + encoding: 'utf8', + input: JSON.stringify({ event: 'before_tool', tool_name: 'run_command' }), + timeout: 3000, + }); + } finally { + rmSync(directory, { recursive: true, force: true }); + } +} + +const posix = process.platform !== 'win32'; + +test('wrapper preserves authoritative allow with exit 0', { skip: !posix }, () => { + const result = runWrapper('process.exit(0);'); + assert.equal(result.status, 0); + assert.equal(result.stdout.trim(), ''); +}); + +test('wrapper preserves JSON block sent on stdout', { skip: !posix }, () => { + const result = runWrapper('console.log(JSON.stringify({ decision: "block", reason: "denied" }));'); + assert.equal(result.status, 0); + assert.deepEqual(JSON.parse(result.stdout), { decision: 'block', reason: 'denied' }); +}); + +test('wrapper converts adapter runtime failure into Klaat blocking exit 2', { skip: !posix }, () => { + const result = runWrapper('process.exit(7);'); + assert.equal(result.status, 2); + assert.match(result.stderr, /failed \(exit 7\)/); +}); + +test('wrapper converts absent adapter into Klaat blocking exit 2', { skip: !posix }, () => { + const result = runWrapper(null); + assert.equal(result.status, 2); + assert.match(result.stderr, /failed \(exit /); +}); + +// The host's hook timeout must exceed the adapter's own 9-second deadline. +// These tests cover shell exit behavior, not integration with a managed Guard runtime. diff --git a/scripts/hol-guard-before-tool.mjs b/scripts/hol-guard-before-tool.mjs new file mode 100644 index 0000000..143208c --- /dev/null +++ b/scripts/hol-guard-before-tool.mjs @@ -0,0 +1,345 @@ +#!/usr/bin/env node +import { spawnSync } from 'node:child_process'; +import { realpathSync } from 'node:fs'; +import { TextDecoder } from 'node:util'; +import { delimiter, isAbsolute, relative, resolve, sep } from 'node:path'; +import { pathToFileURL } from 'node:url'; +import process from 'node:process'; + +const MAX_STDIN_BYTES = 1_000_000; +const GUARD_TIMEOUT_MS = 9_000; + +// The hook switches cwd to the tool directory. Relative PATH entries would +// then resolve there and could select a different, project-local hol-guard. +// Only absolute search directories may be used for Guard's executable lookup. +export function trustedGuardPath(pathValue, untrustedRoots = []) { + if (typeof pathValue !== 'string') return ''; + // The project can put a forged hol-guard binary on an *absolute* PATH too. + // Resolve links and reject project-owned bin directories before spawning. + const roots = untrustedRoots.filter((root) => typeof root === 'string' && isAbsolute(root)) + .map((root) => { + try { return realpathSync(root); } catch { return resolve(root); } + }); + return pathValue.split(delimiter) + .map((entry) => { + if (!entry || !isAbsolute(entry)) return null; + if (!roots.length) return entry; + let directory; + try { directory = realpathSync(entry); } catch { return null; } + const outsideRoots = (candidate) => roots.every((root) => { + const rel = relative(root, candidate); + return rel !== '' && + (rel === '..' || rel.startsWith(`..${sep}`) || isAbsolute(rel)); + }); + // Reject a project-owned executable hidden behind a globally located + // PATH symlink. Filtering only directory links would still run the shim. + if (!outsideRoots(entry) || !outsideRoots(directory)) return null; + for (const name of ['hol-guard', 'hol-guard.exe']) { + const executable = resolve(directory, name); + try { + const target = realpathSync(executable); + if (!outsideRoots(executable) || !outsideRoots(target)) return null; + } catch (error) { + // A missing executable lets spawn search later PATH entries. + // Other lookup failures cannot establish a trusted executable. + if (error?.code !== 'ENOENT') return null; + } + } + return directory; + }) + .filter((entry) => entry !== null) + .join(delimiter); +} + +const NON_AUTHORITATIVE_REASON_CODES = new Set([ + 'native_hook_disabled', + 'native_shadow_diagnostic_disabled', + 'native_policy_not_ready', + 'native_hook_event_unavailable', + 'native_pre_tool_unavailable', + 'native_post_tool_unavailable', + 'native_overloaded', + 'native_hook_worker_unavailable', + 'native_hook_worker_unavailable_before_compatibility', + 'native_hook_worker_unsupported', + 'native_hook_worker_exception', + 'native_hook_compatibility_disabled', + 'native_hook_edge_invalid_response', + 'native_hook_edge_unavailable', + 'python_hook_oracle_unavailable', + 'python_oracle_exception', + 'watch_recording_only', + 'daemon_hook_queue_capacity', + 'daemon_hook_deadline_exhausted', + 'daemon_hook_process_deadline_exhausted', + 'daemon_hook_process_not_ready', + 'daemon_hook_process_failed', + 'daemon_hook_process_invalid_request', + 'daemon_hook_process_guard_home_mismatch', + 'daemon_worker_exception', + 'harness_not_managed', + 'native_degraded_emergency_safe', +]); + +function block(reason) { + const message = typeof reason === 'string' && reason.trim() + ? reason.trim() + : 'HOL Guard did not return an authoritative allow decision.'; + process.stdout.write(`${JSON.stringify({ decision: 'block', reason: message })}\n`); +} + +export function extractKlaatCommand(payload) { + if (!payload || typeof payload !== 'object' || Array.isArray(payload)) { + throw new Error('invalid Klaat hook payload'); + } + // An invalid event or unnamed pre-tool action is not proof that the + // pending action is unrelated to run_command. Fail closed before dispatch. + if (typeof payload.event !== 'string' || !payload.event.trim()) { + throw new Error('Klaat hook event is missing'); + } + if (payload.event !== 'before_tool') return null; + if (typeof payload.tool_name !== 'string' || !payload.tool_name.trim()) { + throw new Error('before_tool identity is missing'); + } + if (payload.tool_name !== 'run_command') return null; + if (typeof payload.tool_args !== 'string') { + throw new Error('run_command tool_args must be a JSON string'); + } + let args; + try { + args = JSON.parse(payload.tool_args); + } catch { + throw new Error('run_command tool_args is not valid JSON'); + } + if (!args || typeof args !== 'object' || typeof args.command !== 'string' || !args.command.trim()) { + throw new Error('run_command command is missing'); + } + return args.command; +} + +export function resolveKlaatCommandCwd(payload) { + const root = payload?.project_root; + if (typeof root !== 'string' || !root.trim() || !isAbsolute(root)) { + throw new Error('run_command project_root must be an absolute path'); + } + let workdir; + if (typeof payload.tool_args === 'string') { + const parsed = JSON.parse(payload.tool_args); + workdir = parsed?.workdir; + } + if (workdir === undefined || workdir === null || workdir === '') return root; + if (typeof workdir !== 'string') { + throw new Error('run_command workdir must be a string'); + } + // Match Klaat's runCommand/safeResolve logic, including tilde paths. + if (workdir.startsWith('/') || workdir.startsWith('~')) { + const expanded = workdir.replace(/^~/, process.env.HOME ?? '~'); + if (!isAbsolute(expanded)) { + throw new Error('run_command effective workdir must be an absolute path'); + } + return expanded; + } + return resolve(root, workdir); +} + +export function buildGuardPayload(payload, command) { + const guardPayload = { + hook_event_name: 'PreToolUse', + tool_name: 'Bash', + tool_input: { command }, + // Guard must inspect from the same directory as run_command executes. + cwd: resolveKlaatCommandCwd(payload), + }; + if (typeof payload.session_id === 'string' && payload.session_id) { + guardPayload.session_id = payload.session_id; + } + return guardPayload; +} + +// Standard JSON.parse keeps the last repeated field. Refuse duplicate keys +// before an allow-shaped response can erase an earlier deny or review. +function containsDuplicateGuardKeys(raw) { + const frames = []; + for (let i = 0; i < raw.length;) { + const char = raw[i]; + if (char === '"') { + const start = i++; + while (i < raw.length) { + if (raw[i] === "\\") { + i += 2; + continue; + } + if (raw[i++] === '"') break; + } + const frame = frames[frames.length - 1]; + if (frame?.isObject && frame.expectKey) { + const key = JSON.parse(raw.slice(start, i)); + if (frame.keys.has(key)) return true; + frame.keys.add(key); + frame.expectKey = false; + } + continue; + } + if (char === '{') frames.push({ isObject: true, expectKey: true, keys: new Set() }); + else if (char === '[') frames.push({ isObject: false }); + else if (char === '}' || char === ']') frames.pop(); + else if (char === ',' && frames[frames.length - 1]?.isObject) { + frames[frames.length - 1].expectKey = true; + } + i++; + } + return false; +} + +export function parseGuardJson(stdout) { + const text = typeof stdout === 'string' ? stdout.trim() : ''; + if (!text) return null; + try { + if (containsDuplicateGuardKeys(text)) return null; + const parsed = JSON.parse(text); + return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : null; + } catch { + // A diagnostic line or second verdict cannot authorize execution. + return null; + } +} + +// Node's default UTF-8 decoding replaces invalid bytes, which could turn a +// malformed native verdict into valid allow-shaped JSON. Reject the bytes. +export function parseGuardBytes(bytes) { + if (!Buffer.isBuffer(bytes)) return null; + try { + return parseGuardJson(new TextDecoder('utf-8', { fatal: true }).decode(bytes)); + } catch { + return null; + } +} + +export function decisionFromGuardResponse(response) { + if (!response || typeof response !== 'object' || Array.isArray(response)) { + return { allow: false, reason: 'HOL Guard returned an invalid response.' }; + } + const hookSpecific = response.hookSpecificOutput; + // Only a concrete PreToolUse verdict is an authorization for this hook. + // A missing event name must fail closed just like a mismatched event. + if (!hookSpecific || typeof hookSpecific !== 'object' || + Array.isArray(hookSpecific) || hookSpecific.hookEventName !== 'PreToolUse') { + return { allow: false, reason: 'HOL Guard returned no matching PreToolUse event.' }; + } + const permissionDecision = hookSpecific.permissionDecision; + if (('continue' in response && response.continue !== true) || + ('decision' in response && response.decision !== 'allow')) { + return { allow: false, reason: 'HOL Guard refused tool continuation.' }; + } + const policyAction = response.policy_action; + const reasonCode = typeof response.reason_code === 'string' + ? response.reason_code.trim() + : ''; + const reason = + (typeof response.reason === 'string' && response.reason) || + (hookSpecific && typeof hookSpecific === 'object' && + typeof hookSpecific.permissionDecisionReason === 'string' && + hookSpecific.permissionDecisionReason) || + (reasonCode && `HOL Guard blocked this command (${reasonCode}).`) || + 'HOL Guard did not return an authoritative allow decision.'; + + if (permissionDecision !== 'allow' || !reasonCode) { + return { allow: false, reason }; + } + + if (NON_AUTHORITATIVE_REASON_CODES.has(reasonCode)) { + return { allow: false, reason }; + } + + // A superficially allow-shaped response with a destructive/review reason + // must not bypass Guard's native classifier. Unknown reasons fail closed. + const provenAllowReason = reasonCode.startsWith('native_exact_safe_') || + reasonCode === 'native_exact_introspection_command' || + reasonCode === 'native_policy_allow' || reasonCode === 'native_custom_mcp_tool_allow'; + if (policyAction === 'allow' && provenAllowReason) { + return { allow: true, reason: '' }; + } + + if (policyAction === 'warn' && reasonCode === 'native_policy_warning') { + return { allow: true, reason: '' }; + } + + return { allow: false, reason }; +} + +async function readStdin() { + const chunks = []; + let size = 0; + for await (const chunk of process.stdin) { + size += chunk.length; + if (size > MAX_STDIN_BYTES) throw new Error('Klaat hook payload exceeds the size limit'); + chunks.push(chunk); + } + return Buffer.concat(chunks).toString('utf8'); +} + +export async function main() { + let payload; + try { + const input = await readStdin(); + payload = JSON.parse(input); + } catch (error) { + block(error instanceof Error ? error.message : 'invalid Klaat hook payload'); + return; + } + + let command; + let guardPayload; + try { + command = extractKlaatCommand(payload); + if (command !== null) guardPayload = buildGuardPayload(payload, command); + } catch (error) { + block(error instanceof Error ? error.message : 'invalid run_command payload'); + return; + } + if (command === null) return; + + const args = ['hook', '--harness', 'codex']; + if (typeof payload.project_root === 'string' && payload.project_root) { + args.push('--workspace', payload.project_root); + } + args.push('--json'); + + const guardPathKey = Object.keys(process.env).find((key) => key.toUpperCase() === 'PATH'); + const guardPath = trustedGuardPath( + guardPathKey ? process.env[guardPathKey] : '', + [payload.project_root, guardPayload.cwd], + ); + if (!guardPath) { + block('HOL Guard needs an absolute trusted executable search path.'); + return; + } + const guardEnv = { ...process.env }; + for (const key of Object.keys(guardEnv)) { + if (key.toUpperCase() === 'PATH') delete guardEnv[key]; + } + guardEnv.PATH = guardPath; + + const result = spawnSync('hol-guard', args, { + input: `${JSON.stringify(guardPayload)}\n`, + timeout: GUARD_TIMEOUT_MS, + maxBuffer: MAX_STDIN_BYTES, + cwd: guardPayload.cwd, + env: guardEnv, + windowsHide: true, + }); + + if (result.error || result.status !== 0) { + block('HOL Guard could not complete an authoritative command review.'); + return; + } + + const response = parseGuardBytes(result.stdout); + const decision = decisionFromGuardResponse(response); + if (!decision.allow) block(decision.reason); +} + +const invokedPath = process.argv[1] ? pathToFileURL(process.argv[1]).href : ''; +if (import.meta.url === invokedPath) { + await main(); +} diff --git a/scripts/hol-guard-before-tool.sh b/scripts/hol-guard-before-tool.sh new file mode 100644 index 0000000..e3e797c --- /dev/null +++ b/scripts/hol-guard-before-tool.sh @@ -0,0 +1,13 @@ +#!/bin/sh +# Klaat Code treats exit 2 as a blocking before_tool hook error. A missing +# Node executable or adapter must not silently turn a security hook into allow. +script_dir=$(CDPATH= cd "$(dirname "$0")" && pwd) || { + printf '%s\n' 'HOL Guard adapter directory is unavailable.' >&2 + exit 2 +} +node "$script_dir/hol-guard-before-tool.mjs" +status=$? +if [ "$status" -ne 0 ]; then + printf 'HOL Guard adapter failed (exit %s); blocking tool call.\n' "$status" >&2 + exit 2 +fi diff --git a/scripts/hol-guard-before-tool.test.mjs b/scripts/hol-guard-before-tool.test.mjs new file mode 100644 index 0000000..4736f57 --- /dev/null +++ b/scripts/hol-guard-before-tool.test.mjs @@ -0,0 +1,374 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; +import { delimiter, join, resolve } from 'node:path'; +import { mkdtempSync, mkdirSync, realpathSync, rmSync, symlinkSync, writeFileSync, chmodSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { spawnSync } from 'node:child_process'; +import { fileURLToPath } from 'node:url'; +import { + buildGuardPayload, + resolveKlaatCommandCwd, + decisionFromGuardResponse, + extractKlaatCommand, + parseGuardJson, + parseGuardBytes, + trustedGuardPath, +} from './hol-guard-before-tool.mjs'; + +test('extracts run_command command from Klaat tool_args', () => { + assert.equal(extractKlaatCommand({ + event: 'before_tool', + tool_name: 'run_command', + tool_args: JSON.stringify({ command: 'git status --short' }), + }), 'git status --short'); +}); + +test('ignores unrelated hook events defensively', () => { + assert.equal(extractKlaatCommand({ event: 'after_tool', tool_name: 'run_command', tool_args: '{}' }), null); +}); + +test('denies missing event and pre-tool identity instead of bypassing Guard', () => { + for (const payload of [ + null, + [], + {}, + { event: null, tool_name: 'run_command' }, + { event: '', tool_name: 'run_command' }, + { event: 'before_tool' }, + { event: 'before_tool', tool_name: null }, + { event: 'before_tool', tool_name: '' }, + { event: 'before_tool', tool_name: 42 }, + ]) { + assert.throws(() => extractKlaatCommand(payload)); + } + assert.equal(extractKlaatCommand({ + event: 'before_tool', + tool_name: 'read_file', + tool_args: '{}', + }), null); +}); + +test('fails closed on malformed run_command input', () => { + assert.throws(() => extractKlaatCommand({ + event: 'before_tool', + tool_name: 'run_command', + tool_args: '{', + })); +}); + +test('builds complete PreToolUse command envelope', () => { + assert.deepEqual( + buildGuardPayload({ session_id: 's1', project_root: '/repo' }, 'pwd'), + { + hook_event_name: 'PreToolUse', + tool_name: 'Bash', + tool_input: { command: 'pwd' }, + session_id: 's1', + cwd: '/repo', + }, + ); +}); + +test('allows authoritative native allow and policy warning decisions', () => { + assert.equal(decisionFromGuardResponse({ + policy_action: 'allow', + reason_code: 'native_exact_safe_command', + hookSpecificOutput: { hookEventName: 'PreToolUse', permissionDecision: 'allow' }, + }).allow, true); + assert.equal(decisionFromGuardResponse({ + policy_action: 'warn', + reason_code: 'native_policy_warning', + hookSpecificOutput: { hookEventName: 'PreToolUse', permissionDecision: 'allow' }, + }).allow, true); +}); + +test('rejects absent, malformed, and mismatched event envelopes', () => { + for (const hookSpecificOutput of [ + { permissionDecision: 'allow' }, + { hookEventName: 'PostToolUse', permissionDecision: 'allow' }, + null, + [], + ]) { + assert.equal(decisionFromGuardResponse({ + policy_action: 'allow', + reason_code: 'native_policy_allow', + hookSpecificOutput, + }).allow, false); + } +}); + +test('fails closed on unavailable and non-authoritative warn decisions', () => { + for (const reason_code of [ + 'native_pre_tool_unavailable', + 'native_policy_not_ready', + 'native_hook_worker_unavailable', + 'harness_not_managed', + 'future_unknown_warning', + ]) { + assert.equal(decisionFromGuardResponse({ + policy_action: 'warn', + reason_code, + reason: 'Guard did not complete an authoritative review.', + hookSpecificOutput: { hookEventName: 'PreToolUse', permissionDecision: 'allow' }, + }).allow, false, reason_code); + } +}); + +test('blocks review, block, malformed, and missing-reason responses', () => { + for (const response of [ + { policy_action: 'review', reason_code: 'native_command_review_required', hookSpecificOutput: { permissionDecision: 'deny' } }, + { policy_action: 'block', reason_code: 'native_destructive_command', hookSpecificOutput: { permissionDecision: 'deny' } }, + { policy_action: 'allow', hookSpecificOutput: { hookEventName: 'PreToolUse', permissionDecision: 'allow' } }, + {}, + ]) { + assert.equal(decisionFromGuardResponse(response).allow, false); + } +}); + +test('accepts one complete verdict, but never extracts an allow from mixed stdout', () => { + const allowed = '{"policy_action":"allow","reason_code":"native_policy_allow","hookSpecificOutput":{"permissionDecision":"allow"}}'; + const denied = '{"policy_action":"block","reason_code":"policy_block","hookSpecificOutput":{"permissionDecision":"deny"}}'; + assert.equal(parseGuardJson(` \n${allowed}\n `)?.policy_action, 'allow'); + for (const output of [ + `diagnostic\n${allowed}`, + `${allowed}\ndiagnostic`, + `${denied}\n${allowed}`, + `${allowed}\n${denied}`, + `${allowed}\n${allowed}`, + ]) { + assert.equal(parseGuardJson(output), null); + } +}); + +test('rejects repeated authoritative Guard keys, including escaped duplicates', () => { + const contradictory = [ + '{"policy_action":"block","policy_action":"allow","reason_code":"native_policy_allow","hookSpecificOutput":{"hookEventName":"PreToolUse","permissionDecision":"allow"}}', + '{"policy_action":"allow","reason_code":"native_policy_allow","hookSpecificOutput":{"hookEventName":"PreToolUse","permissionDecision":"deny","permissionDecision":"allow"}}', + '{"policy_action":"allow","reason_code":"native_policy_allow","hookSpecificOutput":{"hookEventName":"PreToolUse","permissionDecision":"allow"},"metadata":{"note":"deny","note":"allow"}}', + '{"policy_\\u0061ction":"block","policy_action":"allow","reason_code":"native_policy_allow","hookSpecificOutput":{"hookEventName":"PreToolUse","permissionDecision":"allow"}}', + ]; + for (const output of contradictory) { + assert.equal(parseGuardJson(output), null); + assert.equal(decisionFromGuardResponse(parseGuardJson(output)).allow, false); + } + const valid = '{"notes":["repeated","repeated"],"policy_action":"allow","reason_code":"native_policy_allow","hookSpecificOutput":{"hookEventName":"PreToolUse","permissionDecision":"allow"}}'; + assert.deepEqual(parseGuardJson(valid), JSON.parse(valid)); +}); + +test('rejects invalid UTF-8 native Guard bytes even when decoding would look like allow', () => { + const allowed = JSON.stringify({ + policy_action: 'allow', + reason_code: 'native_policy_allow', + hookSpecificOutput: { hookEventName: 'PreToolUse', permissionDecision: 'allow' }, + diagnostic: 'ok', + }); + const valid = Buffer.from(allowed, 'utf8'); + assert.equal(parseGuardBytes(valid)?.policy_action, 'allow'); + + const marker = allowed.lastIndexOf('ok'); + assert.ok(marker > 0); + const invalid = Buffer.concat([ + Buffer.from(allowed.slice(0, marker), 'utf8'), + Buffer.from([0xff]), + Buffer.from(allowed.slice(marker + 2), 'utf8'), + ]); + // Default Node decoding would replace the invalid byte and still parse an allow. + assert.equal(JSON.parse(invalid.toString('utf8')).policy_action, 'allow'); + assert.equal(parseGuardBytes(invalid), null); + assert.equal(parseGuardBytes(allowed), null); +}); + +test('explicit stop fields override otherwise authoritative allows', () => { + const allowed = { + policy_action: 'allow', + reason_code: 'native_policy_allow', + hookSpecificOutput: { hookEventName: 'PreToolUse', permissionDecision: 'allow' }, + }; + for (const stopped of [ + { continue: false }, + { continue: 'false' }, + { continue: 0 }, + { decision: 'deny' }, + { decision: 'review' }, + { decision: 'block' }, + { decision: 0 }, + ]) { + assert.equal(decisionFromGuardResponse({ ...allowed, ...stopped }).allow, false); + } +}); + + +test('matches the effective run_command workdir for Guard inspection', () => { + const root = '/repo'; + for (const [workdir, expected] of [ + ['nested', resolve(root, 'nested')], + ['/tmp/other-worktree', '/tmp/other-worktree'], + ['', root], + ]) { + const payload = { + session_id: 's1', + project_root: root, + tool_args: JSON.stringify({ command: 'git status', workdir }), + }; + assert.equal(resolveKlaatCommandCwd(payload), expected); + assert.equal(buildGuardPayload(payload, 'git status').cwd, expected); + } +}); + +test('rejects falsey non-string workdirs before Guard inspects a different directory', () => { + for (const workdir of [false, 0]) { + const payload = { + project_root: '/repo', + tool_args: JSON.stringify({ command: 'git status', workdir }), + }; + assert.throws(() => resolveKlaatCommandCwd(payload), /workdir must be a string/); + assert.throws(() => buildGuardPayload(payload, 'git status'), /workdir must be a string/); + } +}); + +test('denies an unknown execution directory instead of inspecting the wrong tree', () => { + assert.throws( + () => resolveKlaatCommandCwd({ tool_args: JSON.stringify({ command: 'git status' }) }), + /project_root/, + ); + assert.throws( + () => resolveKlaatCommandCwd({ + project_root: '/repo', + tool_args: JSON.stringify({ command: 'git status', workdir: ['elsewhere'] }), + }), + /workdir must be a string/, + ); +}); + +test('rejects relative project roots before choosing the Guard workspace', () => { + for (const project_root of ['.', 'relative/repo', '']) { + assert.throws( + () => resolveKlaatCommandCwd({ + project_root, + tool_args: JSON.stringify({ command: 'git status' }), + }), + /project_root must be an absolute path/, + ); + } +}); + + +test('Guard executable search excludes relative and empty PATH entries', () => { + const trustedA = resolve('/usr/local/bin'); + const trustedB = resolve('/opt/guard/bin'); + const original = ['.', trustedA, '', './node_modules/.bin', '../other', trustedB].join(delimiter); + assert.equal(trustedGuardPath(original), [trustedA, trustedB].join(delimiter)); + assert.equal(trustedGuardPath('.'), ''); + assert.equal(trustedGuardPath(undefined), ''); +}); + +test('rejects absolute project PATH entries and symlinks into the project', { + skip: process.platform === 'win32', +}, () => { + const root = mkdtempSync(join(tmpdir(), 'klaat-guard-absolute-path-')); + const project = join(root, 'project'); + const projectBin = join(project, 'bin'); + const trustedBin = join(root, 'trusted-bin'); + const linkedProjectBin = join(root, 'linked-project-bin'); + mkdirSync(projectBin, { recursive: true }); + mkdirSync(trustedBin); + symlinkSync(projectBin, linkedProjectBin, 'dir'); + try { + const options = [projectBin, linkedProjectBin, trustedBin].join(delimiter); + assert.equal(trustedGuardPath(options, [project]), realpathSync(trustedBin)); + assert.equal(trustedGuardPath(projectBin, [project]), ''); + } finally { + rmSync(root, { recursive: true, force: true }); + } +}); + +test('rejects executable symlinks that point into a project', { skip: process.platform === 'win32' }, () => { + const temp = mkdtempSync(join(tmpdir(), 'klaat-guard-executable-link-')); + try { + const project = join(temp, 'project'); + const externalBin = join(temp, 'external-bin'); + mkdirSync(project); + mkdirSync(externalBin); + const projectShim = join(project, 'hol-guard'); + writeFileSync(projectShim, '#!/bin/sh\nexit 0\n'); + chmodSync(projectShim, 0o755); + // Directory is outside the repo, but its executable points into it. + symlinkSync(projectShim, join(externalBin, 'hol-guard')); + assert.equal(trustedGuardPath(externalBin, [project]), ''); + // An actual executable outside the project remains eligible. + rmSync(join(externalBin, 'hol-guard')); + writeFileSync(join(externalBin, 'hol-guard'), '#!/bin/sh\nexit 0\n'); + chmodSync(join(externalBin, 'hol-guard'), 0o755); + assert.equal(trustedGuardPath(externalBin, [project]), realpathSync(externalBin)); + } finally { + rmSync(temp, { recursive: true, force: true }); + } +}); + +test('project-local fake hol-guard cannot shadow a trusted PATH executable', { + skip: process.platform === 'win32', +}, () => { + const root = mkdtempSync(join(tmpdir(), 'klaat-hol-guard-path-')); + const toolDirectory = join(root, 'tool-workspace'); + const trustedDirectory = join(root, 'trusted-bin'); + mkdirSync(toolDirectory); + mkdirSync(trustedDirectory); + try { + const fakeAllow = JSON.stringify({ + policy_action: 'allow', + reason_code: 'native_policy_allow', + hookSpecificOutput: { hookEventName: 'PreToolUse', permissionDecision: 'allow' }, + }); + const realBlock = JSON.stringify({ + policy_action: 'block', + reason_code: 'native_policy_block', + hookSpecificOutput: { hookEventName: 'PreToolUse', permissionDecision: 'deny' }, + }); + const fakePath = join(toolDirectory, 'hol-guard'); + const trustedPath = join(trustedDirectory, 'hol-guard'); + writeFileSync(fakePath, "#!/bin/sh\nprintf '%s\\n' '" + fakeAllow + "'\n"); + writeFileSync(trustedPath, "#!/bin/sh\nprintf '%s\\n' '" + realBlock + "'\n"); + chmodSync(fakePath, 0o755); + chmodSync(trustedPath, 0o755); + const scriptPath = fileURLToPath(new URL('./hol-guard-before-tool.mjs', import.meta.url)); + const result = spawnSync(process.execPath, [scriptPath], { + cwd: root, + env: { ...process.env, PATH: ['.', trustedDirectory, process.env.PATH ?? ''].join(delimiter) }, + input: JSON.stringify({ + event: 'before_tool', + tool_name: 'run_command', + project_root: toolDirectory, + tool_args: JSON.stringify({ command: 'git status' }), + }), + encoding: 'utf8', + timeout: 10_000, + }); + assert.equal(result.status, 0, result.stderr); + assert.equal(JSON.parse(result.stdout.trim()).decision, 'block'); + } finally { + rmSync(root, { recursive: true, force: true }); + } +}); + +test('rejects project-controlled PATH link to trusted Guard directory', { + skip: process.platform === 'win32', +}, () => { + const root = mkdtempSync(join(tmpdir(), 'klaat-guard-link-spoof-')); + const project = join(root, 'project'); + const trusted = join(root, 'trusted-bin'); + const outsideAlias = join(root, 'trusted-alias'); + const worktreeAlias = join(project, 'guard-bin-alias'); + mkdirSync(project); + mkdirSync(trusted); + symlinkSync(trusted, outsideAlias, 'dir'); + symlinkSync(trusted, worktreeAlias, 'dir'); + try { + assert.equal(trustedGuardPath(worktreeAlias, [project]), ''); + const sanitized = trustedGuardPath([worktreeAlias, outsideAlias].join(delimiter), [project]); + // The project can retarget its own link, while trusted aliases resolve to + // fixed canonical directories before spawn. + assert.equal(sanitized, realpathSync(trusted)); + } finally { + rmSync(root, { recursive: true, force: true }); + } +});