Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,7 @@ jobs:
test -f scripts/generate-registry.parity.test.ts
test -f src/lib/packName.test.ts
test -f src/lib/urlState.test.ts
test -f scripts/osv-gate.test.ts
bun run test:unit

- name: Store conformance and publish integration (real Postgres)
Expand Down
116 changes: 116 additions & 0 deletions .github/workflows/osv-scanner.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
name: osv-scanner

# Dependency vulnerability scan of bun.lock, reported to code scanning.
#
# GitHub's dependency graph does not resolve bun.lock (its SBOM lists 36 of
# the 206 packages the lock pins), so Dependabot alerts cannot see most of
# this repo's dependencies. osv-scanner reads bun.lock natively and its SARIF
# turns every finding into a code-scanning alert, which is the coverage the
# dependency graph would have given. `bun audit` in ci.yml stays as the
# pull-request check against the npm advisory feed; this adds the OSV
# database, the scheduled re-check, and the alerts.
#
# scripts/osv-gate.ts fails the job on a HIGH/CRITICAL finding (CVSS >= 7.0,
# or an unscored advisory labelled HIGH/CRITICAL) that osv-scanner.toml does
# not accept. Every waiver there has an expiry date; on the day after it, the
# finding blocks again.

on:
push:
branches: [main]
pull_request:
branches: [main]
schedule:
# Weekly, for advisories published against a lock that has not changed.
- cron: "17 5 * * 1"
workflow_dispatch:

permissions:
contents: read

concurrency:
group: osv-scanner-${{ github.event.pull_request.number || github.ref }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}

env:
# Pinned so a scanner release cannot change the verdict without a reviewed
# commit; the vulnerability data is still fetched fresh on every run.
OSV_SCANNER_VERSION: "v2.7.0"
OSV_SCANNER_SHA256: "160c6253e2922e9e0a6a9771c5c4c40a4b3c6090b34a3cdd5e80c96cc2e4218b"

jobs:
scan:
name: Scan bun.lock
runs-on: blacksmith-2vcpu-ubuntu-2404
timeout-minutes: 15
permissions:
contents: read
packages: read # bun install reads the org-internal @gascity/* packages
security-events: write
steps:
- name: Checkout
uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6
with:
persist-credentials: false

- name: Install osv-scanner
run: |
set -euo pipefail
bin_dir="${RUNNER_TEMP}/osv-scanner-bin"
mkdir -p "$bin_dir"
curl -fsSL --retry 3 -o "$bin_dir/osv-scanner" \
"https://github.com/google/osv-scanner/releases/download/${OSV_SCANNER_VERSION}/osv-scanner_linux_amd64"
echo "${OSV_SCANNER_SHA256} $bin_dir/osv-scanner" | sha256sum -c -
chmod +x "$bin_dir/osv-scanner"
echo "$bin_dir" >> "$GITHUB_PATH"

- name: Scan lockfiles
run: |
set -euo pipefail
mkdir -p osv-results
# Exit 1 means "found vulnerabilities", which the gate judges; any
# other nonzero status means the scan did not complete. The JSON run
# lists every package (--all-packages), so the check below can see
# that bun.lock was read even when it has no findings.
for format in json sarif; do
status=0
extra=()
if [ "$format" = json ]; then extra=(--all-packages); fi
osv-scanner scan source -r . --config osv-scanner.toml "${extra[@]}" \
--format "$format" --output-file "osv-results/osv-scanner.$format" || status=$?
if [ "$status" -ne 0 ] && [ "$status" -ne 1 ]; then
echo "::error::osv-scanner --format $format exited $status: the scan did not complete"
exit "$status"
fi
done
# The point of this workflow: fail loudly if bun.lock stops being read.
jq -e '[.results[].source.path | select(endswith("/bun.lock"))] | length > 0' \
osv-results/osv-scanner.json > /dev/null \
|| { echo "::error::osv-scanner did not scan bun.lock"; exit 1; }

- name: Upload SARIF results
# Forks do not get security-events: write, so skip rather than fail there.
if: ${{ always() && hashFiles('osv-results/osv-scanner.sarif') != '' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) }}
uses: github/codeql-action/upload-sarif@8aad20d150bbac5944a9f9d289da16a4b0d87c1e # v4
with:
sarif_file: osv-results/osv-scanner.sarif
category: osv-scanner

- uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2
with:
bun-version: "1.4.4"

- name: Install dependencies
# The gate needs only smol-toml, so no dependency's install script runs
# here: this job's token (NODE_AUTH_TOKEN below) can write code scanning
# alerts.
env:
NODE_AUTH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: bun install --frozen-lockfile --ignore-scripts

- name: Gate on unaccepted HIGH/CRITICAL findings
run: |
bun scripts/osv-gate.ts \
--allowlist osv-scanner.toml \
--osv osv-results/osv-scanner.json \
--summary "$GITHUB_STEP_SUMMARY"
18 changes: 18 additions & 0 deletions osv-scanner.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
# Accepted dependency risks for osv-scanner (.github/workflows/osv-scanner.yml).
#
# osv-scanner reads this file natively (`--config osv-scanner.toml`), and
# scripts/osv-gate.ts applies the same entries to decide the job's verdict.
# An entry matches a finding through any of its ids or aliases, so a CVE id
# also covers the GHSA of the same advisory.
#
# Every entry must carry all three fields (scripts/osv-gate.test.ts parses this
# file, and the gate rejects an entry without them):
#
# [[IgnoredVulns]]
# id = "GHSA-xxxx-xxxx-xxxx" # or the CVE id
# ignoreUntil = 2027-01-31 # a date; every waiver expires
# reason = "why the risk is accepted, and what clears it"
#
# On the day after ignoreUntil, both osv-scanner and the gate treat the finding
# as new again and the job fails until the dependency moves or the waiver is
# re-reviewed. No risk is accepted today.
163 changes: 163 additions & 0 deletions scripts/osv-gate.lib.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,163 @@
import { parse } from "smol-toml";

// The verdict logic of scripts/osv-gate.ts (see .github/workflows/osv-scanner.yml).
// A finding blocks when its CVSS score is 7.0 or higher, or, when it carries no
// score, when its advisory labels itself HIGH or CRITICAL, unless one of its ids
// or aliases has an unexpired [[IgnoredVulns]] entry in osv-scanner.toml. An
// expired entry accepts nothing, so a lapsed waiver turns the scan red. A
// known-malicious package (an OSV MAL-* record from the OpenSSF
// malicious-packages feed) always blocks: those records carry no score and no
// label, so the CVSS rule alone would pass them.

export const HIGH_CVSS = 7.0;
const CRITICAL_CVSS = 9.0;
const MEDIUM_CVSS = 4.0;
export const MALICIOUS = "MALICIOUS";
const BLOCKING_LABELS = new Set(["HIGH", "CRITICAL", MALICIOUS]);
const FALLBACK_LABELS = ["CRITICAL", "HIGH", "MODERATE", "MEDIUM", "LOW"];

export class GateInputError extends Error {}

export type Waiver = { id: string; until: string; reason: string };

export type Finding = {
source: string;
pkg: string;
version: string;
ids: string[];
severity: string;
gating: boolean;
};

export type Verdict = {
blocking: Finding[];
expired: Map<Finding, Waiver>;
accepted: Array<[Finding, Waiver]>;
informational: Finding[];
};

// The subset of osv-scanner's `--format json` report the gate reads.
export type OsvReport = {
results?: Array<{
source?: { path?: string };
packages?: Array<{
package?: { name?: string; version?: string };
vulnerabilities?: Array<{ id?: string; database_specific?: { severity?: string } }>;
groups?: Array<{ ids?: string[]; aliases?: string[]; max_severity?: string }>;
}>;
}>;
};

// Every waiver must name an id, expire on a date (YYYY-MM-DD) and say why.
export function parseAllowlist(text: string, where = "osv-scanner.toml"): Waiver[] {
let doc: Record<string, unknown>;
try {
doc = parse(text) as Record<string, unknown>;
} catch (error) {
throw new GateInputError(`reading allowlist ${where}: ${(error as Error).message}`);
}
const entries = (doc.IgnoredVulns ?? []) as Array<Record<string, unknown>>;
return entries.map((entry, index) => {
const at = `${where} IgnoredVulns[${index}]`;
const id = typeof entry.id === "string" ? entry.id.trim() : "";
if (!id) throw new GateInputError(`${at}: id is required`);
const until = entry.ignoreUntil instanceof Date ? entry.ignoreUntil.toISOString().slice(0, 10) : "";
if (!until) throw new GateInputError(`${at} (${id}): ignoreUntil must be a date; every waiver expires`);
const reason = typeof entry.reason === "string" ? entry.reason.trim() : "";
if (!reason) throw new GateInputError(`${at} (${id}): reason is required`);
return { id, until, reason };
});
}

