Skip to content
Open
37 changes: 37 additions & 0 deletions actions/setup/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,43 @@ This action runs in all workflow jobs to provide scripts that can be used instea

The action copies runtime `.cjs` JavaScript files (excluding tests) from the `js/` directory and `.sh` shell scripts from the `sh/` directory.

### Sandboxed threat detector

`detect_threats.cjs` is the sandbox-side producer for `conclude_threat_detection.cjs`.
It is bundled but not yet selected by the workflow compiler. The host passes a
trusted launch descriptor separately from the agent's staged artifacts:

```sh
node detect_threats.cjs --launch-config launch.json \
--output detection_result.json artifacts/
```

For a gh-aw harness, the descriptor supplies `command` and an `args` prefix
(for example, `node` and `["/opt/gh-aw/copilot_harness.cjs", "copilot"]`).
`convention` (`copilot`, `claude`, or `codex`) selects the argument and prompt
transport independently of the executable name. Optional `model`, `provider`,
`env`, and `cwd` are host-resolved values. Set `mode` to `direct` for a bare
CLI that reads its prompt on stdin instead of a harness that takes `--prompt-file`.
Never load this descriptor from model-authored artifacts.

The detector converts supported Git bundles to diff text offline, in a
disposable object store. Incremental bundles need their prerequisite objects
in the local `$GITHUB_WORKSPACE` checkout; the detector never fetches them.
An unreadable or over-limit bundle is an inspection warning, not evidence of
a clean patch or a threat.

On Linux the supervisor uses Python 3 and `/proc` to reap descendants owned
by the attempt, including tools that start a separate process group.

Only `detection_result.json` is publishable. The adjacent
`detection_result_full.json` contains private reasons and must stay local.
Both destinations are invalidated at the start of each assessment, so a
failed rerun cannot publish an earlier verdict.
The detector checks each attempt's private sink against the original artifact
eligibility, even when the reporting command accepted it. Exit codes are 0
(clean), 1 (finding), and 2 (no usable verdict); stderr ends with a
`THREAT_DETECTION_STATUS:` line for the host conclusion.

JavaScript reads compiled lock metadata and manifests through the bounded JSON
header helper, without parsing the workflow body. The runtime lives entirely in
this action and consumes compiler-produced JSON metadata. Setup does not compile
Expand Down
193 changes: 193 additions & 0 deletions actions/setup/js/detect_threats.cjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,193 @@
// 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 conventionalFull = output ? path.join(dir, `${name}_full${ext}`) : "";
const fullOutput = values["full-output"] ?? conventionalFull;
checkDestinations({ output, fullOutput });
// The host consumes the files even on a nonzero exit. Invalidate both
// before reading launch configuration or examining this run's artifacts.
for (const file of new Set([output, fullOutput, conventionalFull])) if (file) fs.rmSync(file, { force: true });
const rawRetries = process.env.THREAT_DETECTION_RETRIES ?? "";
return {
artifactsDir: path.resolve(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,
};
}

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) {
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, artifactsDir: opts.artifactsDir, 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;
});
116 changes: 116 additions & 0 deletions actions/setup/js/detect_threats.test.cjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
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("does not leave a stale conventional sidecar when full output is disabled", () => {
const root = fixture();
const stale = path.join(root, "result_full.json");
fs.writeFileSync(stale, '{"reasons":["from an earlier run"]}');
const child = run(root, process.execPath, [path.join(__dirname, "detect_threats.cjs"), "--launch-config", "launch.json", "--output", "result.json", "--full-output=", "artifacts"], { ...process.env, SCENARIO: "clean" });
expect(child.status).toBe(0);
expect(fs.existsSync(stale)).toBe(false);
});
it.each(["strict-warning", "timeout"])("invalidates both old results before %s", scenario => {
const root = fixture();
const files = ["result.json", "result_full.json"].map(file => path.join(root, file));
for (const file of files) fs.writeFileSync(file, '{"prompt_injection":false,"secret_leak":false,"malicious_patch":false,"reasons":[]}');
const child = run(root, process.execPath, [path.join(__dirname, "detect_threats.cjs"), "--launch-config", "launch.json", "--output", "result.json", "--engine-timeout", "150ms", "artifacts"], {
...process.env,
SCENARIO: scenario,
GH_AW_DETECTION_CONTINUE_ON_WARNING: scenario === "strict-warning" ? "false" : "true",
});
expect(child.status).toBe(2);
for (const file of files) expect(fs.existsSync(file)).toBe(false);
});
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);
});
});
34 changes: 34 additions & 0 deletions actions/setup/js/testdata/threat-detector/harness.sh
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
Loading
Loading