Repository navigation
Port sandboxed threat detection and eligibility checks to JavaScript #80582
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
davidslater
wants to merge
8
commits into
main
Choose a base branch
from
davidslater-miniature-parakeet
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+2,532
−0
Open
Changes from 3 commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
ef5a50f
Port sandboxed threat detection and binding eligibility to JavaScript
davidslater 42ac570
Merge branch 'main' into davidslater-miniature-parakeet
davidslater cf6eaf0
Restrict detector engine permissions to reporting needs
davidslater 99c7080
Harden detector evidence, launch permissions and process ownership
davidslater 9a4abe8
Merge branch 'main' into davidslater-miniature-parakeet
davidslater a8b5263
Confine detector writes and keep private engine output out of logs
davidslater 67b347a
Require framework markers before labeling a prompt preamble trusted
davidslater a6043b5
Merge branch 'main' into davidslater-miniature-parakeet
davidslater File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,188 @@ | ||
| // Sandboxed producer; conclude_threat_detection.cjs is the host-side consumer. | ||
| const fs = require("node:fs"); | ||
| const os = require("node:os"); | ||
| const path = require("node:path"); | ||
| const { randomUUID } = require("node:crypto"); | ||
| const { parseArgs } = require("node:util"); | ||
| const { prepareAssessment } = require("./threat_assessment.cjs"); | ||
| const { runHarness } = require("./threat_harness.cjs"); | ||
| const { readSink, publishableResult } = require("./threat_report.cjs"); | ||
|
|
||
| function diagnostic(text) { | ||
| const line = String(text) | ||
| .replace(/[\p{Cc}\u2028\u2029]/gu, " ") | ||
| .replaceAll("::", ":\\:") | ||
| .replaceAll("##[", "##\\["); | ||
| process.stderr.write(`[threat-detect] ${line}\n`); | ||
| } | ||
|
|
||
| function intOption(value, fallback) { | ||
| if (value === undefined) return fallback; | ||
| if (!/^\+?\d+$/.test(value) || !Number.isSafeInteger(Number(value))) throw new Error("Expected a nonnegative integer budget"); | ||
| return Number(value); | ||
| } | ||
|
|
||
| function durationMs(value) { | ||
| if (value === "0") return 0; | ||
| const scale = { ns: 1e-6, us: 1e-3, µs: 1e-3, μs: 1e-3, ms: 1, s: 1000, m: 60000, h: 3600000 }; | ||
| const part = /(\d+(?:\.\d*)?|\.\d+)(ns|us|µs|μs|ms|s|m|h)/gy; | ||
| let ms = 0; | ||
| let length = 0; | ||
| for (const m of value.matchAll(part)) { | ||
| length += m[0].length; | ||
| ms += Number(m[1]) * scale[m[2]]; | ||
| } | ||
| if (!length || length !== value.length || !Number.isSafeInteger(Math.ceil(ms))) throw new Error("Invalid engine timeout"); | ||
| return Math.ceil(ms); | ||
| } | ||
|
|
||
| function envTurns() { | ||
| for (const raw of [process.env.THREAT_DETECTION_MAX_TURNS, process.env.GH_AW_MAX_TURNS]) { | ||
| if (/^\+?\d+$/.test(raw?.trim() ?? "") && Number.isSafeInteger(Number(raw))) return Number(raw); | ||
| } | ||
| return 50; | ||
| } | ||
|
|
||
| function readLaunch(file) { | ||
| const launch = JSON.parse(fs.readFileSync(file, "utf8")); | ||
| if (!launch || typeof launch.command !== "string" || !launch.command.trim()) throw new Error("The launch descriptor requires an executable command"); | ||
| if (!["copilot", "claude", "codex"].includes(launch.convention)) throw new Error("Expected a copilot, claude, or codex launch convention"); | ||
| if (launch.args !== undefined && (!Array.isArray(launch.args) || !launch.args.every(arg => typeof arg === "string"))) throw new Error("Launch args must be an array of strings"); | ||
| if (launch.mode !== undefined && !["direct", "harness"].includes(launch.mode)) throw new Error("Expected direct or harness launch mode"); | ||
| return launch; | ||
| } | ||
|
|
||
| function parseOptions(args) { | ||
| const names = ["launch-config", "workflow-name", "workflow-description", "custom-prompt", "custom-prompt-file", "prompt-template", "retries", "max-turns", "engine-timeout", "output", "full-output"]; | ||
| const { values, positionals } = parseArgs({ args, allowPositionals: true, options: Object.fromEntries(names.map(name => [name, { type: "string" }])) }); | ||
| if (positionals.length !== 1 || !values["launch-config"]) throw new Error("Expected --launch-config <trusted JSON file> and one artifacts directory"); | ||
| let timeoutMs = 300000; | ||
| if (process.env.THREAT_DETECTION_ENGINE_TIMEOUT) { | ||
| try { | ||
| timeoutMs = durationMs(process.env.THREAT_DETECTION_ENGINE_TIMEOUT.trim()); | ||
| } catch { | ||
| diagnostic("Invalid THREAT_DETECTION_ENGINE_TIMEOUT; retaining the five-minute default"); | ||
| } | ||
| } | ||
| const output = values.output ?? ""; | ||
| const { dir, name, ext } = path.parse(output); | ||
| const rawRetries = process.env.THREAT_DETECTION_RETRIES ?? ""; | ||
| return { | ||
| artifactsDir: positionals[0], | ||
| launch: readLaunch(values["launch-config"]), | ||
| workflowName: values["workflow-name"], | ||
| workflowDescription: values["workflow-description"], | ||
| customPrompt: values["custom-prompt"], | ||
| customPromptFile: values["custom-prompt-file"], | ||
| promptTemplate: values["prompt-template"], | ||
| retries: intOption(values.retries ?? (/^[+-]?\d+$/.test(rawRetries) ? rawRetries : undefined), 0), | ||
| timeoutMs: values["engine-timeout"] === undefined ? timeoutMs : durationMs(values["engine-timeout"]), | ||
| maxTurns: intOption(values["max-turns"], envTurns()), | ||
| output, | ||
| fullOutput: values["full-output"] ?? (output ? path.join(dir, `${name}_full${ext}`) : ""), | ||
| }; | ||
| } | ||
|
|
||
| function checkDestinations({ output, fullOutput }) { | ||
| if (!output || !fullOutput) return; | ||
| const canonical = file => { | ||
| try { | ||
| return fs.realpathSync(file); | ||
| } catch (err) { | ||
| if (err.code !== "ENOENT") throw err; | ||
| // Resolve existing parent components even when the leaf does not yet exist. | ||
| return path.join(canonical(path.dirname(path.resolve(file))), path.basename(file)); | ||
| } | ||
| }; | ||
| const a = fs.statSync(output, { throwIfNoEntry: false }); | ||
| const b = fs.statSync(fullOutput, { throwIfNoEntry: false }); | ||
| if (canonical(output) === canonical(fullOutput) || (a && b && a.dev === b.dev && a.ino === b.ino)) throw new Error("Publishable and full results must have distinct paths"); | ||
| } | ||
|
|
||
| function writeResult(file, result) { | ||
| const temp = path.join(path.dirname(file), `.threat-result-${randomUUID()}`); | ||
| try { | ||
| fs.writeFileSync(temp, JSON.stringify(result, null, 2), { flag: "wx", mode: 0o600 }); | ||
| fs.renameSync(temp, file); | ||
| } finally { | ||
| fs.rmSync(temp, { force: true }); | ||
| } | ||
| } | ||
|
|
||
| function publish(opts, result, warnings) { | ||
| const full = { ...result, warnings }; // The sink is never authoritative for warnings. | ||
| if (opts.fullOutput) { | ||
| try { | ||
| writeResult(opts.fullOutput, full); | ||
| } catch { | ||
| diagnostic("Could not write the private full result; the verdict is unaffected"); | ||
| } | ||
| } | ||
| try { | ||
| const redacted = publishableResult(full); | ||
| if (opts.output) writeResult(opts.output, redacted); | ||
| else process.stdout.write(`${JSON.stringify(redacted, null, 2)}\n`); | ||
| } catch { | ||
| return { reason: "output_write_error", code: 2 }; | ||
| } | ||
| return { reason: "result_recorded", code: result.prompt_injection || result.secret_leak || result.malicious_patch ? 1 : 0 }; | ||
| } | ||
|
|
||
| async function detect(opts, signal) { | ||
| checkDestinations(opts); | ||
| const { prompt, eligibility, warnings } = prepareAssessment(opts); | ||
| const dir = fs.mkdtempSync(path.join(os.tmpdir(), "threat-detect-")); | ||
| let correction = ""; | ||
| try { | ||
| for (let i = 0; i <= opts.retries; i++) { | ||
| if (signal.aborted) return { reason: "cancelled", code: 2 }; | ||
| // A fresh path for every attempt: no stale or partially written verdict can carry forward. | ||
| const sink = path.join(dir, `attempt-${i}.json`); | ||
| const run = await runHarness({ launch: opts.launch, sink, prompt: prompt + correction, eligibility, maxTurns: opts.maxTurns, timeoutMs: opts.timeoutMs, signal }); | ||
| let result; | ||
| try { | ||
| // Always validate in this process, even if the deadline or an engine error just fired. | ||
| result = readSink(sink, eligibility); | ||
| } catch (err) { | ||
| correction = | ||
| err.code === "ERR_REPORT_INELIGIBLE" | ||
| ? `\n\nYour previous verdict was rejected as structurally ineligible: ${err.message}\nRe-analyze the artifacts and run threat_detection_result again, keeping any category you can still support.` | ||
| : "\n\nYour previous response did not record a verdict. Run threat_detection_result with all three boolean flags. For findings, write reasons to $THREAT_DETECTION_REASONS_FILE and use --reasons-file."; | ||
| } | ||
| if (result) return publish(opts, result, warnings); | ||
| if (signal.aborted) return { reason: "cancelled", code: 2 }; | ||
| if (run.timedOut) return { reason: "engine_timeout", code: 2 }; | ||
| if (run.error) { | ||
| diagnostic(run.error.message); | ||
| return { reason: "engine_error", code: 2 }; | ||
| } | ||
| } | ||
| return { reason: "invalid_report_exhausted", code: 2 }; | ||
| } finally { | ||
| fs.rmSync(dir, { recursive: true, force: true }); | ||
| } | ||
| } | ||
|
|
||
| async function main(args) { | ||
| const controller = new AbortController(); | ||
| const cancel = () => controller.abort(); | ||
| process.on("SIGTERM", cancel); | ||
| process.on("SIGINT", cancel); | ||
| let status; | ||
| try { | ||
| status = await detect(parseOptions(args), controller.signal); | ||
| } catch (err) { | ||
| diagnostic(err.message); | ||
| status = { reason: "config_error", code: 2 }; | ||
| } finally { | ||
| process.off("SIGTERM", cancel); | ||
| process.off("SIGINT", cancel); | ||
| } | ||
| process.stderr.write(`THREAT_DETECTION_STATUS: reason=${status.reason} exit=${status.code}\n`); | ||
| return status.code; | ||
| } | ||
|
|
||
| if (require.main === module) | ||
| main(process.argv.slice(2)).then(code => { | ||
| process.exitCode = code; | ||
| }); | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,96 @@ | ||
| const fs = require("node:fs"); | ||
| const os = require("node:os"); | ||
| const path = require("node:path"); | ||
| const { spawnSync } = require("node:child_process"); | ||
| const cases = require("./testdata/threat-detector/v053.json"); | ||
|
|
||
| // Run these same fixtures against the release executable when explicitly provided. | ||
| // Normal CI compares against the checked-in v0.5.3 observations without a download. | ||
| const producers = ["JavaScript"]; | ||
| if (process.env.GH_AW_TEST_THREAT_DETECT_V053) producers.push("Go v0.5.3"); | ||
| const roots = []; | ||
| afterEach(() => { | ||
| for (const root of roots.splice(0)) fs.rmSync(root, { recursive: true, force: true }); | ||
| }); | ||
|
|
||
| function fixture() { | ||
| const root = fs.mkdtempSync(path.join(os.tmpdir(), "detector-parity-")); | ||
| roots.push(root); | ||
| fs.mkdirSync(path.join(root, "artifacts/aw-prompts"), { recursive: true }); | ||
| for (const file of ["prompt.txt", "prompt-template.txt"]) fs.writeFileSync(path.join(root, "artifacts/aw-prompts", file), "Static prompt"); | ||
| fs.writeFileSync(path.join(root, "artifacts/agent_output.json"), '{"items":[]}'); | ||
| const engine = path.join(root, "fixture-reviewer"); | ||
| fs.copyFileSync(path.join(__dirname, "testdata/threat-detector/harness.sh"), engine); | ||
| fs.chmodSync(engine, 0o700); | ||
| fs.symlinkSync(engine, path.join(root, "copilot")); | ||
| fs.writeFileSync(path.join(root, "launch.json"), JSON.stringify({ command: engine, convention: "copilot", mode: "direct" })); | ||
| return root; | ||
| } | ||
|
|
||
| function run(root, command, args, env) { | ||
| const child = spawnSync(command, args, { cwd: root, env, encoding: "utf8", timeout: 8000 }); | ||
| if (child.error) throw child.error; | ||
| return child; | ||
| } | ||
|
|
||
| describe.each(producers)("%s sandbox producer to host conclusion", producer => { | ||
| it.each(cases.scenarios)("$name", spec => { | ||
| const root = fixture(); | ||
| const env = { | ||
| ...process.env, | ||
| PATH: root + path.delimiter + process.env.PATH, | ||
| SCENARIO: spec.name, | ||
| GH_AW_DETECTION_CONTINUE_ON_ERROR: "false", | ||
| GH_AW_DETECTION_CONTINUE_ON_WARNING: spec.name === "strict-warning" ? "false" : "true", | ||
| }; | ||
| const js = producer === "JavaScript"; | ||
| const common = ["--output", "detection_result.json", "--retries", String(spec.retries || 0), "--engine-timeout", spec.timeout || "5s", "artifacts"]; | ||
| const child = run(root, js ? process.execPath : process.env.GH_AW_TEST_THREAT_DETECT_V053, (js ? [path.join(__dirname, "detect_threats.cjs"), "--launch-config", "launch.json"] : ["--engine", "copilot"]).concat(common), env); | ||
| expect(child.stderr.trimEnd().split("\n").at(-1)).toBe(`THREAT_DETECTION_STATUS: reason=${spec.reason} exit=${spec.exit}`); | ||
| expect(child.status).toBe(spec.exit); | ||
| const attempts = path.join(root, "attempts"); | ||
| expect(fs.existsSync(attempts) ? fs.readFileSync(attempts, "utf8").trim().split("\n").length : 0).toBe(spec.attempts); | ||
| for (const [file, full] of [ | ||
| ["detection_result.json", false], | ||
| ["detection_result_full.json", true], | ||
| ]) { | ||
| const resultFile = path.join(root, file); | ||
| if (spec.exit === 2) expect(fs.existsSync(resultFile)).toBe(false); | ||
| else | ||
| expect(JSON.parse(fs.readFileSync(resultFile, "utf8"))).toEqual({ | ||
| prompt_injection: false, | ||
| secret_leak: spec.exit === 1, | ||
| malicious_patch: false, | ||
| reasons: full && spec.exit === 1 ? ["private fixture reason"] : [], | ||
| warnings: cases.warnings, | ||
| }); | ||
| } | ||
| fs.writeFileSync(path.join(root, "detection.log"), child.stderr); | ||
| const githubOutput = path.join(root, "github-output"); | ||
| const conclude = run(root, process.execPath, [path.join(__dirname, "conclude_threat_detection.cjs"), "detection_result.json"], { ...env, RUN_DETECTION: "true", GITHUB_OUTPUT: githubOutput, GITHUB_ENV: path.join(root, "github-env") }); | ||
| expect(conclude.status).toBe(spec.exit === 0 ? 0 : 1); | ||
| const outputs = fs.readFileSync(githubOutput, "utf8").trimEnd().split("\n"); | ||
| expect(outputs).toContain(`reason=${spec.hostReason}`); | ||
| expect(outputs).toContain(`threat_kinds=${spec.exit === 1 ? "secret_leak" : ""}`); | ||
| }); | ||
| }); | ||
|
|
||
| describe("result destinations", () => { | ||
| it("rejects aliased outputs before invoking the engine", () => { | ||
| const root = fixture(); | ||
| fs.symlinkSync(root, path.join(root, "alias")); | ||
| const child = run(root, process.execPath, [path.join(__dirname, "detect_threats.cjs"), "--launch-config", "launch.json", "--output", "result", "--full-output", "alias/result", "artifacts"], { ...process.env, SCENARIO: "clean" }); | ||
| expect(child.stderr).toContain("reason=config_error exit=2"); | ||
| expect(fs.existsSync(path.join(root, "attempts"))).toBe(false); | ||
| }); | ||
|
|
||
| it.each([ | ||
| ["result", "missing/full", "result_recorded", 0], | ||
| ["missing/public", "full", "output_write_error", 2], | ||
| ])("distinguishes private and public write failures (%s, %s)", (redacted, full, reason, code) => { | ||
| const root = fixture(); | ||
| const child = run(root, process.execPath, [path.join(__dirname, "detect_threats.cjs"), "--launch-config", "launch.json", "--output", redacted, "--full-output", full, "artifacts"], { ...process.env, SCENARIO: "clean" }); | ||
| expect(child.stderr).toContain(`reason=${reason} exit=${code}`); | ||
| expect(child.status).toBe(code); | ||
| }); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,34 @@ | ||
| #!/bin/sh | ||
| # Deterministic stand-in for the model. The reporting tool and its supervisor are real. | ||
| set -eu | ||
| cat > prompt-seen | ||
| printf '1\n' >> attempts | ||
| report() { | ||
| threat_detection_result --prompt-injection=false --secret-leak="$1" --malicious-patch="$2" --reason 'private fixture reason' | ||
| } | ||
| case "$SCENARIO" in | ||
| clean|strict-warning) threat_detection_result --prompt-injection=false --secret-leak=false --malicious-patch=false ;; | ||
| correct) | ||
| if report true true >feedback 2>&1; then exit 9; fi | ||
| grep -q -- '--malicious-patch=true is not eligible' feedback | ||
| test ! -f "$THREAT_DETECTION_RESULT_FILE" | ||
| report true false ;; | ||
| absent|incorrect|retry) | ||
| if [ "$SCENARIO" = retry ] && grep -q 'previous verdict was rejected as structurally ineligible' prompt-seen; then | ||
| report true false | ||
| else | ||
| # Bypass the advisory check, but use the real tool to write the result. | ||
| if [ "$SCENARIO" = absent ]; then | ||
| unset THREAT_DETECTION_ELIGIBLE_MALICIOUS_PATCH | ||
| else | ||
| export THREAT_DETECTION_ELIGIBLE_MALICIOUS_PATCH=true | ||
| fi | ||
| report true true | ||
| fi ;; | ||
| timeout) sleep 10 ;; | ||
| recorded-at-deadline) | ||
| # The short deadline fires before the normal result watcher polls. | ||
| printf '%s' '{"prompt_injection":false,"secret_leak":true,"malicious_patch":false,"reasons":["private fixture reason"]}' > "$THREAT_DETECTION_RESULT_FILE" | ||
| sleep 10 ;; | ||
| failed) exit 3 ;; | ||
| esac |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,20 @@ | ||
| { | ||
| "warnings": [ | ||
| { | ||
| "field": "prompt_import_tree", | ||
| "code": "ERR_VALIDATION", | ||
| "message": "Missing or empty prompt analysis artifact: aw-prompts/prompt-import-tree.json. Trusted-vs-untrusted prompt analysis is degraded; ensure the host stages it non-empty. This failure is not itself evidence of a threat." | ||
| } | ||
| ], | ||
| "scenarios": [ | ||
| { "name": "clean", "exit": 0, "attempts": 1, "reason": "result_recorded", "hostReason": "" }, | ||
| { "name": "correct", "exit": 1, "attempts": 1, "reason": "result_recorded", "hostReason": "threat_detected" }, | ||
| { "name": "absent", "exit": 2, "attempts": 1, "reason": "invalid_report_exhausted", "hostReason": "parse_error" }, | ||
| { "name": "incorrect", "exit": 2, "attempts": 1, "reason": "invalid_report_exhausted", "hostReason": "parse_error" }, | ||
| { "name": "retry", "retries": 1, "exit": 1, "attempts": 2, "reason": "result_recorded", "hostReason": "threat_detected" }, | ||
| { "name": "timeout", "retries": 2, "timeout": "150ms", "exit": 2, "attempts": 1, "reason": "engine_timeout", "hostReason": "agent_failure" }, | ||
| { "name": "recorded-at-deadline", "retries": 2, "timeout": "150ms", "exit": 1, "attempts": 1, "reason": "result_recorded", "hostReason": "threat_detected" }, | ||
| { "name": "failed", "retries": 2, "exit": 2, "attempts": 1, "reason": "engine_error", "hostReason": "agent_failure" }, | ||
| { "name": "strict-warning", "exit": 2, "attempts": 0, "reason": "config_error", "hostReason": "agent_failure" } | ||
| ] | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.