export function labelForScore(score: number): string {
if (score >= CRITICAL_CVSS) return "CRITICAL";
if (score >= HIGH_CVSS) return "HIGH";
if (score >= MEDIUM_CVSS) return "MEDIUM";
return "LOW";
}

function displayPath(path: string, cwd: string): string {
return path.startsWith(`${cwd}/`) ? path.slice(cwd.length + 1) : path;
}

export function osvFindings(report: OsvReport, cwd = process.cwd()): Finding[] {
const findings: Finding[] = [];
for (const result of report.results ?? []) {
const source = displayPath(result.source?.path ?? "?", cwd);
for (const pkg of result.packages ?? []) {
const labels = new Map((pkg.vulnerabilities ?? []).map((v) => [v.id, (v.database_specific?.severity ?? "").toUpperCase()]));
for (const group of pkg.groups ?? []) {
const ids = [...new Set([...(group.ids ?? []), ...(group.aliases ?? [])])];
if (ids.length === 0) throw new GateInputError(`osv-scanner group without ids in ${source}`);
let severity = "UNSCORED";
const raw = (group.max_severity ?? "").trim();
if (ids.some((id) => id.startsWith("MAL-"))) {
severity = MALICIOUS;
} else if (raw) {
const score = Number(raw);
if (!Number.isFinite(score)) throw new GateInputError(`osv-scanner max_severity ${JSON.stringify(raw)} is not a number`);
severity = `${labelForScore(score)} ${raw}`;
} else {
const groupLabels = new Set((group.ids ?? []).map((id) => labels.get(id) ?? ""));
severity = FALLBACK_LABELS.find((label) => groupLabels.has(label)) ?? "UNSCORED";
}
findings.push({
source,
pkg: pkg.package?.name ?? "?",
version: pkg.package?.version ?? "?",
ids,
severity,
gating: BLOCKING_LABELS.has(severity.split(" ")[0]!),
});
}
}
}
return findings;
}

// today and waiver.until are both YYYY-MM-DD, so string order is date order;
// a waiver still accepts on its expiry day.
export function decide(findings: Finding[], waivers: Waiver[], today: string): Verdict {
const verdict: Verdict = { blocking: [], expired: new Map(), accepted: [], informational: [] };
for (const finding of findings) {
const waiver = waivers.find((w) => finding.ids.includes(w.id));
if (waiver && today <= waiver.until) verdict.accepted.push([finding, waiver]);
else if (!finding.gating) verdict.informational.push(finding);
else {
if (waiver) verdict.expired.set(finding, waiver);
verdict.blocking.push(finding);
}
}
return verdict;
}

function row(finding: Finding, note = ""): string {
return `| \`${finding.source}\` | ${finding.pkg}@${finding.version} | ${finding.ids.join(", ")} | ${finding.severity} | ${note} |`;
}

export function render(verdict: Verdict): string {
const header = ["| Source | Package | Advisory | Severity | Note |", "|---|---|---|---|---|"];
const lines = ["## osv-scanner", ""];
if (verdict.blocking.length > 0) {
lines.push(
`**${verdict.blocking.length} unaccepted HIGH/CRITICAL finding(s).** Fix them, or add a time-boxed waiver to osv-scanner.toml in a reviewed change.`,
"",
...header,
...verdict.blocking.map((f) => {
const waiver = verdict.expired.get(f);
return row(f, waiver ? `waiver ${waiver.id} expired ${waiver.until}` : "blocking");
}),
);
} else {
lines.push("No unaccepted HIGH/CRITICAL finding.");
}
if (verdict.accepted.length > 0) {
lines.push("", `### Accepted by osv-scanner.toml (${verdict.accepted.length})`, "", ...header);
lines.push(...verdict.accepted.map(([f, w]) => row(f, `${w.id} until ${w.until}`)));
}
if (verdict.informational.length > 0) {
lines.push("", `### Below the gate (${verdict.informational.length})`, "", ...header);
lines.push(...verdict.informational.map((f) => row(f)));
}
return `${lines.join("\n")}\n`;
}
Loading
Loading