Merge main into patch publication

This commit is contained in:
Michael D'Angelo
2026-10-28 04:40:12 +00:00
536 changed files with 45288 additions and 26236 deletions
+3
View File
@@ -1,5 +1,7 @@
.git
.github
plugins/codex-security/tests
sdk/typescript/tests-ts/*.test.ts
**/.DS_Store
**/.env
**/.env.*
@@ -13,3 +15,4 @@
**/security-scans
**/state
**/*.log
docker/wolfi/build
+3
View File
@@ -13,3 +13,6 @@
# Bundled dependencies contain intentional whitespace in strings and comments.
github-action/dist/*.cjs linguist-generated=true -whitespace
# This checksum-pinned upstream license contains its original whitespace.
docker/wolfi/payload/notices/BUBBLEWRAP-COPYING -text -whitespace
+7 -2
View File
@@ -1,9 +1,14 @@
paths:
.github/workflows/{container-release,node-github-release,node-release-cut,node-release,release-progress}.yml:
.github/workflows/{container-release,node-github-release,node-ci,node-release-cut,node-release-pr,node-release,release-progress}.yml:
ignore:
# actionlint 1.7.12 predates GitHub's queue: max support. Keep release queuing.
# actionlint 1.7.12 predates GitHub's queue: max support. Keep the supported queue setting.
# https://docs.github.com/en/actions/how-tos/write-workflows/choose-when-workflows-run/control-workflow-concurrency
- '^unexpected key "queue" for "concurrency" section\.'
.github/workflows/native-artifacts.yml:
ignore:
# actionlint 1.7.12 predates GitHub’s reference to the defining workflow's commit.
# https://docs.github.com/en/actions/reference/workflows-and-actions/workflow-syntax#jobsjob_idstepsuses
- '^specifying action "\$/\.github/actions/native-cache-key" in invalid format because ref is missing\.'
.github/workflows/invoice-desk-scan.yml:
ignore:
# actionlint 1.7.12 predates GitHub's job-level cache permissions.
@@ -4,7 +4,7 @@ runs:
using: composite
steps:
- name: Set up Action Node.js runtime
uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0
uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
with:
node-version: "24"
package-manager-cache: false
+1 -1
View File
@@ -3,7 +3,7 @@ description: Prepare the verified universal native payload for package builds.
runs:
using: composite
steps:
- uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1
- uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
with:
name: native-universal-${{ github.sha }}
path: plugins/codex-security/native/prebuilt
@@ -0,0 +1,12 @@
name: Native cache key
description: Fingerprint the checked-out native build and proof inputs.
outputs:
key:
description: Exact key for this source and UTC week.
value: ${{ steps.key.outputs.key }}
runs:
using: composite
steps:
- id: key
shell: bash
run: bash "$GITHUB_ACTION_PATH/key.sh" >> "$GITHUB_OUTPUT"
+43
View File
@@ -0,0 +1,43 @@
#!/usr/bin/env bash
set -euo pipefail
# Include filenames and modes, not only file contents. Windows proofs
# bundle MCP helpers, including their schema and workbench dependencies.
empty_tree="$(git hash-object -t tree --stdin </dev/null)"
# These existing CI entrypoints run outside the native jobs.
ci_only=':(exclude).github/scripts/'
source_hash="$(git diff-tree -r -z --no-abbrev "$empty_tree" HEAD -- \
.gitattributes .cargo .npmrc .pnpmfile.cjs package.json pnpm-workspace.yaml \
.github/actions/{native-cache-key,setup-tools} .github/scripts \
"${ci_only}"invoice-desk-{source,target}{,.test}.mjs \
"${ci_only}"{check-ci-results,select-ci-checks,test-ci-selection,test-release-guide}.mjs \
"${ci_only}"{verify-pr-source,test-verify-pr-source,release-progress,test_release_progress}.mjs \
"${ci_only}"test_check_plugin_source_compatibility.mts \
"${ci_only}"{install-ripgrep.sh,require_native_python_report.py,test_require_native_python_report.py} \
.github/workflows/native-artifacts.yml \
.github/workflows/native-unix.yml \
.github/workflows/native-windows.yml \
.github/workflows/native-musl.yml \
sdk/typescript/.npmrc sdk/typescript/.pnpmfile.cjs \
sdk/typescript/package.json sdk/typescript/pnpm-lock.yaml \
sdk/typescript/pnpm-workspace.yaml \
sdk/typescript/tsconfig.json sdk/typescript/tsconfig.ci.json \
plugins/codex-security/native plugins/codex-security/mcp-app \
':(exclude)plugins/codex-security/mcp-app/tests' \
plugins/codex-security/schemas plugins/codex-security/scripts \
plugins/codex-security/shared | git hash-object --stdin)"
# Hosted runner images can change without a source change.
# Keep a protected push in the week it was classified, including at UTC rollover.
week=${NATIVE_CACHE_WEEK:-0}
if [[ $week == 0 ]]; then week="$(date -u +%G%V)"; fi
key="native-universal-v1-${week:0:4}-${week:4}-$source_hash"
if [[ ${1-} == cold-group ]]; then
printf 'week=%s\n' "$week"
# The listing is only a scheduling hint. prepare always restores or builds.
hit="$(timeout 5s gh cache list --ref refs/heads/main --key "$key" --limit 1 --json key --jq '.[0].key // empty')"
# Keep adjacent misses together, with at most 15 other runs in the group.
if [[ "$hit" != "$key" ]]; then
printf 'cold-group=%s-%s\n' "$key" "$(((GITHUB_RUN_NUMBER - 1) / 16))"
fi
else
printf 'key=%s\n' "$key"
fi
+5 -5
View File
@@ -1,9 +1,9 @@
name: Set up TypeScript tools
description: Install the pinned package manager and Node.js runtime for repository tools.
inputs:
setup-node:
description: Install the pinned Node.js runtime; false keeps an earlier setup step.
default: "true"
node-version:
description: Node.js version for repository tools.
default: "22.13.0"
cache-dependency-path:
description: Lockfiles used for the pnpm store cache.
default: "sdk/typescript/pnpm-lock.yaml"
@@ -20,9 +20,9 @@ runs:
package_json_file: package.json
# setup-node saves its cache only after a successful job.
- name: Set up Node.js and pnpm cache
uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0
uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
with:
node-version: ${{ inputs.setup-node == 'true' && '22.13.0' || '' }}
node-version: ${{ inputs.node-version }}
architecture: ${{ inputs.architecture }}
cache: pnpm
cache-dependency-path: ${{ inputs.cache-dependency-path }}
+3 -1
View File
@@ -55,7 +55,9 @@ updates:
- package-ecosystem: github-actions
labels: [dependencies]
directory: /
directories:
- /
- "/.github/actions/*"
schedule:
interval: cron
cronjob: "0 9 * * *"
+6 -31
View File
@@ -1,25 +1,13 @@
<!-- release-version: 0.6.0 -->
<!-- release-version: 0.8.0 -->
<!-- release-section: highlights:start -->
## Highlights
Codex Security 0.6.0 adds vendor report imports, optional owner suggestions, and hosted remediation commands. Severity classification now uses a built-in rubric and three independent reviews by default; review the model-access and cost changes below before upgrading.
Codex Security 0.8.0 adds OpenGrep report imports and changes how scan results record scope and review details.
- **Import vendor findings.** Import supported Wiz, Snyk Open Source, Semgrep Code, and Endor Labs reports with `publish findings --to local`, or publish them with `--to cloud`. Read local evidence with `findings imported`. Local imports require no Cloud login or model call and remain separate from assessed scan findings. See the [Wiz](https://github.com/openai/codex-security/blob/npm-v0.6.0/sdk/typescript/docs/cli.md#import-wiz-findings), [Snyk](https://github.com/openai/codex-security/blob/npm-v0.6.0/docs/scanner-imports/snyk.md), [Semgrep](https://github.com/openai/codex-security/blob/npm-v0.6.0/docs/scanner-imports/semgrep.md), and [Endor](https://github.com/openai/codex-security/blob/npm-v0.6.0/docs/scanner-imports/endor.md) format guides.
- **Configurable severity reviews.** `classify-severity` uses a bundled rubric when no custom rubric is supplied. `--runs N` selects 1–10 independent reviews, with three by default. The most common severity wins, with the highest severity breaking ties. ([#1765](https://github.com/openai/codex-security/pull/1765))
- **Optional owner suggestions.** `scan --owner-suggestions` writes a separate owner-suggestion report after supported committed Git scans. Suggestions preserve the completed scan and do not assign users. Owner enrichment is skipped when a scan cost limit is set. ([#1760](https://github.com/openai/codex-security/pull/1760))
- **Hosted patching and source-only verification.** `patch --host` and `verify-fix --host` expose the hosted remediation protocol through the CLI. Ordinary patch and verification commands accept `--verification-mode static` to assess source evidence; omitting it preserves standard verification. Static mode sets the assessment scope and does not enforce a command-execution boundary. See the [hosted remediation guide](https://github.com/openai/codex-security/blob/npm-v0.6.0/sdk/typescript/docs/hosted-remediation.md). ([#1854](https://github.com/openai/codex-security/pull/1854))
- **Policy previews without Python.** Policy diffs now run in Node while preserving diff formatting, cancellation, and source freshness checks. ([#1837](https://github.com/openai/codex-security/pull/1837))
<details>
<summary>Other improvements</summary>
- Patch project-trust overrides are serialized correctly for Codex. ([#1861](https://github.com/openai/codex-security/pull/1861))
- Update Hono and the Linear SDK dependencies. ([#1831](https://github.com/openai/codex-security/pull/1831), [#1852](https://github.com/openai/codex-security/pull/1852))
- Release verification runs test shards in parallel and reports publication progress on the release PR. ([#1798](https://github.com/openai/codex-security/pull/1798))
</details>
- **OpenGrep imports.** Import a native JSON or gzip-compressed report into the local workbench or publish it to Cloud with `publish findings --provider opengrep`. Supply `--source-repository-url` and enable external imports with `CODEX_SECURITY_ENABLE_EXTERNAL_IMPORTS=1`. Imported findings retain their scanner evidence and start as unassessed. See the [OpenGrep guide](https://github.com/openai/codex-security/blob/npm-v0.8.0/docs/scanner-imports/opengrep.md).
- **Scan recovery.** Resume an interrupted Deep Scan after clearing its additional instructions. Read a completed Workbench scan’s saved artifacts even after moving or removing the original checkout.
<!-- release-section: highlights:end -->
@@ -27,20 +15,7 @@ Codex Security 0.6.0 adds vendor report imports, optional owner suggestions, and
## Upgrade notes
### Severity classification requires model access
Classification without `--rubric` previously inherited the scanner's severity without model work. It now requires Codex authentication and model access, using three model calls per uncached finding by default. Set `--runs 1` (SDK: `classificationRuns: 1`) for a single review. All requested reviews must succeed; failures do not fall back to the scanner's severity or save a partial vote.
Older classification checkpoints without a recorded review count, and former inherited assessments without a rubric hash, are reclassified on the next classification request. Changing the review count or rubric also invalidates matching checkpoints. Existing results remain readable, and publication does not silently classify findings. Use `--reprocess` when changing only the model or reasoning effort. See the [classification guide](https://github.com/openai/codex-security/blob/npm-v0.6.0/sdk/typescript/docs/cli.md#classify-finding-severity).
### Policy preview interpreter selection is deprecated
`securityPolicyDiff(draft, python, signal)` retains its call shape, but interpreter strings and paths returned by resolver callbacks no longer select or validate an executable. `previewPolicy()` no longer resolves Python, and `pythonPath` and `PYTHON` do not affect previews. Update integrations that relied on an invalid interpreter failing or a custom executable producing the diff. Explicit resolver callbacks still run for changed drafts and propagate their errors. Omit the second argument in new code, or pass `undefined` when supplying a cancellation signal. Python-dependent generation and other operations are unchanged.
### Import identity and earlier upgrades
Keep a stable source key and acquisition format across vendor imports. Switching formats can create separate records or replace richer evidence with less detail; omitted findings remain stored. Review each provider's format guide before changing inputs.
If upgrading from before 0.5.1, also review the [0.5.1 upgrade notes](https://github.com/openai/codex-security/releases/tag/npm-v0.5.1) and their guidance for earlier versions. Use `openai/codex-security@action-v0.6.0` for the matching GitHub Action, or pin the distribution commit in its companion release after publication.
- **SDK and JSON consumers.** Replace reads of `ScanResult.coverage` or the serialized `coverage` field with `review` for comparison exclusions. Read scan mode and scope from `manifest.scan`. Integrations that write drafts should put reviewed surfaces, unfinished work, and open questions in `reviewState`.
- **Saved files and GitHub Actions.** New scans no longer write `coverage.json`. Replace `ScanResult.coveragePath` with `manifestPath` and read `scan.review` in `scan-manifest.json`. Workflows that read the Action’s `coverage-path` output should switch to `manifest-path`. The legacy output is empty for current scans. Existing saved scans remain readable. See [Action outputs](https://github.com/openai/codex-security/blob/npm-v0.8.0/github-action/README.md#outputs).
<!-- release-section: upgrades:end -->
+6 -6
View File
@@ -1,14 +1,14 @@
{
"baseVersion": "0.5.1",
"baseCommit": "b2fa51576d81cda5e311e7eb89131ffb13daad8b",
"baseVersion": "0.7.0",
"baseCommit": "f05a0b096cc881242ddf34a4d6b3ce0f322f3cf9",
"sections": {
"highlights": {
"generatedHash": "9c17957f706150b5ebfb2effc42159606c808ed05bc44f80320bd0fb1518c5fc",
"humanOwned": true
"generatedHash": "224dbb6af33c8755c91d742f64872e8b9aa18dac218ed0fca3f1bcaec5957e07",
"humanOwned": false
},
"upgrades": {
"generatedHash": "cdbfb62364372edf0e5202f7db41239aa0301d69187e022b9e9a9c9b0fcab298",
"humanOwned": true
"generatedHash": "dba3f33340a5a700d43c6f01b1f3d795b9a3a750328b8040a36965b7e76c6827",
"humanOwned": false
}
}
}
+14 -11
View File
@@ -8,16 +8,10 @@ export function failedChecks(needs) {
const required = ["static-checks"];
const groups = {
"package-required": ["native", "package", "compatibility"],
"source-required": [
"test",
"mcp",
"plugin-host",
"plugin-source",
"windows-test",
"windows-verify",
],
"source-required": ["test", "windows-test"],
"container-required": ["container-validate"],
"plugin-tests-required": ["mcp", "plugin-host", "plugin-source"],
"workflow-quality": ["workflow-quality"],
"container-validate": ["container-validate"],
"action-ci": ["action-ci"],
"eval-contracts": ["eval-contracts"],
};
@@ -36,9 +30,18 @@ if (
process.argv[1] &&
import.meta.url === pathToFileURL(process.argv[1]).href
) {
const failures = failedChecks(JSON.parse(process.env.CI_RESULTS));
const needs = JSON.parse(process.env.CI_RESULTS);
const failures = failedChecks(needs);
if (failures.length) {
console.error(`Required CI checks did not pass: ${failures.join(", ")}`);
const details = failures.map((name) => {
if (name.endsWith(" classification"))
return `${name} (missing or invalid)`;
const result = needs[name]?.result;
if (name === "action-ci" && result === "success")
return `${name} (passed output was not "true")`;
return `${name} (${result || "missing result"})`;
});
console.error(`Required CI checks did not pass: ${details.join(", ")}`);
process.exitCode = 1;
} else console.log("All selected required CI checks passed.");
}
+66 -107
View File
@@ -27,53 +27,59 @@ function pullRequest(overrides = {}) {
};
}
test("selects the requested PR head rather than the trusted workflow commit", async () => {
assert.deepEqual(
await resolveScanTargets(context, async (number) => {
assert.equal(number, "7");
return pullRequest();
}),
[{ pr: 7, sha: sourceSha }],
);
});
test("includes fork and draft PRs without depending on a PR workflow run", async () => {
assert.deepEqual(
await resolveScanTargets(context, async () =>
pullRequest({
draft: true,
head: { sha: sourceSha, repo: { full_name: "contributor/invoices" } },
}),
),
[{ pr: 7, sha: sourceSha }],
);
});
test("rechecking after approval excludes closed, retargeted, and superseded PRs", async () => {
assert.deepEqual(
await resolveScanTargets(context, async () => pullRequest()),
[{ pr: 7, sha: sourceSha }],
);
for (const changed of [
{ state: "closed" },
{ base: { ref: "release", repo: { full_name: repository } } },
{ base: { ref: "main", repo: { full_name: "other/invoices" } } },
{ head: { sha: "3".repeat(40) } },
]) {
assert.deepEqual(
await resolveScanTargets(context, async () => pullRequest(changed)),
[],
);
test("initial selection and approval recheck require the selected PR and revision to remain eligible", async () => {
const target = { pr: 7, sha: sourceSha };
// The approval step must use its matrix target even if dispatch inputs differ.
const recheck = {
...context,
target: { ...target },
event: { inputs: { pr_number: "9", source_sha: mainSha } },
};
for (const request of [context, recheck]) {
for (const [overrides, expected] of [
[{}, [target]],
[
{
draft: true,
head: { sha: sourceSha, repo: { full_name: "contributor/invoices" } },
},
[target],
],
[{ state: "closed" }, []],
[{ base: { ref: "release", repo: { full_name: repository } } }, []],
[{ base: { ref: "main", repo: { full_name: "other/invoices" } } }, []],
[{ head: { sha: mainSha } }, []],
[{ head: { sha: "3".repeat(40) } }, []],
]) {
const actual = await resolveScanTargets(request, async (number) => {
assert.equal(number, "7");
return pullRequest(overrides);
});
assert.deepEqual(actual, expected);
}
}
});
test("manual baseline scans use the trusted workflow commit", async () => {
assert.deepEqual(
await resolveScanTargets({ ...context, event: { inputs: {} } }, () =>
assert.fail("unexpected API call"),
),
[{ pr: 0, sha: mainSha }],
);
test("manual and scheduled baselines use the trusted workflow commit before and after approval", async () => {
const target = { pr: 0, sha: mainSha };
const scheduled = {
...context,
eventName: "schedule",
event: { schedule: "17 3 * * 1" },
};
for (const request of [
{ ...context, event: { inputs: {} } },
scheduled,
{ ...context, target: { ...target } },
{ ...scheduled, target: { ...target } },
]) {
assert.deepEqual(
await resolveScanTargets(request, () =>
assert.fail("unexpected API call"),
),
[target],
);
}
});
test("incomplete or invalid PR inputs fail instead of falling back to a baseline", async () => {
@@ -92,74 +98,27 @@ test("incomplete or invalid PR inputs fail instead of falling back to a baseline
}
});
test("ignores unexpected events without querying GitHub", async () => {
assert.deepEqual(
await resolveScanTargets({ ...context, eventName: "pull_request" }, () =>
assert.fail("unexpected API call"),
),
[],
);
});
test("scheduled baseline scans use the trusted workflow commit", async () => {
assert.deepEqual(
await resolveScanTargets(
{ ...context, eventName: "schedule", event: { schedule: "17 3 * * 1" } },
() => assert.fail("unexpected API call"),
),
[{ pr: 0, sha: mainSha }],
);
});
test("completed behavior workflows no longer queue inference", async () => {
assert.deepEqual(
await resolveScanTargets(
{
...context,
eventName: "workflow_run",
event: {
workflow_run: {
event: "pull_request",
conclusion: "success",
head_sha: sourceSha,
pull_requests: [{ number: 7 }],
},
test("PR events and completed PR workflows do not queue inference or query GitHub", async () => {
for (const trigger of [
{ eventName: "pull_request", event: { pull_request: pullRequest() } },
{
eventName: "workflow_run",
event: {
workflow_run: {
event: "pull_request",
conclusion: "success",
head_sha: sourceSha,
pull_requests: [{ number: 7 }],
},
},
() => assert.fail("unexpected API call"),
),
[],
);
});
test("approval recheck stays bound to its matrix PR and source revision", async () => {
const run = { ...context, target: { pr: 7, sha: sourceSha } };
for (const changed of [
{ state: "closed" },
{ base: { ref: "release", repo: { full_name: repository } } },
{ head: { sha: mainSha } },
},
]) {
assert.deepEqual(
await resolveScanTargets(run, async (number) => {
assert.equal(number, "7");
return pullRequest(changed);
}),
[],
);
}
assert.deepEqual(await resolveScanTargets(run, async () => pullRequest()), [
{ pr: 7, sha: sourceSha },
]);
});
test("baseline approval recheck retains the original trusted workflow commit", async () => {
for (const eventName of ["workflow_dispatch", "schedule"]) {
assert.deepEqual(
await resolveScanTargets(
{ ...context, eventName, target: { pr: 0, sha: mainSha } },
() => assert.fail("unexpected API call"),
await resolveScanTargets({ ...context, ...trigger }, () =>
assert.fail("unexpected API call"),
),
[{ pr: 0, sha: mainSha }],
[],
trigger.eventName,
);
}
});
+17
View File
@@ -0,0 +1,17 @@
#!/usr/bin/env bash
release_npm_version=11.12.1
release_npm_prefix="$RUNNER_TEMP/codex-security-provenance-npm"
release_npm_bin="$release_npm_prefix/node_modules/.bin"
verify_release_npm() {
if [[ "$1" != "$release_npm_bin/npm" || "$("$1" --version)" != "$release_npm_version" ]]; then
echo "Expected npm $release_npm_version at $release_npm_bin/npm for provenance verification." >&2
return 1
fi
}
install_release_npm() {
npm install --prefix "$release_npm_prefix" --ignore-scripts --no-audit --no-fund \
--registry=https://openai.firewall.socket.dev/npm/ "npm@$release_npm_version"
verify_release_npm "$release_npm_bin/npm"
}
+66 -33
View File
@@ -1,44 +1,70 @@
import { execFileSync } from "node:child_process";
import { appendFileSync, readFileSync } from "node:fs";
import { pathToFileURL } from "node:url";
import { checkoutBase } from "./verify-pr-source.mjs";
const documentation =
/^(?:README\.md|CONTRIBUTING\.md|CODE_OF_CONDUCT\.md|docs\/.*\.md|github-action\/README\.md|docker\/README\.md)$/;
const ordinarySource =
/^(?:sdk\/typescript\/(?:src|tests-ts)|plugins\/codex-security\/mcp-app\/(?:src|tests))\/.*\.ts$/;
const pythonTest = /^plugins\/codex-security\/tests\/test_[^/]*\.py$/;
const sdkTest = /^sdk\/typescript\/tests-ts\/[^/]+\.test\.ts$/;
const actionFiles =
/^(?:action\.yml|github-action\/(?:README\.md|(?:runtime\/)?package(?:-lock)?\.json|dist\/(?:index|post)\.cjs|(?:src|scripts|tests)\/[^/]+\.(?:mjs|ts)))$/;
const evalFiles =
/^evals\/(?:standard-time-budget\/(?:[^/]+\.mts|experiment\.json|README\.md)|triage-finding\/(?:package\.json|pnpm-lock\.yaml|README\.md|(?:assertions|scripts)\/[^/]+\.mts))$/;
function scopeFor(paths, event, baseChanged) {
const packageManifest = JSON.parse(
readFileSync(
new URL("../../sdk/typescript/package.json", import.meta.url),
"utf8",
),
);
const packagedDocs = new Set(
packageManifest.files
.filter((file) => file.endsWith(".md"))
.map((file) => `sdk/typescript/${file}`),
);
const isDocumentation = (path) =>
documentation.test(path) || packagedDocs.has(path);
function scopeFor(paths, { event, baseChanged, modifiedOnly }) {
if (event !== "pull_request" || baseChanged || !paths.length) return "full";
if (paths.every((path) => documentation.test(path))) return "docs";
if (modifiedOnly && paths.every((path) => pythonTest.test(path)))
return "python-tests";
if (paths.every((path) => isDocumentation(path) || path === "RELEASING.md")) {
// The Action profile already builds the package and installs it on Node 24.
// Select the separate Action job from its own inputs below.
return paths.some((path) => packagedDocs.has(path)) ? "action" : "docs";
}
if (paths.every((path) => actionFiles.test(path))) return "action";
if (paths.every((path) => evalFiles.test(path))) return "evals";
if (
paths.every((path) => ordinarySource.test(path) || documentation.test(path))
)
if (paths.every((path) => ordinarySource.test(path) || isDocumentation(path)))
return "source";
return "full";
}
export function selectChecks(paths, { event, baseChanged = false }) {
const scope = scopeFor(paths, event, baseChanged);
const full = scope === "full";
export function selectChecks(paths, options) {
const scope = scopeFor(paths, options);
const full = scope === "full" || scope === "python-tests";
const source = full || scope === "source";
const sdkTestsOnly =
scope === "source" && paths.every((path) => sdkTest.test(path));
const sourceBeyondSdkTests = source && !sdkTestsOnly;
const action =
full ||
scope === "action" ||
paths.some(
(path) =>
path === "github-action/README.md" ||
path === "sdk/typescript/src/git-remote.ts",
actionFiles.test(path) || path === "sdk/typescript/src/git-remote.ts",
);
const compatibility = ["22.13.0", "24.0.0", "24", "26.0.0", "26"]
.filter((version) => full || version !== "26")
.map((version) => ({ os: "ubuntu-latest", node: version }));
compatibility.push({ os: "macos-latest", node: "22.13.0" });
if (scope !== "python-tests") {
compatibility.push({ os: "windows-latest", node: "22.13.0" });
if (full) compatibility.push({ os: "windows-latest", node: "24" });
}
const pythonMatrix = [
...["3.10", "3.12", "3.14"]
.filter((version) => full || version === "3.12")
@@ -58,24 +84,33 @@ export function selectChecks(paths, { event, baseChanged = false }) {
markers: "cross_platform or native_windows",
},
];
return {
const selected = {
"source-required": String(source),
"container-required": String(
sourceBeyondSdkTests && scope !== "python-tests",
),
"plugin-tests-required": String(sourceBeyondSdkTests),
"package-required": String(source || scope === "action"),
"action-ci": String(action),
"eval-contracts": String(source || scope === "evals"),
"eval-contracts": String(
sourceBeyondSdkTests ||
scope === "evals" ||
paths.includes("sdk/typescript/tests-ts/codex-dependency-pins.test.ts"),
),
"workflow-quality": String(full),
"container-validate": String(source),
"compatibility-matrix": JSON.stringify({
include:
scope === "action"
scope === "action" || sdkTestsOnly
? [{ os: "ubuntu-latest", node: "24" }]
: compatibility,
}),
"python-matrix": JSON.stringify({ include: pythonMatrix }),
"windows-node-matrix": JSON.stringify({
node: full ? ["22.13.0", "24"] : ["22.13.0"],
}),
};
if (scope === "python-tests") {
for (const name of ["source-required", "action-ci", "eval-contracts"])
selected[name] = "false";
}
return selected;
}
if (
@@ -85,33 +120,31 @@ if (
const event = process.env.EVENT_NAME;
const baseChanged = process.env.BASE_CHANGED === "true";
if (event === "pull_request" && baseChanged) {
const { base, head } = JSON.parse(
const { changes, pull_request: pr } = JSON.parse(
readFileSync(process.env.GITHUB_EVENT_PATH, "utf8"),
).pull_request;
const parents = execFileSync("git", ["show", "-s", "--format=%P", "HEAD"], {
encoding: "utf8",
}).trim();
const expected = `${base.sha} ${head.sha}`;
console.log(
`Requested base ${base.ref}. Expected merge parents ${expected}. Checked out ${parents}.`,
);
if (parents !== expected) {
throw new Error(
"GitHub supplied a stale test merge. After the merge ref updates, reopen the pull request to start a fresh source run. Rerunning this attempt uses the same commit.",
);
// Ordinary edits already proved their live target before falling back to full checks.
if (changes?.base) {
const base = checkoutBase(pr, process.env.GITHUB_SHA);
if (base !== pr.base.sha)
throw new Error(
`Stale test merge. Requested ${pr.base.ref} at ${pr.base.sha}, checked out base ${base} with head ${pr.head.sha}. Start a fresh pull request event after the merge ref updates.`,
);
}
}
const paths =
const changes =
event === "pull_request" && !baseChanged
? execFileSync(
"git",
["diff", "--no-renames", "--name-only", "-z", "HEAD^1", "HEAD"],
["diff", "--no-renames", "--name-status", "-z", "HEAD^1", "HEAD"],
{ encoding: "utf8" },
)
.split("\0")
.filter(Boolean)
: [];
const selected = selectChecks(paths, { event, baseChanged });
const paths = changes.filter((_, i) => i % 2);
const modifiedOnly = changes.every((field, i) => i % 2 || field === "M");
const selected = selectChecks(paths, { event, baseChanged, modifiedOnly });
appendFileSync(
process.env.GITHUB_OUTPUT,
Object.entries(selected)
+192 -45
View File
@@ -1,5 +1,8 @@
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import { execFileSync, spawnSync } from "node:child_process";
import * as fs from "node:fs";
import { tmpdir } from "node:os";
import { join, resolve } from "node:path";
import { test } from "node:test";
import { selectChecks } from "./select-ci-checks.mjs";
import { failedChecks } from "./check-ci-results.mjs";
@@ -7,13 +10,18 @@ import { failedChecks } from "./check-ci-results.mjs";
const select = (paths, options = {}) =>
selectChecks(paths, { event: "pull_request", ...options });
const ubuntuNode24Install = JSON.stringify({
include: [{ os: "ubuntu-latest", node: "24" }],
});
const regularSource = {
"source-required": "true",
"container-required": "true",
"plugin-tests-required": "true",
"package-required": "true",
"action-ci": "false",
"eval-contracts": "true",
"workflow-quality": "false",
"container-validate": "true",
"compatibility-matrix": JSON.stringify({
include: [
{ os: "ubuntu-latest", node: "22.13.0" },
@@ -21,6 +29,7 @@ const regularSource = {
{ os: "ubuntu-latest", node: "24" },
{ os: "ubuntu-latest", node: "26.0.0" },
{ os: "macos-latest", node: "22.13.0" },
{ os: "windows-latest", node: "22.13.0" },
],
}),
"python-matrix": JSON.stringify({
@@ -38,13 +47,11 @@ const regularSource = {
},
],
}),
"windows-node-matrix": JSON.stringify({ node: ["22.13.0"] }),
};
const fullQualification = {
...regularSource,
"action-ci": "true",
"workflow-quality": "true",
"container-validate": "true",
"compatibility-matrix": JSON.stringify({
include: [
{ os: "ubuntu-latest", node: "22.13.0" },
@@ -53,6 +60,8 @@ const fullQualification = {
{ os: "ubuntu-latest", node: "26.0.0" },
{ os: "ubuntu-latest", node: "26" },
{ os: "macos-latest", node: "22.13.0" },
{ os: "windows-latest", node: "22.13.0" },
{ os: "windows-latest", node: "24" },
],
}),
"python-matrix": JSON.stringify({
@@ -72,17 +81,85 @@ const fullQualification = {
},
],
}),
"windows-node-matrix": JSON.stringify({ node: ["22.13.0", "24"] }),
};
const docs = {
...regularSource,
"source-required": "false",
"container-required": "false",
"plugin-tests-required": "false",
"package-required": "false",
"eval-contracts": "false",
"container-validate": "false",
};
test("the Docker context excludes the test modules skipped by container CI", () => {
const ignore = ["Dockerfile.dockerignore", ".dockerignore"]
.map((file) => new URL(`../../${file}`, import.meta.url))
.find((file) => fs.existsSync(file));
const rules = fs.readFileSync(ignore, "utf8");
assert.match(rules, /^plugins\/codex-security\/tests\r?$/m);
assert.match(rules, /^sdk\/typescript\/tests-ts\/\*\.test\.ts\r?$/m);
assert.doesNotMatch(rules, /^\s*!/m);
});
test("only edits to existing direct pytest modules skip independent jobs", (t) => {
const cwd = fs.mkdtempSync(resolve(tmpdir(), "ci-pytest-"));
t.after(() => fs.rmSync(cwd, { recursive: true, force: true }));
const files = join(cwd, "plugins/codex-security/tests");
const output = join(cwd, "output");
const script = join(import.meta.dirname, "select-ci-checks.mjs");
const env = {
...process.env,
EVENT_NAME: "pull_request",
BASE_CHANGED: "false",
GITHUB_OUTPUT: output,
};
// A Git hook may export its own repository and index into this process.
for (const name of Object.keys(env))
if (/^GIT_/iu.test(name)) delete env[name];
env.GIT_CONFIG_GLOBAL = join(cwd, "empty.gitconfig");
env.GIT_CONFIG_NOSYSTEM = "1";
const git = (...args) => execFileSync("git", args, { cwd, env });
git("init", "-q");
git("config", "user.name", "CI Fixture");
git("config", "user.email", "fixture@example.com");
fs.mkdirSync(files, { recursive: true });
let revision = 0;
function commit(...names) {
for (const name of names)
fs.writeFileSync(join(files, name), String(revision++));
git("add", "--force", "plugins");
git("commit", "-qm", "fixture");
}
commit("test_2fa.py", "conftest.py");
const reduced = {
...fullQualification,
"compatibility-matrix": JSON.stringify({
include: JSON.parse(
fullQualification["compatibility-matrix"],
).include.filter(({ os }) => os !== "windows-latest"),
}),
"source-required": "false",
"container-required": "false",
"action-ci": "false",
"eval-contracts": "false",
};
for (const [names, expected] of [
[["test_2fa.py"], reduced],
[["test_2fa.py", "test_added.py"], fullQualification],
[["test_2fa.py", "conftest.py"], fullQualification],
]) {
commit(...names);
fs.writeFileSync(output, "");
execFileSync(process.execPath, [script], { cwd, env });
const lines = fs.readFileSync(output, "utf8").trim().split("\n");
assert.deepEqual(
Object.fromEntries(lines.map((line) => line.split("="))),
expected,
);
}
});
test("ordinary documentation selects static checks", () => {
assert.deepEqual(select(["README.md", "docs/bedrock.md"]), docs);
for (const path of [
@@ -124,9 +201,7 @@ test("Action-only changes require Action CI and integration against the built pa
...docs,
"package-required": "true",
"action-ci": "true",
"compatibility-matrix": JSON.stringify({
include: [{ os: "ubuntu-latest", node: "24" }],
}),
"compatibility-matrix": ubuntuNode24Install,
};
for (const paths of [
["action.yml", "github-action/README.md"],
@@ -202,41 +277,32 @@ test("Standard and triage eval changes require all deterministic eval contracts"
);
});
test("packaged SDK documentation keeps package validation selected", () => {
const manifest = JSON.parse(
readFileSync(
new URL("../../sdk/typescript/package.json", import.meta.url),
"utf8",
),
);
for (const file of manifest.files.filter((file) => file.endsWith(".md"))) {
const path = `sdk/typescript/${file}`;
const selected = select([path]);
assert.deepEqual(selected, fullQualification, path);
test("packaged guides keep the archive and installed-package gates", () => {
const expected = {
...docs,
"package-required": "true",
"compatibility-matrix": ubuntuNode24Install,
};
for (const paths of [
["sdk/typescript/README.md"],
["RELEASING.md", "sdk/typescript/docs/cli.md"],
// --no-renames includes the old required path even when the new path is ordinary docs.
["sdk/typescript/docs/hosted-scans.md", "docs/hosted-scans.md"],
]) {
assert.deepEqual(select(paths), expected, paths.join(", "));
}
// The --no-renames diff reports the old path when a required doc is renamed.
const renamed = select([
"sdk/typescript/docs/hosted-scans.md",
"docs/hosted-scans.md",
]);
assert.equal(renamed["source-required"], "true");
assert.equal(
select(["README.md", "sdk/typescript/README.md"])["source-required"],
"true",
assert.deepEqual(
failedChecks({
"classify-changes": { result: "success", outputs: expected },
"static-checks": { result: "success" },
}),
["native", "package", "compatibility"],
);
});
test("release recovery documentation keeps its SDK contract selected", () => {
for (const paths of [["RELEASING.md"], ["README.md", "RELEASING.md"]]) {
const outputs = select(paths);
assert.deepEqual(outputs, fullQualification);
// release-automation.test.ts validates the documented recovery marker.
const missing = failedChecks({
"classify-changes": { result: "success", outputs },
"static-checks": { result: "success" },
});
assert.ok(missing.includes("test"));
}
test("release guide changes select the static route", () => {
assert.deepEqual(select(["RELEASING.md"]), docs);
assert.deepEqual(select(["README.md", "RELEASING.md"]), docs);
});
test("release helper changes select their release-progress regression checks", () => {
@@ -249,14 +315,49 @@ test("release helper changes select their release-progress regression checks", (
test("ordinary TypeScript source and tests retain the reduced version matrices", () => {
for (const path of [
"sdk/typescript/src/cost.ts",
"sdk/typescript/tests-ts/skeleton.test.ts",
"sdk/typescript/src/index.ts",
"sdk/typescript/tests-ts/support/test-subprocess.ts",
"plugins/codex-security/mcp-app/src/stdio-transport.ts",
"plugins/codex-security/mcp-app/tests/test_deep_scan_executor.ts",
"plugins/codex-security/mcp-app/tests/support/fixture.ts",
]) {
assert.deepEqual(select([path]), regularSource, path);
assert.deepEqual(select(["README.md", path]), regularSource, path);
for (const guide of ["README.md", "sdk/typescript/docs/cli.md"]) {
assert.deepEqual(select([guide, path]), regularSource, path);
}
}
});
test("SDK test-only PRs skip independent suites and retain any changed eval input", () => {
const paths = [
"sdk/typescript/tests-ts/skeleton.test.ts",
"sdk/typescript/tests-ts/windows-machine-policy.test.ts",
];
const sdk = {
...regularSource,
"container-required": "false",
"plugin-tests-required": "false",
"compatibility-matrix": ubuntuNode24Install,
};
assert.deepEqual(select(paths), { ...sdk, "eval-contracts": "false" });
assert.deepEqual(
select([...paths, "sdk/typescript/tests-ts/codex-dependency-pins.test.ts"]),
sdk,
);
for (const other of [
"README.md",
"sdk/typescript/tests-ts/support/test-subprocess.ts",
"sdk/typescript/src/api.ts",
]) {
assert.deepEqual(select([...paths, other]), regularSource, other);
}
for (const options of [
{ event: "push" },
{ event: "schedule" },
{ event: "workflow_dispatch" },
{ baseChanged: true },
]) {
assert.deepEqual(select(paths, options), fullQualification);
}
});
@@ -272,6 +373,9 @@ test("unknown paths and dependency configuration receive full qualification", ()
["other/sdk/typescript/src/runtime.ts"],
[".npmrc"],
["sdk/typescript/.npmrc"],
["sdk/typescript/docs/unlisted.md"],
["RELEASING.md", "sdk/typescript/src/api.ts"],
["sdk/typescript/docs/cli.md", "sdk/typescript/docs/unlisted.md"],
["plugins/codex-security/mcp-app/src/.npmrc"],
["pnpm-workspace.yaml"],
["sdk/typescript/pnpm-workspace.yaml"],
@@ -300,6 +404,13 @@ test("unknown paths and dependency configuration receive full qualification", ()
test("tooling and non-TypeScript product inputs receive full qualification", () => {
for (const path of [
"Dockerfile",
".github/workflows/container-ci.yml",
".github/workflows/container-validate.yml",
".github/workflows/container-release.yml",
".github/workflows/native-windows.yml",
"sdk/typescript/scripts/run-ci-tests.mts",
"plugins/codex-security/skills/example/SKILL.md",
"package.json",
"sdk/typescript/pnpm-lock.yaml",
"sdk/typescript/bunfig.toml",
@@ -332,7 +443,7 @@ test("main, scheduled, manual, empty and retargeted changes receive full qualifi
assert.deepEqual(select([]), fullQualification);
});
test("the final gate rejects every missing or unsuccessful selected check", () => {
function successfulFullRun() {
const outputs = select([".github/workflows/node-ci.yml"]);
const needs = Object.fromEntries(
[
@@ -347,13 +458,17 @@ test("the final gate rejects every missing or unsuccessful selected check", () =
"plugin-host",
"plugin-source",
"windows-test",
"windows-verify",
"workflow-quality",
"container-validate",
].map((name) => [name, { result: "success" }]),
);
needs["action-ci"].outputs = { passed: "true" };
needs["classify-changes"] = { result: "success", outputs };
return needs;
}
test("the final gate rejects every missing or unsuccessful selected check", () => {
const needs = successfulFullRun();
assert.deepEqual(failedChecks(needs), []);
for (const name of Object.keys(needs)) {
for (const result of ["failure", "cancelled", "skipped", undefined]) {
@@ -365,6 +480,37 @@ test("the final gate rejects every missing or unsuccessful selected check", () =
}
});
test("the final gate distinguishes a failed check from a skipped dependent job", () => {
const run = (needs) =>
spawnSync(process.execPath, ["check-ci-results.mjs"], {
cwd: new URL(".", import.meta.url),
env: { ...process.env, CI_RESULTS: JSON.stringify(needs) },
encoding: "utf8",
});
const needs = successfulFullRun();
const pythonTests = select(["plugins/codex-security/tests/test_workbench.py"], {
modifiedOnly: true,
});
const passed = run({
...needs,
"classify-changes": { result: "success", outputs: pythonTests },
test: { result: "failure" },
"windows-test": { result: "cancelled" },
"container-validate": { result: "skipped" },
});
assert.equal(passed.status, 0, passed.stderr);
assert.equal(passed.stdout.trim(), "All selected required CI checks passed.");
needs["static-checks"].result = "failure";
needs["container-validate"].result = "skipped";
const failed = run(needs);
assert.equal(failed.status, 1, failed.stderr);
assert.match(
failed.stderr,
/^Required CI checks did not pass: static-checks \(failure\), container-validate \(skipped\)$/m,
);
});
test("documentation requires static checks and explicit selection, without skipped source failures", () => {
const outputs = select(["README.md"]);
const needs = {
@@ -378,11 +524,12 @@ test("documentation requires static checks and explicit selection, without skipp
);
for (const key of [
"source-required",
"container-required",
"plugin-tests-required",
"package-required",
"action-ci",
"eval-contracts",
"workflow-quality",
"container-validate",
]) {
assert.deepEqual(
failedChecks({
+21
View File
@@ -0,0 +1,21 @@
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import { test } from "node:test";
import { extractHistoricalReleaseSummary } from "../../sdk/typescript/scripts/release-automation.mjs";
test("the release recovery guide documents a canonical historical-summary block", () => {
const guide = readFileSync(
new URL("../../RELEASING.md", import.meta.url),
"utf8",
);
const recovery = guide.split("## Recover or repair a release")[1] ?? "";
const start = "<!-- codex-security-release-summary:start -->";
const end = "<!-- codex-security-release-summary:end -->";
const block = [...recovery.matchAll(/^```text\r?\n([\s\S]*?)^```[ \t]*$/gmu)]
.map((match) => match[1].replaceAll("\r\n", "\n"))
.find((example) => example.includes(start) && example.includes(end));
assert.ok(block?.startsWith(`${start}\n`));
assert.ok(block.includes(`${end}\n\n`));
assert.equal(extractHistoricalReleaseSummary(block), "Reviewed summary");
});
+70 -20
View File
@@ -6,7 +6,7 @@ import { join } from "node:path";
import test from "node:test";
import { pathToFileURL } from "node:url";
import {
checkCheckout,
checkoutBase,
confirmEdit,
realSource,
verifyEdit,
@@ -23,6 +23,7 @@ const passed = { status: "completed", conclusion: "success" };
function run(id, changes = {}) {
return {
id,
html_url: `https://github.com/example/repo/actions/runs/${id}`,
run_number: id,
run_attempt: 1,
run_started_at: id,
@@ -39,11 +40,7 @@ function run(id, changes = {}) {
const edit = (id, changes) =>
run(id, { display_title: "PR edit CI · PR #42 → main", ...changes });
function evidence(id, selected = "success") {
const names = [
"ci",
"classify changes",
...["ubuntu", "macos", "windows"].map((os) => os + "-latest / node-22"),
];
const names = ["ci", "classify changes"];
const selection = {
name: "Select required checks",
status: "completed",
@@ -60,7 +57,14 @@ function evidence(id, selected = "success") {
}
function fixture(
history,
{ jobs = evidence, targets = [target], wait = false, runAttempt = 1 } = {},
{
jobs = evidence,
targets = [target],
wait = false,
runAttempt = 1,
base = pr.base.sha,
comparisons = [],
} = {},
) {
let current = [],
live = target;
@@ -70,6 +74,12 @@ function fixture(
if (live instanceof Error) throw live;
return live;
}
if (path.startsWith("compare/")) {
assert.equal(path, "compare/refs%2Fheads%2Fmain...base?per_page=1");
const result = comparisons.shift();
if (result instanceof Error) throw result;
return result;
}
const runId = path.match(/runs\/(\d+)\/jobs/);
if (runId) return jobs(Number(runId[1]));
current = history.shift() ?? current;
@@ -78,7 +88,7 @@ function fixture(
const runs = [edit(99, { run_attempt: runAttempt }), ...current];
return { total_count: runs.length, workflow_runs: runs };
};
const input = { pr, sha, runId: 99, runAttempt, api };
const input = { pr, sha, base, runId: 99, runAttempt, api };
return {
check: () => verifyEdit(input, () => wait),
finish: (id, classifierAttempt = runAttempt) =>
@@ -134,8 +144,9 @@ test("only fresh canonical source jobs and genuine selection can qualify a sourc
assert.ok(realSource(page, source));
for (const change of [
{ total_count: 99 },
{ jobs: page.jobs.slice(1) },
{ total_count: 6, jobs: [...page.jobs, page.jobs[0]] },
{ total_count: 1, jobs: page.jobs.slice(1) },
{ total_count: 1, jobs: page.jobs.slice(0, 1) },
{ total_count: 3, jobs: [...page.jobs, page.jobs[0]] },
{ jobs: page.jobs.map((j) => ({ ...j, run_id: 1 })) },
{ jobs: page.jobs.map((j) => ({ ...j, run_attempt: 2 })) },
{
@@ -148,7 +159,7 @@ test("only fresh canonical source jobs and genuine selection can qualify a sourc
assert.ok(!realSource({ ...page, ...change }, source));
});
test("pending sources settle, genuine red remains red, and newer attempts cannot be masked", async () => {
test("pending sources settle, genuine red remains red, and newer attempts cannot be masked", async (t) => {
const green = run(3),
red = run(3, { conclusion: "failure" }),
pending = run(3, { status: "in_progress" });
@@ -163,10 +174,14 @@ test("pending sources settle, genuine red remains red, and newer attempts cannot
await fixture([[green, run(1, { run_attempt: 2 })]]).check(),
"full",
);
const log = t.mock.method(console, "log", () => {});
assert.equal(
await fixture([[edit(8, { conclusion: "failure" }), red]]).check(),
"failed",
);
assert.deepEqual(log.mock.calls[0]?.arguments, [
`Failed source CI: ${red.html_url}/attempts/1`,
]);
for (const changed of [
[run(3, { run_attempt: 2 })],
[run(5, { conclusion: "failure" }), green],
@@ -187,7 +202,7 @@ test("retrying a failed edit cannot replace its full checks with older green res
await retry.finish();
});
test("even full fallback needs a current target; repeat this check just before the aliases", async () => {
test("even full fallback needs a current target when the CI gate finishes", async () => {
const stale = { ...target, base: { ...pr.base, ref: "other" } },
unavailable = new Error("target unavailable");
for (const history of [
@@ -218,6 +233,45 @@ test("even full fallback needs a current target; repeat this check just before t
);
});
test("an edit can use a newer test-merge base only while its named branch still proves that advance", async () => {
const base = "new-base";
const current = { base_commit: { sha: base }, status: "behind" };
const changed = { base_commit: { sha: "moved" }, status: "behind" };
const check = (comparisons, history = [[run(2)]]) =>
fixture(history, { base, comparisons });
const updated = { ...target, base: { ...pr.base, sha: base } };
const source = run(2, { pull_requests: [updated] });
const caughtUp = fixture([[run(2)], [source]], {
base,
comparisons: [current, current, current],
targets: [target, updated],
});
assert.equal(await caughtUp.check(), 2);
await caughtUp.finish(2);
await assert.rejects(
fixture([[source]], {
base,
targets: [{ ...updated, base: { ...pr.base, sha: "unrelated" } }],
}).finish(2),
/target changed/,
);
assert.equal(await check([current, current], [[]]).check(), "full");
for (const invalid of [
changed,
{ ...current, status: "ahead" },
{ ...current, status: "diverged" },
{ ...current, status: "identical" },
new Error("comparison unavailable"),
]) {
const error =
invalid instanceof Error ? /comparison unavailable/ : /Stale test merge/;
await assert.rejects(check([invalid]).check(), error);
await assert.rejects(check([current, invalid]).check(), error);
await assert.rejects(check([invalid]).finish(2), error);
await assert.rejects(check([invalid]).finish(), error);
}
});
test("the final gate reads both actual merge parents from a depth-one checkout", (t) => {
const root = mkdtempSync(join(tmpdir(), "ci-source-parents-"));
t.after(() => rmSync(root, { recursive: true, force: true }));
@@ -262,14 +316,10 @@ test("the final gate reads both actual merge parents from a depth-one checkout",
);
assert.equal(git(checkout, "rev-parse", "--is-shallow-repository"), "true");
const pull = { base: { sha: base }, head: { sha: head } };
checkCheckout(pull, merge, checkout);
assert.equal(checkoutBase(pull, merge, checkout), base);
assert.throws(
() => checkCheckout({ ...pull, base: { sha: head } }, merge, checkout),
/checked-out merge/,
() => checkoutBase({ ...pull, head: { sha: base } }, merge, checkout),
/Stale test merge/,
);
assert.throws(
() => checkCheckout({ ...pull, head: { sha: base } }, merge, checkout),
/checked-out merge/,
);
assert.throws(() => checkCheckout(pull, base, checkout), /checked-out merge/);
assert.throws(() => checkoutBase(pull, base, checkout), /Stale test merge/);
});
@@ -92,10 +92,10 @@ test("checkout preserves source size with autocrlf", () => {
git(root, "add", "--", ".gitattributes", name);
unlinkSync(source);
git(root, "checkout-index", "--", name);
const result = runChecker("--plugin-root", root);
assert.equal(result.status, 0, result.stderr);
assert.deepEqual(readFileSync(source), content);
}
const result = runChecker("--plugin-root", root);
assert.equal(result.status, 0, result.stderr);
});
test("accepts Markdown structures, natural line endings, and inline markup", () => {
+39 -27
View File
@@ -7,51 +7,61 @@ const utf8 = { encoding: "utf8" };
const successful = (job) =>
job.status === "completed" && job.conclusion === "success";
function samePull(candidate, pr) {
function samePull(candidate, pr, base) {
return (
candidate?.number === pr.number &&
candidate.head?.sha === pr.head.sha &&
[pr.base.sha, base].includes(candidate.base?.sha) &&
["head", "base"].every(
(side) =>
candidate[side]?.ref === pr[side].ref &&
candidate[side]?.sha === pr[side].sha &&
candidate[side].repo?.id === pr[side].repo.id,
)
);
}
export function checkCheckout(pr, sha, cwd) {
const git = (args) =>
execFileSync("git", args, { encoding: "utf8", cwd }).trim();
// The CI gate uses a depth-one checkout. Read its parent IDs from the raw object.
const headers = git(["cat-file", "-p", "HEAD"])
export function checkoutBase(pr, sha, cwd) {
// A depth-one checkout still contains the raw commit and its parent IDs.
const [object, ...headers] = execFileSync("git", ["cat-file", "--batch"], {
cwd,
input: "HEAD\n",
encoding: "utf8",
})
.split("\n\n", 1)[0]
.split("\n");
const parents = headers
.filter((h) => h.startsWith("parent "))
.map((h) => h.slice(7));
.filter((line) => line.startsWith("parent "))
.map((line) => line.slice(7));
if (
git(["rev-parse", "HEAD"]) !== sha ||
parents.join(" ") !== `${pr.base.sha} ${pr.head.sha}`
!object.startsWith(`${sha} commit `) ||
parents.length !== 2 ||
parents[1] !== pr.head.sha
)
throw new Error(
"The checked-out merge does not match the pull request base and head. Reopen the pull request or push a commit to qualify its current target.",
`Stale test merge. Expected ${sha} with head ${pr.head.sha}, checked out ${object} with parents ${parents.join(" ")}. Start a fresh pull request event.`,
);
return parents[0];
}
export async function confirmTarget(pr, sha, api) {
async function confirmTarget({ pr, sha, base, api }) {
const live = await api(`pulls/${pr.number}`);
if (!samePull(live, pr) || live.merge_commit_sha !== sha)
if (!samePull(live, pr, base) || live.merge_commit_sha !== sha)
throw new Error(
"The pull request target changed while its checks were running.",
);
if (base !== pr.base.sha) {
// PR metadata can lag its test merge. Compare the named branch itself, including its ancestry.
const ref = encodeURIComponent(`refs/heads/${pr.base.ref}`);
const comparison = await api(`compare/${ref}...${pr.base.sha}?per_page=1`);
if (comparison.base_commit.sha !== base || comparison.status !== "behind")
throw new Error(
`Stale test merge. Checked out base ${base}, but ${pr.base.ref} is at ${comparison.base_commit.sha} and event base ${pr.base.sha} is ${comparison.status}. Reopen the pull request or push a commit after its merge ref updates.`,
);
}
}
export function realSource(page, run) {
const required = [
"ci",
"classify changes",
...["ubuntu", "macos", "windows"].map((os) => `${os}-latest / node-22`),
];
const required = ["ci", "classify changes"];
const jobs = page.jobs.filter((job) => required.includes(job.name));
if (
page.total_count !== page.jobs.length ||
@@ -70,7 +80,7 @@ export function realSource(page, run) {
);
}
function sourceCandidate(runs, { pr, sha }) {
function sourceCandidate(runs, { pr, sha, base }) {
const target = `PR #${pr.number} → ${pr.base.ref}`;
const source = `Source CI · ${target}`;
const edit = `PR edit CI · ${target}`;
@@ -80,7 +90,7 @@ function sourceCandidate(runs, { pr, sha }) {
run.event === "pull_request" &&
run.head_sha === pr.head.sha &&
run.run_attempt === 1 &&
run.pull_requests.some((p) => samePull(p, pr)) &&
run.pull_requests.some((p) => samePull(p, pr, base)) &&
refs?.length &&
refs.every(
(ref) => ref.sha === sha && ref.ref === `refs/pull/${pr.number}/merge`,
@@ -97,7 +107,10 @@ function sourceCandidate(runs, { pr, sha }) {
return "full";
if (runs.some((r) => r.status !== "completed")) return "pending";
if (runs.every(successful)) return first;
if (runs.every((r) => r.conclusion === "failure")) return "failed";
if (runs.every((r) => r.conclusion === "failure")) {
console.log(`Failed source CI: ${first.html_url}/attempts/1`);
return "failed";
}
return "full";
}
@@ -142,8 +155,7 @@ async function verifyHistory(input, wait) {
}
export async function verifyEdit(input, wait) {
const { pr, sha, api } = input;
await confirmTarget(pr, sha, api);
await confirmTarget(input);
let result;
try {
result = await verifyHistory(input, wait);
@@ -154,7 +166,7 @@ export async function verifyEdit(input, wait) {
result = "full";
}
// A history failure can select full CI only while the originating PR target is still current.
await confirmTarget(pr, sha, api);
await confirmTarget(input);
return result;
}
@@ -165,7 +177,7 @@ export async function confirmEdit(input, expectedId, classifierAttempt) {
throw new Error(
"The selected source qualification changed before the CI gate finished.",
);
await confirmTarget(input.pr, input.sha, input.api);
await confirmTarget(input);
}
if (
@@ -177,7 +189,6 @@ if (
readFileSync(env.GITHUB_EVENT_PATH, "utf8"),
);
const sha = env.GITHUB_SHA;
checkCheckout(pr, sha);
function api(path) {
const endpoint = `repos/${env.GITHUB_REPOSITORY}/${path}`;
return JSON.parse(execFileSync("gh", ["api", endpoint], utf8));
@@ -185,6 +196,7 @@ if (
const input = {
pr,
sha,
base: checkoutBase(pr, sha),
runId: Number(env.GITHUB_RUN_ID),
runAttempt: Number(env.GITHUB_RUN_ATTEMPT),
api,
@@ -0,0 +1,21 @@
name: Clean merged PR caches
on:
pull_request_target:
branches: [main]
types: [closed]
permissions: {}
jobs:
clean:
if: github.event.pull_request.merged
runs-on: ubuntu-latest
permissions:
actions: write
steps:
- name: Delete caches for this PR's merge ref
env:
GH_TOKEN: ${{ github.token }}
PR_NUMBER: ${{ github.event.pull_request.number }}
run: gh cache delete --all --ref "refs/pull/$PR_NUMBER/merge" --succeed-on-no-caches --repo "$GITHUB_REPOSITORY"
+2
View File
@@ -73,6 +73,8 @@ jobs:
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@f87e5991a6d7451dcb8d9637bfbc97413f497069 # v4.4.1
with:
driver-opts: provenance-add-gha=false
- name: Build native customer image
uses: docker/build-push-action@c3c9e263c25d99ce0380d002d59b67737d91b0dc # v7.4.0
+12 -34
View File
@@ -11,6 +11,10 @@ on:
description: Reuse this week's verified payload when all native build and proof inputs match.
type: boolean
default: false
cache-week:
description: UTC ISO year and week selected by the source CI classifier; zero uses the current week.
type: number
default: 0
workflow_dispatch:
permissions:
@@ -30,29 +34,10 @@ jobs:
persist-credentials: false
- name: Identify native build and proof inputs
id: key
shell: bash
run: |
set -euo pipefail
# Include filenames and modes, not only file contents. Windows proofs
# bundle MCP helpers, including their schema and workbench dependencies.
empty_tree="$(git hash-object -t tree --stdin </dev/null)"
source_hash="$(git diff-tree -r -z --no-abbrev "$empty_tree" HEAD -- \
.gitattributes .cargo .npmrc .pnpmfile.cjs package.json pnpm-workspace.yaml \
.github/actions/setup-tools .github/scripts ':(exclude).github/scripts/invoice-desk-*.mjs' \
.github/workflows/native-artifacts.yml \
.github/workflows/native-unix.yml \
.github/workflows/native-windows.yml \
.github/workflows/native-musl.yml \
sdk/typescript/.npmrc sdk/typescript/.pnpmfile.cjs \
sdk/typescript/package.json sdk/typescript/pnpm-lock.yaml \
sdk/typescript/pnpm-workspace.yaml \
sdk/typescript/tsconfig.json sdk/typescript/tsconfig.ci.json \
plugins/codex-security/native plugins/codex-security/mcp-app \
':(exclude)plugins/codex-security/mcp-app/tests' \
plugins/codex-security/schemas plugins/codex-security/scripts \
plugins/codex-security/shared | git hash-object --stdin)"
# Hosted runner images can change without a source change.
printf 'key=native-universal-v1-%s-%s\n' "$(date -u +%G-%V)" "$source_hash" >> "$GITHUB_OUTPUT"
# Resolve the helper from this workflow even when the caller selects an older checkout.
uses: $/.github/actions/native-cache-key
env:
NATIVE_CACHE_WEEK: ${{ inputs.cache-week }}
- name: Restore verified native payload
if: inputs.reuse-verified
id: restore
@@ -90,32 +75,26 @@ jobs:
ref: ${{ inputs.ref || github.sha }}
bundle:
needs: [prepare, unix, windows, musl]
if: ${{ !cancelled() }}
if: ${{ !cancelled() && (needs.prepare.result != 'success' || needs.prepare.outputs.cache-hit != 'true') }}
runs-on: ubuntu-24.04
steps:
- name: Require a verified native payload
- name: Require every native build to pass
shell: bash
env:
PREPARE_RESULT: ${{ needs.prepare.result }}
CACHE_HIT: ${{ needs.prepare.outputs.cache-hit }}
UNIX_RESULT: ${{ needs.unix.result }}
WINDOWS_RESULT: ${{ needs.windows.result }}
MUSL_RESULT: ${{ needs.musl.result }}
run: |
set -euo pipefail
[[ "$PREPARE_RESULT" == success ]] || exit 1
if [[ "$CACHE_HIT" != true ]]; then
[[ "$UNIX_RESULT" == success && "$WINDOWS_RESULT" == success && "$MUSL_RESULT" == success ]] || exit 1
fi
[[ "$PREPARE_RESULT" == success && "$UNIX_RESULT" == success &&
"$WINDOWS_RESULT" == success && "$MUSL_RESULT" == success ]]
- name: Download verified platform payloads
if: needs.prepare.outputs.cache-hit != 'true'
uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
with:
pattern: native-platform-*-${{ inputs.ref || github.sha }}
merge-multiple: true
path: native
- name: Upload universal native payload
if: needs.prepare.outputs.cache-hit != 'true'
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
with:
name: native-universal-${{ inputs.ref || github.sha }}
@@ -125,7 +104,6 @@ jobs:
retention-days: 7
- name: Save verified native payload from main
if: >-
needs.prepare.outputs.cache-hit != 'true' &&
github.ref == 'refs/heads/main' &&
(github.event_name == 'push' || github.event_name == 'schedule') &&
(inputs.ref == '' || inputs.ref == github.sha)
+50 -86
View File
@@ -29,17 +29,19 @@ jobs:
actions: read
pull-requests: read
outputs:
native-cache-group: ${{ steps.native-cache.outputs.cold-group }}
native-cache-week: ${{ steps.native-cache.outputs.week }}
source-run: ${{ steps.proof.outputs.source-run }}
edit-attempt: ${{ steps.proof.outputs.edit-attempt }}
source-required: ${{ steps.scope.outputs.source-required }}
container-required: ${{ steps.scope.outputs.container-required }}
plugin-tests-required: ${{ steps.scope.outputs.plugin-tests-required }}
package-required: ${{ steps.scope.outputs.package-required }}
action-ci: ${{ steps.scope.outputs.action-ci }}
eval-contracts: ${{ steps.scope.outputs.eval-contracts }}
container-validate: ${{ steps.scope.outputs.container-validate }}
workflow-quality: ${{ steps.scope.outputs.workflow-quality }}
compatibility-matrix: ${{ steps.scope.outputs.compatibility-matrix }}
python-matrix: ${{ steps.scope.outputs.python-matrix }}
windows-node-matrix: ${{ steps.scope.outputs.windows-node-matrix }}
steps:
- name: Checkout repository for change classification
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
@@ -60,6 +62,14 @@ jobs:
BASE_CHANGED: ${{ github.event.action == 'edited' }}
run: node .github/scripts/select-ci-checks.mjs
- name: Group protected pushes waiting for the same native cache
id: native-cache
if: github.event_name == 'push' && github.ref == 'refs/heads/main' && github.ref_protected && github.run_attempt == 1
continue-on-error: true
env:
GH_TOKEN: ${{ github.token }}
run: bash .github/actions/native-cache-key/key.sh cold-group >> "$GITHUB_OUTPUT"
workflow-quality:
needs: classify-changes
if: needs.classify-changes.outputs.workflow-quality == 'true'
@@ -104,8 +114,8 @@ jobs:
env:
GH_TOKEN: ${{ github.token }}
run: node --experimental-strip-types sdk/typescript/scripts/check-devcontainer-cooldown.mts
- name: Test CI selection and result gating
run: node --test .github/scripts/test-ci-selection.mjs .github/scripts/test-verify-pr-source.mjs
- name: Test CI selection, result gating and the release guide
run: node --test .github/scripts/test-ci-selection.mjs .github/scripts/test-verify-pr-source.mjs .github/scripts/test-release-guide.mjs
- name: Typecheck
run: pnpm --dir sdk/typescript run types
- name: Check formatting
@@ -118,13 +128,18 @@ jobs:
native:
if: needs.classify-changes.outputs.package-required == 'true'
needs: classify-changes
# Hits and PRs keep a unique group. Every entrant restores or rebuilds on its own commit.
concurrency:
group: native-producer-${{ github.run_attempt == 1 && needs.classify-changes.outputs.native-cache-group || github.run_id }}
queue: max
uses: ./.github/workflows/native-artifacts.yml
with:
reuse-verified: true
cache-week: ${{ fromJSON(github.run_attempt == 1 && needs.classify-changes.outputs.native-cache-week || '0') }}
container-validate:
needs: [classify-changes, native, static-checks]
if: needs.classify-changes.outputs.container-validate == 'true'
if: needs.classify-changes.outputs.container-required == 'true'
uses: ./.github/workflows/container-validate.yml
package:
@@ -161,9 +176,13 @@ jobs:
retention-days: 7
test:
if: needs.classify-changes.outputs.source-required == 'true'
if: &run-sdk-shards >-
${{ !cancelled() && needs.package.result == 'success' &&
needs['classify-changes'].outputs['source-required'] == 'true' &&
(github.event_name != 'pull_request' || github.event.action == 'edited' ||
needs['static-checks'].result == 'success') }}
name: tests / ${{ matrix.os }} / shard-${{ matrix.shard }}
needs: [classify-changes, package]
needs: &sdk-shard-needs [classify-changes, package, static-checks]
runs-on: ${{ matrix.os }}
timeout-minutes: ${{ matrix.os == 'macos-latest' && 30 || 20 }}
strategy:
@@ -192,6 +211,7 @@ jobs:
run: |
tar -xzf dist/*.tgz --strip-components=1 -C sdk/typescript package/_bundled_plugin
cp -R sdk/typescript/_bundled_plugin/mcp/native/. plugins/codex-security/native/prebuilt
python3 -I -m compileall -q --invalidation-mode checked-hash sdk/typescript/_bundled_plugin/scripts
- name: Set up Linux test tools and sandbox
if: matrix.os == 'ubuntu-latest'
run: |
@@ -204,6 +224,7 @@ jobs:
TMP: ${{ runner.temp }}
TMPDIR: ${{ runner.temp }}
CODEX_SECURITY_ALLOW_MACHINE_POLICY_TEST: "false"
CODEX_SECURITY_TEST_MCP_WORKERS_SEPARATE: ${{ needs.classify-changes.outputs.plugin-tests-required }}
run: node --experimental-strip-types scripts/run-ci-tests.mts ${{ matrix.shard }}/6 --seed=${{ github.run_number }} ${{ matrix.os == 'ubuntu-latest' && '--coverage --coverage-reporter=text --coverage-reporter=lcov' || '' }}
- name: Upload test reports
if: always()
@@ -230,16 +251,19 @@ jobs:
matrix: ${{ fromJSON(needs.classify-changes.outputs.compatibility-matrix) }}
steps:
- *checkout-repository
- &set-up-node-js
name: Set up Node.js
- name: Set up Python on Windows
if: runner.os == 'Windows'
uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0
with:
python-version: "3.12"
- name: Set up Node.js
id: node
uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
with:
node-version: ${{ matrix.node }}
cache: npm
cache-dependency-path: sdk/typescript/pnpm-lock.yaml
- &resolve-npm-cache
name: Resolve npm download cache
- name: Resolve npm download cache
id: npm-cache
if: steps.node.outputs.cache-hit != 'true'
shell: bash
@@ -248,8 +272,7 @@ jobs:
run: |
echo "path=$(npm config get cache)" >> "$GITHUB_OUTPUT"
echo "restore-prefix=${PRIMARY_CACHE_KEY%-*}-" >> "$GITHUB_OUTPUT"
- &restore-npm-cache
name: Restore previous npm downloads
- name: Restore previous npm downloads
if: steps.node.outputs.cache-hit != 'true'
uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
with:
@@ -259,8 +282,9 @@ jobs:
- *download-package-for-this-commit
- name: Inspect installed package
working-directory: sdk/typescript
env: &package-deep-retry
# On PRs, exercise the real retry delay on each OS's floor or only runtime.
shell: bash
env:
# A successful main push can be tagged for release. Only PRs sample retries by runtime.
PACKAGE_DEEP_RETRY: ${{ github.event_name != 'pull_request' || matrix.node == '22.13.0' || strategy.job-total == 1 }}
run: node scripts/check-package.mjs ../../dist/*.tgz
@@ -269,7 +293,7 @@ jobs:
uses: ./.github/actions/check-action-candidate
mcp:
if: needs.classify-changes.outputs.source-required == 'true'
if: needs.classify-changes.outputs.plugin-tests-required == 'true'
name: MCP app tests (${{ matrix.shard }}/${{ strategy.job-total }})
needs: [classify-changes, package]
runs-on: ubuntu-latest
@@ -294,11 +318,9 @@ jobs:
run: tar -xzf dist/*.tgz --strip-components=1 -C sdk/typescript package/_bundled_plugin
- name: Test MCP app
working-directory: plugins/codex-security/mcp-app
# Keep Node options before the glob; trailing shard flags run every file.
run: >-
node --experimental-strip-types --test --test-concurrency=2
--test-shard=${{ matrix.shard }}/${{ strategy.job-total }}
--test-reporter=./scripts/test_reporter.mts "tests/test_*.ts"
node --experimental-strip-types ../../../sdk/typescript/scripts/run-mcp-test-shard.mts
${{ matrix.shard }} ${{ strategy.job-total }}
- name: Upload MCP test reports
if: always()
continue-on-error: true
@@ -311,7 +333,7 @@ jobs:
retention-days: 14
plugin-host:
if: needs.classify-changes.outputs.source-required == 'true'
if: needs.classify-changes.outputs.plugin-tests-required == 'true'
name: standalone plugin / ${{ matrix.os }}
needs: classify-changes
runs-on: ${{ matrix.os }}
@@ -335,7 +357,7 @@ jobs:
run: node --experimental-strip-types --test plugins/codex-security/mcp-app/scripts/test_host_build.mts
plugin-source:
if: needs.classify-changes.outputs.source-required == 'true'
if: needs.classify-changes.outputs.plugin-tests-required == 'true'
name: plugin source contracts / ${{ matrix.os }} / python-${{ matrix.python }}
needs: classify-changes
runs-on: ${{ matrix.os }}
@@ -345,16 +367,10 @@ jobs:
matrix: ${{ fromJSON(needs.classify-changes.outputs.python-matrix) }}
steps:
- *checkout-repository
- name: Set up Node.js
if: matrix.os == 'ubuntu-latest' && matrix.python == '3.12'
uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
with:
node-version: "22.13.0"
- name: Set up pnpm
- name: Set up TypeScript tools
if: matrix.os == 'ubuntu-latest' && matrix.python == '3.12'
uses: ./.github/actions/setup-tools
with:
setup-node: false
compile: true
cache-dependency-path: |
sdk/typescript/pnpm-lock.yaml
@@ -425,14 +441,10 @@ jobs:
- *set-up-bun
- name: Check the Codex version across the SDK, MCP app and evals
run: bun test sdk/typescript/tests-ts/codex-dependency-pins.test.ts
- uses: pnpm/action-setup@ea17c68df8912ef543352723c149a84f56e3d413 # v6.1.0
with:
package_json_file: package.json
- name: Set up eval Node.js and pnpm cache
uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
- name: Set up eval tools
uses: ./.github/actions/setup-tools
with:
node-version: "24.15.0"
cache: pnpm
cache-dependency-path: |
sdk/typescript/pnpm-lock.yaml
plugins/codex-security/mcp-app/pnpm-lock.yaml
@@ -442,8 +454,6 @@ jobs:
uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0
with:
python-version: "3.12"
- name: Install ripgrep
run: .github/scripts/install-ripgrep.sh
- name: Set up eval dependencies and host runtime
run: |
pnpm --dir sdk/typescript install --frozen-lockfile
@@ -480,9 +490,8 @@ jobs:
container-validate,
workflow-quality,
windows-test,
windows-verify,
]
if: &source-aggregate always()
if: always()
runs-on: ubuntu-latest
permissions:
contents: read
@@ -502,33 +511,10 @@ jobs:
CLASSIFIER_ATTEMPT: ${{ needs.classify-changes.outputs.edit-attempt }}
run: node .github/scripts/verify-pr-source.mjs confirm-target
# Retain required names until the repository ruleset has migrated to `ci`.
required-test:
name: ${{ matrix.os }} / node-22
needs: [classify-changes, ci]
if: *source-aggregate
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
os: [ubuntu-latest, macos-latest, windows-latest]
steps:
- name: Require CI gate
if: needs.ci.result != 'success'
run: exit 1
- name: Require the edit classifier from this attempt
if: >-
github.event_name == 'pull_request' && github.event.action == 'edited' &&
github.event.changes.base == null &&
needs['classify-changes'].outputs['edit-attempt'] != github.run_attempt
run: |
echo 'Re-run all jobs to qualify this pull request edit.'
exit 1
windows-test:
if: needs.classify-changes.outputs.source-required == 'true'
if: *run-sdk-shards
name: windows-latest / node-22 / tests-${{ matrix.shard }}
needs: [classify-changes, package]
needs: *sdk-shard-needs
runs-on: windows-latest
timeout-minutes: 120
strategy:
@@ -579,25 +565,3 @@ jobs:
TMPDIR: ${{ steps.windows-temp.outputs.path }}
CODEX_SECURITY_ALLOW_MACHINE_POLICY_TEST: "true"
run: bun test --timeout 360000 ./tests-ts/windows-machine-policy.test.ts
windows-verify:
if: needs.classify-changes.outputs.source-required == 'true'
name: windows-latest / node-${{ matrix.node == '22.13.0' && '22' || matrix.node }} / verify
needs: [classify-changes, package]
runs-on: windows-latest
timeout-minutes: 20
strategy:
fail-fast: false
matrix: ${{ fromJSON(needs.classify-changes.outputs.windows-node-matrix) }}
steps:
- *checkout-repository
- *set-up-python
- *set-up-node-js
- *resolve-npm-cache
- *restore-npm-cache
- *download-package-for-this-commit
- name: Inspect installed package
working-directory: sdk/typescript
shell: bash
env: *package-deep-retry
run: node scripts/check-package.mjs ../../dist/*.tgz
+7 -20
View File
@@ -56,29 +56,16 @@ jobs:
shell: bash
run: |
set -euo pipefail
npm_tools="$RUNNER_TEMP/codex-security-provenance-npm"
npm install \
--prefix "$npm_tools" \
--ignore-scripts \
--no-audit \
--no-fund \
--registry=https://openai.firewall.socket.dev/npm/ \
npm@11.12.1
source .github/scripts/release-npm.sh
install_release_npm
printf '%s\n' "$release_npm_bin" >> "$GITHUB_PATH"
if [[ "$("$npm_tools/node_modules/.bin/npm" --version)" != "11.12.1" ]]; then
echo "npm 11.12.1 is required to verify Sigstore attestations." >&2
exit 1
fi
printf '%s\n' "$npm_tools/node_modules/.bin" >> "$GITHUB_PATH"
- name: Verify bundled provenance-capable npm
- name: Verify npm on PATH
shell: bash
run: |
set -euo pipefail
if [[ "$(npm --version)" != "11.12.1" ]]; then
echo "npm 11.12.1 is required to verify Sigstore attestations." >&2
exit 1
fi
source .github/scripts/release-npm.sh
verify_release_npm "$(command -v npm)"
- name: Resolve the successful protected release
id: release
@@ -529,7 +516,7 @@ jobs:
uses: SocketDev/action@ba6de6cc0565af1f42295590380973573297e31f # v1.3.2
with:
mode: firewall-free
firewall-version: "1.15.0"
firewall-version: "1.15.4"
- name: Set up the Ubuntu sandbox
run: bash automation/github-action/scripts/setup-ubuntu-sandbox.sh
+50 -39
View File
@@ -10,12 +10,22 @@ on:
permissions:
contents: read
concurrency:
group: node-release-cut
queue: max
jobs:
progress:
if: >-
github.repository == 'openai/codex-security' &&
github.event_name == 'workflow_run' &&
github.event.workflow_run.event == 'push'
uses: ./.github/workflows/release-progress.yml
permissions:
actions: write
contents: read
pull-requests: write
cut:
concurrency:
group: node-release-cut
queue: max
if: >-
github.repository == 'openai/codex-security' &&
(github.event_name == 'workflow_dispatch' ||
@@ -35,6 +45,9 @@ jobs:
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
fetch-depth: 0
sparse-checkout: |
.github
sdk/typescript/scripts
persist-credentials: false
ref: ${{ github.event.workflow_run.head_sha || github.sha }}
@@ -89,47 +102,45 @@ jobs:
fi
if [[ "$GITHUB_EVENT_NAME" == "workflow_run" ]] &&
previous_sha="$(git rev-parse "$RELEASE_SHA^" 2>/dev/null)"; then
if previous_manifest="$(git show "$previous_sha:sdk/typescript/package.json" 2>/dev/null)"; then
previous_version="$(
printf '%s\n' "$previous_manifest" |
node --input-type=module --eval '
import { readFileSync } from "node:fs";
const manifest = JSON.parse(readFileSync(0, "utf8"));
if (typeof manifest.version !== "string") {
throw new Error("The previous package version is missing.");
}
process.stdout.write(manifest.version);
'
previous_manifest_oid="$(git rev-parse --verify "$RELEASE_SHA^:sdk/typescript/package.json" 2>/dev/null)"; then
previous_version="$(
git cat-file blob "$previous_manifest_oid" |
node --input-type=module --eval '
import { readFileSync } from "node:fs";
const manifest = JSON.parse(readFileSync(0, "utf8"));
if (typeof manifest.version !== "string") {
throw new Error("The previous package version is missing.");
}
process.stdout.write(manifest.version);
'
)"
if [[ "$version" == "$previous_version" ]]; then
release_mode="$(
printf '%s\n' "$published_versions" |
node sdk/typescript/scripts/release-automation.mjs \
release-mode "$version"
)"
if [[ "$version" == "$previous_version" ]]; then
release_mode="$(
printf '%s\n' "$published_versions" |
node sdk/typescript/scripts/release-automation.mjs \
release-mode "$version"
if [[ "$release_mode" == "recover" ]]; then
echo "Package version is unchanged and already published."
echo "changed=false" >> "$GITHUB_OUTPUT"
exit 0
fi
if tagged_sha="$(git rev-parse --verify "refs/tags/npm-v$version^{commit}" 2>/dev/null)" &&
[[ "$tagged_sha" != "$RELEASE_SHA" ]] &&
git merge-base --is-ancestor "$tagged_sha" "$RELEASE_SHA"; then
tagged_version="$(
git show "$tagged_sha:sdk/typescript/package.json" |
node -p 'JSON.parse(require("node:fs").readFileSync(0, "utf8")).version'
)"
if [[ "$release_mode" == "recover" ]]; then
echo "Package version is unchanged and already published."
if [[ "$tagged_version" == "$version" ]]; then
echo "Package version is unchanged and already tagged at $tagged_sha."
echo "changed=false" >> "$GITHUB_OUTPUT"
exit 0
fi
if tagged_sha="$(git rev-parse --verify "refs/tags/npm-v$version^{commit}" 2>/dev/null)" &&
[[ "$tagged_sha" != "$RELEASE_SHA" ]] &&
git merge-base --is-ancestor "$tagged_sha" "$RELEASE_SHA"; then
tagged_version="$(
git show "$tagged_sha:sdk/typescript/package.json" |
node -p 'JSON.parse(require("node:fs").readFileSync(0, "utf8")).version'
)"
if [[ "$tagged_version" == "$version" ]]; then
echo "Package version is unchanged and already tagged at $tagged_sha."
echo "changed=false" >> "$GITHUB_OUTPUT"
exit 0
fi
fi
else
node sdk/typescript/scripts/release-automation.mjs \
require-increase "$version" "$previous_version" >/dev/null
fi
else
node sdk/typescript/scripts/release-automation.mjs \
require-increase "$version" "$previous_version" >/dev/null
fi
fi
+7 -1
View File
@@ -15,7 +15,8 @@ permissions:
pull-requests: read
concurrency:
group: node-release-pr
# A newer push can replace a pending push without displacing a manual run.
group: node-release-pr-${{ github.event_name == 'push' && 'push' || github.run_id }}
cancel-in-progress: false
jobs:
@@ -26,6 +27,10 @@ jobs:
(github.event_name != 'workflow_dispatch' && vars.RELEASE_PR_ENABLED != 'true'))
name: preview release PR
runs-on: ubuntu-latest
# Keep the writer from changing the release branch while a preview reads it.
concurrency: &release-pr-queue
group: node-release-pr
queue: max
env:
RELEASE_PR_DRY_RUN: "true"
@@ -56,6 +61,7 @@ jobs:
(github.event_name != 'workflow_dispatch' && vars.RELEASE_PR_ENABLED == 'true'))
name: maintain release PR
runs-on: ubuntu-latest
concurrency: *release-pr-queue
permissions:
contents: write
pull-requests: write
+7 -33
View File
@@ -50,7 +50,7 @@ jobs:
uses: SocketDev/action@ba6de6cc0565af1f42295590380973573297e31f # v1.3.2
with:
mode: firewall-free
firewall-version: "1.15.0"
firewall-version: "1.15.4"
- &setup-release-node
name: Set up Node.js
@@ -329,42 +329,16 @@ jobs:
shell: bash
run: |
set -euo pipefail
npm_tools="$RUNNER_TEMP/codex-security-provenance-npm"
npm install \
--prefix "$npm_tools" \
--ignore-scripts \
--no-audit \
--no-fund \
--registry=https://openai.firewall.socket.dev/npm/ \
npm@11.12.1
source .github/scripts/release-npm.sh
install_release_npm
printf '%s\n' "$release_npm_bin" >> "$GITHUB_PATH"
if [[ "$("$npm_tools/node_modules/.bin/npm" --version)" != "11.12.1" ]]; then
echo "npm 11.12.1 is required to verify Sigstore attestations." >&2
exit 1
fi
printf '%s\n' "$npm_tools/node_modules/.bin" >> "$GITHUB_PATH"
- name: Verify bundled trusted-publishing npm
- name: Verify npm on PATH
shell: bash
run: |
set -euo pipefail
node --eval '
const version = process.argv[1];
const match = /^(\d+)\.(\d+)\.(\d+)$/.exec(version);
const [major, minor, patch] = match?.slice(1).map(Number) ?? [];
if (
!match ||
major < 11 ||
(major === 11 && (minor < 5 || (minor === 5 && patch < 1)))
) {
console.error(
"npm 11.5.1 or newer is required for trusted publishing; found " +
version +
".",
);
process.exit(1);
}
' "$(npm --version)"
source .github/scripts/release-npm.sh
verify_release_npm "$(command -v npm)"
- name: Download verified package
uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
+5 -11
View File
@@ -1,8 +1,9 @@
name: release-progress
on:
workflow_call:
workflow_run:
workflows: ["node-ci", "node-release", "node-github-release"]
workflows: ["node-release", "node-github-release"]
types: [in_progress, completed]
workflow_dispatch:
inputs:
@@ -20,19 +21,14 @@ permissions: {}
concurrency:
# Refreshes read the latest upstream state, so only one pending refresh is needed.
# Observers must not hold that slot while their upstream run awaits approval.
group: release-progress-${{ inputs.run-id || github.event.workflow_run.id }}-${{ (inputs.watch || (github.event.action == 'in_progress' && github.event.workflow_run.name != 'node-ci')) && github.run_id || 'refresh' }}
group: release-progress-${{ inputs.run-id || github.event.workflow_run.id }}-${{ (inputs.watch || github.event.action == 'in_progress') && github.run_id || 'refresh' }}
cancel-in-progress: false
jobs:
identify:
if: >-
github.repository == 'openai/codex-security' &&
(github.event_name != 'workflow_dispatch' || github.ref == 'refs/heads/main') &&
(github.event_name != 'workflow_run' ||
github.event.workflow_run.name != 'node-ci' ||
(github.event.action == 'completed' &&
github.event.workflow_run.event == 'push' &&
github.event.workflow_run.head_branch == 'main'))
(github.event_name != 'workflow_dispatch' || github.ref == 'refs/heads/main')
name: identify release
runs-on: ubuntu-latest
continue-on-error: true
@@ -116,9 +112,7 @@ jobs:
if: >-
needs.report.outputs.pull != '' &&
((github.event_name == 'workflow_dispatch' && inputs.watch) ||
(github.event_name == 'workflow_run' &&
github.event.action == 'in_progress' &&
github.event.workflow_run.name != 'node-ci'))
(github.event_name == 'workflow_run' && github.event.action == 'in_progress'))
name: observe release milestones
runs-on: ubuntu-latest
continue-on-error: true
+33 -36
View File
@@ -30,10 +30,8 @@ env:
jobs:
native:
if: ${{ !inputs.native-artifacts-ready }}
if: inputs.compare-layouts && !inputs.native-artifacts-ready
uses: ./.github/workflows/native-artifacts.yml
with:
reuse-verified: ${{ !inputs.compare-layouts }}
runner:
needs: native
@@ -89,7 +87,7 @@ jobs:
- { os: windows-latest, shard: 12, count: 14, mode: expanded }
- { os: windows-latest, shard: 13, count: 14, mode: expanded }
- { os: windows-latest, shard: 14, count: 14, mode: expanded }
steps: &sdk-test-steps
steps:
- &actions-checkout
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
@@ -101,14 +99,9 @@ jobs:
python-version: "3.12"
- name: Prepare native runtime
uses: ./.github/actions/download-native
- &actions-setup-node
uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
with:
node-version: "22.13.0"
- name: Set up pnpm
- name: Set up TypeScript tools
uses: ./.github/actions/setup-tools
with:
setup-node: false
cache-dependency-path: |
sdk/typescript/pnpm-lock.yaml
plugins/codex-security/mcp-app/pnpm-lock.yaml
@@ -126,7 +119,8 @@ jobs:
run: |
bash github-action/scripts/setup-ubuntu-sandbox.sh
.github/scripts/install-ripgrep.sh
- name: Prepare private Windows test root
- &prepare-windows-test-root
name: Prepare private Windows test root
if: runner.os == 'Windows'
id: windows-temp
shell: pwsh
@@ -134,23 +128,14 @@ jobs:
- name: Build bundled plugin
run: pnpm --dir sdk/typescript run build:plugin
- name: Test shard layout
if: inputs.compare-layouts
working-directory: sdk/typescript
env: &test-temp
TEMP: ${{ steps.windows-temp.outputs.path || runner.temp }}
TMP: ${{ steps.windows-temp.outputs.path || runner.temp }}
TMPDIR: ${{ steps.windows-temp.outputs.path || runner.temp }}
run: node --experimental-strip-types scripts/run-ci-tests.mts ${{ env.SHARD }} ${{ runner.os == 'Linux' && '--coverage --coverage-reporter=lcov' || '' }} --coverage-dir=reports/coverage-${{ env.REPORT_ID }} --seed=${{ env.CODEX_SECURITY_PROPERTY_SEED }} --reporter-outfile=reports/runner-${{ env.REPORT_ID }}.xml
- name: Test rotating properties
if: ${{ !inputs.compare-layouts }}
working-directory: sdk/typescript
shell: bash
env: *test-temp
run: |
git grep -lzF 'support/property' -- 'tests-ts/*.test.ts' > "$RUNNER_TEMP/property-tests"
mkdir -p reports
xargs -0 bun test --timeout="$CODEX_SECURITY_TEST_TIMEOUT_MS" --seed="$CODEX_SECURITY_PROPERTY_SEED" --reporter=junit --reporter-outfile=reports/properties.xml < "$RUNNER_TEMP/property-tests"
- name: Upload runner report
- &upload-runner-report
name: Upload runner report
if: always()
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
with:
@@ -162,8 +147,7 @@ jobs:
properties:
name: ${{ matrix.os }} / rotating properties
needs: native
if: ${{ !cancelled() && !inputs.compare-layouts && (inputs.native-artifacts-ready || needs.native.result == 'success') }}
if: ${{ !inputs.compare-layouts }}
runs-on: ${{ matrix.os }}
timeout-minutes: 20
env:
@@ -174,7 +158,27 @@ jobs:
fail-fast: false
matrix:
os: [ubuntu-latest, macos-latest, windows-latest]
steps: *sdk-test-steps
steps:
- *actions-checkout
- &set-up-sdk-tools
name: Set up TypeScript tools
uses: ./.github/actions/setup-tools
- *set-up-bun
- &install-sdk-dependencies
name: Install dependencies
run: pnpm --dir sdk/typescript install --frozen-lockfile
- *prepare-windows-test-root
- name: Test rotating properties
working-directory: sdk/typescript
shell: bash
env: *test-temp
run: |
git grep -lzF 'support/property' -- 'tests-ts/*.test.ts' > "$RUNNER_TEMP/property-tests"
mkdir -p reports _bundled_plugin/examples
cp -R ../../plugins/codex-security/examples/completed-scan _bundled_plugin/examples/
cp -R ../../plugins/codex-security/schemas _bundled_plugin/
xargs -0 bun test --timeout="$CODEX_SECURITY_TEST_TIMEOUT_MS" --seed="$CODEX_SECURITY_PROPERTY_SEED" --reporter=junit --reporter-outfile=reports/properties.xml < "$RUNNER_TEMP/property-tests"
- *upload-runner-report
compare:
name: Runner inventory and timing
@@ -183,13 +187,8 @@ jobs:
runs-on: ubuntu-latest
steps:
- *actions-checkout
- *actions-setup-node
- &github-actions-setup-tools
uses: ./.github/actions/setup-tools
with:
setup-node: false
- name: Install dependencies
run: pnpm --dir sdk/typescript install --frozen-lockfile
- *set-up-sdk-tools
- *install-sdk-dependencies
- uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
with:
pattern: runner-*
@@ -228,14 +227,12 @@ jobs:
timeout-minutes: 20
steps:
- *actions-checkout
- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
- uses: ./.github/actions/setup-tools
with:
# Stryker 10's Babel 8 requires Node 22.18+ or 24.11+.
node-version: "24.15.0"
- *github-actions-setup-tools
- *set-up-bun
- name: Install dependencies
run: pnpm --dir sdk/typescript install --frozen-lockfile
- *install-sdk-dependencies
- name: Run mutation trial
run: pnpm --dir sdk/typescript run test:mutation
- name: Upload mutation report
+1 -1
View File
@@ -38,7 +38,7 @@ jobs:
SHELLCHECK_OPTS: --severity=warning
run: |
actionlint -color
shellcheck .github/scripts/install-ripgrep.sh docker/verify-container-compose.sh github-action/scripts/setup-ubuntu-sandbox.sh
shellcheck .github/scripts/*.sh docker/verify-container-compose.sh github-action/scripts/setup-ubuntu-sandbox.sh
- name: Test release progress reporting
run: node --test .github/scripts/test_release_progress.mjs
- name: Check workflow security
+2
View File
@@ -1,6 +1,8 @@
rules:
dangerous-triggers:
ignore:
# Deletes only the merged PR's cache ref without checking out any code.
- clean-merged-pr-caches.yml:3
# Labels only: no checkout or execution of pull request code.
- node-release-labels.yml:3
# Reads run metadata and comments using helpers checked out from protected main.
+1
View File
@@ -271,6 +271,7 @@ for examples.
- [Online documentation](https://learn.chatgpt.com/docs/security/cli)
- [Agent workflows and recovery](docs/agent-workflows.md)
- [CLI reference](sdk/typescript/docs/cli.md)
- [Scanner file import schema and capability guide](docs/scanner-imports/schema-guide.md)
- [Project configuration](docs/project-configuration.md)
- [Examples](examples/README.md)
+32 -18
View File
@@ -92,6 +92,8 @@ Review this policy before enabling automation for `1.x`.
## Rolling release PRs
`node-release-pr` runs after pushes to `main` and can be dispatched manually.
Newer pushes can replace pending pushes. Manual runs keep their own place.
Previews and writes share one queue so a preview sees a consistent proposal.
It defaults to a read-only preview. It does not merge, tag, publish, or change
the existing publication gates.
@@ -108,7 +110,8 @@ the latest `main` and appends a commit; the updater never force-pushes.
A concurrent commit causes it to reread and
retry. It requests Codex review when the proposal files change. Updates that
only incorporate `main` keep CI current without repeating the same proposal
review. New suggestions for human-owned notes still appear in a comment.
review, even when the earlier request names an older commit. New suggestions
for human-owned notes still appear in a comment.
Before merging the proposal, check CI and request a final Codex review
if the last review targets an older head.
@@ -127,7 +130,10 @@ changes; other workflow content comes from the latest `main`. After the release
PR merges, this example can reference the new version before npm publication
finishes. Wait for publication before using that pin.
If a run reports that GitHub has not exposed the updated PR head, manually
After updating an existing release branch and its title, the updater waits briefly
if GitHub still shows the exact commit it just replaced. A different head or a
newer `main` stops that review handoff; the next updater can use the current branches.
If GitHub still has not exposed the updated PR head, manually
rerun the updater with **dry_run** disabled after the PR catches up. This
allows any deferred review request or note suggestions to be posted. Verify
review on the current head before merging the proposal.
@@ -225,8 +231,11 @@ job with read-only permissions for both scopes.
Review the resulting PR and select **Approve workflows to run** in its merge
box to start hosted CI. GitHub requires this approval for PRs created or updated
with `GITHUB_TOKEN`. Check the Codex review on the current head as well, and
request it manually if the automated request has not started a review.
with `GITHUB_TOKEN`. Check that a Codex code review completed on the current
commit; a passing security check alone does not confirm this. If the automated
request does not start a review or the integration asks the automated account
to connect, a maintainer with a connected account should request the code
review manually and verify it completed on that commit.
For CI to start without this approval, optionally configure a GitHub App
installed on this repository with **Contents: write** and **Pull requests: write**.
@@ -256,9 +265,12 @@ Generated PRs leave the disclosure attestations unchecked for maintainer review.
pull-request inventory to the generated section.
4. Open a pull request with a strict Conventional Commit title such as
`chore(release): 0.2.0`.
5. Run the checks required by the changed files and record the results in the
pull request. Do not merge until required CI, review, and public disclosure
checks pass on the current commit.
5. Run the checks required by the changed files and record the initial results
in the PR description. Post later manual test results in a comment or review
with the tested commit SHA. Editing the description to update status can
trigger CI. Before merging, confirm that required CI passed in the **Checks**
tab and that review and the PR's public disclosure checklist cover the current
commit.
Review the summary with the same standard as product documentation. Keep it
specific, describe behavior before implementation, and do not include private
@@ -320,8 +332,9 @@ do not prepare a release by editing or committing files there.
The merged release PR receives one progress comment covering post-merge CI,
release verification, protected npm approval, public-package provenance,
installation checks, Action publication, and container approval and publication.
It links to the relevant workflow
runs and updates at workflow boundaries. Each automatic release dispatch starts
The main CI completion handler requests the first update for a merged release
PR, including when CI fails. Subsequent updates link to the relevant workflows
and track each publication stage. Each automatic release dispatch starts
a separate observer using the returned run ID; this does not depend on chained
`workflow_run` events from the built-in token. The observer checks release jobs
every 30 seconds, including while protected approval is pending, and requests a refresh
@@ -336,7 +349,7 @@ and `watch` enabled. GitHub publication starts its own observer after npm succee
The observer and comment writer execute only helpers from protected `main`.
Only the comment writer can update PR comments, and only the observer can request
a refresh. Both run outside the publication workflows. Verification and
a refresh. Reporting runs independently of the tag-cut job. Verification and
publication jobs retain their existing permissions. The dispatch jobs use their
existing Actions permission for a best-effort notification bounded to 15 seconds,
within the downstream resolver's 60-second completion wait. Progress-reporting
@@ -375,15 +388,14 @@ See [Container releases](docker/README.md) for publication and verification.
## Publish to GitHub Marketplace
Publishing the companion `action-vX.Y.Z` GitHub Release does not publish its
Marketplace listing. Complete this step separately for each Action version
that should appear in Marketplace:
Before announcing a new release that includes the GitHub Action, a maintainer
must publish the companion `action-vX.Y.Z` release to GitHub Marketplace.
1. Wait for `node-github-release` to succeed for the version.
2. Open the existing `action-vX.Y.Z` release and choose **Edit**. Select
**Publish this Action to the GitHub Marketplace**. Use the Action release,
whose tag contains the tested distribution, rather than the `npm-vX.Y.Z`
source release or a new tag on `main`.
1. After `node-github-release` succeeds, follow **edit the Action release** in
the **release status** job summary, or open `action-vX.Y.Z` and choose **Edit**.
That tag contains the tested Action distribution. `npm-vX.Y.Z` points to the
CLI source.
2. Under **Release Action**, select **Publish this Action to the GitHub Marketplace**.
3. Confirm the metadata checks pass. The Marketplace display name comes from
`name` in the tagged `action.yml`, currently **OpenAI Codex Security**.
GitHub requires a globally unique Action name. If a released version's name
@@ -417,6 +429,8 @@ Check the published state before announcing the release:
Its companion GitHub Release contains the manifest and SBOM, links to the
npm changelog, and lists that full distribution commit SHA. The manifest and
runtime lock identify the same CLI version and npm integrity.
- For new releases with the Action, the public Marketplace listing offers the
matching `action-vX.Y.Z` version.
- The newest npm release is marked Latest. Action releases and historical
backfills are not.
- For releases created under this process, the reviewed highlights, category
+4 -2
View File
@@ -1,5 +1,5 @@
name: OpenAI Codex Security
description: Scan code with Codex Security, enforce findings policy, and produce JSON, coverage, and SARIF reports.
description: Scan code with Codex Security, enforce findings policy, and produce JSON and SARIF reports.
branding:
icon: shield
color: black
@@ -60,8 +60,10 @@ outputs:
description: Absolute validated SARIF file path, or empty when unavailable or withheld.
json-path:
description: Absolute canonical findings JSON path, or empty when unavailable or withheld.
manifest-path:
description: Absolute scan manifest path, including scan status and scope, or empty when unavailable or withheld.
coverage-path:
description: Absolute coverage JSON path, or empty when unavailable or withheld.
description: Legacy coverage JSON path. Empty for current CLI results.
results-directory:
description: Runner-local reports directory; do not upload it recursively.
scan-status:
+1
View File
@@ -11,6 +11,7 @@ services:
environment:
CODEX_API_KEY:
CODEX_SECURITY_EMBEDDINGS_URL:
CODEX_SECURITY_ENABLE_EXTERNAL_IMPORTS:
CODEX_SECURITY_GIT_HOST:
GH_TOKEN:
GITHUB_TOKEN:
+1
View File
@@ -13,6 +13,7 @@ services:
environment:
CODEX_API_KEY:
CODEX_SECURITY_EMBEDDINGS_URL:
CODEX_SECURITY_ENABLE_EXTERNAL_IMPORTS:
CODEX_SECURITY_GIT_HOST:
GH_TOKEN:
GITHUB_TOKEN:
+3
View File
@@ -149,6 +149,9 @@ docker build --target scanner -t codex-security:local .
export CODEX_SECURITY_IMAGE=codex-security:local
```
For a local Linux amd64 build of the pinned npm release on Wolfi, see the
[melange and apko recipe](wolfi/README.md).
The existing `CODEX_SECURITY_RESULTS` and `CODEX_SECURITY_STATE` settings select
the host directories (default `./results` and `./state`):
+6 -6
View File
@@ -5,20 +5,20 @@ set -euo pipefail
# Resolve the environment on the host; these checks need no running container.
for compose_file in compose.yaml compose.runner.yaml; do
endpoint="https://embeddings.example.com/custom/v1/embeddings?api-version=synthetic"
CODEX_SECURITY_EMBEDDINGS_URL="$endpoint" \
CODEX_SECURITY_EMBEDDINGS_URL="$endpoint" CODEX_SECURITY_ENABLE_EXTERNAL_IMPORTS=1 \
docker compose --env-file /dev/null -f "$compose_file" config --format json |
jq --exit-status --arg endpoint "$endpoint" \
'.services["codex-security"].environment.CODEX_SECURITY_EMBEDDINGS_URL == $endpoint' > /dev/null
'.services["codex-security"].environment | .CODEX_SECURITY_EMBEDDINGS_URL == $endpoint and .CODEX_SECURITY_ENABLE_EXTERNAL_IMPORTS == "1"' > /dev/null
env -u CODEX_SECURITY_EMBEDDINGS_URL \
env -u CODEX_SECURITY_EMBEDDINGS_URL -u CODEX_SECURITY_ENABLE_EXTERNAL_IMPORTS \
docker compose --env-file /dev/null -f "$compose_file" config --format json |
jq --exit-status \
'.services["codex-security"].environment.CODEX_SECURITY_EMBEDDINGS_URL == null' > /dev/null
'.services["codex-security"].environment | .CODEX_SECURITY_EMBEDDINGS_URL == null and .CODEX_SECURITY_ENABLE_EXTERNAL_IMPORTS == null' > /dev/null
CODEX_SECURITY_EMBEDDINGS_URL="" \
CODEX_SECURITY_EMBEDDINGS_URL="" CODEX_SECURITY_ENABLE_EXTERNAL_IMPORTS="" \
docker compose --env-file /dev/null -f "$compose_file" config --format json |
jq --exit-status \
'.services["codex-security"].environment.CODEX_SECURITY_EMBEDDINGS_URL == ""' > /dev/null
'.services["codex-security"].environment | .CODEX_SECURITY_EMBEDDINGS_URL == "" and .CODEX_SECURITY_ENABLE_EXTERNAL_IMPORTS == ""' > /dev/null
done
mkdir -p results state
+4
View File
@@ -0,0 +1,4 @@
/.build/
/build/
*.rsa
__pycache__/
+97
View File
@@ -0,0 +1,97 @@
# Build a local Wolfi scanner image
This recipe packages the published `@openai/codex-security@0.7.0` for
Linux amd64. [melange](https://github.com/chainguard-dev/melange) creates
the scanner APK; [apko](https://github.com/chainguard-dev/apko) assembles it
with packages from the [public Wolfi repository](https://github.com/wolfi-dev/os).
The image uses the same entrypoint, UID/GID 10001, and `/input`, `/output`, and
`/state` directories as the [published scanner](../README.md). It is a local
alternative to that image. It does not build unreleased changes in this checkout
or publish tags to a registry.
## Build and inspect
Use a Linux amd64 builder with user namespaces and Bubblewrap, apko 1.4.13,
melange 0.61.1, Python 3.9 or later, Node.js with npm 11, OpenSSL,
and Docker for runtime testing. From the repository root:
```sh
docker/wolfi/build.sh /tmp/codex-security-wolfi
docker load --input /tmp/codex-security-wolfi/image.tar
docker run --rm --pull=never --network=none codex-security:wolfi-amd64 --version
```
Use a new output directory for each build. Alongside the Docker archive,
the builder writes the signed scanner APK and index, apko locks, SPDX SBOMs,
a [component inventory](verify-public.py), and a signed `SHA256SUMS`. To verify
the saved files later, use the public key retained from that build:
```sh
cd /tmp/codex-security-wolfi
openssl dgst -sha256 -verify melange.rsa.pub -signature SHA256SUMS.sig SHA256SUMS
sha256sum --check SHA256SUMS
```
Each run generates a local signing key, adds its public half to the APK keyring,
and removes the private key at exit. The key identifies that build; it is not
an upstream release signature. A new key changes the APK and image digests.
To test that the melange guest can be built without access to Wolfi, run a
build with the [offline melange wrapper](tests/offline-melange.sh) on a Linux
builder that permits `unshare --net`:
```sh
MELANGE="$PWD/docker/wolfi/tests/offline-melange.sh" docker/wolfi/build.sh /tmp/codex-security-offline-guest
```
The wrapper disconnects melange before it installs the guest packages. Staging
the inputs and resolving the runtime lock still need the network.
## Run the offline smoke test
On a native Linux amd64 Docker host with AppArmor and user namespaces, load
the built image and run the following from the repository root. If the
`codex-security-container` AppArmor profile is already loaded, omit the setup
and cleanup commands. Otherwise use a disposable test host:
```sh
sudo apparmor_parser --skip-cache --add docker/codex-security.apparmor
docker/wolfi/tests/smoke.sh codex-security:wolfi-amd64
sudo apparmor_parser --skip-cache --remove docker/codex-security.apparmor
```
The test uses the repository's seccomp profile with a read-only root filesystem,
no capabilities, and no external network. It exercises the CLI, the native plugin,
artifact and SARIF output, saved history, and a model turn against a loopback
fixture. It also checks that a sandboxed child can read the test repository but
cannot modify it. A real scan needs a compatible model endpoint; the image
does not include a model.
## Inputs and updates
[builder.yaml](builder.yaml) and [apko.yaml](apko.yaml) list the exact builder
and runtime packages. [build-inputs.json](build-inputs.json) pins their resolved
lock identities and Wolfi's signing key. The build downloads the locked builder
APKs, verifies their bytes, and gives melange only a local, signed index of those
files. The
[npm lock](payload/package-lock.json) pins the scanner and dependencies.
[stage.py](payload/stage.py) checks the target dependency graph, skips npm
lifecycle scripts, and stages the Linux scanner. [melange.yaml](melange.yaml)
checks the normalized tar hash before installing it. The APK omits the optional
voice runtime and plugin binaries for other platforms; it keeps the matching
Linux addon, Codex, code-mode host, Bubblewrap, ripgrep, and license notices.
In the image, `/usr/share/licenses/codex-security/SOURCES.json` records the
sources and hashes of the native files along with the npm dependency inventory.
The original npm lock is retained, including optional packages for other
platforms; the inventory lists only packages installed in the image.
Components keep their upstream licenses.
If the public Wolfi index moves past a pinned version, refresh the affected
package pins and review the resulting apko locks and component inventory before
updating the lock digests. For a new scanner release, update the npm dependency
and lock, the native source and notice pins, the APK version in the
[package](melange.yaml) and [image](apko.yaml) recipes and build inputs, and the
smoke test's expected versions. Regenerate the payload with
`python3 docker/wolfi/payload/stage.py /tmp/wolfi-stage` and update the normalized
tar hash after reviewing what changed. Build the image and repeat the native
smoke test for either kind of update.
+97
View File
@@ -0,0 +1,97 @@
# The image lock binds the public Wolfi packages and the locally signed scanner.
contents:
repositories:
- https://packages.wolfi.dev/os
build_repositories:
- ./packages
keyring:
- ./wolfi-signing.rsa.pub
- ./melange.rsa.pub
packages:
- busybox=1.38.0-r3
- c-ares=1.34.9-r0
- ca-certificates-bundle=20261020-r0
- codex-security=0.7.0-r1
- cyrus-sasl-heimdal-libs=2.1.28-r58
- gdbm=1.26-r8
- git=2.56.0-r3
- glibc-2.44-locale-posix=2.44-r9
- glibc-2.44=2.44-r9
- heimdal-libs=7.8.0-r54
- icu78-data-full=78.3-r4
- keyutils-libs=1.6.3-r41
- krb5-conf=1.0-r10
- krb5-libs=1.22.2-r5
- ld-linux-2.44=2.44-r9
- libbrotlicommon1=1.2.1-r1
- libbrotlidec1=1.2.1-r1
- libbrotlienc1=1.2.1-r1
- libbz2-1=1.0.8-r27
- libcom_err=1.47.4-r4
- libcrypt1-2.44=2.44-r9
- libcurl-openssl4=8.23.0-r2
- libedit=3.1-r20
- libexpat1=2.9.0-r0
- libffi=3.8.0-r2
- libgcc=16.2.0-r1
- libicu78=78.3-r4
- libidn2=2.3.8-r11
- libldap-2.7=2.7.2-r0
- libnghttp2-14=1.70.0-r6
- libpcre2-8-0=10.49-r1
- libpsl=0.23.3-r3
- libselinux=3.11-r2
- libsepol=3.11-r3
- libstdc++=16.2.0-r1
- libunistring=1.5-r0
- libuuid=2.42.4-r1
- libuv=1.53.0-r0
- libverto=0.3.2-r10
- libxcrypt=4.5.2-r6
- mpdecimal=4.0.1-r5
- ncurses-terminfo-base=6.6.20261024-r0
- ncurses=6.6.20261024-r0
- nghttp3=1.18.0-r2
- ngtcp2=1.25.0-r6
- nodejs-26=26.12.1-r2
- openssh-client=10.6_p1-r0
- openssl-4.0-libcrypto=4.0.3-r8
- openssl-4.0-libssl=4.0.3-r8
- openssl-provider-legacy-allowed=4.1.0-r0
- py3-pip-wheel=26.2.2-r0
- python-3.13-base=3.13.17_git20261023-r0
- python-3.13=3.13.17_git20261023-r0
- readline=8.3-r3
- sqlite-libs=3.54.1-r0
- wolfi-baselayout=20230201-r30
- xz=5.8.4-r0
- zlib=1.3.2.1_rc20260921-r0
archs:
- x86_64
accounts:
groups:
- groupname: codex-security
gid: 10001
users:
- username: codex-security
uid: 10001
gid: 10001
homedir: /state
shell: /bin/sh
run-as: '10001:10001'
paths:
- {path: /input, type: directory, uid: 0, gid: 0, permissions: 0o755}
- {path: /output, type: directory, uid: 10001, gid: 10001, permissions: 0o755}
- {path: /state, type: directory, uid: 10001, gid: 10001, permissions: 0o755}
environment:
PATH: /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
HOME: /state
CODEX_HOME: /state
CODEX_SECURITY_STATE_DIR: /output/.codex-security-state
GIT_TERMINAL_PROMPT: '0'
PYTHON: /usr/bin/python3
SSL_CERT_FILE: /etc/ssl/certs/ca-certificates.crt
work-dir: /state
entrypoint:
command: /usr/local/bin/codex-security-entrypoint
cmd: --help
+14
View File
@@ -0,0 +1,14 @@
{
"wolfi_key_source": "https://packages.wolfi.dev/os/wolfi-signing.rsa.pub",
"wolfi_key_sha256": "f0031424cf46f7db780ce63a45f0fd6aa6f85f601e6bb3b7a91fe3d4d5b7d2cc",
"repository": "https://packages.wolfi.dev/os",
"local_package": "codex-security=0.7.0-r1",
"snapshots": {
"builder": {
"lock_identity_sha256": "77cd79a5f9b66efc5d0f03dee78f2e24b66dc1a5acfc2454ba33e124aeb758a0"
},
"runtime": {
"lock_identity_sha256": "6ed7b6d59587eb43f7e831ca4faca86310d6c2a6438288e2ef5a98b870d5517a"
}
}
}
+105
View File
@@ -0,0 +1,105 @@
#!/usr/bin/env bash
# Build and verify a local linux/amd64 image from the public Wolfi repository.
set -euo pipefail
usage() {
cat <<'EOF'
Usage: ./build.sh [NEW_OUTPUT_DIR] (default: ./build next to this script)
Requires Linux with an x86_64-capable melange/bubblewrap runner, melange 0.61.1,
apko 1.4.13, Python 3.9+, OpenSSL, and npm 11 for payload staging.
APKO and MELANGE optionally name the installed tool executables.
STAGED_PAYLOAD optionally names an absolute path to an already staged payload
matching the hash in melange.yaml. All OS packages come from packages.wolfi.dev.
Each run generates a new local signing key and removes the private key at exit.
EOF
}
die() { printf '%s\n' "$*" >&2; exit 1; }
[[ ${1:-} != -h && ${1:-} != --help ]] || { usage; exit 0; }
[[ $# -le 1 && ${1:-} != -* ]] || { usage >&2; exit 2; }
root=$(cd "$(dirname "$0")" && pwd -P)
out=${1:-"$root/build"}
apko=${APKO:-apko}; melange=${MELANGE:-melange}
"$apko" version | grep -Eq '^GitVersion:[[:space:]]+v1\.4\.13$' || die 'Expected apko 1.4.13'
"$melange" version | grep -Eq '^GitVersion:[[:space:]]+v0\.61\.1$' || die 'Expected melange 0.61.1'
python3 -c 'import sys; sys.exit(0 if sys.version_info >= (3,9) else "Python 3.9+ required")'
if [[ -n ${STAGED_PAYLOAD:-} ]]; then
[[ $STAGED_PAYLOAD == /* && -f $STAGED_PAYLOAD ]] || die 'STAGED_PAYLOAD must be an existing absolute file path'
else
[[ $(npm --version) == 11.* ]] || die 'Expected npm 11'
fi
mkdir -p "$(dirname "$out")"
(umask go-w; mkdir "$out") || die 'Use a new output directory for each build'
cd "$out"; out=$(pwd -P)
scratch=$(mktemp -d /tmp/codex-security-build.XXXXXXXX)
trap 'rm -rf -- "$scratch"' EXIT
trap 'exit 130' INT; trap 'exit 143' TERM
unset HTTP_AUTH SOURCE_DATE_EPOCH
mkdir -p src packages sbom
cp "$root"/{wolfi-signing.rsa.pub,builder.yaml,apko.yaml,melange.yaml,build-inputs.json} .
(cd "$scratch"; "$melange" keygen melange.rsa)
cp "$scratch/melange.rsa.pub" .
stamp=2026-10-26T11:30:14Z
# Authenticate the upstream indexes with the reviewed Wolfi key.
python3 -c 'import hashlib, json, pathlib, sys
actual = hashlib.sha256(pathlib.Path("wolfi-signing.rsa.pub").read_bytes()).hexdigest()
if actual != json.load(open("build-inputs.json"))["wolfi_key_sha256"]: sys.exit("Unexpected Wolfi signing key")'
# Verify the lock's origin, architecture, control/data checksums and exact keyring.
check_lock() {
python3 - "$1" "$2" <<'PY'
import hashlib, json, sys
from pathlib import Path
m=json.loads(Path("build-inputs.json").read_text()); which=sys.argv[1]; snap=m["snapshots"][which]
c=json.loads(Path(sys.argv[2]).read_text())["contents"]; local_spec=m["local_package"]
rows=[]; local=[]
for p in c["packages"]:
n=p["name"]; v=p["version"]; filename=f"{n}-{v}.apk"
if p["architecture"]!="x86_64": raise ValueError(f"Unexpected architecture: {n}")
if p["url"]=="./packages/x86_64/"+filename: local.append(n+"="+v)
else:
if p["url"]!=m["repository"]+"/x86_64/"+filename: raise ValueError(f"Unexpected package URL: {n}")
rows.append({k:v for k,v in p.items() if k!="url"})
rows.sort(key=lambda r:r["name"])
digest=hashlib.sha256(json.dumps(rows,sort_keys=True,separators=(",",":")).encode()).hexdigest()
if digest!=snap["lock_identity_sha256"] or local!=([] if which=="builder" else [local_spec]):
raise ValueError(f"{which}: package identities differ from the public snapshot")
keys={(Path(k["name"]).name,k["content"]) for k in c["keyring"]}
expected={"wolfi-signing.rsa.pub":Path("wolfi-signing.rsa.pub").read_text()}
if which=="runtime": expected["melange.rsa.pub"]=Path("melange.rsa.pub").read_text()
if keys!=set(expected.items()): raise ValueError(f"{which}: unrecognized or missing APK signing keys")
PY
}
"$apko" lock builder.yaml --arch x86_64 --output builder.lock.json --cache-dir "$scratch/cache"
check_lock builder builder.lock.json
# Sign an index over exactly the APK bytes authenticated by the builder lock.
snapshot=$scratch/builder-repo
python3 "$root/snapshot-builder.py" builder.lock.json "$snapshot"
"$melange" index --arch x86_64 --signing-key "$scratch/melange.rsa" \
--output "$snapshot/x86_64/APKINDEX.tar.gz" "$snapshot"/x86_64/*.apk
if [[ -n ${STAGED_PAYLOAD:-} ]]; then
cp "$STAGED_PAYLOAD" src/payload.tar.gz
else
python3 "$root/payload/stage.py" "$out/src"
fi
pins=$(python3 -c 'import json; print(",".join(p["name"]+"="+p["version"] for p in json.load(open("builder.lock.json"))["contents"]["packages"]))')
"$melange" build melange.yaml --source-dir "$out/src" --arch x86_64 --runner bubblewrap \
--signing-key "$scratch/melange.rsa" --generate-index --out-dir "$out/packages" \
--repository-append "$snapshot" --keyring-append "$out/melange.rsa.pub" --package-append "$pins" \
--build-date "$stamp" --apk-cache-dir "$scratch/guest-apk-cache" --cache-dir "$scratch/melange-cache"
"$apko" lock apko.yaml --arch x86_64 --output image.lock.json --cache-dir "$scratch/cache"
check_lock runtime image.lock.json
tag=codex-security:wolfi
"$apko" build apko.yaml "$tag" .image.unverified.tar --arch x86_64 --lockfile image.lock.json \
--cache-dir "$scratch/cache" --vcs=false --sbom-path ./sbom --build-date "$stamp"
python3 "$root/verify-public.py" .image.unverified.tar image.lock.json
mv .image.unverified.tar image.tar
# This single detached signature covers the image, locks, SBOMs and signed local APK evidence.
sha256sum build-inputs.json builder.yaml builder.lock.json apko.yaml image.lock.json melange.yaml \
melange.rsa.pub wolfi-signing.rsa.pub verification.json public-components.json image.tar sbom/*.spdx.json \
packages/x86_64/APKINDEX.tar.gz packages/x86_64/*.apk > SHA256SUMS
openssl dgst -sha256 -sign "$scratch/melange.rsa" -out SHA256SUMS.sig SHA256SUMS
openssl dgst -sha256 -verify melange.rsa.pub -signature SHA256SUMS.sig SHA256SUMS
sha256sum -c SHA256SUMS
loaded_tag=$(python3 -c 'import json; print(json.load(open("verification.json"))["tag"])')
printf 'Built %s: %s/image.tar\n' "$loaded_tag" "$out"
+18
View File
@@ -0,0 +1,18 @@
# Public packages used to populate the local melange repository.
contents:
repositories:
- https://packages.wolfi.dev/os
keyring:
- ./wolfi-signing.rsa.pub
packages:
- busybox=1.38.0-r3
- ca-certificates-bundle=20261020-r0
- glibc-2.44=2.44-r9
- glibc-2.44-locale-posix=2.44-r9
- ld-linux-2.44=2.44-r9
- libcrypt1-2.44=2.44-r9
- libgcc=16.2.0-r1
- libxcrypt=4.5.2-r6
- wolfi-baselayout=20230201-r30
archs:
- x86_64
+43
View File
@@ -0,0 +1,43 @@
# Stage once using payload/stage.py; pass that directory as melange --source-dir.
# build.sh supplies the signed local repository prepared from builder.lock.json.
package:
name: codex-security
version: "0.7.0"
epoch: 1
description: Codex Security repository scanner and bundled Linux amd64 Codex runtime
target-architecture: [x86_64]
copyright:
- license: Apache-2.0
# The npm native add-ons are loaded by Node, not system SONAME providers.
# Their shared runtime requirements are declared explicitly below.
options:
no-provides: true
no-depends: true
dependencies:
runtime:
- busybox
- ca-certificates-bundle
- cmd:node
- git
- glibc
- libgcc
- openssh-client
- python3
environment:
contents:
packages:
- busybox
pipeline:
- name: Verify and install the locked Linux scanner payload
runs: |
set -eu
expected=db42f7b5b4d0bfc79975e38778ece88d02d31887a262f8a5c0e5bdfdbbe3563d
actual=$(gzip -dc payload.tar.gz | sha256sum)
test "${actual%% *}" = "$expected"
mkdir -p "${{targets.destdir}}"
tar -xzf payload.tar.gz -C "${{targets.destdir}}"
test -x "${{targets.destdir}}/usr/bin/codex-security"
test -x "${{targets.destdir}}/usr/local/bin/codex-security-entrypoint"
test -s "${{targets.destdir}}/usr/share/licenses/codex-security/SOURCES.json"
+6
View File
@@ -0,0 +1,6 @@
OpenAI Codex
Copyright 2025 OpenAI
This project includes code derived from [Ratatui](https://github.com/ratatui/ratatui), licensed under the MIT license.
Copyright (c) 2016-2022 Florian Dehau
Copyright (c) 2023-2025 The Ratatui Developers
@@ -0,0 +1,481 @@
GNU LIBRARY GENERAL PUBLIC LICENSE
Version 2, June 1991
Copyright (C) 1991 Free Software Foundation, Inc.
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
[This is the first released version of the library GPL. It is
numbered 2 because it goes with version 2 of the ordinary GPL.]
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
Licenses are intended to guarantee your freedom to share and change
free software--to make sure the software is free for all its users.
This license, the Library General Public License, applies to some
specially designated Free Software Foundation software, and to any
other libraries whose authors decide to use it. You can use it for
your libraries, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
this service if you wish), that you receive source code or can get it
if you want it, that you can change the software or use pieces of it
in new free programs; and that you know you can do these things.
To protect your rights, we need to make restrictions that forbid
anyone to deny you these rights or to ask you to surrender the rights.
These restrictions translate to certain responsibilities for you if
you distribute copies of the library, or if you modify it.
For example, if you distribute copies of the library, whether gratis
or for a fee, you must give the recipients all the rights that we gave
you. You must make sure that they, too, receive or can get the source
code. If you link a program with the library, you must provide
complete object files to the recipients so that they can relink them
with the library, after making changes to the library and recompiling
it. And you must show them these terms so they know their rights.
Our method of protecting your rights has two steps: (1) copyright
the library, and (2) offer you this license which gives you legal
permission to copy, distribute and/or modify the library.
Also, for each distributor's protection, we want to make certain
that everyone understands that there is no warranty for this free
library. If the library is modified by someone else and passed on, we
want its recipients to know that what they have is not the original
version, so that any problems introduced by others will not reflect on
the original authors' reputations.
Finally, any free program is threatened constantly by software
patents. We wish to avoid the danger that companies distributing free
software will individually obtain patent licenses, thus in effect
transforming the program into proprietary software. To prevent this,
we have made it clear that any patent must be licensed for everyone's
free use or not licensed at all.
Most GNU software, including some libraries, is covered by the ordinary
GNU General Public License, which was designed for utility programs. This
license, the GNU Library General Public License, applies to certain
designated libraries. This license is quite different from the ordinary
one; be sure to read it in full, and don't assume that anything in it is
the same as in the ordinary license.
The reason we have a separate public license for some libraries is that
they blur the distinction we usually make between modifying or adding to a
program and simply using it. Linking a program with a library, without
changing the library, is in some sense simply using the library, and is
analogous to running a utility program or application program. However, in
a textual and legal sense, the linked executable is a combined work, a
derivative of the original library, and the ordinary General Public License
treats it as such.
Because of this blurred distinction, using the ordinary General
Public License for libraries did not effectively promote software
sharing, because most developers did not use the libraries. We
concluded that weaker conditions might promote sharing better.
However, unrestricted linking of non-free programs would deprive the
users of those programs of all benefit from the free status of the
libraries themselves. This Library General Public License is intended to
permit developers of non-free programs to use free libraries, while
preserving your freedom as a user of such programs to change the free
libraries that are incorporated in them. (We have not seen how to achieve
this as regards changes in header files, but we have achieved it as regards
changes in the actual functions of the Library.) The hope is that this
will lead to faster development of free libraries.
The precise terms and conditions for copying, distribution and
modification follow. Pay close attention to the difference between a
"work based on the library" and a "work that uses the library". The
former contains code derived from the library, while the latter only
works together with the library.
Note that it is possible for a library to be covered by the ordinary
General Public License rather than by this special one.
GNU LIBRARY GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License Agreement applies to any software library which
contains a notice placed by the copyright holder or other authorized
party saying it may be distributed under the terms of this Library
General Public License (also called "this License"). Each licensee is
addressed as "you".
A "library" means a collection of software functions and/or data
prepared so as to be conveniently linked with application programs
(which use some of those functions and data) to form executables.
The "Library", below, refers to any such software library or work
which has been distributed under these terms. A "work based on the
Library" means either the Library or any derivative work under
copyright law: that is to say, a work containing the Library or a
portion of it, either verbatim or with modifications and/or translated
straightforwardly into another language. (Hereinafter, translation is
included without limitation in the term "modification".)
"Source code" for a work means the preferred form of the work for
making modifications to it. For a library, complete source code means
all the source code for all modules it contains, plus any associated
interface definition files, plus the scripts used to control compilation
and installation of the library.
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running a program using the Library is not restricted, and output from
such a program is covered only if its contents constitute a work based
on the Library (independent of the use of the Library in a tool for
writing it). Whether that is true depends on what the Library does
and what the program that uses the Library does.
1. You may copy and distribute verbatim copies of the Library's
complete source code as you receive it, in any medium, provided that
you conspicuously and appropriately publish on each copy an
appropriate copyright notice and disclaimer of warranty; keep intact
all the notices that refer to this License and to the absence of any
warranty; and distribute a copy of this License along with the
Library.
You may charge a fee for the physical act of transferring a copy,
and you may at your option offer warranty protection in exchange for a
fee.
2. You may modify your copy or copies of the Library or any portion
of it, thus forming a work based on the Library, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) The modified work must itself be a software library.
b) You must cause the files modified to carry prominent notices
stating that you changed the files and the date of any change.
c) You must cause the whole of the work to be licensed at no
charge to all third parties under the terms of this License.
d) If a facility in the modified Library refers to a function or a
table of data to be supplied by an application program that uses
the facility, other than as an argument passed when the facility
is invoked, then you must make a good faith effort to ensure that,
in the event an application does not supply such function or
table, the facility still operates, and performs whatever part of
its purpose remains meaningful.
(For example, a function in a library to compute square roots has
a purpose that is entirely well-defined independent of the
application. Therefore, Subsection 2d requires that any
application-supplied function or table used by this function must
be optional: if the application does not supply it, the square
root function must still compute square roots.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Library,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Library, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote
it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Library.
In addition, mere aggregation of another work not based on the Library
with the Library (or with a work based on the Library) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may opt to apply the terms of the ordinary GNU General Public
License instead of this License to a given copy of the Library. To do
this, you must alter all the notices that refer to this License, so
that they refer to the ordinary GNU General Public License, version 2,
instead of to this License. (If a newer version than version 2 of the
ordinary GNU General Public License has appeared, then you can specify
that version instead if you wish.) Do not make any other change in
these notices.
Once this change is made in a given copy, it is irreversible for
that copy, so the ordinary GNU General Public License applies to all
subsequent copies and derivative works made from that copy.
This option is useful when you wish to copy part of the code of
the Library into a program that is not a library.
4. You may copy and distribute the Library (or a portion or
derivative of it, under Section 2) in object code or executable form
under the terms of Sections 1 and 2 above provided that you accompany
it with the complete corresponding machine-readable source code, which
must be distributed under the terms of Sections 1 and 2 above on a
medium customarily used for software interchange.
If distribution of object code is made by offering access to copy
from a designated place, then offering equivalent access to copy the
source code from the same place satisfies the requirement to
distribute the source code, even though third parties are not
compelled to copy the source along with the object code.
5. A program that contains no derivative of any portion of the
Library, but is designed to work with the Library by being compiled or
linked with it, is called a "work that uses the Library". Such a
work, in isolation, is not a derivative work of the Library, and
therefore falls outside the scope of this License.
However, linking a "work that uses the Library" with the Library
creates an executable that is a derivative of the Library (because it
contains portions of the Library), rather than a "work that uses the
library". The executable is therefore covered by this License.
Section 6 states terms for distribution of such executables.
When a "work that uses the Library" uses material from a header file
that is part of the Library, the object code for the work may be a
derivative work of the Library even though the source code is not.
Whether this is true is especially significant if the work can be
linked without the Library, or if the work is itself a library. The
threshold for this to be true is not precisely defined by law.
If such an object file uses only numerical parameters, data
structure layouts and accessors, and small macros and small inline
functions (ten lines or less in length), then the use of the object
file is unrestricted, regardless of whether it is legally a derivative
work. (Executables containing this object code plus portions of the
Library will still fall under Section 6.)
Otherwise, if the work is a derivative of the Library, you may
distribute the object code for the work under the terms of Section 6.
Any executables containing that work also fall under Section 6,
whether or not they are linked directly with the Library itself.
6. As an exception to the Sections above, you may also compile or
link a "work that uses the Library" with the Library to produce a
work containing portions of the Library, and distribute that work
under terms of your choice, provided that the terms permit
modification of the work for the customer's own use and reverse
engineering for debugging such modifications.
You must give prominent notice with each copy of the work that the
Library is used in it and that the Library and its use are covered by
this License. You must supply a copy of this License. If the work
during execution displays copyright notices, you must include the
copyright notice for the Library among them, as well as a reference
directing the user to the copy of this License. Also, you must do one
of these things:
a) Accompany the work with the complete corresponding
machine-readable source code for the Library including whatever
changes were used in the work (which must be distributed under
Sections 1 and 2 above); and, if the work is an executable linked
with the Library, with the complete machine-readable "work that
uses the Library", as object code and/or source code, so that the
user can modify the Library and then relink to produce a modified
executable containing the modified Library. (It is understood
that the user who changes the contents of definitions files in the
Library will not necessarily be able to recompile the application
to use the modified definitions.)
b) Accompany the work with a written offer, valid for at
least three years, to give the same user the materials
specified in Subsection 6a, above, for a charge no more
than the cost of performing this distribution.
c) If distribution of the work is made by offering access to copy
from a designated place, offer equivalent access to copy the above
specified materials from the same place.
d) Verify that the user has already received a copy of these
materials or that you have already sent this user a copy.
For an executable, the required form of the "work that uses the
Library" must include any data and utility programs needed for
reproducing the executable from it. However, as a special exception,
the source code distributed need not include anything that is normally
distributed (in either source or binary form) with the major
components (compiler, kernel, and so on) of the operating system on
which the executable runs, unless that component itself accompanies
the executable.
It may happen that this requirement contradicts the license
restrictions of other proprietary libraries that do not normally
accompany the operating system. Such a contradiction means you cannot
use both them and the Library together in an executable that you
distribute.
7. You may place library facilities that are a work based on the
Library side-by-side in a single library together with other library
facilities not covered by this License, and distribute such a combined
library, provided that the separate distribution of the work based on
the Library and of the other library facilities is otherwise
permitted, and provided that you do these two things:
a) Accompany the combined library with a copy of the same work
based on the Library, uncombined with any other library
facilities. This must be distributed under the terms of the
Sections above.
b) Give prominent notice with the combined library of the fact
that part of it is a work based on the Library, and explaining
where to find the accompanying uncombined form of the same work.
8. You may not copy, modify, sublicense, link with, or distribute
the Library except as expressly provided under this License. Any
attempt otherwise to copy, modify, sublicense, link with, or
distribute the Library is void, and will automatically terminate your
rights under this License. However, parties who have received copies,
or rights, from you under this License will not have their licenses
terminated so long as such parties remain in full compliance.
9. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Library or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Library (or any work based on the
Library), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Library or works based on it.
10. Each time you redistribute the Library (or any work based on the
Library), the recipient automatically receives a license from the
original licensor to copy, distribute, link with or modify the Library
subject to these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties to
this License.
11. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Library at all. For example, if a patent
license would not permit royalty-free redistribution of the Library by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Library.
If any portion of this section is held invalid or unenforceable under any
particular circumstance, the balance of the section is intended to apply,
and the section as a whole is intended to apply in other circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
12. If the distribution and/or use of the Library is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Library under this License may add
an explicit geographical distribution limitation excluding those countries,
so that distribution is permitted only in or among countries not thus
excluded. In such case, this License incorporates the limitation as if
written in the body of this License.
13. The Free Software Foundation may publish revised and/or new
versions of the Library General Public License from time to time.
Such new versions will be similar in spirit to the present version,
but may differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the Library
specifies a version number of this License which applies to it and
"any later version", you have the option of following the terms and
conditions either of that version or of any later version published by
the Free Software Foundation. If the Library does not specify a
license version number, you may choose any version ever published by
the Free Software Foundation.
14. If you wish to incorporate parts of the Library into other free
programs whose distribution conditions are incompatible with these,
write to the author to ask for permission. For software which is
copyrighted by the Free Software Foundation, write to the Free
Software Foundation; we sometimes make exceptions for this. Our
decision will be guided by the two goals of preserving the free status
of all derivatives of our free software and of promoting the sharing
and reuse of software generally.
NO WARRANTY
15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO
WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR
OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY
KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE
LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME
THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY
AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU
FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR
CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE
LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
DAMAGES.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Libraries
If you develop a new library, and you want it to be of the greatest
possible use to the public, we recommend making it free software that
everyone can redistribute and change. You can do so by permitting
redistribution under these terms (or, alternatively, under the terms of the
ordinary General Public License).
To apply these terms, attach the following notices to the library. It is
safest to attach them to the start of each source file to most effectively
convey the exclusion of warranty; and each file should have at least the
"copyright" line and a pointer to where the full notice is found.
<one line to give the library's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Also add information on how to contact you by electronic and paper mail.
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the library, if
necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the
library `Frob' (a library for tweaking knobs) written by James Random Hacker.
<signature of Ty Coon>, 1 April 1990
Ty Coon, President of Vice
That's all there is to it!
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2020 Jeremy Danyow
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2022 OpenAI, Shantanu Jain
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
@@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2015 Andrew Gallant
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
@@ -0,0 +1,64 @@
The ISC License
Copyright (c) Contributors
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
====
The following license is the one that governed sax, from which saxes
was forked. Isaac Schlueter is not *directly* involved with saxes so
don't go bugging him for saxes issues.
The ISC License
Copyright (c) Isaac Z. Schlueter and Contributors
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
====
`String.fromCodePoint` by Mathias Bynens is no longer used, but it can
still be found in old commits. It was once used according to terms of
MIT License, as follows:
Copyright Mathias Bynens <https://mathiasbynens.be/>
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2023-present Scalar
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) Facebook, Inc. and its affiliates.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+30
View File
@@ -0,0 +1,30 @@
{
"BUBBLEWRAP-COPYING": {
"source": "https://raw.githubusercontent.com/openai/codex/6aaac694803004a63c6f393d153c96d22521a6b9/codex-rs/vendor/bubblewrap/COPYING",
"sha256": "b7993225104d90ddd8024fd838faf300bea5e83d91203eab98e29512acebd69c"
},
"CFWORKER-LICENSE": {
"source": "https://raw.githubusercontent.com/cfworker/cfworker/5409fdc2bd144f68e8b28c61c71fcb16600000a6/LICENSE.md",
"sha256": "376944252ab78ca6b41aee44ddea8894927ee67891e77e61eb9d59af63e35094"
},
"JS-TIKTOKEN-LICENSE": {
"source": "https://raw.githubusercontent.com/dqbd/tiktoken/4c8b748e07992c00386f3180af5c574b27b65139/LICENSE",
"sha256": "418cb499b436128d653d79941333a5437b7be2ea9213dcc2f04d15d5d2c51d86"
},
"RIPGREP-LICENSE-MIT": {
"source": "https://raw.githubusercontent.com/BurntSushi/ripgrep/e89fff89ac9af12e8d4ce9d5fd07beb408ca730f/LICENSE-MIT",
"sha256": "0f96a83840e146e43c0ec96a22ec1f392e0680e6c1226e6f3ba87e0740af850f"
},
"SAXES-LICENSE": {
"source": "https://raw.githubusercontent.com/lddubeau/saxes/211fa0ebec9b628affc09219199639887174bfc3/LICENSE",
"sha256": "0fac2374380621b22e6b50451057721a9c52935b02d16d106a9f04897f061d0e"
},
"SCALAR-LICENSE": {
"source": "https://raw.githubusercontent.com/scalar/scalar/71c72fbc1c3860ac741812617057141db2033fcd/LICENSE",
"sha256": "380cd0a6ad700e1f821f2a509f0dd9ff835041cee2d43daf5dedc1adb2bcc620"
},
"YOGA-LICENSE": {
"source": "https://raw.githubusercontent.com/react/yoga/042f5013152eb81c1552dec945b88f7b95ca350f/LICENSE",
"sha256": "52412d7bc7ce4157ea628bbaacb8829e0a9cb3c58f57f99176126bc8cf2bfc85"
}
}
File diff suppressed because it is too large Load Diff
+6
View File
@@ -0,0 +1,6 @@
{
"name": "codex-security-image-payload",
"version": "0.7.0",
"private": true,
"dependencies": { "@openai/codex-security": "0.7.0" }
}
+222
View File
@@ -0,0 +1,222 @@
#!/usr/bin/env python3
"""Stage the open-source scanner payload for offline Linux/amd64 melange builds.
Usage: python3 payload/stage.py PATH_TO_MELANGE_SOURCE_DIR
Requires Python 3.9+, Node and npm 11 on a POSIX host. No target code is run.
"""
import argparse
import gzip
import hashlib
import json
import os
import re
import shutil
import subprocess
import tarfile
import tempfile
from pathlib import Path
HERE = Path(__file__).resolve().parent
DOCKER = HERE.parent.parent
REPO = DOCKER.parent
INSTALL = Path("usr/lib/codex-security")
SDK = "node_modules/@openai/codex-security"
VENDOR = "node_modules/@openai/codex-linux-x64/vendor/x86_64-unknown-linux-musl"
TARGET = {"os": "linux", "cpu": "x64", "libc": "glibc"}
LICENSE_DIR = Path("usr/share/licenses/codex-security")
REVIEWED_NPM_LICENSES = {"Apache-2.0", "BSD-3-Clause", "ISC", "MIT", "(MIT OR CC0-1.0)"}
CODEX_SOURCE = "https://github.com/openai/codex/tree/6aaac694803004a63c6f393d153c96d22521a6b9"
SCANNER_SOURCE = "https://github.com/openai/codex-security/tree/f05a0b096cc881242ddf34a4d6b3ce0f322f3cf9"
OFF_TARGET_PLUGIN_TARGETS = {
"darwin-arm64", "darwin-x64", "linux-arm64-gnu", "linux-arm64-musl",
"linux-x64-musl", "win32-arm64", "win32-x64",
}
# Reuse this repository's Docker scripts at their released hashes. The root
# LICENSE is byte-identical to the LICENSE in the pinned native Codex release.
EXTRAS = {
DOCKER / "entrypoint.sh": ("usr/local/bin/codex-security-entrypoint", "5bcce4a6b0f6a57d938f3e9def0aea93660d41356fdf0ddad1d343a067fc6610"),
DOCKER / "git-credential.sh": ("usr/local/bin/codex-security-git-credential", "0b792c2304abcd60366aed3040287ecee4d8e336c121516d8112f577fc2af360"),
REPO / "LICENSE": ("usr/share/licenses/codex-security/CODEX-LICENSE", "d17f227e4df5da1600391338865ce0f3055211760a36688f816941d58232d8dc"),
HERE / "CODEX-NOTICE": ("usr/share/licenses/codex-security/CODEX-NOTICE", "9d71575ecfd9a843fc1677b0efb08053c6ba9fd686a0de1a6f5382fd3c220915"),
}
def read_json(path):
return json.loads(path.read_text())
def matches_target(package):
for key, target in TARGET.items():
values = package.get(key, [])
allowed = [v for v in values if not v.startswith("!")]
if "!" + target in values or (allowed and target not in allowed):
return False
return True
def source_url(pkg):
repo = pkg.get("repository")
raw = repo.get("url") if isinstance(repo, dict) else repo
# npm accepts both GitHub shorthand and conventional git URLs. Do not
# silently accept missing metadata, new repository hosts or unknown terms.
match = re.fullmatch(r"(?:(?:git\+https://|https://|git://|git@)github\.com[:/]|github:)?([A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+)", raw or "")
if not match:
raise ValueError(f"Review repository for {pkg['name']}: {raw}")
return "https://github.com/" + match[1].removesuffix(".git")
def select_scanner_payload(app):
# Voice belongs to the interactive client, not repository scanning. The
# MCP server uses Node's target (Linux x64 glibc), while the Codex executable
# itself is the upstream static musl build.
shutil.rmtree(app / VENDOR / "codex-resources/voice")
native = app / SDK / "_bundled_plugin/mcp/native"
if {p.name for p in native.iterdir() if p.is_dir()} != OFF_TARGET_PLUGIN_TARGETS | {"licenses", "linux-x64-gnu"}:
raise ValueError("Review changed native MCP targets")
for target in OFF_TARGET_PLUGIN_TARGETS:
shutil.rmtree(native / target)
known = {
"bin/codex", "bin/codex-code-mode-host", "codex-resources/bwrap",
"codex-path/rg", "codex-package.json",
}
vendor = app / VENDOR
if {p.relative_to(vendor).as_posix() for p in vendor.rglob("*") if p.is_file()} != known:
raise ValueError("Review changed Codex release files")
def write_attributions(root, app, wanted):
license_dir = root / LICENSE_DIR
notices = read_json(HERE / "notices/sources.json")
for name, item in notices.items():
source = HERE / "notices" / name
if hashlib.sha256(source.read_bytes()).hexdigest() != item["sha256"]:
raise ValueError(f"Changed upstream notice: {name}")
shutil.copyfile(source, license_dir / name)
shutil.copyfile(HERE / "notices/sources.json", license_dir / "NOTICE-SOURCES.json")
npm = []
for key, lock_record in sorted(wanted.items()):
pkg = read_json(app / key / "package.json")
if pkg.get("license") != lock_record.get("license") or pkg.get("license") not in REVIEWED_NPM_LICENSES:
raise ValueError(f"Review license for {key}: {pkg.get('license')}")
npm.append({"path": key, "name": pkg["name"], "version": pkg["version"], "license": pkg["license"],
"repository": source_url(pkg), "input_archive": lock_record["resolved"], "integrity": lock_record["integrity"]})
codex_native = {
VENDOR + "/bin/codex": CODEX_SOURCE + "/codex-rs/cli",
VENDOR + "/bin/codex-code-mode-host": CODEX_SOURCE + "/codex-rs/code-mode-host",
VENDOR + "/codex-resources/bwrap": CODEX_SOURCE + "/codex-rs/vendor/bubblewrap",
VENDOR + "/codex-path/rg": "https://github.com/BurntSushi/ripgrep/tree/e89fff89ac9af12e8d4ce9d5fd07beb408ca730f",
SDK + "/_bundled_plugin/mcp/native/linux-x64-gnu/unix.node": SCANNER_SOURCE + "/plugins/codex-security/native",
"node_modules/@napi-rs/canvas-linux-x64-gnu/skia.linux-x64-gnu.node": "https://github.com/Brooooooklyn/canvas/tree/00a115d9903647f116daf86eccd2c6ba36128371",
}
native_records = []
for file, source in codex_native.items():
hasher = hashlib.sha256()
with (app / file).open("rb") as f:
while chunk := f.read(1 << 20):
hasher.update(chunk)
native_records.append({"path": file, "source": source, "sha256": hasher.hexdigest()})
manifest = {"scanner_source": SCANNER_SOURCE, "codex_source": CODEX_SOURCE, "npm": npm,
"native_executables_and_addons": native_records,
"omitted": [VENDOR + "/codex-resources/voice"] +
[SDK + "/_bundled_plugin/mcp/native/" + target for target in sorted(OFF_TARGET_PLUGIN_TARGETS)]}
(license_dir / "SOURCES.json").write_text(json.dumps(manifest, indent=2) + "\n")
def stage_root(root):
app = root / INSTALL
app.mkdir(parents=True)
for name in ("package.json", "package-lock.json"):
shutil.copyfile(HERE / name, app / name)
lock = read_json(app / "package-lock.json")
packages = {k: v for k, v in lock["packages"].items() if k}
# An unexpected package manager script or nonregistry artifact requires review.
for name, pkg in packages.items():
if (not pkg["resolved"].startswith("https://registry.npmjs.org/")
or not pkg["integrity"].startswith("sha512-") or pkg.get("hasInstallScript")):
raise ValueError(f"Unexpected source, integrity, or lifecycle script: {name}")
global_config = root.parent / "empty-npmrc"
global_config.touch()
subprocess.run([
"npm", "ci", "--os=linux", "--cpu=x64", "--libc=glibc", "--omit=dev",
"--include=optional", "--ignore-scripts", "--no-audit", "--no-fund",
"--userconfig=/dev/null", f"--globalconfig={global_config}", "--registry=https://registry.npmjs.org",
], cwd=app, check=True)
# npm treats failed optional installs as success. Check the full target graph,
# including platform packages, before accepting the install.
installed = read_json(app / "node_modules/.package-lock.json")["packages"]
wanted = {k: v for k, v in packages.items() if matches_target(v)}
if installed.keys() != wanted.keys():
raise ValueError(f"Installed graph differs from lock: {sorted(installed.keys() ^ wanted.keys())}")
for key, pkg in wanted.items():
if installed[key]["integrity"] != pkg["integrity"] or read_json(app / key / "package.json")["version"] != pkg["version"]:
raise ValueError(f"Installed version/integrity differs for {key}")
# Keep the original lock usable by npm ci. SOURCES.json records the subset
# installed for this platform.
(app / "node_modules/.package-lock.json").unlink() # transient local npm cache
select_scanner_payload(app)
for name in ("bin/codex", "bin/codex-code-mode-host", "codex-resources/bwrap", "codex-path/rg"):
binary = app / VENDOR / name
with binary.open("rb") as f:
header = f.read(20)
if header[:6] != b"\x7fELF\x02\x01" or header[18:20] != b"\x3e\x00" or not os.access(binary, os.X_OK):
raise ValueError(f"Missing executable ELF64 x86-64 {name}")
for name in (".codex-plugin/plugin.json", "scripts/launch_codex_security_mcp", "mcp/native/linux-x64-gnu/unix.node", "mcp/server.mjs", "mcp/native/THIRD_PARTY_NOTICES.txt"):
if not (app / SDK / "_bundled_plugin" / name).is_file():
raise ValueError(f"Incomplete bundled plugin: {name}")
bindir = root / "usr/bin"
bindir.mkdir()
for name in ("cs", "codex-security"):
(bindir / name).symlink_to("../lib/codex-security/" + SDK + "/bin/codex-security.mjs")
for source, (dest, sha) in EXTRAS.items():
data = source.read_bytes()
if hashlib.sha256(data).hexdigest() != sha:
raise ValueError(f"Release file differs from pin: {source.name}")
path = root / dest
path.parent.mkdir(parents=True, exist_ok=True)
path.write_bytes(data)
path.chmod(0o755 if source.suffix == ".sh" else 0o644)
write_attributions(root, app, wanted)
return len(wanted)
def normalize(entry):
if not (entry.isdir() or entry.isreg() or entry.issym()):
raise ValueError(f"Unexpected file type: {entry.name}")
entry.uid = entry.gid = entry.mtime = 0
entry.uname = entry.gname = "root"
entry.mode = (0o777 if entry.issym() else 0o755 if entry.isdir() or entry.mode & 0o111 else 0o644)
return entry
def main():
args = argparse.ArgumentParser(description=__doc__)
args.add_argument("stage", type=Path, help="melange --source-dir (only payload.tar.gz will be written)")
output = args.parse_args().stage.resolve()
output.mkdir(parents=True, exist_ok=True)
with tempfile.TemporaryDirectory(prefix="codex-security-payload-") as work:
root = Path(work) / "root"
count = stage_root(root)
# The recipe pins the uncompressed tar hash, independent of gzip/zlib.
# Normalize sort order, mtime, owners and permissions across build hosts.
with tempfile.NamedTemporaryFile(dir=output, prefix="payload-", delete=False) as temp:
temporary = Path(temp.name)
try:
with temporary.open("wb") as raw, gzip.GzipFile(filename="", mode="wb", fileobj=raw, compresslevel=3, mtime=0) as gz:
with tarfile.open(fileobj=gz, mode="w|", format=tarfile.GNU_FORMAT) as archive:
archive.add(root / "usr", arcname="usr", filter=normalize)
digest = hashlib.sha256()
with gzip.open(temporary, "rb") as gz:
while chunk := gz.read(1024 * 1024):
digest.update(chunk)
temporary.chmod(0o644)
temporary.replace(output / "payload.tar.gz")
print(f"{count} locked production packages; uncompressed tar SHA-256: {digest.hexdigest()}")
finally:
temporary.unlink(missing_ok=True)
if __name__ == "__main__":
main()
+71
View File
@@ -0,0 +1,71 @@
#!/usr/bin/env python3
"""Stage the APKs from a verified apko builder lock for an offline Melange build."""
import argparse
import base64
import hashlib
import json
import re
import tempfile
from pathlib import Path
from urllib.request import HTTPRedirectHandler, build_opener
ARCH = "x86_64"
REPO = "https://packages.wolfi.dev/os/" + ARCH
class NoRedirect(HTTPRedirectHandler):
def redirect_request(self, *args):
return None # Only fetch the exact URLs in the lock.
def stage_package(pkg, directory, fetch):
name, version = pkg["name"], pkg["version"]
filename = f"{name}-{version}.apk"
if not all(re.fullmatch(r"[a-zA-Z0-9][a-zA-Z0-9.+_~-]*", s) for s in (name, version)):
raise ValueError(f"Invalid package name or version: {filename}")
if pkg["architecture"] != ARCH or pkg["url"] != f"{REPO}/{filename}":
raise ValueError(f"Unexpected package source or architecture: {filename}")
with (directory / filename).open("xb") as dest, fetch(pkg["url"], timeout=60) as source:
offset = 0
for part, algorithm in (("signature", "sha1"), ("control", "sha1"), ("data", "sha256")):
record = pkg[part]
if part == "signature" and record == {"range": "", "checksum": ""}:
continue
match = re.fullmatch(r"bytes=([0-9]+)-([0-9]+)", record["range"])
if not match or int(match[1]) != offset or int(match[2]) < offset:
raise ValueError(f"{filename}: invalid {part} range {record['range']!r}")
length = int(match[2]) + 1 - offset
block = source.read(length)
digest = base64.b64encode(hashlib.new(algorithm, block).digest()).decode("ascii")
if len(block) != length or f"{algorithm}-{digest}" != record["checksum"]:
raise ValueError(f"{filename}: {part} differs from builder lock")
dest.write(block)
offset += length
if source.read(1):
raise ValueError(f"{filename}: bytes beyond locked ranges")
def snapshot(lock, output, fetch):
if lock["version"] != "v1" or not lock["contents"]["packages"]:
raise ValueError("Expected a nonempty apko v1 builder lock")
output.mkdir(parents=True, exist_ok=True)
if output.is_symlink() or any(output.iterdir()):
raise ValueError("Builder repository must be a new or empty directory")
with tempfile.TemporaryDirectory(dir=output) as staging:
packages = Path(staging) / ARCH
packages.mkdir()
for pkg in lock["contents"]["packages"]:
stage_package(pkg, packages, fetch)
packages.rename(output / ARCH) # Publish only after the entire lock verifies.
if __name__ == "__main__":
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("lock", type=Path)
parser.add_argument("repository", type=Path)
args = parser.parse_args()
try:
snapshot(json.loads(args.lock.read_bytes()), args.repository, build_opener(NoRedirect()).open)
except (KeyError, ValueError, OSError) as exc:
parser.exit(1, f"Could not stage builder repository: {exc}\n")
+8
View File
@@ -0,0 +1,8 @@
#!/usr/bin/env bash
# Use as MELANGE for a build: the guest must install from the local snapshot
# even when melange itself has no route to the upstream repository.
set -euo pipefail
if [[ $1 == build ]]; then
exec unshare --net -- "${REAL_MELANGE:-melange}" "$@"
fi
exec "${REAL_MELANGE:-melange}" "$@"
+166
View File
@@ -0,0 +1,166 @@
// Read from stdin in a fresh isolated container by smoke.sh.
import assert from "node:assert/strict";
import { execFile, execFileSync, spawnSync } from "node:child_process";
import { createHash, randomUUID } from "node:crypto";
import { accessSync, constants, mkdtempSync, readFileSync,
realpathSync, statSync, writeFileSync } from "node:fs";
import { createRequire } from "node:module";
import { createServer } from "node:http";
import { once } from "node:events";
import { dirname, join } from "node:path";
import { pathToFileURL } from "node:url";
import { promisify } from "node:util";
const run = (cmd, args, opts = {}) => execFileSync(cmd, args, {
encoding: "utf8", stdio: ["pipe", "pipe", "pipe"], timeout: 180_000,
maxBuffer: 16 * 1024 * 1024, ...opts
}).trim();
const read = (file) => JSON.parse(readFileSync(file, "utf8"));
const cli = (...args) => JSON.parse(run("/usr/local/bin/codex-security-entrypoint", [...args, "--json"]));
assert.equal(process.getuid(), 10001);
assert.equal(process.getgid(), 10001);
assert.equal(process.cwd(), "/state");
assert.equal(process.env.HOME, "/state");
assert.equal(process.env.CODEX_HOME, "/state");
assert.equal(process.env.CODEX_SECURITY_STATE_DIR, "/output/.codex-security-state");
assert.equal(process.env.GIT_TERMINAL_PROMPT, "0");
assert.equal(process.env.PYTHON, "/usr/bin/python3");
accessSync("/input", constants.R_OK | constants.X_OK);
for (const p of ["/state", "/output"]) accessSync(p, constants.W_OK | constants.X_OK);
run(process.env.PYTHON, ["-c",
"import ssl, sqlite3; assert ssl.create_default_context().get_ca_certs(); assert sqlite3.connect(':memory:').execute('select 1').fetchone() == (1,)"]);
console.log("PASS non-root account, state directories, Python SQLite and CA trust");
const info = cli("info");
assert.equal(info.cliVersion, "0.7.0");
assert.equal(info.codexVersion, "0.164.0");
const launcher = realpathSync(run("/bin/sh", ["-c", "command -v codex-security"]));
const pkg = dirname(dirname(launcher));
assert.equal(read(join(pkg, "package.json")).name, "@openai/codex-security");
const { resolveCodexCommand } = await import(pathToFileURL(join(pkg, "dist/index.js")));
const { command: codex } = resolveCodexCommand({});
assert.equal(run(codex, ["--version"]), `codex-cli ${info.codexVersion}`);
const plugin = join(pkg, "_bundled_plugin");
const libc = process.report.getReport().header.glibcVersionRuntime ? "gnu" : "musl";
const addon = join(plugin, "mcp/native", `linux-${process.arch}-${libc}`, "unix.node");
assert.equal(createRequire(import.meta.url)(addon).unixEnvironment(Buffer.from("HOME")).toString(), "/state");
const mcp = read(join(plugin, ".mcp.json")).mcpServers["codex-security"];
const initialized = JSON.parse(run(join(plugin, mcp.command), mcp.args, { cwd: plugin,
input: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "initialize", params: {
protocolVersion: "2025-11-25", capabilities: {}, clientInfo: { name: "offline-image-test", version: "1" }
} }) + "\n" }));
assert.equal(initialized.result.serverInfo.name, "codex-security");
console.log(`PASS native Codex ${info.codexVersion}, plugin addon and MCP startup on linux/${process.arch}; Node ${process.version}`);
const helper = "/usr/local/bin/codex-security-git-credential";
const helperResult = (host) => run(helper, ["get"], { env: { ...process.env, GH_TOKEN: "fixture-only" },
input: `protocol=https\nhost=${host}\n\n` });
assert.equal(helperResult("github.com"), "username=x-access-token\npassword=fixture-only");
assert.equal(helperResult("not-github.example"), "");
console.log("PASS Git credential helper is limited to its configured host");
process.umask(0o077);
const repo = mkdtempSync("/input/codex-smoke-");
const scanDir = join(mkdtempSync("/output/codex-smoke-"), "scan");
const source = join(repo, "hello.py");
const original = 'print("offline fixture")\n';
writeFileSync(source, original);
const git = (...args) => run("git", ["-C", repo, ...args]);
git("init", "-q"); git("add", "hello.py");
git("-c", "user.name=Fixture", "-c", "user.email=fixture@example.invalid", "commit", "-qm", "fixture");
// /input is a writable, disposable tmpfs in this test. Use the exact same
// child in both cases to distinguish Codex confinement from a Docker mount.
const probe = [process.env.PYTHON, "-c", `from pathlib import Path
import errno,sys
p=Path(sys.argv[1])
if p.read_text() != sys.argv[2]: sys.exit(41)
try: p.write_text("changed")
except OSError as e: sys.exit({errno.EROFS:45, errno.EACCES:46, errno.EPERM:47}.get(e.errno, 48))
sys.exit(42)`, source, original];
const launch = (args) => spawnSync(args[0], args.slice(1), {cwd: repo, encoding: "utf8", timeout: 30_000});
const control = launch(probe);
assert.equal(control.status, 42, control.error?.message || control.stderr);
assert.equal(readFileSync(source, "utf8"), "changed");
writeFileSync(source, original);
const sandbox = launch([codex, "sandbox", "--permission-profile", ":read-only", "--", ...probe]);
const why = {45: "EROFS", 46: "EACCES", 47: "EPERM"}[sandbox.status];
assert(why, `sandbox code=${sandbox.status} signal=${sandbox.signal}; ${sandbox.error?.message || sandbox.stderr}`);
assert.equal(readFileSync(source, "utf8"), original);
assert.equal(git("status", "--porcelain"), "");
console.log(`PASS read-only sandbox: the child read hello.py and its write failed with ${why}; the same child wrote it outside, and the checkout is clean`);
// This turn goes through the installed native model client and its shell tool.
// The only server is this loopback Responses fixture.
const nonce = randomUUID();
const draft = `python3 - <<'PY'
import json,os
from pathlib import Path
assert (Path(os.environ["CODEX_SECURITY_REPOSITORY"])/"hello.py").read_text() == ${JSON.stringify(original)}
out = Path(os.environ["CODEX_SECURITY_SCAN_DIR"])
docs = {"scan-manifest.json":{"scan":{"target":{"kind":os.environ["CODEX_SECURITY_TARGET_KIND"]},
"scope":{"summary":"Synthetic offline smoke test: ${nonce}"}}}, "findings.json":{"findings":[]},
"coverage.json":{"inventoryStrategy":"repository","surfaces":[],"explicitExclusions":[],"deferred":[]}}
for name,data in docs.items():
with (out/name).open("x") as f: json.dump(data,f)
print("fixture-draft-written")
PY`;
let requests = 0;
let fixtureError;
const server = createServer(async (req, res) => {
try {
assert.equal(req.method, "POST");
assert.equal(req.url, "/openai/v1/responses");
const chunks = [];
for await (const chunk of req) chunks.push(chunk);
const request = JSON.parse(Buffer.concat(chunks));
requests++;
let item;
if (requests === 1) {
assert(request.tools.some(t => t.name === "exec_command"));
item = {type: "function_call", call_id: "draft", name: "exec_command",
arguments: JSON.stringify({cmd: draft})};
} else {
assert.equal(requests, 2);
assert(request.input.some(i => i.type === "function_call_output" && i.call_id === "draft" &&
JSON.stringify(i.output).includes("fixture-draft-written")));
item = {type: "message", role: "assistant", id: "reply", content: [{type: "output_text", text: nonce}]};
}
const response = {id: `r${requests}`, usage: {input_tokens: 1, output_tokens: 1, total_tokens: 2}};
const events = [{type:"response.created",response}, {type:"response.output_item.done",item},
{type:"response.completed",response}];
res.writeHead(200, {"Content-Type": "text/event-stream"});
res.end(events.map(e => `data: ${JSON.stringify(e)}\n\n`).join(""));
} catch (error) {
fixtureError = error;
res.writeHead(400).end("invalid fixture request");
}
});
server.listen(0, "127.0.0.1");
await once(server, "listening");
try {
const base = `http://127.0.0.1:${server.address().port}/openai/v1`;
await promisify(execFile)("/usr/local/bin/codex-security-entrypoint",
["scan", repo, "--mode", "standard", "--headless", "--output-dir", scanDir, "--provider", "amazon-bedrock", "--model", "openai.gpt-5.6-luna",
"--codex", `model_providers.amazon-bedrock.base_url="${base}"`, "--codex", 'model_providers.amazon-bedrock.aws.region="us-west-2"'],
{env:{...process.env, AWS_ACCESS_KEY_ID:"offline-test", AWS_SECRET_ACCESS_KEY:"offline-test-only",
AWS_REGION:"us-west-2", AWS_EC2_METADATA_DISABLED:"true", NO_PROXY:"127.0.0.1,localhost"},timeout:75_000});
assert.ifError(fixtureError);
assert.equal(requests, 2);
const scan = read(join(scanDir, "scan-manifest.json")).scan;
assert(scan.status === "completed" && scan.sealedAt && scan.scope.summary.includes(nonce));
assert(scan.artifacts.length > 0);
for (const artifact of scan.artifacts) {
const sha256 = createHash("sha256").update(readFileSync(join(scanDir, artifact.path))).digest("hex");
assert.equal(sha256, artifact.sha256, artifact.path);
}
assert.deepEqual(read(join(scanDir, "findings.json")).findings, []);
assert.equal(read(join(scanDir, "exports/results.sarif")).version, "2.1.0");
assert(statSync(join(process.env.CODEX_SECURITY_STATE_DIR, "workbench.sqlite3")).size > 0);
assert(cli("scans", "list", repo).scans.some(s => s.scanId === scan.id));
assert.equal(git("status", "--porcelain"), "");
console.log("PASS loopback scan: native shell tool, sealed marker and artifact hashes, SARIF, SQLite history, unchanged source");
} finally {
server.closeAllConnections();
server.close();
}
+35
View File
@@ -0,0 +1,35 @@
#!/usr/bin/env bash
# Native Linux/amd64. Load the repository's Docker AppArmor profile first.
# The offline fixture creates its own repository and output in disposable tmpfs.
set -euo pipefail
if (( $# != 1 )); then
echo 'usage: tests/smoke.sh LOCAL_IMAGE' >&2
exit 2
fi
test_dir=$(cd -- "$(dirname -- "$0")" && pwd)
docker_dir=$(cd -- "$test_dir/../.." && pwd)
case "$(docker info --format '{{.OSType}}/{{.Architecture}}')" in
linux/x86_64|linux/amd64) ;;
*) echo 'Run on native Linux/amd64 so the nested sandbox can be tested.' >&2; exit 2 ;;
esac
image=$(docker image inspect "$1" --format '{{.Id}}')
[[ $(docker image inspect "$image" --format '{{.Os}}/{{.Architecture}} {{join .Config.Entrypoint " "}}') == 'linux/amd64 /usr/local/bin/codex-security-entrypoint' ]]
echo "Image: $image"
flags=(--rm --pull=never --network=none --read-only --cap-drop=ALL
--security-opt=no-new-privileges --security-opt=apparmor=codex-security-container
--security-opt="seccomp=$docker_dir/codex-security-seccomp.json"
--tmpfs /tmp:rw,nodev,nosuid,mode=1777
--tmpfs /input:rw,nodev,nosuid,uid=10001,gid=10001,mode=0755
--tmpfs /output:rw,nodev,nosuid,uid=10001,gid=10001
--tmpfs /state:rw,nodev,nosuid,uid=10001,gid=10001)
# Exercise the image's configured entrypoint & CMD before using Node as a harness.
help=$(docker run "${flags[@]}" "$image")
[[ $help == *'Usage: codex-security'* ]]
version=$(docker run "${flags[@]}" "$image" --version)
[[ $version == 0.7.0 ]]
status=0
reason=$(docker run "${flags[@]}" "$image" bulk-scan 2>&1) || status=$?
[[ $status == 2 && $reason == *'bulk-scan requires a repository CSV'* ]]
echo "PASS default help, version $version, and noninteractive bulk-scan guard"
docker run "${flags[@]}" -i --entrypoint /usr/bin/node "$image" --input-type=module - < "$test_dir/runtime.mjs"
@@ -0,0 +1,70 @@
import base64
import gzip
import hashlib
import io
import runpy
import tempfile
import unittest
from pathlib import Path
snapshot = runpy.run_path(str(Path(__file__).resolve().parents[1] / "snapshot-builder.py"))["snapshot"]
def fixture(name, signed):
# APK v2 stores consecutive, independently compressed gzip members.
url = f"https://packages.wolfi.dev/os/x86_64/{name}-1-r0.apk"
pkg = {"name": name, "version": "1-r0", "url": url, "architecture": "x86_64"}
data = b""
for part, algorithm in (("signature", "sha1"), ("control", "sha1"), ("data", "sha256")):
if part == "signature" and not signed:
pkg[part] = {"range": "", "checksum": ""}
continue
block = gzip.compress(f"{name} {part}".encode(), mtime=0)
digest = base64.b64encode(hashlib.new(algorithm, block).digest()).decode()
pkg[part] = {"range": f"bytes={len(data)}-{len(data) + len(block) - 1}",
"checksum": f"{algorithm}-{digest}"}
data += block
return pkg, data
class SnapshotTest(unittest.TestCase):
def setUp(self):
self.first, self.a = fixture("first", signed=False)
self.second, self.b = fixture("second", signed=True)
self.lock = {"version": "v1", "contents": {"packages": [self.first, self.second]}}
self.served = {self.first["url"]: self.a, self.second["url"]: self.b}
temp = tempfile.TemporaryDirectory()
self.addCleanup(temp.cleanup)
self.repo = Path(temp.name) / "repository"
def fetch(self, url, *, timeout):
return io.BytesIO(self.served[url])
def test_stages_exact_bytes_for_signed_and_unsigned_packages(self):
snapshot(self.lock, self.repo, self.fetch)
apks = {f.name: f.read_bytes() for f in (self.repo / "x86_64").iterdir()}
self.assertEqual(apks, {"first-1-r0.apk": self.a, "second-1-r0.apk": self.b})
def test_same_url_tampering_never_publishes_a_partial_repository(self):
corrupt = {"truncated": self.b[:-1], "extra": self.b + b"x"}
for part in ("signature", "control", "data"):
offset = int(self.second[part]["range"].split("=")[1].split("-")[0])
corrupt[part] = self.b[:offset] + bytes([self.b[offset] ^ 1]) + self.b[offset + 1:]
for case, changed in corrupt.items():
with self.subTest(case=case):
self.served[self.second["url"]] = changed
with self.assertRaises(ValueError):
snapshot(self.lock, self.repo, self.fetch)
self.assertEqual(list(self.repo.iterdir()), [])
def test_refuses_a_gap_before_control_and_an_unlocked_origin(self):
self.first["control"]["range"] = self.first["control"]["range"].replace("bytes=0-", "bytes=1-")
with self.assertRaisesRegex(ValueError, "invalid control range"):
snapshot(self.lock, self.repo, self.fetch)
self.first["url"] = "https://example.org/first-1-r0.apk"
with self.assertRaisesRegex(ValueError, "Unexpected package source"):
snapshot(self.lock, self.repo, self.fetch)
if __name__ == "__main__":
unittest.main()
+189
View File
@@ -0,0 +1,189 @@
#!/usr/bin/env python3
"""Verify the local apko image and write verification.json and public-components.json."""
import argparse
import gzip
import hashlib
import json
import re
import tarfile
from pathlib import Path
WOLFI = "https://packages.wolfi.dev/os"
REGISTRY = "https://registry.npmjs.org/"
APP = "usr/lib/codex-security/"
ENTRYPOINT = "/usr/local/bin/codex-security-entrypoint"
SOURCES = "usr/share/licenses/codex-security/SOURCES.json"
APK_DATABASES = {"lib/apk/db/installed", "usr/lib/apk/db/installed"}
# A package can contain other package.json files (for example, in examples/).
NPM_MANIFEST = re.compile(r"(?:node_modules/(?:@[^/]+/)?[^/]+/)+package\.json")
LICENSES = set("""MIT Apache-2.0 BSD-1-Clause BSD-2-Clause BSD-3-Clause BSD-4-Clause-UC
ISC CC0-1.0 MPL-2.0 PSF-2.0 OLDAP-2.8 Artistic-1.0-Perl GPL-1.0-only GPL-1.0-or-later
GPL-2.0-only GPL-2.0-or-later GPL-3.0-or-later LGPL-2.0-or-later LGPL-2.1 LGPL-2.1-only
LGPL-2.1-or-later LGPL-3.0-or-later GCC-exception-3.1 libselinux-1.0 blessing CC-PDDC AND OR WITH""".split())
def check(ok, message):
if not ok:
raise SystemExit(message)
def check_license(name, expression):
terms = set(re.findall(r"[\w.+-]+", expression or ""))
check(terms and not (terms - LICENSES), f"Unreviewed license for {name}: {expression}")
class HashingReader:
"""Hash what the gzip and tar readers consume, including trailing tar padding."""
def __init__(self, stream):
self.stream = stream
self.hash = hashlib.sha256()
def read(self, size):
chunk = self.stream.read(size)
self.hash.update(chunk)
return chunk
@property
def digest(self):
return "sha256:" + self.hash.hexdigest()
def read_blob(tar, descriptor):
data = tar.extractfile(descriptor["digest"]).read()
check(len(data) == descriptor["size"] and "sha256:" + hashlib.sha256(data).hexdigest() == descriptor["digest"],
f"OCI blob does not match descriptor: {descriptor['digest']}")
return json.loads(data)
def inspect_layer(fs):
raw, manifests, keys, native = {}, {}, {}, {}
executable = False
for ent in fs:
path = ent.name.removeprefix("./")
check(path.rsplit("/", 1)[-1] != "melange.rsa", f"Signing private key in the image: {path}")
if path == ENTRYPOINT.lstrip("/"):
bit = 0o100 if ent.uid == 10001 else 0o010 if ent.gid == 10001 else 0o001
executable = ent.isfile() and bool(ent.mode & bit)
elif path.startswith("etc/apk/keys/"):
check(ent.isfile(), f"Unexpected public key format: {path}")
keys[path.removeprefix("etc/apk/keys/")] = fs.extractfile(ent).read()
elif ent.isfile():
if path in APK_DATABASES or path in {"etc/apk/repositories", APP + "package-lock.json", SOURCES}:
raw[path] = fs.extractfile(ent).read()
elif path.startswith(APP) and NPM_MANIFEST.fullmatch(path[len(APP):]):
manifests[path[len(APP):-len("/package.json")]] = json.load(fs.extractfile(ent))
elif ("/@openai/codex-linux-x64/vendor/" in path and ent.mode & 0o111) or (path.startswith(APP) and path.endswith(".node")):
h = hashlib.sha256()
stream = fs.extractfile(ent)
for chunk in iter(lambda: stream.read(1024 * 1024), b""):
h.update(chunk)
native[path] = h.hexdigest()
check(executable, "Expected a regular entrypoint executable by UID/GID 10001")
return raw, manifests, keys, native
def inventory_apks(database, packages):
apks = []
lock = {p["name"]:p for p in packages}
for record in database.decode().strip().split("\n\n"):
fields = dict(line.split(":",1) for line in record.splitlines() if line[:2] in {"P:","V:","L:","o:"})
name, version, license = fields["P"],fields["V"],fields["L"]
check_license(name, license)
item = lock.pop(name)
check(item["version"] == version, "Lock version mismatch: "+name)
url = f"{WOLFI}/x86_64/{name}-{version}.apk"
if name == "codex-security":
url = f"./packages/x86_64/{name}-{version}.apk"
check(item["url"] == url, "Unexpected package source: "+item["url"])
apks.append({"name":name, "version":version, "origin":fields["o"], "license":license, "source":url})
check(not lock, "Missing locked APKs")
return sorted(apks, key=lambda p: p["name"])
def inventory_npm(manifests, packages, sources):
paths = {p["path"] for p in sources}
check(len(paths) == len(sources) and paths == manifests.keys(),
"Installed npm package paths differ from SOURCES.json")
npm = []
for item in sources:
path = item["path"]
pkg = packages[path]
meta = manifests[path]
check(pkg["resolved"].startswith(REGISTRY) and pkg["integrity"].startswith("sha512-"), "Unexpected npm source: "+path)
# npm aliases have a different package name from their installed path.
identity = (pkg.get("name", path.rsplit("node_modules/", 1)[-1]), pkg["version"], pkg["license"])
check(identity == (meta["name"], meta["version"], meta["license"]) == (item["name"], item["version"], item["license"]),
"npm metadata mismatch: "+path)
check((pkg["resolved"], pkg["integrity"]) == (item["input_archive"], item["integrity"]), "npm source mismatch: "+path)
check_license(path, meta["license"])
repository = meta.get("repository")
npm.append({"path":path, "name":meta["name"], "version":meta["version"], "license":meta["license"],
"source":pkg["resolved"], "integrity":pkg["integrity"],
"source_repository":repository.get("url") if isinstance(repository,dict) else repository})
return npm
def verify(archive, lock):
with tarfile.open(archive) as tar:
manifest, = json.load(tar.extractfile("manifest.json"))
index, = json.load(tar.extractfile("index.json"))["manifests"]
platform = {"architecture": "amd64", "os": "linux"}
check(index["platform"] == platform, "Expected Linux amd64")
oci = read_blob(tar, index)
check(manifest["Config"] == oci["config"]["digest"], "Docker and OCI configuration disagree")
config = read_blob(tar, oci["config"])
check(all(config[k] == v for k, v in platform.items()), "Unexpected image platform")
c = config["config"]
check((c["Entrypoint"], c["Cmd"], c["User"]) == ([ENTRYPOINT], ["--help"], "10001:10001"),
"Unexpected entrypoint, default command or user")
layer, = manifest["Layers"]
descriptor, = oci["layers"]
check(tar.getmember(layer).size == descriptor["size"], "OCI layer size mismatch")
with tar.extractfile(layer) as stream:
compressed = HashingReader(stream)
with gzip.GzipFile(fileobj=compressed, mode="rb") as gz:
uncompressed = HashingReader(gz)
with tarfile.open(fileobj=uncompressed, mode="r|", bufsize=1024*1024) as fs:
raw, manifests, keys, native = inspect_layer(fs)
while uncompressed.read(1024*1024): # gzip trailer and any remaining tar padding
pass
check(compressed.digest == descriptor["digest"], "Compressed layer checksum mismatch")
check(config["rootfs"]["diff_ids"] == [uncompressed.digest], "Uncompressed layer checksum mismatch")
repos = raw["etc/apk/repositories"].decode().splitlines()
check(repos == [WOLFI], "Unexpected runtime repository")
expected = {Path(k["name"]).name: k["content"].encode() for k in lock["keyring"]}
check(set(expected) == {"wolfi-signing.rsa.pub", "melange.rsa.pub"} and keys == expected, "Incorrect runtime APK trust keys")
key_hashes = {name: hashlib.sha256(data).hexdigest() for name, data in sorted(keys.items())}
databases = {raw[p] for p in APK_DATABASES if p in raw}
check(len(databases) == 1, "Missing or conflicting installed APK database")
apks = inventory_apks(databases.pop(), lock["packages"])
local = sum(p["name"] == "codex-security" for p in apks)
check(local == 1, "Expected one local scanner APK")
src = json.loads(raw[SOURCES])
npm = inventory_npm(manifests, json.loads(raw[APP+"package-lock.json"])["packages"], src["npm"])
records = src["native_executables_and_addons"]
check(len(records) == 6 and all(p["source"].startswith("https://github.com/") for p in records),
"Unknown native runtime source")
check({APP+p["path"]:p["sha256"] for p in records} == native, "Native files differ from source inventory")
components = {"image_manifest":index["digest"], "platform":"linux/amd64", "apk_repository":WOLFI,
"apk_trust_sha256":key_hashes, "apk_count":len(apks), "installed_apks":apks,
"npm_package_count":len(npm), "installed_npm":npm, "bundled_native":records,
"scope":"Installed package sources and declared licenses. The model service is external to the image."
}
verification = {"platform":"linux/amd64", "tag":manifest["RepoTags"][0], "config_digest":manifest["Config"],
"oci_manifest":index["digest"], "runtime_repositories":repos, "entrypoint":ENTRYPOINT, "user":c["User"],
"public_upstream_packages":len(apks)-local, "local_scanner_packages":local,
"keyring_sha256":{k:"sha256:"+v for k,v in key_hashes.items()},
"signed_build_manifest":"SHA256SUMS", "manifest_signature":"SHA256SUMS.sig"}
return {"verification.json": verification, "public-components.json": components}
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("archive", type=Path)
parser.add_argument("lock", type=Path)
args = parser.parse_args()
reports = verify(args.archive, json.loads(args.lock.read_bytes())["contents"])
for name, report in reports.items():
Path(name).write_text(json.dumps(report, indent=2) + "\n")
if __name__ == "__main__":
main()
+14
View File
@@ -0,0 +1,14 @@
-----BEGIN PUBLIC KEY-----
MIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEA5qQUHmzqX9oa/RS3OSgL
YTYB1mzvVmnWC0JXsAafdgRkavJ9xRhsXMKXWPKMghZw6UnkxuxQCZlB9UhaFqed
X7SWfQ8qRgECFmdGUjoeV7P3VUkg17RU0mUKsXZZF/2mU+jCGyk5eweKcLWrk6bn
lNNF1vBJ9EXbHdfvbQsA5GfLku5tJhqRJ4FVQAGCw+1JoSKu+o3q+6xP7z6kMfR9
cp54FSj48rTJUibbAv+cPtZ3AnbpjdyarV7SYMfxp14Q/KR0CJYDihG3CFoU+TaM
dr7LUrgXaYw7m7g8hA2PY1jF8aqDqVFjVu/csPKnKVQSqNHfm4C4gljwT6TDVhPe
6xKSGKfAUNvHx2RIqSsZJCh68Af+VnfuimbHMYzGhzV4/efihpJlYsDnOXJj/PeY
SbEIYG2yoI3AYvDFyFX2OAOtQ9d4TPs4zS4aDg4R3UseXLib46FX3ZTfIi1/W0IO
eC3AFU5mK+02jq+7swcGbgzem30dFA/B3n8NQExJjF2WlGNJxFw2WnJQqKIkIh0s
km5jaxJ28xYgik+bEgxy1LsilKTowdkbEPRKv36JGdap4dOEGR+LwZsM+ontF1AO
wY6tvwtZKJWhgj7ES3BdtiC1GA2htFnP90lA7KnKbSMOxwWtSCH8spitdPdzgI8G
SxrOb0SZs6ZFAxYYe3GlvS0CAwEAAQ==
-----END PUBLIC KEY-----
+62 -36
View File
@@ -5,25 +5,46 @@ ordinary documentation-only change runs static checks and the final `ci` gate.
Static checks format the tracked Markdown in this route. The Action README also
runs Action CI to check generated input documentation and usage examples.
Plugin skills, references, schemas, examples, and unrecognized paths receive
full qualification because plugin Markdown is part of the product. SDK README and
documentation changes also receive full qualification because those files are
required package contents. Deleting or renaming them must pass archive checks.
`RELEASING.md` also receives full qualification because SDK tests validate its
canonical release recovery example.
full qualification because plugin Markdown is part of the product.
Source changes run the complete SDK suite on Linux, macOS, and Windows, plus
MCP, standalone-plugin, native-runtime, and installed-package checks. Tests
PRs limited to the SDK package manifest's Markdown files, optionally mixed with
ordinary docs or `RELEASING.md`, require the native payload, the real package
build and archive inspection, and one Ubuntu Node 24 installation. Removing or
renaming a required guide must still pass archive inspection. The static job
validates the canonical recovery example in `RELEASING.md` on docs-only PRs too.
Mixing the release guide with product source selects full qualification.
Product source changes run the complete SDK suite on Linux, macOS, and Windows,
plus MCP, standalone-plugin, native-runtime, and installed-package checks. Tests
are discovered from the source tree, including new files without timing data.
Platform-specific filesystem, credential, process, cancellation, and resumed
worker cases remain enabled.
SDK shards wait for static checks and a successful package build. A failing
static check skips the shards when a PR opens, reopens, or receives new commits.
Pushes to `main`, nightly and manual runs, and PR edits that need full
qualification still run the shards.
The two Linux MCP jobs discover the same test files as local MCP testing. CI
assigns files by observed runtimes and starts the longest files first on each
job's two Node workers. Refresh the
slow-file estimates in `run-mcp-test-shard.mts` when the jobs drift apart.
Pull requests limited to `.ts` files under `sdk/typescript/src/`,
`sdk/typescript/tests-ts/`, `plugins/codex-security/mcp-app/src/`, and
`plugins/codex-security/mcp-app/tests/`, optionally mixed with ordinary docs,
`plugins/codex-security/mcp-app/tests/`, plus any ordinary docs or packaged SDK guides,
use reduced version matrices. They test the minimum Node 22, 24, and 26 versions,
current Node 24 for the Action adapter, macOS installation, and Windows Node 22
installation. Python runs the full suite on 3.12 and the native subsets on macOS
and Windows. All source changes still select container validation.
installation. When selected, Python runs the full suite on 3.12 and the native
subsets on macOS and Windows. Product source changes select container validation.
PRs limited to top-level `sdk/typescript/tests-ts/*.test.ts` keep all SDK shards,
static checks, native builds, and packaging. Docker excludes these top-level
test modules, so these PRs skip container validation. Test support files used by
package inspection remain in the build context. The test modules are outside the
npm package, so one Ubuntu Node 24 install checks it and the Action adapter.
These PRs skip the plugin suites and run evals only for `codex-dependency-pins.test.ts`.
Mixed changes follow the usual source or full route.
PRs limited to Action metadata, wrapper implementation, tests, npm manifests,
locks, or checked-in bundles run Action CI. It verifies a clean rebuild, runs
@@ -40,8 +61,13 @@ README, or to the triage eval's scripts, assertions, README, manifest or lock,
run the deterministic eval job and static checks. The eval job builds the SDK
and host plugin, checks the Codex version across the SDK, MCP and triage
lockfiles, and runs the triage, secret-discovery, Standard time-budget and
workflow-routing suites. This job also runs on source changes, independently
of the Python matrix.
workflow-routing suites.
Edits limited to existing top-level `plugins/codex-security/tests/test_*.py`
modules keep all five Python jobs, static and workflow checks, MCP, plugin host,
native builds, packaging, and Unix installs. Docker excludes these modules from
the image. Adding, removing, or renaming modules, editing shared helpers, or
including any other path selects full qualification.
Inputs outside these routes select full qualification, including workflow checks,
containers, current Node 26, Windows Node 24 installation, and Python 3.10 and
@@ -56,6 +82,10 @@ successful CI for the exact main commit before publication. Title and body edits
leave source CI running. On an edit, CI checks the source result for the same
pull request, base, head and test merge. It waits for a running source check and
reports a verified result, including static checks, through the required checks.
If the PR event reports an older base, CI can verify the edit on a newer test
merge whose first parent is the current tip of that same branch. A stale merge
or a retarget with different parents needs a fresh PR event after the merge ref
updates. Reopening the PR or pushing a commit starts one.
Only the original source run and an uninterrupted sequence of successful edits
can carry a green result. A cancelled or retried run, a changed target, missing
evidence or conflicting results require full qualification. Use **Re-run all
@@ -70,26 +100,16 @@ job can be skipped. Static checks are always required. The separate `test-qualit
workflow runs weekly property and mutation tests. Dispatch it to compare full SDK
shard layouts.
One compatibility matrix forwards the `ci` result to the three OS-named Node 22
checks required by the current `main` ruleset. Migrate the required checks in
this order.
1. Merge the workflow change and verify that `ci` is reported for source and
documentation pull requests, including a failing selected-check example.
2. Change the repository's required status checks to `ci` and `Validate PR Title`,
preserving their GitHub Actions integration and all unrelated protection rules.
3. Remove the compatibility matrix `required-test` and its three OS check
names from source verification in a follow-up.
Do not remove the old contexts before changing the rules. The workflow change
itself does not change repository protection settings.
The required GitHub Actions checks on `main` are `ci` and `Validate PR Title`.
The title check runs on pull request edits. To diagnose a failed `ci`, open
the selected job named in the gate output.
## Diagnostics and local checks
The workflow-selection and gate tests run without installing dependencies:
```bash
node --test .github/scripts/test-ci-selection.mjs .github/scripts/test-verify-pr-source.mjs
node --test .github/scripts/test-ci-selection.mjs .github/scripts/test-verify-pr-source.mjs .github/scripts/test-release-guide.mjs
```
The [SDK testing guide](../sdk/typescript/TESTING.md) describes local behavioral
@@ -102,19 +122,25 @@ Linux coverage artifacts are review evidence, not a percentage-based merge
gate. Mutation diagnostics also measure results without enforcing a minimum
score. Ordinary report upload failures do not replace the test result.
Only the same pull request can reuse caches saved on `refs/pull/<number>/merge`.
After the PR merges into `main`, a maintenance job deletes those caches.
When measuring CI changes, separate time to required-green from summed job
execution time, prerequisite waits, runner scheduling, approval waits, and
manual retry delays. Compare matching revisions and test configurations, and
record failures as well as successful runs.
When a batch of merges can wait, check **Restore verified native payload** in
an active `node-ci` push or scheduled run on `main`. On a miss, another push
with the same inputs can start all eight platform builds again. Before merging
a PR that leaves those inputs unchanged, look for the exact key in
`gh cache list --ref refs/heads/main --key KEY`. Once it is there, it does not
matter which `main` run saved it. Different inputs can build in parallel.
Protected `main` pushes that miss the same native cache share a queue per block
of 16 consecutive workflow numbers. Each run waits behind at most 15 others,
then restores the verified payload or builds and proves all eight platforms.
Hits, unavailable listings, different inputs, and PR checks can start independently.
The key uses the UTC week and the paths listed in **Identify native build and
proof inputs**. Compare the next change against current `main`: its PR run may
have tested an older base or skipped native preparation entirely. PR runs
cannot populate this cache for `main`.
When a batch can wait, look for the first protected cache save before landing
more changes with the same inputs: `gh cache list --ref refs/heads/main --key KEY`.
The key uses the UTC week selected for the run and the paths in
[the native key action](../.github/actions/native-cache-key/key.sh). Repository
scripts are included by default: a native proof can load a helper at runtime.
The workflow excludes known CI entrypoints that run elsewhere. Compare the
next change against current `main`: its PR run may have tested an older base
or skipped native preparation. PRs cannot populate this
cache for `main`.
+42
View File
@@ -76,6 +76,48 @@ cd ../..
node sdk/typescript/bin/codex-security.mjs scan . -c docs/examples/codex-security.yaml --dry-run --json
```
## Desktop and conversational Deep Scans
Deep Scan setup accepts an explicitly selected `.yaml`, `.yml`, or `.json` project
file using the same format. For example:
```yaml
scan:
mode: deep
max_time_minutes: 30
deep:
workers: 2
subagents_per_worker: 1
stop_after_no_new: 2
max_discovery_runs: 4
```
The plugin's `inspect_codex_security_setup` tool accepts `projectConfigPath` and
returns `setup.deepScanConfig`: effective worker count, subagents per worker,
novelty-stop threshold, consecutive-error threshold, review cap, and discovery
time limit, with the source of each value. Desktop setup clients should display
these values before starting a scan. Conversational scans inspect the same setup
before passing `projectConfigPath` to `start_codex_security_deep_scan`.
Explicit project settings override per-user `[deep_scan]` settings, which override
built-in defaults. The per-user file remains
`$CODEX_HOME/codex-security/config.toml`, or the existing
`CODEX_SECURITY_DEEP_SCAN_CONFIG_PATH` selection. The project selection does not
change that file or unrelated scans. No repository configuration is discovered or
activated automatically.
This integration supports `scan.mode: deep`, `scan.max_time_minutes`, and all
`scan.deep` fields listed below. Other configured fields, including `codex`,
`auth`, scope, context files, cost limits, output, and exit policy, are rejected
with their names before model work starts. Use CLI/SDK configuration for those
settings. If both minute and hour limits are present, they must agree.
Saving native setup freezes the effective settings and their sources. Headless
scans freeze them when first started. Reconnecting or resuming with the returned
scan ID uses that snapshot even if the selected file or global defaults change.
The time limit bounds discovery; scans may stop sooner after novelty or review
limits, and aggregation and reporting can continue afterward.
## Settings
| Field | Meaning | Default |
+4
View File
@@ -1,5 +1,9 @@
# Import Endor Labs findings
Vendor finding import and readback require `CODEX_SECURITY_ENABLE_EXTERNAL_IMPORTS=1`.
See the [opt-in instructions](../../sdk/typescript/docs/cli.md#import-vendor-findings-locally)
and [how saved scanner reports map to imported evidence](schema-guide.md).
Use authenticated `endorctl` to export complete native Finding JSON through the
[official CLI API](https://docs.endorlabs.com/developers-api/cli/commands/api).
Scope the export to one project and context, omit `--field-mask`, and use
+146
View File
@@ -0,0 +1,146 @@
# Import OpenGrep findings
Set `CODEX_SECURITY_ENABLE_EXTERNAL_IMPORTS=1` in the command environment to enable external imports.
Import native OpenGrep JSON, including gzip-compressed reports, into the local
workbench or Cloud. This reader accepts scanner output, not SARIF, normalized
JSONL, or an API summary. It preserves findings as unassessed scanner evidence.
From the source repository root, use a fresh report directory outside the
checkout. The following commands use the shell's temporary directory:
```sh
report_dir=$(mktemp -d) &&
opengrep scan --config /path/to/rules.yaml --json --output "$report_dir/opengrep.json" . &&
codex-security publish findings "$report_dir/opengrep.json" --to local \
--provider opengrep --source-key opengrep/ORGANIZATION/PROJECT/BRANCH \
--source-repository-url https://github.com/example/project \
--repository . --dry-run --format json
```
Native JSON includes dataflow traces when the scanner produces them.
`--dataflow-traces` controls text and SARIF rendering; it is not required for JSON.
See OpenGrep's [output options](https://github.com/opengrep/opengrep/blob/main/src/osemgrep/cli_scan/Scan_CLI.ml)
and [JSON formatter](https://github.com/opengrep/opengrep/blob/main/src/osemgrep/reporting/Cli_json_output.ml).
Review the source repository, findings, exclusions, diagnostics, and destination.
Repeat the import without `--dry-run` to confirm interactively, or add `--yes`
after reviewing the preview. Local imports require no Cloud login or model call.
Read the stored evidence with:
```sh
codex-security findings imported . --format json
```
For Cloud, use the same report and source namespace with a Cloud destination:
```sh
codex-security publish findings "$report_dir/opengrep.json" --to cloud \
--provider opengrep --source-key opengrep/ORGANIZATION/PROJECT/BRANCH \
--source-repository-url https://github.com/example/project \
--repository https://github.com/example/project --dry-run --format json
```
`--source-repository-url` is required and declares where the report came from.
The importer checks it against configured local Git remotes or the selected
Cloud repository. It does not infer the scanner's revision from the current
checkout. Cloud preview requires the existing ChatGPT login and an authorized
repository and environment; review the preview before approving the upload.
## Provider identity and evidence
`--provider opengrep` selects the OpenGrep reader. Local storage and Cloud use the
existing `semgrep` source-provider contract for compatibility, while typed
`scanner_origin` identifies **OpenGrep**. The preview shows this mapping. This
does not add a native OpenGrep provider to the Cloud service. Cloud publication
requires that deployment to support the existing Semgrep import contract;
successful local imports do not verify hosted availability.
Keep an OpenGrep-specific source key, such as
`opengrep/ORGANIZATION/PROJECT/BRANCH`, stable across runs. Occurrence IDs use the
rule, path, and source range. The importer normalizes redundant slash-separated
components in repository-relative paths and preserves literal backslashes in
filenames. An unmapped path keeps its original spelling in the occurrence ID.
Keep Windows path spellings consistent across runs because changing them can
create a second record. Multiple dataflow traces for the same occurrence are
grouped into one finding. For Cloud imports, check `excluded` for traces that
could not fit. If independently valid traces exceed the 256 KiB limit together,
the whole occurrence is excluded. Moving a match creates a new record and leaves
its earlier record intact. The raw scanner
fingerprints remain evidence and do not override this location-based identity.
Omitting a finding from a later report does not close or delete it.
The adapter retains rule metadata, source ranges, snippets, traces, ignored state,
and original severity. Normalized severity is `unknown`: OpenGrep rule levels
such as `ERROR` or `WARNING` are not a verified vulnerability severity. Ignored
matches remain source evidence, separate from a Codex assessment. Importing a
report does not assess findings, apply fixes, or create a completed Codex scan.
## Diagnostics and coverage
OpenGrep can return matches alongside parse failures, partial parsing, timeouts,
and other diagnostics. Warning diagnostics can accompany exit code 0 with the
default `--no-strict`; `--strict` changes warning handling, while `--error`
separately makes findings produce exit code 1. Inspect the report's diagnostics
and the scanner's exit status. Neither zero findings nor a successful exit
establishes complete coverage. See OpenGrep's
[error classification](https://github.com/opengrep/opengrep/blob/main/src/core/Core_error.ml).
The JSON preview and result retain the native report envelope, without `results`,
in `report`, including diagnostics and path metadata for an empty local report.
Individual stored findings retain the original observations in
`source_data.results` and a `source_data.scan_error_count`. Their compact
`source_data.report` retains only the scanner version, keeping scan-wide metadata
such as diagnostics and matching explanations outside each finding's evidence
budget. Full report metadata is
returned by the SDK and CLI; it is not saved as a separate durable scan record.
Keep the original JSON if you need the complete run metadata later.
Add OpenGrep's `--verbose` when collecting
skipped-target details; its [output handling](https://github.com/opengrep/opengrep/blob/main/src/osemgrep/reporting/Output.ml)
can omit those details otherwise.
Publication status describes import processing and acknowledged records, not
scanner coverage. A `complete` publication does not resolve scan diagnostics or
establish a clean security result. Cloud publication requires at least one
supported finding; an empty report can still be previewed locally with its
metadata. Review exclusions before approving either destination.
## Assess an imported finding locally
Copy an imported record's `id` from `findings imported --format json`. Use an
authorized checkout corresponding to the report's revision, then pass its
evidence to the existing SDK validator:
```ts
import {
CodexSecurity,
listLocalExternalFindings,
} from "@openai/codex-security";
const repositoryPath = "/path/to/repository";
const [record] = await listLocalExternalFindings({
repository: repositoryPath,
id: "IMPORTED_FINDING_ID",
});
if (!record) throw new Error("Imported finding not found.");
const security = new CodexSecurity();
try {
const assessment = await security.validate({
repositoryPath,
finding: record.evidence,
});
console.log(record.id, assessment.disposition);
console.log(assessment.report);
} finally {
await security.close();
}
```
Validation sends the finding evidence, including snippets and traces, to the
configured Codex model provider. A hosted provider requires network connectivity.
The validator reads the checkout in a read-only tool sandbox with network access
disabled. It returns an assessment and leaves the stored import `not_assessed`. See
[standalone validation](../../sdk/typescript/README.md#validate-an-existing-finding)
for dispositions and report handling. Hosts that already provide model execution
can use [validateRecords](../../sdk/typescript/docs/validate-records.md) instead.
+187
View File
@@ -0,0 +1,187 @@
# How saved scanner reports map to imported evidence
This guide covers the Wiz, Endor Labs, Snyk Open Source, Semgrep Code and GitHub
**file readers** used by `publish findings`. Acquisition produces the artifact:
for example, `snyk test` scans a workspace, while `codex-security import github`
retrieves selected code-scanning alerts. File ingestion reads the saved report.
Use the mappings to decide what one record represents, whether a later export
updates it, and what evidence a consumer can use. For setup and confirmation,
see
[import vendor findings locally](../../sdk/typescript/docs/cli.md#import-vendor-findings-locally).
## Choose the record and source key
A stored source record is scoped to **destination repository + provider + source
key + source finding ID**. Choose the key for the stream you intend to replay,
not the export date. A CVE or GHSA names an advisory; a CWE or rule ID describes
a class of issue. Neither identifies a particular installed dependency, code
location, or affected asset. Matching titles, packages or advisories are reasons
to investigate records together, not instructions to merge them.
| Reader and accepted input | Source finding ID basis | Keep the source key stable for |
| --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------ |
| [Wiz package JSON or detailed CSV](../../sdk/typescript/docs/cli.md#package-vulnerability-inputs); CSV requires `CloudPlatform=GitHub` and `CloudProviderURL` for a GitHub repository `/tree/<ref>` | Vendor occurrence `id` (CSV: `ID`), not the CVE | Tenant and finding family |
| [Wiz named repository collections](../../sdk/typescript/docs/cli.md#sast-repository-secrets-and-iac-inputs) | `sast:<id>`, `secret:<id>`, `iac:<id>` | Tenant and finding family |
| [Endor Finding JSON or endorctl SARIF](endor.md) | Finding `uuid` or SARIF `properties["finding-uuid"]` | Namespace, project and context |
| [Snyk Open Source CLI JSON, plugin v1 or SARIF](snyk.md) | CLI: manager, manifest, advisory, package/version and dependency path; plugin: supplied composite; SARIF: advisory, manifest set and project when known | Repository, branch, scan target and format |
| [Semgrep Code CLI/CI JSON or SARIF](semgrep.md) | Fingerprint; otherwise rule, literal path and start/end lines and columns | Organization, project and branch |
| [GitHub saved `import github` output](../../sdk/typescript/docs/cli.md#import-github-findings-locally-or-to-cloud) | Host, repository, alert number and hash of selected ref | Host, repository and code-scanning family |
| [GitHub saved `import github-advisories` output](../../sdk/typescript/docs/cli.md#import-ghsa-advisories-separately) | Host, repository **or** global scope, and GHSA ID | Separate advisory stream from alerts |
Within **one input**, duplicate IDs are ambiguous, not corroboration. Wiz and
GitHub reject a selection with duplicate accepted IDs. Endor, Snyk and Semgrep
exclude every record with the colliding identity. Inspect the source and select
the intended occurrence; don't rename records simply to make them import. Across
**separate local imports**, changed evidence updates the same record; omission
does not delete or resolve it. Cloud publication sends an expected version;
resuming a saved request keeps that value. An item error such as
`version_conflict` or `stale_source_snapshot` can reject an update instead of
replacing a newer report. Inspect the item error and current source report
before preparing a fresh submission.
## Interpret the provider evidence
- **Wiz:** `detailedName`, version, advisory and fixed version describe a
package occurrence. Repository-branch paths can be manifests; container paths
cannot. JSON prefers `vendorSeverity` over `severity`; repository CSV uses
`Severity`, then `VendorSeverity`, then `CVSSSeverity`. Keep named
`sastFindings`, `secretInstances` or `iacFindings` nodes with a repository URL
or matching inventory. SAST can map a range, snippet, CWE and vendor verdict;
repository secrets map detector and validation metadata, not a scanned
revision from the introduced commit; IaC maps expected/actual configuration,
not proof of deployment. The Wiz file reader does not map workload secrets,
cloud configuration or external network scans. It also accepts explicitly
normalized JSONL: supply the reviewed `source_finding_id` and `evidence`,
retaining the raw row. The reader does not infer a mapping for other CSV
profiles.
- **Endor Labs:** Prefer a complete native Finding, array or `list.objects`.
`spec.level`, dependency paths/versions, advisory aliases, source SHA and
primary SAST/AI SAST locations map when present. The project UUID does not
verify the repository. Proposed upgrades, reachability and dismissals remain
source claims. SARIF keeps the rule/result and direct locations but reports
`unknown` severity, not CVSS or diagnostic level. Importing SARIF over native
JSON for the same UUID **replaces**, rather than enriches, its snapshot.
- **Snyk CLI, plugin and Open Source SARIF:** Prefer ungrouped native
`snyk test` JSON for package versions,
dependency chains, advisory aliases and fix advice. A different dependency
path can be another occurrence of the same advisory. Plugin evidence can be
abbreviated; SARIF groups occurrences. Scan-target-relative manifests are not
Git-root locations, and a synthetic SARIF line 1 is not a code finding. The
formats do not reconcile their IDs. Licenses, Code, Container, IaC and
platform backlog are outside these Open Source file formats.
- **Semgrep Code CLI and SARIF:** Supply `--source-repository-url` for these
file formats. JSON `extra.fingerprint` or
SARIF `matchBasedId/v1` survives a location change; without a usable
fingerprint, a move creates a new record. Use the mapped rule, range, snippet
and CWE to locate code. Ignored/suppressed is source state. JSON distinguishes
Critical from High; both become diagnostic `error`, mapped to High, in Semgrep
SARIF. Inspect the selected result for trace/fix details. Platform/MCP
envelopes and general Supply Chain/Secrets feeds are not Code CLI or SARIF exports.
- **GitHub:** For code scanning, the selected instance supplies path/range, ref
and commit. The rule's `security_severity_level` supplies severity; diagnostic
`error` alone means `unknown`. An alert-wide dismissal takes precedence over
instance state. For GHSA, a repository disclosure identifies its publisher; a
global disclosure has no source repository. Both can carry CVE aliases,
affected ranges and patched versions. Neither proves installation or
applicability. Raw API pages, Dependabot and secret-scanning alerts are not
these saved inputs.
## Read the right field
- The
[evidence schema](../../sdk/typescript/schemas/external-findings.schema.json)
separates the source ID from `evidence`. Its required `title` and `severity`
are reported evidence, not a Codex rating. Severity is one of `critical`,
`high`, `medium`, `low`, `informational`, or `unknown`; source status,
confidence, verdicts and fix advice do not change `assessment.state`.
- `packages[].installed_version` is an observation; `vulnerable_version_range`
is a claim about affected versions; `fixed_versions` is source guidance. Use
`locations[].path/line` for repository navigation and optional
`details.code.end_line` for the first location. Missing evidence stays
missing; don't fill in a commit from the current checkout.
- Optional `details.kind` is **not** a universal scanner taxonomy. Its values
are `sast`, `secret`, `iac` and `advisory`. Package occurrences from Wiz/Snyk
and native Endor findings use top-level fields without requiring a kind. For
an advisory, inspect `details.advisory.source`, not the chosen destination, to
distinguish repository and global scope.
- Use `source_data` to inspect what the reader actually received: e.g. a Wiz
row, Endor Finding, Snyk vulnerability plus project context, Semgrep result or
GitHub collector envelope. It's selected evidence, not necessarily the whole
export: unrelated scan inventories can be omitted and plugin or SARIF output
may already be lossy. Retain the input privately if collection scope matters.
## Operate the two destinations
Local readback returns `sourceKey`, `sourceFindingId`, `version`, `evidence` and
`assessment` alongside the local record ID. The Cloud publisher sends
`source.provider` and `source.source_key` with an expected version, source
finding ID and evidence for each item. Receipt IDs for the source report,
observation and canonical finding are **destination** references, not vendor
occurrence IDs. Use the source report for evidence, not the receipt counts.
**One project, local triage.** From a checkout with a saved native Snyk report
outside it:
```sh
export CODEX_SECURITY_ENABLE_EXTERNAL_IMPORTS=1
codex-security publish findings ../reports/snyk.json --to local --provider snyk \
--repository . --source-key example/project/main/root/native-sca --dry-run --format json
```
Check the selected repository, IDs, evidence and exclusions. Repeat without
`--dry-run` and confirm; then run
`codex-security findings imported . --format json`. Workbench SQLite stores the
snapshot and version. Repeating identical evidence is unchanged. A source
repository claim is checked against configured remotes when available; when
provenance is absent you must verify the target yourself. These records remain
`not_assessed`, separate from `findings list` and completed scans. To
investigate, compare the reported installed version or location against the
selected revision; import alone is not validation.
**Many repositories, reviewed publication.** Partition complete exports by
repository and source namespace first; don't attach a fleet-wide export to one
destination. For example, preview one Endor project and context against its
connected repository:
```sh
codex-security publish findings ../reports/endor-project-main.json --to cloud \
--repository https://github.com/example/project --provider endor \
--source-key example-namespace/example-project/main --dry-run --format json
```
This reads authorized destination state; it doesn't upload. Check the account,
repository, environments, eligible records and exclusions before confirming.
Local file imports do not apply the Cloud evidence limits. Cloud limits include
256 KiB per finding, depth 20 and 5 MiB per request; an oversized record is
excluded, not truncated. For example, 240 eligible findings for one destination
require at least three requests at the 100-item ceiling, possibly more for size
or environment boundaries.
Read the
[result and recovery contract](../../sdk/typescript/docs/cli.md#results-and-exit-codes):
`partial` (exit 1) can include acknowledged records alongside exclusions or item
errors. Correct the rejected records; do not treat the whole selection as
failed. After `interrupted` (exit 2), a lost response is **not** proof of
rejection. A reset can also fail during preparation. Inspect the error,
receipts, cumulative counts and unacknowledged items before choosing how to
recover:
- **`savedSubmission` identifies an existing checkpoint:** rerun the same
approved command with unchanged input, source key, destination and endpoint to
resume its saved requests. This also applies if the initial request was saved
but persisting a later receipt failed.
- **No resumable checkpoint:** a repository reset retires the old request, and
an initial checkpoint-write failure may leave no request to resume. Inspect
the destination and correct the error; run a fresh `--dry-run` and get fresh
approval before publishing. Do not blindly replay a command containing
`--yes`.
Verified source-report readback is evidence of import, not a security
assessment, UI visibility or a vendor state change.
**Privacy.** Reports, full JSON previews, local state and saved Cloud request
bodies can contain source snippets, secret metadata, internal paths, private
advisories and vendor links. Select only authorized metadata (not credential
values), keep artifacts outside the checkout with restricted access and review
the destination before uploading. Don't paste raw evidence or checkpoints into
public tickets, CI logs or PRs. The readers do not promise to redact them.
+8 -4
View File
@@ -1,5 +1,9 @@
# Import Semgrep Code findings
Vendor finding import and readback require `CODEX_SECURITY_ENABLE_EXTERNAL_IMPORTS=1`.
See the [opt-in instructions](../../sdk/typescript/docs/cli.md#import-vendor-findings-locally)
and [how saved scanner reports map to imported evidence](schema-guide.md).
Prefer native **Semgrep Code/SAST CLI or CI JSON** for this reader. It preserves
the scanner's original severity and source evidence. Self-contained SARIF 2.1.0
is a compatibility path. Both formats may be plain or gzip-compressed.
@@ -79,10 +83,10 @@ trace and fix evidence. Its Critical and High ratings both become diagnostic
Original evidence stays in `source_data`, and source state stays separate from a
Codex assessment.
Both local and Cloud file imports currently apply the shared Cloud evidence
bounds, including a maximum JSON depth of 20. Deeply nested native taint traces
can exceed that bound and are excluded with a reason in the preview. The reader
preserves accepted source evidence without flattening or truncating traces.
Cloud imports apply the service's evidence limits, including a maximum JSON
depth of 20. A deeply nested taint trace can exceed that bound and be excluded
with a reason in the Cloud preview. Local storage does not impose the Cloud
size or depth limits. Neither path flattens or truncates accepted traces.
Keep the supplied JSON `extra.fingerprint` or SARIF `matchBasedId/v1`
fingerprint. If a later report supplies the same fingerprint after the code
+27 -13
View File
@@ -1,5 +1,9 @@
# Snyk Open Source imports
Vendor finding import and readback require `CODEX_SECURITY_ENABLE_EXTERNAL_IMPORTS=1`.
See the [opt-in instructions](../../sdk/typescript/docs/cli.md#import-vendor-findings-locally)
and [how saved scanner reports map to imported evidence](schema-guide.md).
Use the [official Snyk Codex plugin](https://github.com/snyk/studio-recipes/tree/main/plugins/codex)
to collect a fresh workspace scan. The existing
[`publish findings` command](../../sdk/typescript/docs/cli.md#import-snyk-open-source-findings)
@@ -57,10 +61,27 @@ alternate dependency paths. The plugin cannot recover data its MCP server did
not return. See the [official SCA mapper](https://github.com/snyk/studio-mcp/blob/main/internal/oss/map.go).
The bundle's composite occurrence identity includes package version and dependency
path. Keep the same source key for each repository, branch and scan target across
exports; a changed occurrence has a new ID. Plugin v1 paths are relative to the
scan target and do not carry its Git-root offset. They remain in original evidence
exports. A change to the composite identity produces a new source ID; changing
only the evidence preserves that ID. Plugin v1 paths are relative to the scan
target and do not carry its Git-root offset. They remain in original evidence
without being projected as repository locations or package manifest paths.
### How to read import counts
For the same repository and source key, `created` means a new source identity.
For an existing identity, `updated` means the whole evidence snapshot changed;
`unchanged` means it did not. These counts describe imported Snyk evidence, not
new vulnerabilities, fixes, or Codex assessments.
Each plugin finding retains its collection context. If a scan's `issueCount`
falls from three to two, both remaining findings can get a new version even if
neither occurrence changed. Their source IDs stay the same, and omitting the
third finding does not close it. Native CLI JSON likewise retains the project's
[`uniqueCount`](https://github.com/snyk/cli/blob/8b2d0a695c6b1b31f681e32039db958fba6f0c2f/src/lib/snyk-test/run-test.ts#L555)
when supplied. It counts distinct vulnerabilities, not dependency-path
occurrences: two paths to the same advisory contribute one to the count.
Keep the original evidence; do not edit or strip scan metadata to suppress updates.
### Native CLI JSON
For automation, use the [Snyk CLI](https://docs.snyk.io/developer-tools/snyk-cli/commands/test)
@@ -145,14 +166,7 @@ repository when using the default SSH port or port 22. The public
`github.com`. Other hosts, nondefault SSH ports and explicit HTTPS ports remain
distinct; the importer does not infer an Enterprise host from the artifact alone.
Unknown repository context requires the user to select the correct destination.
Gzip and UTF-8 BOM input are supported. All three file formats
normalize to the Cloud evidence model before either local import or Cloud publication.
Records exceeding that model's field or total-size limits appear as exclusions in
the preview, without truncation. The normalized local SDK import API has a separate
contract that accepts larger evidence. Inspect preview exclusions before importing.
The plugin and CLI paths scan the current workspace. Existing Snyk platform
findings need a separate [REST Issues API](https://docs.snyk.io/snyk-api/reference/issues)
reader with tenant access and repository mapping. This adapter does not read that
backlog or synchronize triage decisions. Synthetic contract and publication tests
do not establish live tenant, plugin-runtime or deployed Cloud compatibility.
Gzip and UTF-8 BOM input are supported. Records exceeding the destination's
field or total-size limits appear as exclusions in the preview, without
truncation. Inspect preview exclusions before importing. Synthetic tests do
not establish live tenant, plugin-runtime or deployed Cloud compatibility.
+1 -1
View File
@@ -94,7 +94,7 @@ export const outputSchema = object({
remediation: text,
}),
),
coverage: object({
reviewState: object({
surfaces: array(
object({
label: text,
+55 -66
View File
@@ -58,16 +58,18 @@ interface TestResult extends Result {
};
resolved_questions?: TestFinding[];
}
function retainedResult(fixture: ReturnType<typeof createFixture>): TestResult {
const fixture = createFixture();
function retainedResult(source = fixture): TestResult {
return {
findings: fixture.positives.map((expected) => ({
findings: source.positives.map((expected) => ({
title: "Embedded credential",
taxonomy: { category: "hardcoded-credentials", cwe: [expected.cwes[0]] },
locations: [
{ path: expected.path, startLine: expected.line, role: "root_control" },
],
codeEvidence: [
sourceEvidence(fixture, expected.path, expected.line, expected.endLine),
sourceEvidence(source, expected.path, expected.line, expected.endLine),
],
})),
coverage: {
@@ -79,14 +81,8 @@ function retainedResult(fixture: ReturnType<typeof createFixture>): TestResult {
};
}
function retainedFixture() {
const fixture = createFixture();
return { fixture, result: retainedResult(fixture) };
}
test("counts every retained secret location, including unused and integration source", () => {
const fixture = createFixture();
const report = gradeResult(retainedResult(fixture), fixture);
const report = gradeResult(retainedResult(), fixture);
assert.equal(report.passed, true);
assert.equal(report.recall, 1);
assert.deepEqual(
@@ -103,7 +99,7 @@ test("counts every retained secret location, including unused and integration so
});
test("resolved, deferred, and intermediate findings do not satisfy final recall", () => {
const { fixture, result } = retainedFixture();
const result = retainedResult();
result.coverage.deferred = result.findings;
result.resolved_questions = result.findings;
result.findings = [];
@@ -145,7 +141,7 @@ for (const [name, mutate] of [
],
] as const) {
test(`rejects ${name}`, () => {
const { fixture, result } = retainedFixture();
const result = retainedResult();
mutate(result.findings[0]);
const report = gradeResult(result, fixture);
assert.equal(report.passed, false);
@@ -173,7 +169,7 @@ for (const category of [
"without-credentials",
]) {
test(`rejects negated category ${category}`, () => {
const { fixture, result } = retainedFixture();
const result = retainedResult();
result.findings[0].taxonomy.category = category;
const report = gradeResult(result, fixture);
assert.equal(report.passed, false);
@@ -182,10 +178,9 @@ for (const category of [
}
test("rejects unrelated categories containing credential-term substrings", () => {
const fixture = createFixture();
for (const category of ["tokenization-error", "secretary-data"]) {
for (const cwe of ["CWE-798", "CWE-200"]) {
const result = retainedResult(fixture);
const result = retainedResult();
result.findings[0].taxonomy = { category, cwe: [cwe] };
const report = gradeResult(result, fixture);
assert.equal(report.passed, false, `${category}:${cwe}`);
@@ -195,7 +190,6 @@ test("rejects unrelated categories containing credential-term substrings", () =>
});
test("accepts plural and identifier-style credential categories", () => {
const fixture = createFixture();
for (const category of [
"tokens-exposed",
"secrets_in_source",
@@ -203,14 +197,14 @@ test("accepts plural and identifier-style credential categories", () => {
"hardcodedCredentials",
"credentialExposure",
]) {
const result = retainedResult(fixture);
const result = retainedResult();
result.findings[0].taxonomy.category = category;
assert.equal(gradeResult(result, fixture).passed, true, category);
}
});
test("accepts credential exposure with non-secret context in the category", () => {
const { fixture, result } = retainedFixture();
const result = retainedResult();
for (const category of [
"credential exposure with non-secret context",
"credential exposure with no-secret context",
@@ -223,7 +217,7 @@ test("accepts credential exposure with non-secret context in the category", () =
});
test("accepts a secret's valid source range and sensitive-data category", () => {
const { fixture, result } = retainedFixture();
const result = retainedResult();
result.findings[0].locations[0].endLine = fixture.positives[0].line + 1;
result.findings[0].taxonomy.category = "sensitive-data-exposure";
assert.equal(gradeResult(result, fixture).passed, true);
@@ -235,14 +229,13 @@ for (const category of [
"api-key-exposure",
]) {
test(`accepts credential category ${category}`, () => {
const { fixture, result } = retainedFixture();
const result = retainedResult();
result.findings[0].taxonomy.category = category;
assert.equal(gradeResult(result, fixture).passed, true);
});
}
test("accepts equivalent CWE spelling without weakening generic disclosure categories", () => {
const fixture = createFixture();
for (const [cwe, generic] of [
["cwe-798", false],
["CWE-0798", false],
@@ -250,7 +243,7 @@ test("accepts equivalent CWE spelling without weakening generic disclosure categ
[" cwe-00200 ", true],
["CWE-0540", true],
] as const) {
const result = retainedResult(fixture);
const result = retainedResult();
result.findings[0].taxonomy.cwe = ["CWE-798", cwe];
assert.equal(gradeResult(result, fixture).passed, true, cwe);
if (generic) {
@@ -261,7 +254,6 @@ test("accepts equivalent CWE spelling without weakening generic disclosure categ
});
test("rejects unrelated or malformed CWE identifiers after normalization", () => {
const fixture = createFixture();
for (const cwe of [
" cwe-0089 ",
"CWE-798-extra",
@@ -270,7 +262,7 @@ test("rejects unrelated or malformed CWE identifiers after normalization", () =>
"CWE-321",
]) {
for (const withValidCwe of [false, true]) {
const result = retainedResult(fixture);
const result = retainedResult();
result.findings[0].taxonomy.cwe = withValidCwe ? ["CWE-798", cwe] : [cwe];
const report = gradeResult(result, fixture);
assert.equal(report.passed, false, cwe);
@@ -281,12 +273,11 @@ test("rejects unrelated or malformed CWE identifiers after normalization", () =>
});
test("matches path casing only on Windows while preserving citation checks", () => {
const fixture = createFixture();
const descriptor = Object.getOwnPropertyDescriptor(process, "platform");
try {
for (const platform of ["linux", "win32"]) {
Object.defineProperty(process, "platform", { value: platform });
const result = retainedResult(fixture);
const result = retainedResult();
const finding = result.findings[0];
finding.locations.push(
{ path: "src/client.py", startLine: 7, role: "sink" },
@@ -315,7 +306,7 @@ test("matches path casing only on Windows while preserving citation checks", ()
for (const cwe of ["CWE-256", "CWE-259", "CWE-260"]) {
test(`accepts ${cwe} for the password in the database configuration`, () => {
const { fixture, result } = retainedFixture();
const result = retainedResult();
const databaseIndex = fixture.positives.findIndex(
(entry) => entry.id === "dotenv-url",
);
@@ -328,7 +319,7 @@ for (const cwe of ["CWE-256", "CWE-259", "CWE-260"]) {
for (const cwe of ["CWE-312", "CWE-313"]) {
test(`accepts ${cwe} for credentials stored in source and configuration files`, () => {
const { fixture, result } = retainedFixture();
const result = retainedResult();
for (const finding of result.findings) finding.taxonomy.cwe = [cwe];
assert.equal(gradeResult(result, fixture).passed, true);
@@ -340,7 +331,6 @@ for (const cwe of ["CWE-312", "CWE-313"]) {
}
test("keeps password and cryptographic-key CWEs specific to those exposures", () => {
const fixture = createFixture();
for (const [index, expected] of fixture.positives.entries()) {
for (const [cwe, applicableId] of [
["CWE-256", "dotenv-url"],
@@ -349,7 +339,7 @@ test("keeps password and cryptographic-key CWEs specific to those exposures", ()
["CWE-321", "private-key"],
] as const) {
if (expected.id === applicableId) continue;
const result = retainedResult(fixture);
const result = retainedResult();
result.findings[index].taxonomy.cwe = [cwe];
const report = gradeResult(result, fixture);
assert.equal(report.passed, false, `${expected.id}:${cwe}`);
@@ -360,7 +350,7 @@ test("keeps password and cryptographic-key CWEs specific to those exposures", ()
for (const cwe of ["CWE-200", "CWE-540"]) {
test(`accepts ${cwe} for specifically categorized credential exposure`, () => {
const { fixture, result } = retainedFixture();
const result = retainedResult();
for (const finding of result.findings) finding.taxonomy.cwe = [cwe];
assert.equal(gradeResult(result, fixture).passed, true);
@@ -373,7 +363,7 @@ for (const cwe of ["CWE-200", "CWE-540"]) {
for (const negativeIndex of [0, 1, 2, 3]) {
test(`rejects a finding against negative control ${negativeIndex}`, () => {
const { fixture, result } = retainedFixture();
const result = retainedResult();
result.findings.push({
taxonomy: { category: "hardcoded-credentials", cwe: ["CWE-798"] },
locations: [
@@ -399,13 +389,12 @@ for (const role of [
"expected_control",
]) {
test(`benign ${role} context does not become a false positive`, () => {
const fixture = createFixture();
for (const path of [
fixture.negatives[0],
`./${fixture.negatives[0]}`,
`.\\${fixture.negatives[0].replaceAll("/", "\\")}`,
]) {
const result = retainedResult(fixture);
const result = retainedResult();
result.findings[0].locations.push({
path,
startLine: 1,
@@ -419,7 +408,6 @@ for (const role of [
});
test(`rejects invalid ${role} source citations`, () => {
const fixture = createFixture();
for (const location of [
{ path: "src/absent.py", startLine: 999 },
{ path: "src/runtime_config.py", startLine: 0 },
@@ -428,7 +416,7 @@ for (const role of [
{ path: "src/runtime_config.py", startLine: 3, endLine: 1 },
{ path: "src/runtime_config.py", startLine: 1, endLine: 999 },
]) {
const result = retainedResult(fixture);
const result = retainedResult();
result.findings[0].locations.push({ ...location, role });
const report = gradeResult(result, fixture);
assert.equal(report.recall, 1);
@@ -445,7 +433,7 @@ for (const [name, location] of [
["negative control", { path: "src/runtime_config.py", startLine: 1 }],
] as const) {
test(`rejects an additional non-supporting location at ${name}`, () => {
const { fixture, result } = retainedFixture();
const result = retainedResult();
result.findings[0].locations.push({ ...location, role: "root_control" });
const report = gradeResult(result, fixture);
assert.equal(report.recall, 1);
@@ -456,7 +444,7 @@ for (const [name, location] of [
for (const role of ["root_control", "sink"]) {
test(`rejects a ${role} citation classified only by a different finding`, () => {
const { fixture, result } = retainedFixture();
const result = retainedResult();
const finding = result.findings[0];
finding.taxonomy.cwe = ["CWE-522"];
const key = fixture.positives.find(
@@ -481,7 +469,6 @@ for (const role of ["root_control", "sink"]) {
}
test("correct finding locations cannot hide missing or unrelated code evidence", () => {
const fixture = createFixture();
for (const evidence of [
undefined,
[],
@@ -489,7 +476,7 @@ test("correct finding locations cannot hide missing or unrelated code evidence",
[sourceEvidence(fixture, "src/runtime_config.py", 3)],
[{ ...sourceEvidence(fixture, "src/client.py", 3), code: " \n" }],
]) {
const result = retainedResult(fixture);
const result = retainedResult();
result.findings[0].codeEvidence = evidence as CodeEvidence[];
const report = gradeResult(result, fixture);
assert.equal(report.recall, 1);
@@ -499,7 +486,6 @@ test("correct finding locations cannot hide missing or unrelated code evidence",
});
test("rejects fabricated source text at otherwise valid evidence locations", () => {
const fixture = createFixture();
for (const code of [
"invented source",
sourceEvidence(fixture, "src/client.py", 1).code,
@@ -508,7 +494,7 @@ test("rejects fabricated source text at otherwise valid evidence locations", ()
"OTHER_TOKEN",
),
]) {
const result = retainedResult(fixture);
const result = retainedResult();
result.findings[0].codeEvidence[0].code = code;
const report = gradeResult(result, fixture);
assert.equal(report.recall, 1);
@@ -516,7 +502,7 @@ test("rejects fabricated source text at otherwise valid evidence locations", ()
assert.deepEqual(report.errors, ["missing or invalid code evidence"]);
}
const result = retainedResult(fixture);
const result = retainedResult();
result.findings[0].codeEvidence.push({
...sourceEvidence(fixture, "README.md", 1),
code: "invented supporting context",
@@ -527,14 +513,13 @@ test("rejects fabricated source text at otherwise valid evidence locations", ()
});
test("rejects invented and out-of-bounds citations alongside valid evidence", () => {
const fixture = createFixture();
for (const citation of [
{ path: "src/absent.py", startLine: 1 },
{ path: "src/client.py", startLine: 0 },
{ path: "src/client.py", startLine: 999 },
{ path: "src/client.py", startLine: 7, code: "first line\nsecond line" },
]) {
const result = retainedResult(fixture);
const result = retainedResult();
result.findings[0].codeEvidence.push({
...sourceEvidence(fixture, "src/client.py", 3),
...citation,
@@ -546,12 +531,11 @@ test("rejects invented and out-of-bounds citations alongside valid evidence", ()
});
test("accepts multiline exposure and consumer excerpts with supporting context", () => {
const fixture = createFixture();
for (const [startLine, endLine] of [
[1, 3],
[4, 7],
] as const) {
const result = retainedResult(fixture);
const result = retainedResult();
result.findings[0].codeEvidence = [
sourceEvidence(fixture, "src/client.py", startLine, endLine),
sourceEvidence(fixture, "src/runtime_config.py", 3),
@@ -564,7 +548,6 @@ test("accepts multiline exposure and consumer excerpts with supporting context",
});
test("consumer evidence and sinks must cover credential use, not function framing", () => {
const fixture = createFixture();
for (const [id, line] of [
["active-source", 5],
["active-source", 6],
@@ -575,7 +558,7 @@ test("consumer evidence and sinks must cover credential use, not function framin
] as const) {
const index = fixture.positives.findIndex((expected) => expected.id === id);
const expected = fixture.positives[index];
const result = retainedResult(fixture);
const result = retainedResult();
result.findings[index].codeEvidence = [
sourceEvidence(fixture, expected.path, line),
];
@@ -585,7 +568,7 @@ test("consumer evidence and sinks must cover credential use, not function framin
`${id}:${line}`,
);
const invalidSink = retainedResult(fixture);
const invalidSink = retainedResult();
invalidSink.findings[index].locations.push({
path: expected.path,
startLine: line,
@@ -600,14 +583,13 @@ test("consumer evidence and sinks must cover credential use, not function framin
});
test("accepts actual credential-use lines and excerpts containing them", () => {
const fixture = createFixture();
for (const [index, expected] of fixture.positives.entries()) {
if (expected.consumerLine === null) continue;
for (const [startLine, endLine] of [
[expected.consumerLine, expected.consumerLine],
[5, expected.lineCount],
] as const) {
const result = retainedResult(fixture);
const result = retainedResult();
result.findings[index].codeEvidence = [
sourceEvidence(fixture, expected.path, startLine, endLine),
];
@@ -623,7 +605,7 @@ test("accepts actual credential-use lines and excerpts containing them", () => {
});
test("multiple expected exposures can share a finding", () => {
const { fixture, result } = retainedFixture();
const result = retainedResult();
const unused = result.findings.splice(1, 1)[0];
result.findings[0].locations.push(...unused.locations);
assert.deepEqual(gradeResult(result, fixture).errors, [
@@ -634,7 +616,7 @@ test("multiple expected exposures can share a finding", () => {
});
test("grouped exposures retain their applicable CWE classifications", () => {
const { fixture, result } = retainedFixture();
const result = retainedResult();
const indices = ["dotenv-url", "private-key"].map((id) =>
fixture.positives.findIndex((expected) => expected.id === id),
);
@@ -663,7 +645,7 @@ test("grouped exposures retain their applicable CWE classifications", () => {
for (const role of ["supporting", "expected_control"]) {
test(`${role} citations cannot satisfy an independently missed exposure`, () => {
const { fixture, result } = retainedFixture();
const result = retainedResult();
const unused = result.findings.splice(1, 1)[0];
result.findings[0].locations.push({
...unused.locations[0],
@@ -676,7 +658,7 @@ for (const role of ["supporting", "expected_control"]) {
}
test("accepts real credential-use sinks without treating them as separate exposures", () => {
const { fixture, result } = retainedFixture();
const result = retainedResult();
for (const [index, expected] of fixture.positives.entries()) {
if (expected.consumerLine === null) continue;
const sink = {
@@ -686,7 +668,7 @@ test("accepts real credential-use sinks without treating them as separate exposu
role: "sink",
};
result.findings[index].locations.push(sink);
const onlyConsumer = retainedResult(fixture);
const onlyConsumer = retainedResult();
onlyConsumer.findings[index].locations = [sink];
assert.equal(gradeResult(onlyConsumer, fixture).cases[index].found, false);
}
@@ -697,7 +679,7 @@ test("accepts real credential-use sinks without treating them as separate exposu
{ path: "src/absent.py", startLine: 5 },
{ path: "src/client.py", startLine: 1 },
]) {
const invalid = retainedResult(fixture);
const invalid = retainedResult();
invalid.findings[0].locations.push({ ...location, role: "sink" });
assert.equal(gradeResult(invalid, fixture).falsePositiveCount, 1);
}
@@ -708,9 +690,8 @@ for (const [name, separator] of [
["Windows", "\\"],
] as const) {
test(`accepts ${name} source and credential-use paths with relative prefixes`, () => {
const fixture = createFixture();
for (const prefix of ["", "./", "././", ".\\", ".\\./", "./.\\"]) {
const result = retainedResult(fixture);
const result = retainedResult();
for (const [index, expected] of fixture.positives.entries()) {
const path = `${prefix}${expected.path.replaceAll("/", separator)}`;
result.findings[index].locations[0].path = path;
@@ -730,7 +711,6 @@ for (const [name, separator] of [
}
test("path normalization does not make unrelated or unsafe source locations valid", () => {
const fixture = createFixture();
for (const path of [
"./src/absent.py",
"./src/../src/client.py",
@@ -740,7 +720,7 @@ test("path normalization does not make unrelated or unsafe source locations vali
"\\src\\client.py",
"C:\\src\\client.py",
]) {
const result = retainedResult(fixture);
const result = retainedResult();
result.findings[0].locations[0].path = path;
const report = gradeResult(result, fixture);
assert.equal(report.cases[0].found, false, path);
@@ -750,7 +730,7 @@ test("path normalization does not make unrelated or unsafe source locations vali
});
test("accepts the private-key body and rejects reversed source ranges", () => {
const { fixture, result } = retainedFixture();
const result = retainedResult();
const keyIndex = fixture.positives.findIndex(
(entry) => entry.id === "private-key",
);
@@ -763,7 +743,7 @@ test("accepts the private-key body and rejects reversed source ranges", () => {
for (const footerLocation of [true, false]) {
test(`rejects footer-only private-key evidence with ${footerLocation ? "footer" : "declaration"} location`, () => {
const { fixture, result } = retainedFixture();
const result = retainedResult();
const keyIndex = fixture.positives.findIndex(
(entry) => entry.id === "private-key",
);
@@ -784,7 +764,7 @@ for (const footerLocation of [true, false]) {
}
test("accepts public-key context alongside credential evidence", () => {
const { fixture, result } = retainedFixture();
const result = retainedResult();
result.findings[0].codeEvidence.push(
sourceEvidence(fixture, "src/signing.mjs", 2, 4),
sourceEvidence(fixture, "config/public.pem", 1, 3),
@@ -793,7 +773,7 @@ test("accepts public-key context alongside credential evidence", () => {
});
test("scope notes neither fail correct findings nor compensate for missing findings", () => {
const { fixture, result } = retainedFixture();
const result = retainedResult();
Object.assign(result.coverage, {
completeness: "partial",
explicitExclusions: [
@@ -950,3 +930,12 @@ test("named read-only profile excludes gold and credentials without a legacy san
undefined,
);
});
test("grades current worker review state", () => {
const result = retainedResult();
const { coverage, ...draft } = result;
assert.equal(
gradeResult({ ...draft, reviewState: coverage }, fixture).passed,
true,
);
});
+3 -5
View File
@@ -289,11 +289,9 @@ async function nativeFixture(
await mkdir(dirname(executable), { recursive: true });
const tools = join(dirname(dirname(executable)), "codex-path");
await mkdir(tools);
await writeFile(
join(tools, "rg"),
`#!${process.execPath}\nconsole.log("synthetic rg");\n`,
{ mode: 0o755 },
);
await writeFile(join(tools, "rg"), "#!/bin/sh\necho synthetic rg\n", {
mode: 0o755,
});
const result = {
findings: prepared.fixture.positives.map((expected) => ({
taxonomy: { category: "hardcoded-credentials", cwe: [expected.cwes[0]] },
+1 -1
View File
@@ -139,7 +139,7 @@ export function createStandardRunner({
result.turnResult.usage ?? options.observation.usage;
const semanticResult = {
findings: result.findings.findings,
coverage: result.coverage,
review: result.review,
threatModel: result.threatModel,
};
return {
+2 -2
View File
@@ -14,9 +14,9 @@
"test:calibration-generate": "node --experimental-strip-types scripts/test-generate-calibration-tests.mts",
"test:calibration-hydrate": "node --experimental-strip-types scripts/test-hydrate-calibration-repos.mts",
"test:dataset": "node --experimental-strip-types scripts/test-calibration-dataset.mts",
"test:deterministic": "node --experimental-strip-types scripts/test-app-surface-instructions.mts && node --experimental-strip-types scripts/test-triage-io.mts && node --experimental-strip-types scripts/test-intake-assertions.mts && node --experimental-strip-types scripts/test-calibration-dataset.mts && node --experimental-strip-types scripts/test-generate-calibration-tests.mts && node --experimental-strip-types scripts/test-promptfoo-runtime.mts && node --experimental-strip-types scripts/test-calibration-evidence.mts && node --experimental-strip-types scripts/test-hydrate-calibration-repos.mts && node --experimental-strip-types sastbench/scripts/test-sastbench-lib.mts && node --experimental-strip-types sastbench/scripts/test-install-sastbench.mts && node --experimental-strip-types sastbench/scripts/test-hydrate-sastbench-repos.mts && node --experimental-strip-types sastbench/scripts/test-sastbench-result.mts && node --experimental-strip-types sastbench/scripts/test-promptfoo-native-harness.mts && node --experimental-strip-types --test scripts/test-promptfoo-runner.mts scripts/test-triage-provider.mts",
"test:deterministic": "node --experimental-strip-types scripts/test-app-surface-instructions.mts && node --experimental-strip-types scripts/test-triage-io.mts && node --experimental-strip-types scripts/test-intake-assertions.mts && node --experimental-strip-types scripts/test-calibration-dataset.mts && node --experimental-strip-types scripts/test-generate-calibration-tests.mts && node --experimental-strip-types scripts/test-promptfoo-runtime.mts && node --experimental-strip-types scripts/test-calibration-evidence.mts && node --experimental-strip-types scripts/test-hydrate-calibration-repos.mts && node --experimental-strip-types sastbench/scripts/test-sastbench-lib.mts && node --experimental-strip-types sastbench/scripts/test-install-sastbench.mts && node --experimental-strip-types sastbench/scripts/test-sastbench-result.mts && node --experimental-strip-types sastbench/scripts/test-promptfoo-native-harness.mts && node --experimental-strip-types --test scripts/test-promptfoo-runner.mts scripts/test-triage-provider.mts",
"test:instructions": "node --experimental-strip-types scripts/test-app-surface-instructions.mts",
"test:sastbench": "node --experimental-strip-types sastbench/scripts/test-sastbench-lib.mts && node --experimental-strip-types sastbench/scripts/test-install-sastbench.mts && node --experimental-strip-types sastbench/scripts/test-hydrate-sastbench-repos.mts && node --experimental-strip-types sastbench/scripts/test-sastbench-result.mts && node --experimental-strip-types sastbench/scripts/test-promptfoo-native-harness.mts",
"test:sastbench": "node --experimental-strip-types sastbench/scripts/test-sastbench-lib.mts && node --experimental-strip-types sastbench/scripts/test-install-sastbench.mts && node --experimental-strip-types sastbench/scripts/test-sastbench-result.mts && node --experimental-strip-types sastbench/scripts/test-promptfoo-native-harness.mts",
"validate": "PROMPTFOO_CONFIG_DIR=.promptfoo PROMPTFOO_DISABLE_WAL_MODE=true node --experimental-strip-types scripts/run-promptfoo.mts validate config -c ./promptfooconfig.yaml",
"validate:calibration": "PROMPTFOO_CONFIG_DIR=.promptfoo PROMPTFOO_DISABLE_WAL_MODE=true node --experimental-strip-types scripts/run-promptfoo.mts validate config -c ./promptfooconfig.calibration.yaml",
"validate:sastbench": "PROMPTFOO_CONFIG_DIR=.promptfoo PROMPTFOO_DISABLE_WAL_MODE=true node --experimental-strip-types scripts/run-promptfoo.mts validate config -c ./sastbench/promptfooconfig.sastbench.yaml",
+9 -10
View File
@@ -10,7 +10,6 @@ overrides:
'@opencode-ai/sdk': 1.19.3
ibm-cloud-sdk-core@5.6.0>axios: 1.20.0
get-uri@8.0.1>basic-ftp: 6.2.1
socks@2.8.10>ip-address: 10.7.2
importers:
@@ -2055,8 +2054,8 @@ packages:
fast-string-width@3.0.2:
resolution: {integrity: sha512-gX8LrtNEI5hq8DVUfRQMbr5lpaS4nMIWV+7XEbXk2b8kiQIizgnlr12B4dA3ZEx3308ze0O4Q1R+cHts8kyUJg==}
fast-uri@3.1.8:
resolution: {integrity: sha512-GZMtZUTNRpOVIECoXwLNZS5xUGE+mVNbTB8h/7Rwh2TFWcBQiPzTgyZi05BF9UMZKkLJv8XBRJTlU7zg8+ZfMg==}
fast-uri@3.1.9:
resolution: {integrity: sha512-hS/0Wt3Ya043oKXs0sIxrMpKQITXhMLIrVAKKXi4gozGC9v7YRWVnXIZzjNPTO02M9BdxLCWqK1yRXgNziVyJQ==}
fast-wrap-ansi@0.2.2:
resolution: {integrity: sha512-7F2Fl+TjRSenLqlU3UjSH0iyqopqoZIu7eZVpEirP2g1GtWa2G/ecEmBdgz31+Mxr+ELclgg6sokpSFIQiZ02Q==}
@@ -2289,8 +2288,8 @@ packages:
inherits@2.0.4:
resolution: {integrity: sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==}
ip-address@10.7.2:
resolution: {integrity: sha512-7H/2gFSIitxc0hG3nOI1glS8QLo/EHBFFLk8vEUjXY/xu0AdL8jZ9U1IzO2PUm0d2D/ofQcAifb0g6OBkt8U7w==}
ip-address@10.7.4:
resolution: {integrity: sha512-DWBMKyeM25D70nrIiTkgQth59/G+naKOTep6huF9j+GmeK3DMD60Zvxg5d5qQnz+38AHgou6ean2LECX+lrKDg==}
engines: {node: '>= 12'}
ipaddr.js@1.9.1:
@@ -5174,7 +5173,7 @@ snapshots:
ajv@8.20.0:
dependencies:
fast-deep-equal: 3.1.3
fast-uri: 3.1.8
fast-uri: 3.1.9
json-schema-traverse: 1.0.0
require-from-string: 2.0.2
@@ -5650,7 +5649,7 @@ snapshots:
dependencies:
debug: 4.4.3
express: 5.2.1
ip-address: 10.7.2
ip-address: 10.7.4
transitivePeerDependencies:
- supports-color
optional: true
@@ -5704,7 +5703,7 @@ snapshots:
dependencies:
fast-string-truncated-width: 3.0.3
fast-uri@3.1.8: {}
fast-uri@3.1.9: {}
fast-wrap-ansi@0.2.2:
dependencies:
@@ -6044,7 +6043,7 @@ snapshots:
inherits@2.0.4: {}
ip-address@10.7.2: {}
ip-address@10.7.4: {}
ipaddr.js@1.9.1: {}
@@ -7257,7 +7256,7 @@ snapshots:
socks@2.8.10:
dependencies:
ip-address: 10.7.2
ip-address: 10.7.4
smart-buffer: 4.2.0
source-map@0.6.1:
-1
View File
@@ -12,7 +12,6 @@ overrides:
"@opencode-ai/sdk": "$@opencode-ai/sdk"
"ibm-cloud-sdk-core@5.6.0>axios": 1.20.0
"get-uri@8.0.1>basic-ftp": 6.2.1
"socks@2.8.10>ip-address": 10.7.2
allowBuilds:
"@playwright/browser-chromium": false
@@ -1,68 +0,0 @@
#!/usr/bin/env node
import assert from "node:assert/strict";
import path from "node:path";
import { buildHydrationPlan, parseArgs } from "./hydrate-sastbench-repos.mts";
const repoUrl = "https://github.com/example/project";
const firstCommit = "1".repeat(40);
const secondCommit = "2".repeat(40);
const baseRecord = {
repo_name: "example/project",
repo_url: repoUrl,
commit_hash: firstCommit,
ground_truth: "true_positive",
};
const records = [
{ ...baseRecord },
{ ...baseRecord, ground_truth: "false_positive" },
{ ...baseRecord, commit_hash: secondCommit },
];
const cacheRoot = path.resolve("/tmp/sastbench-git-cache");
const targetRoot = path.resolve("/tmp/sastbench-targets");
assert.equal(parseArgs(["--", "--dry-run"]).dryRun, true);
const jobs = buildHydrationPlan(records, { cacheRoot, targetRoot });
assert.equal(
buildHydrationPlan(records, { cacheRoot, targetRoot })[0].cacheDir,
jobs[0].cacheDir,
);
assert.equal(jobs.length, 2);
assert.equal(jobs[0].caseCount, 2);
assert.equal(jobs[1].caseCount, 1);
assert.equal(
jobs[0].cacheDir,
path.join(cacheRoot, "repo-acb9cf7430784a93.git"),
);
for (const job of jobs) {
assert.equal(
path.relative(targetRoot, job.targetDir).startsWith(".."),
false,
);
assert.equal(path.relative(cacheRoot, job.cacheDir).startsWith(".."), false);
assert.equal(job.repoUrl, repoUrl);
}
assert.throws(
() =>
buildHydrationPlan(
[
{
...baseRecord,
repo_name: "same/name",
repo_url: "https://github.com/example/one",
},
{
...baseRecord,
repo_name: "same/name",
repo_url: "https://github.com/example/two",
commit_hash: secondCommit,
},
],
{ cacheRoot, targetRoot },
),
/maps to multiple repository URLs/,
);
console.log("sastbench hydration planning tests passed");
@@ -1,7 +1,7 @@
#!/usr/bin/env node
import assert from "node:assert/strict";
import path from "node:path";
import { buildHydrationPlan } from "./hydrate-sastbench-repos.mts";
import { buildHydrationPlan, parseArgs } from "./hydrate-sastbench-repos.mts";
import {
REPRESENTATIVE_SAMPLE_SPEC,
@@ -119,15 +119,36 @@ assert.equal(
);
const stateId = repositoryStateId(positive);
assert.match(stateId, /^state-[a-f0-9]{16}$/);
assert.equal(repositoryStateId(negative), stateId);
const jobs = buildHydrationPlan([positive, negative], { targetRoot });
assert.equal(jobs.length, 1);
assert.equal(jobs[0].caseCount, 2);
assert.equal(jobs[0].repoUrl, positive.repo_url);
assert.equal(jobs[0].commitHash, positive.commit_hash);
assert.equal(jobs[0].targetDir, path.join(targetRoot, stateId));
assert.equal(parseArgs(["--", "--dry-run"]).dryRun, true);
const cacheRoot = path.resolve("/tmp/sastbench-git-cache");
const otherRevision = { ...positive, commit_hash: "2".repeat(40) };
const jobs = buildHydrationPlan([positive, negative, otherRevision], {
cacheRoot,
targetRoot,
});
assert.deepEqual(
jobs.map((job) => job.caseCount),
[2, 1],
);
for (const [index, record] of [positive, otherRevision].entries()) {
const job = jobs[index]!;
assert.equal(job.repoUrl, record.repo_url);
assert.equal(job.commitHash, record.commit_hash);
const target = repositoryStateId(record);
assert.match(target, /^state-[a-f0-9]{16}$/);
assert.equal(job.targetDir, path.join(targetRoot, target));
assert.equal(job.cacheDir, path.join(cacheRoot, "repo-acb9cf7430784a93.git"));
}
assert.throws(
() =>
buildHydrationPlan([
positive,
{ ...otherRevision, repo_url: "https://github.com/example/other" },
]),
/maps to multiple repository URLs/,
);
const promptVars = buildPromptVars(positive, 0, targetRoot);
assert.equal(promptVars.case_id, "sastbench-000000");
+17 -11
View File
@@ -74,6 +74,7 @@ function stageSkillRuntime() {
async function runPromptfoo(
promptfooArgs: string[],
environment: NodeJS.ProcessEnv = {},
builtMcp?: string,
) {
const runtimeRoot = stageSkillRuntime();
const artifacts = path.join(EVAL_ROOT, "artifacts");
@@ -131,17 +132,22 @@ async function runPromptfoo(
});
}
try {
const built = await runChild(
[
path.join(PLUGIN_ROOT, "mcp-app", "scripts", "build_mcp_app.mjs"),
"--output",
path.join(runtimeRoot, "plugins", "codex-security", "mcp"),
"--native",
"host",
],
path.join(PLUGIN_ROOT, "mcp-app"),
);
if (built !== 0) return built;
const mcp = path.join(runtimeRoot, "plugins", "codex-security", "mcp");
if (builtMcp) {
copyDirectory(builtMcp, mcp);
} else {
const built = await runChild(
[
path.join(PLUGIN_ROOT, "mcp-app", "scripts", "build_mcp_app.mjs"),
"--output",
mcp,
"--native",
"host",
],
path.join(PLUGIN_ROOT, "mcp-app"),
);
if (built !== 0) return built;
}
return await runChild(
[
"--import",
@@ -0,0 +1,4 @@
import { runPromptfoo } from "./run-promptfoo.mts";
const [builtMcp, ...args] = process.argv.slice(2);
process.exitCode = await runPromptfoo(args, {}, builtMcp);
@@ -4,59 +4,74 @@ import path from "node:path";
const pluginRoot = path.resolve(
import.meta.dirname,
"..",
"..",
"..",
"plugins",
"codex-security",
"../../../plugins/codex-security",
);
const skillRoot = path.join(pluginRoot, "skills", "triage-finding");
const skillPath = path.join(skillRoot, "SKILL.md");
const skill = fs.readFileSync(skillPath, "utf8");
const ticketIntakePath = path.join(skillRoot, "references", "ticket-intake.md");
const ticketIntake = fs.readFileSync(ticketIntakePath, "utf8");
const agentPath = path.join(skillRoot, "agents", "openai.yaml");
const agent = fs.readFileSync(agentPath, "utf8");
const pluginPath = path.join(pluginRoot, ".codex-plugin", "plugin.json");
const plugin = JSON.parse(fs.readFileSync(pluginPath, "utf8"));
function readPluginFile(relativePath: string) {
return fs.readFileSync(path.join(pluginRoot, relativePath), "utf8");
}
const skillRoot = "skills/triage-finding";
const skill = readPluginFile(`${skillRoot}/SKILL.md`);
const ticketIntake = readPluginFile(`${skillRoot}/references/ticket-intake.md`);
const agent = readPluginFile(`${skillRoot}/agents/openai.yaml`);
const plugin = JSON.parse(readPluginFile(".codex-plugin/plugin.json"));
assert.match(skill, /### Jira and Linear intake/);
assert.match(skill, /references\/ticket-intake\.md/);
assert.match(ticketIntake, /Atlassian[\s\S]*JQL/);
assert.match(
ticketIntake,
/\bsearchJiraIssuesUsingJql`?\s+for\s+collections\b|\bfor\s+collections,\s+use\s+`?searchJiraIssuesUsingJql\b/i,
);
assert.match(ticketIntake, /natural-language search[\s\S]*discover[\s\S]*JQL/);
assert.match(skill, /security or vulnerability Jira\/Linear tickets/);
assert.match(skill, /Atlassian and Linear mentions are connector hints/);
assert.match(skill, /generic ticket or duplicate triage/);
assert.match(
ticketIntake,
/Normalize Jira and Linear vulnerability tickets as `source_type: "scanner_ticket"`/,
);
assert.match(
ticketIntake,
/issue key[\s\S]*URL[\s\S]*project[\s\S]*status[\s\S]*labels[\s\S]*components[\s\S]*priority/,
);
assert.match(
ticketIntake,
/Default to read-only import and triage[\s\S]*Do not add comments, transition or close issues, assign owners, or change labels/,
);
assert.match(agent, /default_prompt:.*Use \$triage-finding/);
assert.match(ticketIntake, /exhaust[\s\S]*pag(?:es|ination)/i);
assert.match(ticketIntake, /missing connector|connector.*unavailable/i);
assert.match(ticketIntake, /authentication|reauthorize/i);
assert.match(ticketIntake, /insufficient permission|request access/i);
assert.match(ticketIntake, /not found|inaccessible/i);
assert.match(ticketIntake, /transient/i);
assert.match(ticketIntake, /exhaust[\s\S]*pag(?:es|ination)/i);
assert.match(ticketIntake, /independent vulnerability claim/i);
assert.match(ticketIntake, /ambiguous[\s\S]*ask/i);
assert.match(ticketIntake, /deterministic[\s\S]*tree order/i);
assert.equal(plugin.interface.defaultPrompt.length, 3);
const provenance =
ticketIntake
.split(/\n\s*\n/u)
.find((paragraph) => paragraph.includes("normalized_input.references")) ??
"";
for (const field of [
"issue key",
"URL",
"project",
"status",
"labels",
"components",
"priority",
]) {
assert.ok(provenance.includes(field), field);
}
const sentences = ticketIntake
.split(/[.!?]|\n\s*\n|^#{1,6}[ \t]+.*$/m)
.map((sentence) => sentence.trim().replace(/\s+/g, " "));
assert.ok(
sentences.some((sentence) =>
sentence.startsWith("Default to read-only import and triage"),
),
);
assert.ok(
sentences.some(
(sentence) =>
sentence.startsWith(
"Do not add comments, transition or close issues, assign owners, or change labels",
) &&
/\b(?:without|unless)\b.*\bexplicit(?:ly)?\b.*\brequest(?:ed|s)?\b/i.test(
sentence,
),
),
);
assert.match(agent, /default_prompt:.*Use \$triage-finding/);
assert.ok(plugin.interface.defaultPrompt.length <= 3);
assert(
plugin.interface.defaultPrompt.every(
(prompt: string) => [...prompt].length <= 128,
),
);
assert(
plugin.interface.defaultPrompt.includes(
"Triage existing security findings against this repository.",
plugin.interface.defaultPrompt.some(
(prompt: string) =>
/\btriage\b/i.test(prompt) && /\bfindings?\b/i.test(prompt),
),
);
@@ -1,8 +1,9 @@
import assert from "node:assert/strict";
import { spawn } from "node:child_process";
import { spawn, type ChildProcess } from "node:child_process";
import { once } from "node:events";
import fs from "node:fs";
import path from "node:path";
import test from "node:test";
import test, { type TestContext } from "node:test";
import { pathToFileURL } from "node:url";
import { stageSkillRuntime } from "./run-promptfoo.mts";
@@ -88,6 +89,43 @@ test("initializes native providers only in the Promptfoo child", async () => {
}
});
async function interruptRunner(
t: TestContext,
child: ChildProcess,
interrupt: () => void,
exitCode: number,
) {
t.after(() => {
if (child.exitCode === null) child.kill("SIGKILL");
});
let stderr = "";
child.stderr!.on("data", (chunk) => {
stderr += chunk;
});
const exited = once(child, "exit");
const outputEnded = once(child.stdout!, "end");
let output = "";
const ready = new Promise<{ root: string }>((resolve) => {
child.stdout!.on("data", (chunk) => {
output += chunk;
if (output.includes("\n")) resolve(JSON.parse(output.split("\n")[0]));
});
});
const { root } = await Promise.race([
ready,
exited.then(() => {
throw new Error(`runner exited early: ${stderr}`);
}),
]);
t.after(() => fs.rmSync(root, { recursive: true, force: true }));
assert.ok(fs.existsSync(root));
interrupt();
assert.deepEqual(await exited, [exitCode, null], stderr);
assert.equal(fs.existsSync(root), false);
await outputEnded;
return output;
}
test(
"Windows console Ctrl+C lets the child save progress before runtime cleanup",
{ timeout: 15000 },
@@ -137,112 +175,64 @@ test(
["--experimental-strip-types", "--eval", driver],
{ stdio: ["ignore", "pipe", "pipe", "ipc"] },
);
t.after(() => {
if (child.exitCode === null) child.kill("SIGKILL");
});
let stderr = "";
child.stderr!.on("data", (chunk) => {
stderr += chunk;
});
const exited = new Promise<number | null>((resolve, reject) => {
child.once("error", reject);
child.once("close", resolve);
});
let output = "";
const ready = new Promise<{ root: string }>((resolve) => {
child.stdout!.on("data", (chunk) => {
output += chunk;
if (output.includes("\n")) resolve(JSON.parse(output.split("\n")[0]));
});
});
const { root } = await Promise.race([
ready,
exited.then(() => {
throw new Error(`runner exited early: ${stderr}`);
}),
]);
t.after(() => fs.rmSync(root, { recursive: true, force: true }));
assert.ok(fs.existsSync(root));
child.send("console-interrupt");
assert.equal(await exited, 130, stderr);
const output = await interruptRunner(
t,
child,
() => child.send("console-interrupt"),
130,
);
assert.match(output, /saved:1:true/);
assert.doesNotMatch(output, /forced:/);
assert.equal(fs.existsSync(root), false);
},
);
for (const [signal, exitCode] of [
["SIGINT", 130],
["SIGTERM", 143],
for (const [signal, exitCode, delivery] of [
["SIGINT", 130, "pid"],
["SIGINT", 130, "group"],
["SIGTERM", 143, "pid"],
["SIGTERM", 143, "group"],
] as const) {
for (const delivery of ["pid", "group"]) {
test(
`runner forwards ${signal} once (${delivery}) and removes its runtime after the child exits`,
{ skip: process.platform === "win32", timeout: 15000 },
async (t) => {
const target = `
let received = 0;
process.on(${JSON.stringify(signal)}, () => {
received++;
if (received > 1) process.exit(99);
setTimeout(() => { console.log("graceful:" + received); process.exit(0); }, 150);
});
console.log(JSON.stringify({ root: process.env.TRIAGE_RUNTIME_ROOT }));
setInterval(() => {}, 1000);
`;
const driver = `
const cp = require('node:child_process');
const spawn = cp.spawn;
cp.spawn = (command, args, options) => spawn(process.execPath, ['--eval', args[0].endsWith("build_mcp_app.mjs") ? "" : ${JSON.stringify(target)}], options);
import(${JSON.stringify(new URL("./run-promptfoo.mts", import.meta.url).href)}).then(({ runPromptfoo }) => runPromptfoo([])).then(code => { process.exitCode = code; });
test(
`runner forwards ${signal} once (${delivery}) and removes its runtime after the child exits`,
{ skip: process.platform === "win32", timeout: 15000 },
async (t) => {
const target = `
let received = 0;
process.on(${JSON.stringify(signal)}, () => {
received++;
if (received > 1) process.exit(99);
setTimeout(() => {
console.log("graceful:" + received + ":" + require("node:fs").existsSync(process.env.TRIAGE_RUNTIME_ROOT));
process.exit(0);
}, 150);
});
console.log(JSON.stringify({ root: process.env.TRIAGE_RUNTIME_ROOT }));
setInterval(() => {}, 1000);
`;
const child = spawn(
process.execPath,
["--experimental-strip-types", "--eval", driver],
{
stdio: ["ignore", "pipe", "pipe"],
detached: true,
},
);
t.after(() => {
if (child.exitCode === null) child.kill("SIGKILL");
});
let stderr = "";
child.stderr.on("data", (chunk) => {
stderr += chunk;
});
const exited = new Promise<{
code: number | null;
signal: NodeJS.Signals | null;
}>((resolve, reject) => {
child.once("error", reject);
child.once("exit", (code, signal) => resolve({ code, signal }));
});
let text = "";
const ready = new Promise<{ root: string }>((resolve) => {
child.stdout.on("data", (chunk) => {
text += chunk;
if (text.includes("\n")) resolve(JSON.parse(text.split("\n")[0]));
});
});
const { root } = await Promise.race([
ready,
exited.then(() => {
throw new Error(`runner exited early: ${stderr}`);
}),
]);
t.after(() => fs.rmSync(root, { recursive: true, force: true }));
assert.ok(fs.existsSync(root));
if (delivery === "group") process.kill(-child.pid!, signal);
else child.kill(signal);
assert.deepEqual(
await exited,
{ code: exitCode, signal: null },
stderr,
);
assert.match(text, /graceful:1/);
assert.equal(fs.existsSync(root), false);
},
);
}
const driver = `
const cp = require('node:child_process');
const spawn = cp.spawn;
cp.spawn = (command, args, options) => spawn(process.execPath, ['--eval', args[0].endsWith("build_mcp_app.mjs") ? "" : ${JSON.stringify(target)}], options);
import(${JSON.stringify(new URL("./run-promptfoo.mts", import.meta.url).href)}).then(({ runPromptfoo }) => runPromptfoo([])).then(code => { process.exitCode = code; });
`;
const child = spawn(
process.execPath,
["--experimental-strip-types", "--eval", driver],
{
stdio: ["ignore", "pipe", "pipe"],
detached: true,
},
);
const output = await interruptRunner(
t,
child,
() => {
if (delivery === "group") process.kill(-child.pid!, signal);
else child.kill(signal);
},
exitCode,
);
assert.match(output, /graceful:1:true/);
},
);
}
@@ -3,7 +3,6 @@
import assert from "node:assert/strict";
import fs from "node:fs";
import path from "node:path";
import { pathToFileURL } from "node:url";
import { parse } from "yaml";
import runtimeVars from "./runtime-vars.mts";
@@ -162,15 +161,4 @@ assert.ok(
"Read and follow plugins/codex-security/skills/triage-finding/SKILL.md",
),
);
// Load the installed scanner so its Git imports are checked at runtime.
const promptfooDist = path.join(evalRoot, "node_modules/promptfoo/dist/src");
const scanner = fs
.readdirSync(promptfooDist)
.find((name) => name.startsWith("scanner-") && name.endsWith(".js"));
assert.ok(scanner, "Promptfoo scanner entrypoint must be installed");
const scannerModule = await import(
pathToFileURL(path.join(promptfooDist, scanner)).href
);
assert.equal(typeof scannerModule.executeScan, "function");
console.log("triage Promptfoo runtime tests passed");
@@ -1,16 +1,119 @@
import assert from "node:assert/strict";
import { spawn } from "node:child_process";
import { execFileSync, spawn } from "node:child_process";
import fs from "node:fs";
import os from "node:os";
import { createServer } from "node:net";
import path from "node:path";
import test from "node:test";
import test, { after, type TestContext } from "node:test";
import { DatabaseSync } from "node:sqlite";
import { parse } from "yaml";
import { beforeAll } from "./triage-provider.mts";
const evalRoot = path.resolve(import.meta.dirname, "..");
const runner = path.join(import.meta.dirname, "run-promptfoo.mts");
const fixtureRunner = path.join(
import.meta.dirname,
"run-provider-fixture.mts",
);
const fixtureRoot = fs.realpathSync(
fs.mkdtempSync(path.join(os.tmpdir(), "triage-provider-bundle-")),
);
after(() => fs.rmSync(fixtureRoot, { recursive: true, force: true }));
let builtMcp: string | undefined;
function replayRunnerArgs() {
if (!builtMcp) {
const output = path.join(fixtureRoot, "mcp");
const mcpApp = path.join(evalRoot, "../../plugins/codex-security/mcp-app");
execFileSync(
process.execPath,
[
path.join(mcpApp, "scripts/build_mcp_app.mjs"),
"--output",
output,
"--native",
"host",
],
{ cwd: mcpApp },
);
builtMcp = output;
}
// Every child copies the same build into its own throwaway skill runtime.
return ["--experimental-strip-types", fixtureRunner, builtMcp];
}
const probeFixturePolicy = `
const launcher = path.join(cwd, 'plugins/codex-security/scripts/launch_codex_security_mcp');
const fixture = path.join(cwd, 'evals/triage-finding/fixtures/repo');
fs.writeFileSync(path.join(fixture, 'SECURITY.md'), '# Synthetic policy\\n');
const policy = require('node:child_process').execFileSync(launcher, ['--helper', 'resolve-security-md', '--repo', fixture, '--scope', 'src/server.js', '--out', '-'], {encoding:'utf8'});
`;
async function replayInViewer(
t: TestContext,
environment: NodeJS.ProcessEnv,
request: {
evaluationId: unknown;
prompt: string;
variables: Record<string, unknown>;
},
) {
const listener = createServer();
await new Promise<void>((resolve) =>
listener.listen(0, "127.0.0.1", resolve),
);
const address = listener.address();
assert.ok(address && typeof address !== "string");
const port = address.port;
await new Promise<void>((resolve, reject) =>
listener.close((error) => (error ? reject(error) : resolve())),
);
const viewer = spawn(
process.execPath,
[...replayRunnerArgs(), "view", "--port", String(port), "--no"],
{
cwd: evalRoot,
env: { ...process.env, ...environment, NODE_USE_ENV_PROXY: "" },
stdio: ["ignore", "pipe", "pipe"],
},
);
let viewerOutput = "";
for (const stream of [viewer.stdout, viewer.stderr])
stream.on("data", (chunk) => {
viewerOutput += chunk;
});
const closed = new Promise<number | null>((resolve, reject) => {
viewer.once("error", reject);
viewer.once("close", resolve);
});
t.after(async () => {
if (viewer.exitCode === null) viewer.kill("SIGTERM");
await closed;
});
const url = `http://127.0.0.1:${port}`;
while (true) {
try {
const response = await fetch(`${url}/api/eval`);
if (response.ok) break;
} catch {
/* The actual viewer is still building its staged runtime. */
}
assert.equal(viewer.exitCode, null, viewerOutput);
await new Promise((resolve) => setTimeout(resolve, 50));
}
const replay = await fetch(`${url}/api/eval/replay`, {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ testIndex: 0, ...request }),
});
assert.equal(replay.status, 200, viewerOutput);
const replayResult = (await replay.json()) as { output: unknown };
assert.equal(replayResult.output, "ok", JSON.stringify(replayResult));
viewer.kill("SIGTERM");
await closed;
return viewerOutput;
}
function providerConfig(name: string) {
return parse(
fs.readFileSync(path.join(evalRoot, "providers", `${name}.yaml`), "utf8"),
@@ -36,18 +139,18 @@ const proxies = {
NO_PROXY: "localhost,.example.test",
};
function invoke(args: string[], environment: NodeJS.ProcessEnv) {
function invoke(
args: string[],
environment: NodeJS.ProcessEnv,
runnerArgs = replayRunnerArgs(),
) {
return new Promise<{ code: number | null; output: string }>(
(resolve, reject) => {
const child = spawn(
process.execPath,
["--experimental-strip-types", runner, ...args],
{
cwd: evalRoot,
env: { ...process.env, ...environment, NODE_USE_ENV_PROXY: "" },
stdio: ["ignore", "pipe", "pipe"],
},
);
const child = spawn(process.execPath, [...runnerArgs, ...args], {
cwd: evalRoot,
env: { ...process.env, ...environment, NODE_USE_ENV_PROXY: "" },
stdio: ["ignore", "pipe", "pipe"],
});
let output = "";
child.stdout.on("data", (chunk) => {
output += chunk;
@@ -191,7 +294,8 @@ const fs = require('node:fs');
const path = require('node:path');
const cwd = process.argv[process.argv.indexOf('--cd') + 1];
fs.readFileSync(path.join(cwd, 'plugins/codex-security/skills/triage-finding/SKILL.md'));
fs.writeFileSync(${JSON.stringify(capture)}, JSON.stringify({cwd,node:process.env.CODEX_MCP_NODE_PATH,directories:process.argv.flatMap((arg,index)=>arg==='--add-dir'?[process.argv[index+1]]:[])}));
${probeFixturePolicy}
fs.writeFileSync(${JSON.stringify(capture)}, JSON.stringify({cwd,policy,node:process.env.CODEX_MCP_NODE_PATH,directories:process.argv.flatMap((arg,index)=>arg==='--add-dir'?[process.argv[index+1]]:[])}));
console.log(JSON.stringify({type:'thread.started',thread_id:'synthetic-cli-provider'}));
console.log(JSON.stringify({type:'item.completed',item:{id:'message',type:'agent_message',text:'ok'}}));
console.log(JSON.stringify({type:'turn.completed',usage:{input_tokens:1,output_tokens:1}}));
@@ -234,10 +338,12 @@ console.log(JSON.stringify({type:'turn.completed',usage:{input_tokens:1,output_t
PROMPTFOO_DISABLE_TELEMETRY: "1",
PROMPTFOO_DISABLE_UPDATE: "1",
},
["--experimental-strip-types", runner],
);
assert.equal(result.code, 0, result.output);
const row = JSON.parse(fs.readFileSync(capture, "utf8"));
assert.notEqual(row.cwd, evalRoot);
assert.match(row.policy, /Synthetic policy/);
assert.equal(fs.existsSync(row.cwd), false);
assert.equal(row.node, process.execPath);
assert.deepEqual(row.directories, [
@@ -248,33 +354,44 @@ console.log(JSON.stringify({type:'turn.completed',usage:{input_tokens:1,output_t
},
);
// Exercise the pinned provider and Codex SDK subprocess without a model request.
// The normal setup command supplies the host helper build used by the runner.
test(
"provider preserves proxies and rebinds saved evaluations to fresh runtimes",
{ skip: process.platform === "win32", timeout: 120000 },
async (t) => {
const root = fs.realpathSync(
fs.mkdtempSync(path.join(os.tmpdir(), "triage-provider-")),
// Reuse the immutable Node binaries; captures and Promptfoo databases belong to each test.
function providerNode(...parts: string[]) {
const executable = path.join(fixtureRoot, ...parts);
if (!fs.existsSync(executable)) {
fs.mkdirSync(path.dirname(executable), { recursive: true });
fs.copyFileSync(
process.execPath,
executable,
fs.constants.COPYFILE_FICLONE,
);
t.after(() => fs.rmSync(root, { recursive: true, force: true }));
const capture = path.join(root, "captures.jsonl");
const fakeCodex = path.join(root, "codex");
const fail = path.join(root, "fail");
fs.writeFileSync(
fakeCodex,
`#!${process.execPath}
}
return executable;
}
function captureProvider(t: TestContext, mode: "launcher" | "replay") {
const root = fs.realpathSync(
fs.mkdtempSync(path.join(os.tmpdir(), "triage-provider-")),
);
t.after(() => fs.rmSync(root, { recursive: true, force: true }));
const capture = path.join(root, "captures.jsonl");
const fakeCodex = path.join(root, "codex");
const fail = path.join(root, "fail");
fs.writeFileSync(
fakeCodex,
`#!${process.execPath}
const fs = require('node:fs');
const path = require('node:path');
const cp = require('node:child_process');
const cwd = process.argv[process.argv.indexOf('--cd') + 1];
const launcher = path.join(cwd, 'plugins/codex-security/scripts/launch_codex_security_mcp');
const fixture = path.join(cwd, 'evals/triage-finding/fixtures/repo');
fs.writeFileSync(path.join(fixture, 'SECURITY.md'), '# Synthetic policy\\n');
const policy = cp.execFileSync(launcher, ['--helper', 'resolve-security-md', '--repo', fixture, '--scope', 'src/server.js', '--out', '-'], {encoding:'utf8'});
fs.readFileSync(path.join(cwd, 'plugins/codex-security/skills/triage-finding/SKILL.md'));
// Each replay has a fresh cwd. One concurrent caller claims its helper probe.
let capturedPolicy = '';
if (${mode === "launcher"} || (!fs.existsSync(${JSON.stringify(fail)}) && fs.mkdirSync(path.join(cwd, '.policy-probe'), {recursive: true}))) {
${probeFixturePolicy}
capturedPolicy = policy;
}
const directories = process.argv.flatMap((arg, index) => arg === '--add-dir' ? [process.argv[index + 1]] : []);
const overrides = process.argv.flatMap((arg, index) => arg === '--config' ? [process.argv[index + 1]] : []);
fs.appendFileSync(${JSON.stringify(capture)}, JSON.stringify({cwd,policy,directories,overrides,nodePath:process.env.CODEX_MCP_NODE_PATH,nodeTarget:fs.realpathSync.native(process.env.CODEX_MCP_NODE_PATH), proxies: Object.fromEntries(${JSON.stringify(Object.keys(proxies))}.map(key => [key,process.env[key]]))}) + '\\n');
fs.appendFileSync(${JSON.stringify(capture)}, JSON.stringify({cwd,policy:capturedPolicy,directories,overrides,nodePath:process.env.CODEX_MCP_NODE_PATH,nodeTarget:fs.realpathSync.native(process.env.CODEX_MCP_NODE_PATH), proxies: Object.fromEntries(${JSON.stringify(Object.keys(proxies))}.map(key => [key,process.env[key]]))}) + '\\n');
console.log(JSON.stringify({type:'thread.started', thread_id:'synthetic-thread'}));
if (fs.existsSync(${JSON.stringify(fail)})) {
console.log(JSON.stringify({type:'turn.failed',error:{message:'synthetic retryable failure'}}));
@@ -283,24 +400,52 @@ if (fs.existsSync(${JSON.stringify(fail)})) {
console.log(JSON.stringify({type:'turn.completed',usage:{input_tokens:1,cached_input_tokens:0,output_tokens:1}}));
}
`,
{ mode: 0o755 },
);
const ambientNode = path.join(root, "ambient-node", "bin", "node");
fs.mkdirSync(path.dirname(ambientNode), { recursive: true });
fs.copyFileSync(
process.execPath,
{ mode: 0o755 },
);
const ambientNode = providerNode("ambient-node", "bin", "node");
const customNode = providerNode("custom-node", "bin", "node");
const selectedNode = providerNode("selected-node", "bin", "synthetic-node");
const environment = {
...proxies,
CODEX_MCP_NODE_PATH: ambientNode,
OPENAI_API_KEY: "synthetic-test-key",
PROMPTFOO_CONFIG_DIR: path.join(root, "state"),
PROMPTFOO_DISABLE_WAL_MODE: "true",
PROMPTFOO_DISABLE_TELEMETRY: "1",
PROMPTFOO_DISABLE_UPDATE: "1",
};
const readRows = (): Capture[] =>
fs
.readFileSync(capture, "utf8")
.trim()
.split("\n")
.map((line) => JSON.parse(line) as Capture);
return {
root,
fakeCodex,
fail,
ambientNode,
customNode,
selectedNode,
environment,
readRows,
};
}
// Exercise the pinned provider and Codex SDK subprocess without a model request.
test(
"provider preserves proxies and selects each Node launcher",
{ skip: process.platform === "win32", timeout: 120000 },
async (t) => {
const {
root,
fakeCodex,
ambientNode,
fs.constants.COPYFILE_FICLONE,
);
const environment = {
...proxies,
CODEX_MCP_NODE_PATH: ambientNode,
OPENAI_API_KEY: "synthetic-test-key",
PROMPTFOO_CONFIG_DIR: path.join(root, "state"),
PROMPTFOO_DISABLE_WAL_MODE: "true",
PROMPTFOO_DISABLE_TELEMETRY: "1",
PROMPTFOO_DISABLE_UPDATE: "1",
};
customNode,
selectedNode,
environment,
readRows,
} = captureProvider(t, "launcher");
const configPath = path.join(root, "config.json");
const provider = providerConfig("triage");
provider.config.codex_path_override = fakeCodex;
@@ -315,26 +460,7 @@ if (fs.existsSync(${JSON.stringify(fail)})) {
const calibration = providerConfig("calibration");
calibration.id = provider.id;
calibration.config.codex_path_override = fakeCodex;
const customNode = path.join(root, "custom-node", "bin", "node");
fs.mkdirSync(path.dirname(customNode), { recursive: true });
fs.copyFileSync(
process.execPath,
customNode,
fs.constants.COPYFILE_FICLONE,
);
calibration.config.cli_env.CODEX_MCP_NODE_PATH = customNode;
const selectedNode = path.join(
root,
"selected-node",
"bin",
"synthetic-node",
);
fs.mkdirSync(path.dirname(selectedNode), { recursive: true });
fs.copyFileSync(
process.execPath,
selectedNode,
fs.constants.COPYFILE_FICLONE,
);
const nodeAlias = path.join(root, "node-alias");
const nodeDispatcher = path.join(root, "node-runtime", "dispatcher");
fs.mkdirSync(path.dirname(nodeDispatcher));
@@ -406,11 +532,7 @@ case "$0" in */node-alias) exec '${process.execPath.replaceAll("'", "'\\''")}' "
);
for (const result of simultaneous)
assert.equal(result.code, 0, result.output);
const rows = fs
.readFileSync(capture, "utf8")
.trim()
.split("\n")
.map((line) => JSON.parse(line) as Capture);
const rows = readRows();
assert.equal(rows.length, 8);
assert.equal(new Set(rows.map((row) => row.cwd)).size, 3);
for (const row of rows) {
@@ -439,9 +561,23 @@ case "$0" in */node-alias) exec '${process.execPath.replaceAll("'", "'\\''")}' "
.length,
1,
);
},
);
// Prompt-specific settings merge and render separately for each concurrent
// case, including the original configuration saved for retry and resume.
test(
"provider rebinds saved templated settings for retry and resume",
{ skip: process.platform === "win32", timeout: 120000 },
async (t) => {
const {
root,
fakeCodex,
fail,
customNode,
selectedNode,
environment,
readRows,
} = captureProvider(t, "replay");
const provider = providerConfig("triage");
const templatedConfig = path.join(root, "templated.json");
fs.writeFileSync(
templatedConfig,
@@ -451,6 +587,7 @@ case "$0" in */node-alias) exec '${process.execPath.replaceAll("'", "'\\''")}' "
...provider,
config: {
...provider.config,
codex_path_override: fakeCodex,
cli_env: {
...provider.config.cli_env,
CODEX_MCP_NODE_PATH: "{{node_path}}",
@@ -487,11 +624,6 @@ case "$0" in */node-alias) exec '${process.execPath.replaceAll("'", "'\\''")}' "
})),
}),
);
const templatedEnvironment = {
...environment,
PROMPTFOO_CONFIG_DIR: path.join(root, "templated-state"),
};
const startingRows = rows.length;
fs.writeFileSync(fail, "");
const templatedInitial = await invoke(
[
@@ -504,7 +636,7 @@ case "$0" in */node-alias) exec '${process.execPath.replaceAll("'", "'\\''")}' "
"--no-share",
"--no-progress-bar",
],
templatedEnvironment,
environment,
);
assert.notEqual(templatedInitial.code, 0, templatedInitial.output);
assert.match(templatedInitial.output, /synthetic retryable failure/);
@@ -517,28 +649,28 @@ case "$0" in */node-alias) exec '${process.execPath.replaceAll("'", "'\\''")}' "
"--no-share",
"--no-progress-bar",
],
templatedEnvironment,
environment,
);
assert.equal(templatedRetry.code, 0, templatedRetry.output);
const templatedDatabase = new DatabaseSync(
path.join(templatedEnvironment.PROMPTFOO_CONFIG_DIR, "promptfoo.db"),
path.join(environment.PROMPTFOO_CONFIG_DIR, "promptfoo.db"),
{ enableForeignKeyConstraints: false },
);
templatedDatabase.prepare("DELETE FROM eval_results").run();
templatedDatabase.close();
const templatedResume = await invoke(
["eval", "--resume", "--no-cache", "--no-share", "--no-progress-bar"],
templatedEnvironment,
environment,
);
assert.equal(templatedResume.code, 0, templatedResume.output);
const templatedRows = fs
.readFileSync(capture, "utf8")
.trim()
.split("\n")
.map((line) => JSON.parse(line) as Capture)
.slice(startingRows);
const templatedRows = readRows();
assert.equal(templatedRows.length, 12);
assert.equal(new Set(templatedRows.map((row) => row.cwd)).size, 3);
const replayProbes = templatedRows.filter((row) => row.policy);
assert.equal(replayProbes.length, 2);
assert.equal(new Set(replayProbes.map((row) => row.cwd)).size, 2);
for (const row of replayProbes)
assert.match(row.policy, /Synthetic policy/);
assert.equal(
templatedRows.filter((row) => row.nodePath === customNode).length,
6,
@@ -1124,70 +1256,13 @@ if (fs.existsSync(${JSON.stringify(failure)})) {
const replayVariables =
JSON.parse((resumedResult.metadata as string) || "{}").inputVars ||
JSON.parse(resumedResult.test_case).vars;
const listener = createServer();
await new Promise<void>((resolve) =>
listener.listen(0, "127.0.0.1", resolve),
);
const address = listener.address();
assert.ok(address && typeof address !== "string");
const port = address.port;
await new Promise<void>((resolve, reject) =>
listener.close((error) => (error ? reject(error) : resolve())),
);
const viewer = spawn(
process.execPath,
[
"--experimental-strip-types",
runner,
"view",
"--port",
String(port),
"--no",
],
{
cwd: evalRoot,
env: { ...process.env, ...environment, NODE_USE_ENV_PROXY: "" },
stdio: ["ignore", "pipe", "pipe"],
},
);
let viewerOutput = "";
for (const stream of [viewer.stdout, viewer.stderr])
stream.on("data", (chunk) => {
viewerOutput += chunk;
});
const closed = new Promise<number | null>((resolve, reject) => {
viewer.once("error", reject);
viewer.once("close", resolve);
await replayInViewer(t, environment, {
evaluationId: stored.id,
prompt:
"Read and follow skills/triage-finding/SKILL.md.\nTARGET=" +
replayVariables.target_repo,
variables: replayVariables,
});
t.after(async () => {
if (viewer.exitCode === null) viewer.kill("SIGTERM");
await closed;
});
const url = `http://127.0.0.1:${port}`;
while (true) {
try {
if ((await fetch(`${url}/api/eval`)).ok) break;
} catch {}
assert.equal(viewer.exitCode, null, viewerOutput);
await new Promise((resolve) => setTimeout(resolve, 50));
}
const replay = await fetch(`${url}/api/eval/replay`, {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({
evaluationId: stored.id,
testIndex: 0,
prompt:
"Read and follow skills/triage-finding/SKILL.md.\nTARGET=" +
replayVariables.target_repo,
variables: replayVariables,
}),
});
assert.equal(replay.status, 200, viewerOutput);
const replayResult = (await replay.json()) as { output: unknown };
assert.equal(replayResult.output, "ok", JSON.stringify(replayResult));
viewer.kill("SIGTERM");
await closed;
const rows = fs
.readFileSync(capture, "utf8")
.trim()
@@ -1452,71 +1527,11 @@ if (fs.existsSync(${JSON.stringify(failure)})) {
.inputVars || JSON.parse(resumedResult.test_case).vars;
assert.equal(typeof replayVariables.target_repo, "string");
const listener = createServer();
await new Promise<void>((resolve) =>
listener.listen(0, "127.0.0.1", resolve),
);
const address = listener.address();
assert.ok(address && typeof address !== "string");
const port = address.port;
await new Promise<void>((resolve, reject) =>
listener.close((error) => (error ? reject(error) : resolve())),
);
const viewer = spawn(
process.execPath,
[
"--experimental-strip-types",
runner,
"view",
"--port",
String(port),
"--no",
],
{
cwd: evalRoot,
env: { ...process.env, ...environment, NODE_USE_ENV_PROXY: "" },
stdio: ["ignore", "pipe", "pipe"],
},
);
let viewerOutput = "";
for (const stream of [viewer.stdout, viewer.stderr])
stream.on("data", (chunk) => {
viewerOutput += chunk;
});
const closed = new Promise<number | null>((resolve, reject) => {
viewer.once("error", reject);
viewer.once("close", resolve);
const viewerOutput = await replayInViewer(t, environment, {
evaluationId: stored.id,
prompt: "hello",
variables: replayVariables,
});
t.after(async () => {
if (viewer.exitCode === null) viewer.kill("SIGTERM");
await closed;
});
const url = `http://127.0.0.1:${port}`;
while (true) {
try {
const response = await fetch(`${url}/api/eval`);
if (response.ok) break;
} catch {
/* The actual viewer is still building its staged runtime. */
}
assert.equal(viewer.exitCode, null, viewerOutput);
await new Promise((resolve) => setTimeout(resolve, 50));
}
const replay = await fetch(`${url}/api/eval/replay`, {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({
evaluationId: stored.id,
testIndex: 0,
prompt: "hello",
variables: replayVariables,
}),
});
assert.equal(replay.status, 200, viewerOutput);
const replayResult = (await replay.json()) as { output: unknown };
assert.equal(replayResult.output, "ok", JSON.stringify(replayResult));
viewer.kill("SIGTERM");
await closed;
assert.doesNotMatch(viewerOutput, /afterEach extension hook failed/);
const rows = fs
.readFileSync(capture, "utf8")
+8 -7
View File
@@ -81,21 +81,22 @@ test("stages every production skill unchanged without the labels or harness", as
assert.equal(entry.sha256, sha256(source));
}
for (const scenario of cases) {
if (scenario.skill) assert.ok(skill(scenario.skill));
if (scenario.skill !== null) assert.ok(skill(scenario.skill), scenario.id);
assert.ok(!routingPrompt(scenario).includes(scenario.id));
assert.ok(!routingPrompt(scenario).includes("$"));
}
});
for (const scenario of cases) {
test(`accepts the expected observed route: ${scenario.id}`, () => {
const reads = scenario.skill ? [read(skill(scenario.skill))] : [];
test("accepts an observed skill read and a completed turn without a skill", () => {
for (const entry of prepared.skills) {
assert.equal(
grade(scenario.skill, [...reads, message, completed]).passed,
grade(entry.name, [read(entry), message, completed]).passed,
true,
entry.name,
);
});
}
}
assert.equal(grade(null, [message, completed]).passed, true);
});
test("a claimed choice or filename listing cannot satisfy a skill read", () => {
const expected = skill("security-scan");
+1 -1
View File
@@ -70,7 +70,7 @@ complete repository inventory; use full scans to track the baseline over time.
## Results and failures
The `codex-security` pipeline artifact contains `result.json`, available
`report.md`, `coverage.json`, and `findings.json`, plus `results.sarif` after a
`report.md`, `scan-manifest.json`, and `findings.json`, plus `results.sarif` after a
successful export. Check the JSON/report for findings, scope, runtime, and
usage. Scope exclusions and deferred investigations do not fail the scan or
bypass the findings policy; exit `2` indicates an execution error.
+1 -1
View File
@@ -147,7 +147,7 @@ jobs:
targetType: inline
script: |
set -euo pipefail
for report in report.md coverage.json findings.json; do
for report in report.md scan-manifest.json findings.json; do
if [[ -f "$SCAN_DIRECTORY/$report" ]]; then
cp "$SCAN_DIRECTORY/$report" "$REPORT_DIRECTORY/$report"
fi
+2 -2
View File
@@ -32,7 +32,7 @@ jobs:
security-events: write
actions: read
env:
CODEX_SECURITY_VERSION: "0.6.0"
CODEX_SECURITY_VERSION: "0.8.0"
BEDROCK_MODEL_ID: ${{ vars.BEDROCK_MODEL_ID }}
# Report-only by default. Set to "high" to fail on high/critical findings.
FAIL_ON_SEVERITY: ""
@@ -139,5 +139,5 @@ jobs:
${{ runner.temp }}/codex-security-result.json
${{ runner.temp }}/codex-security.sarif
${{ runner.temp }}/codex-security-scan/report.md
${{ runner.temp }}/codex-security-scan/coverage.json
${{ runner.temp }}/codex-security-scan/scan-manifest.json
${{ runner.temp }}/codex-security-scan/findings.json
+5 -5
View File
@@ -1,8 +1,7 @@
# Codex Security GitHub Action
Run Codex Security scans in GitHub Actions. Scan a repository or pull request,
check findings against a severity threshold, and export JSON, coverage, and
SARIF reports.
check findings against a severity threshold, and export JSON and SARIF reports.
## Quick start
@@ -360,7 +359,7 @@ are report-only; scanner and required reporting failures still fail the job.
A completed scan means the configured analysis produced a valid result. Scope
exclusions, deferred investigations, and other coverage notes remain in the
coverage report; they do not create a separate scan outcome or bypass the
review notes, they do not create a separate scan outcome or bypass the
findings policy. Completion does not certify that every vulnerability was found.
The Action follows the CLI outcome consistently:
@@ -459,7 +458,7 @@ and artifact uploads retain their existing controls.
- **Missing SARIF uploads:** inspect `scan-status`, `report-status`, and
`sarif-upload-ready`.
- **Failed scans:** inspect the CLI diagnostics for execution errors. Scope
exclusions and deferred investigations in the coverage report do not cause
exclusions and deferred investigations in the review notes do not cause
execution failures or bypass the severity policy.
CLI diagnostics stream by default. Set `verbose: 'false'` for lifecycle and
@@ -547,7 +546,8 @@ All outputs are strings. An empty cost or count means unavailable, not zero.
| --------------------- | -------------------------------------------------------------------------------------------------------------------------------------- |
| `sarif-path` | Absolute validated SARIF file path, or empty when unavailable or withheld. |
| `json-path` | Absolute canonical findings JSON path, or empty when unavailable or withheld. |
| `coverage-path` | Absolute coverage JSON path, or empty when unavailable or withheld. |
| `manifest-path` | Absolute scan manifest path, including scan status and scope, or empty when unavailable or withheld. |
| `coverage-path` | Legacy coverage JSON path. Empty for current CLI results. |
| `results-directory` | Runner-local reports directory; do not upload it recursively. |
| `scan-status` | completed, failed, or skipped. Completed means analysis produced a valid result. Skipped is reserved for empty diffs or dry-run. |
| `skip-reason` | empty-diff or dry-run when no scan ran; otherwise empty. |
+5 -3
View File
@@ -56379,7 +56379,7 @@ async function analyzeResults(options) {
result.errors.push(value.message);
return result;
}
if (!value?.manifest?.scan?.target || !Array.isArray(value?.findings?.findings) || !value?.coverage)
if (!value?.manifest?.scan?.target || !Array.isArray(value?.findings?.findings) || !(value?.review ?? value?.coverage))
throw new Error();
} catch {
result.errors.push("CLI did not return a usable JSON scan result. See the CLI diagnostics.");
@@ -56423,7 +56423,7 @@ async function analyzeResults(options) {
resultsDirectory: options.resultsDirectory,
manifestPath: (0, import_node_path5.join)(options.resultsDirectory, "scan-manifest.json"),
jsonPath: (0, import_node_path5.join)(options.resultsDirectory, "findings.json"),
coveragePath: (0, import_node_path5.join)(options.resultsDirectory, "coverage.json"),
coveragePath: value.coverage ? (0, import_node_path5.join)(options.resultsDirectory, "coverage.json") : "",
sarifPath: ""
};
const warnings = value.warnings ?? [];
@@ -99440,7 +99440,7 @@ function resultSummary(result, inputs, target) {
<pre>${esc(finding.summary, 1200)}</pre>`);
}
if (result.findings.length > 30) parts.push(`${result.findings.length - 30} additional findings are available in the JSON/SARIF reports.`);
parts.push("Use the action outputs for full JSON, coverage, and SARIF. Upload SARIF only when sarif-upload-ready is true. Reports can contain source code and vulnerability details.");
parts.push("Use the action outputs for full JSON and SARIF. Upload SARIF only when sarif-upload-ready is true. Reports can contain source code and vulnerability details.");
return Buffer.from(parts.join("\n\n")).subarray(0, 58e3).toString("utf8").replace(/\uFFFD$/, "");
}
function emitAnnotations(result) {
@@ -99461,6 +99461,7 @@ function emitAnnotations(result) {
var OUTPUT_NAMES = [
"sarif-path",
"json-path",
"manifest-path",
"coverage-path",
"results-directory",
"scan-status",
@@ -99497,6 +99498,7 @@ function outputs(result, target, exitCode) {
"sarif-path": result.paths.sarifPath,
"json-path": result.paths.jsonPath,
"coverage-path": result.paths.coveragePath,
"manifest-path": result.paths.manifestPath,
"results-directory": result.paths.resultsDirectory,
"scan-status": result.scanStatus,
"policy-status": result.policyStatus,
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "codex-security-action",
"version": "0.6.0",
"version": "0.8.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "codex-security-action",
"version": "0.6.0",
"version": "0.8.0",
"dependencies": {
"@actions/artifact": "6.3.1",
"@actions/core": "3.0.1",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "codex-security-action",
"version": "0.6.0",
"version": "0.8.0",
"private": true,
"type": "module",
"description": "Run Codex Security in GitHub Actions with explicit scope, budgets, and scan health reporting",
+3 -3
View File
@@ -1201,9 +1201,9 @@
}
},
"node_modules/fast-uri": {
"version": "3.1.8",
"resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.8.tgz",
"integrity": "sha512-GZMtZUTNRpOVIECoXwLNZS5xUGE+mVNbTB8h/7Rwh2TFWcBQiPzTgyZi05BF9UMZKkLJv8XBRJTlU7zg8+ZfMg==",
"version": "3.1.9",
"resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.9.tgz",
"integrity": "sha512-hS/0Wt3Ya043oKXs0sIxrMpKQITXhMLIrVAKKXi4gozGC9v7YRWVnXIZzjNPTO02M9BdxLCWqK1yRXgNziVyJQ==",
"funding": [
{
"type": "github",
+37 -31
View File
@@ -1,6 +1,7 @@
// Exercise the locked CLI or an installed release candidate with synthetic local requests only.
import assert from 'node:assert/strict';
import { execFile, execFileSync, spawnSync } from 'node:child_process';
import { existsSync } from 'node:fs';
import { copyFile, mkdir, mkdtemp, readFile, realpath, rm, writeFile } from 'node:fs/promises';
import { createServer, type IncomingHttpHeaders } from 'node:http';
import { tmpdir } from 'node:os';
@@ -57,16 +58,23 @@ try {
const cliResult = JSON.parse(stdout);
assert.equal(cliResult.turn.mock, true, 'The integration scan must remain synthetic');
assert.ok(cliResult.findings.findings.length > 0);
// Verify native SARIF, then exercise the CLI's manual export without model calls.
assert.equal(cliResult.sarifPath, join(resultsDirectory, 'exports/results.sarif'));
run(['export', resultsDirectory, '--export-format', 'sarif', '--source-root', repository,
'--output', cliResult.sarifPath], 0);
// Analyze one native scan export untouched; exercise manual export on the other run.
if (threshold) {
await rm(cliResult.sarifPath);
run(['export', resultsDirectory, '--export-format', 'sarif', '--source-root', repository,
'--output', cliResult.sarifPath], 0);
}
const result = await analyzeResults({ stdout, resultsDirectory, exitCode, publishable: true, scannedSha:git('rev-parse', 'HEAD').trim() });
assert.equal(result.scanStatus, 'completed');
assert.equal(result.policyStatus, threshold ? 'failed' : 'passed');
assert.equal(result.reportStatus, 'ready');
assert.equal(result.sarifUploadReady, true);
const sarif = JSON.parse(await readFile(result.paths.sarifPath, 'utf8'));
const expectedIds = cliResult.findings.findings.map((finding: any) => [finding.occurrenceId, finding.ruleId]);
assert.ok(expectedIds.flat().every((id: unknown) => typeof id === 'string' && id.length > 0));
assert.deepEqual(sarif.runs.flatMap((run: any) => run.results.map((finding: any) =>
[finding.properties?.occurrenceId, finding.ruleId])).sort(), expectedIds.sort());
assert.ok(sarif.runs.every((run: any) => run.automationDetails === undefined),
'upload-sarif must be able to apply the workflow category to the real CLI export');
assert.equal(result.findings.length, cliResult.findings.findings.length);
@@ -82,7 +90,9 @@ try {
}
// Deep Scan cannot use --mock; validate the Action's actual arguments without model calls.
const deepInputs: Record<string, string> = {mode: 'deep', 'max-time-hours': '0.25', paths: 'example.ts', 'dry-run': 'true'};
// Exercise all explicit cyber programs in existing CLI preflights; the Action input
// tests cover forwarding every spelling in both modes.
const deepInputs: Record<string, string> = {mode: 'deep', 'cyber-access-program': 'daybreak_blue', 'max-time-hours': '0.25', paths: 'example.ts', 'dry-run': 'true'};
const deepArguments = scanArguments(parseInputs(name => deepInputs[name] ?? '', repository),
{repository}, join(root, 'deep-results'));
const deepPreflight = JSON.parse(run(deepArguments, 0));
@@ -91,32 +101,25 @@ try {
assert.equal(deepPreflight.maxTimeHours, 0.25);
assert.deepEqual(deepPreflight.target.paths, ['example.ts']);
// Validate explicit program selection against the locked CLI, without model calls.
for (const mode of ['standard', 'deep']) for (const program of ['standard', 'daybreak_blue', 'daybreak_red']) {
const values: Record<string, string> = {mode, 'cyber-access-program':program, 'dry-run':'true'};
const args = scanArguments(parseInputs(name => values[name] ?? '', repository),
{repository}, join(root, `cyber-${mode}-${program}`));
const preflight = JSON.parse(run(args, 0));
assert.equal(preflight.dryRun, true);
assert.equal(preflight.mode, mode);
}
// Pass provider/model through the locked CLI without copying its provider setup or validation.
for (const provider of ['amazon-bedrock', 'openrouter', 'fireworks']) for (const mode of ['standard', 'deep']) {
// Exercise each installed provider while covering both scan modes.
for (const [provider, mode] of [['amazon-bedrock', 'deep'], ['openrouter', 'standard'], ['fireworks', 'deep']]) {
const values: Record<string, string> = {provider, model:'synthetic/model', mode, 'dry-run':'true'};
const args = scanArguments(parseInputs(name => values[name] ?? '', repository),
{repository}, join(root, `${provider}-${mode}`));
const preflight = JSON.parse(run(args, 0));
assert.equal(preflight.dryRun, true); assert.equal(preflight.mode, mode);
assert.equal(preflight.model, 'synthetic/model');
assert.equal(preflight.modelProvider, provider);
if (provider === 'amazon-bedrock') assert.equal(preflight.authentication.method, 'aws_credentials');
values.model = '';
const missingModelArgs = scanArguments(parseInputs(name => values[name] ?? '', repository), {repository}, join(root, 'missing-model'));
const missing = spawnSync(process.execPath, [cli, ...missingModelArgs], {cwd:repository, env, encoding:'utf8', timeout:120_000});
if (missing.error) throw missing.error;
assert.equal(missing.status, 2);
assert.match(missing.stderr + missing.stdout, /--model is required when using --provider/);
}
// The CLI shares missing-model validation across external providers and scan modes.
const missingValues: Record<string, string> = {provider:'openrouter', 'dry-run':'true'};
const missingArgs = scanArguments(parseInputs(name => missingValues[name] ?? '', repository),
{repository}, join(root, 'missing-model'));
const missing = spawnSync(process.execPath, [cli, ...missingArgs], {cwd:repository, env, encoding:'utf8', timeout:120_000});
if (missing.error) throw missing.error;
assert.equal(missing.status, 2);
assert.match(missing.stderr + missing.stdout, /--model is required when using --provider openrouter/);
// Exercise Action arguments through the installed CLI and native request serializer.
// A terminal fixture error stops each scan before any model output or tool execution.
@@ -184,7 +187,7 @@ try {
await writeFile(join(repository, '--help/example.ts'), 'export const example = 1;\n');
git('add', '--', '--help/example.ts');
git('commit', '-m', 'Synthetic option-shaped path');
const pathInputs: Record<string, string> = {paths: './--help', 'dry-run': 'true'};
const pathInputs: Record<string, string> = {paths: './--help', 'cyber-access-program':'daybreak_red', 'dry-run': 'true'};
const pathArguments = scanArguments(parseInputs(name => pathInputs[name] ?? '', repository),
{repository}, join(root, 'path-results'));
const pathPreflight = JSON.parse(run(pathArguments, 0));
@@ -200,7 +203,7 @@ try {
}
git('add', '.'); git('commit', '-m', 'Synthetic literal path scopes');
const scopes = ['src/[slug]', ...literalFiles.slice(1)];
const literalInputs: Record<string, string> = {paths: scopes.join('\n'), 'dry-run': 'true'};
const literalInputs: Record<string, string> = {paths: scopes.join('\n'), 'cyber-access-program':'standard', 'dry-run': 'true'};
const python = await resolveTool('python3');
const literalArguments = scanArguments(parseInputs(name => literalInputs[name] ?? '', repository),
{repository}, join(root, 'literal-results'));
@@ -210,9 +213,14 @@ try {
const scopesFile = join(root, 'literal-scopes.json');
const sourceInput = join(root, 'literal-source.jsonl');
await writeFile(scopesFile, JSON.stringify(scopes));
execFileSync(python, [join(cliPackage, '_bundled_plugin/scripts/generate_rank_input.py'),
'make-repo-scope-input', '--repo', repository, '--scopes-file', scopesFile, '--out', sourceInput],
{cwd: repository, env, stdio: ['ignore', 'pipe', 'pipe']});
const legacyGenerator = join(cliPackage, '_bundled_plugin/scripts/generate_rank_input.py');
const usesPythonGenerator = existsSync(legacyGenerator);
const generateScopeInput = (output: string, pythonCommand: string, environment: NodeJS.ProcessEnv) =>
execFileSync(usesPythonGenerator ? pythonCommand : process.execPath,
[usesPythonGenerator ? legacyGenerator : join(cliPackage, '_bundled_plugin/mcp/helpers.mjs'),
'make-repo-scope-input', '--repo', repository, '--scopes-file', scopesFile, '--out', output],
{cwd: repository, env: environment, stdio: ['ignore', 'pipe', 'pipe']});
generateScopeInput(sourceInput, python, env);
const selectedFiles = (await readFile(sourceInput, 'utf8')).trim().split('\n').map(row => JSON.parse(row).path).sort();
assert.deepEqual(selectedFiles, [...literalFiles].sort(), 'Real scope selection must preserve literal names and exclude glob-matching decoys');
@@ -297,12 +305,10 @@ try {
assert.equal(await readFile(outsideFile, 'utf8'), 'unchanged');
assert.equal(await readFile(workspaceFile, 'utf8'), 'scan output');
}
// The actual pinned helper must still work when an MCP-style child drops the loader variable.
// The bundled helper must still work when an MCP-style child drops the loader variable.
const strippedEnv = {...venvEnv, LD_LIBRARY_PATH:undefined};
const loaderSourceInput = join(root, 'loader-source.jsonl');
execFileSync(selected.python, [join(cliPackage, '_bundled_plugin/scripts/generate_rank_input.py'),
'make-repo-scope-input', '--repo', repository, '--scopes-file', scopesFile, '--out', loaderSourceInput],
{cwd:repository, env:strippedEnv, stdio:['ignore','pipe','pipe']});
generateScopeInput(loaderSourceInput, selected.python, strippedEnv);
assert.equal(await readFile(loaderSourceInput, 'utf8'), await readFile(sourceInput, 'utf8'));
const venvArguments = scanArguments(parseInputs(name => deepInputs[name] ?? '', repository),
{repository}, join(root, 'venv-results'));
+2 -2
View File
@@ -9,7 +9,7 @@ import { collectReports, uploadReports } from './artifacts.js';
import { resultSummary, emitAnnotations, plain, resultTitle } from './reporting.js';
export const OUTPUT_NAMES = [
'sarif-path', 'json-path', 'coverage-path', 'results-directory', 'scan-status', 'skip-reason',
'sarif-path', 'json-path', 'manifest-path', 'coverage-path', 'results-directory', 'scan-status', 'skip-reason',
'policy-status', 'report-status', 'exit-code', 'scanned-sha', 'analysis-ref', 'sarif-upload-ready',
'critical-count', 'high-count', 'medium-count', 'low-count', 'informational-count', 'estimated-cost',
] as const;
@@ -30,7 +30,7 @@ async function context(): Promise<EventContext> {
}
function outputs(result: ScanResults, target: Target, exitCode: number): void {
const values: Record<string, string | number | boolean> = {
'sarif-path': result.paths.sarifPath, 'json-path': result.paths.jsonPath, 'coverage-path': result.paths.coveragePath,
'sarif-path': result.paths.sarifPath, 'json-path': result.paths.jsonPath, 'coverage-path': result.paths.coveragePath, 'manifest-path': result.paths.manifestPath,
'results-directory': result.paths.resultsDirectory, 'scan-status': result.scanStatus, 'policy-status': result.policyStatus,
'report-status': result.reportStatus, 'exit-code': exitCode, 'scanned-sha': target.scannedSha,
'analysis-ref': target.analysisRef, 'sarif-upload-ready': result.sarifUploadReady,
+1 -1
View File
@@ -46,7 +46,7 @@ export function resultSummary(result: ScanResults, inputs: Inputs, target: Targe
parts.push(`<h3>${finding.severity.toUpperCase()}: ${esc(finding.title, 200)}</h3>\n\n<code>${esc(finding.path ?? 'No source location')}:${finding.startLine ?? '?'}</code>\n\n<pre>${esc(finding.summary, 1200)}</pre>`);
}
if (result.findings.length > 30) parts.push(`${result.findings.length - 30} additional findings are available in the JSON/SARIF reports.`);
parts.push('Use the action outputs for full JSON, coverage, and SARIF. Upload SARIF only when sarif-upload-ready is true. Reports can contain source code and vulnerability details.');
parts.push('Use the action outputs for full JSON and SARIF. Upload SARIF only when sarif-upload-ready is true. Reports can contain source code and vulnerability details.');
// GitHub check output is byte bounded. Truncate at UTF-8 boundaries.
return Buffer.from(parts.join('\n\n')).subarray(0, 58_000).toString('utf8').replace(/\uFFFD$/, '');
}
+2 -2
View File
@@ -114,7 +114,7 @@ export async function analyzeResults(options: ResultOptions): Promise<ScanResult
result.errors.push(value.message);
return result;
}
if (!value?.manifest?.scan?.target || !Array.isArray(value?.findings?.findings) || !value?.coverage)
if (!value?.manifest?.scan?.target || !Array.isArray(value?.findings?.findings) || !(value?.review ?? value?.coverage))
throw new Error();
} catch {
result.errors.push('CLI did not return a usable JSON scan result. See the CLI diagnostics.');
@@ -150,7 +150,7 @@ export async function analyzeResults(options: ResultOptions): Promise<ScanResult
result.estimatedCost = value.cost?.estimatedUsd;
result.estimatedCostRange = value.cost?.estimatedUsdRange;
result.paths = {resultsDirectory: options.resultsDirectory, manifestPath: join(options.resultsDirectory, 'scan-manifest.json'),
jsonPath: join(options.resultsDirectory, 'findings.json'), coveragePath: join(options.resultsDirectory, 'coverage.json'), sarifPath: ''};
jsonPath: join(options.resultsDirectory, 'findings.json'), coveragePath: value.coverage ? join(options.resultsDirectory, 'coverage.json') : '', sarifPath: ''};
const warnings: string[] = value.warnings ?? [];
// Execution and severity-policy outcomes come from the CLI, not coverage notes.
// Target-change warnings still prevent publication of a changed checkout.

Some files were not shown because too many files have changed in this diff Show More