diff --git a/.github/workflows/coverage.yml b/.github/workflows/coverage.yml index 0ecfc2ca..74ea9db0 100644 --- a/.github/workflows/coverage.yml +++ b/.github/workflows/coverage.yml @@ -55,6 +55,9 @@ jobs: - name: Validate pinned Rust toolchain alignment run: pnpm ci:rust-toolchain:test && pnpm ci:rust-toolchain:check + - name: Validate the secret protection settings check + run: pnpm secrets:test + - name: Mainnet readiness matches the committed manifest (recorded fixture, no RPC, no secrets) run: | pnpm --filter @sub-rosa/sdk exec tsx scripts/mainnet-ready.ts --strict --fixture diff --git a/.github/workflows/secret-scan.yml b/.github/workflows/secret-scan.yml new file mode 100644 index 00000000..e1d5fafa --- /dev/null +++ b/.github/workflows/secret-scan.yml @@ -0,0 +1,68 @@ +name: Secret scan + +on: + push: + branches: [main] + pull_request: + +permissions: + # Lee el repo para escanear el historial y el arbol de trabajo. Escribe + # unicamente en code scanning (SARIF) para que los hallazgos se puedan + # revisar en la pestana Security. No hace push, ni comenta, ni publica. + contents: read + security-events: write + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +jobs: + gitleaks: + runs-on: ubuntu-latest + timeout-minutes: 10 + steps: + - uses: actions/checkout@v4 + with: + # Historial completo: el escaneo tiene que cubrir los commits que + # llegan a main, no solo el ultimo. + fetch-depth: 0 + + - name: Install gitleaks (version fijada + checksum verificado) + run: | + set -euo pipefail + version="v8.30.1" + archive="gitleaks_8.30.1_linux_x64.tar.gz" + curl -sSfL -o "$archive" "https://github.com/gitleaks/gitleaks/releases/download/${version}/${archive}" + curl -sSfL -o checksums.txt "https://github.com/gitleaks/gitleaks/releases/download/${version}/gitleaks_8.30.1_checksums.txt" + grep " ${archive}\$" checksums.txt | sha256sum --check --strict + tar -xzf "$archive" gitleaks + sudo install gitleaks /usr/local/bin/gitleaks + gitleaks version + + - name: Scan history and working tree for secrets + run: | + set -euo pipefail + # --redact nunca imprime el valor detectado: ni en el log del job ni + # en el informe SARIF que se sube a code scanning. + gitleaks detect \ + --source . \ + --config .gitleaks.toml \ + --redact \ + --exit-code 1 \ + --report-format sarif \ + --report-path gitleaks.sarif + + # En pull requests desde un fork GitHub degrada security-events: write a + # solo lectura, asi que la subida fallaria y marcaria en rojo un PR + # limpio. El escaneo sigue corriendo en todos los PR; el SARIF solo se + # publica cuando el token puede escribir (push a main o PR del mismo + # repositorio). + - name: Publish results to code scanning + if: >- + always() && + (github.event_name != 'pull_request' || + github.event.pull_request.head.repo.full_name == github.repository) + uses: github/codeql-action/upload-sarif@v3 + with: + sarif_file: gitleaks.sarif + category: secret-scan diff --git a/.gitleaks.toml b/.gitleaks.toml new file mode 100644 index 00000000..978937d8 --- /dev/null +++ b/.gitleaks.toml @@ -0,0 +1,35 @@ +# Copyright (c) 2026 Sub Rosa contributors +# +# Configuracion de gitleaks para el gate de escaneo de secretos. +# +# Se mantienen las reglas por defecto de gitleaks (proveedores + patrones +# genericos) y solo se permite una lista blanca minima para los valores que +# NO son credenciales: +# +# - IDs de contrato Stellar (C...), IDs de cuenta (G...) y hashes SHA-256 +# que aparecen en fixtures, artefactos de mainnet y trazas de demo. +# +# La lista blanca combina `paths` (los ficheros concretos) con `regexes` (las +# formas de valor). Un credencial real en esos mismos ficheros no encaja en +# ninguna de esas formas, asi que sigue saltando la alerta. + +title = "Sub Rosa secret scanning configuration" + +[extend] +useDefault = true + +[[allowlists]] +description = "Public Stellar identifiers and hashes used by fixtures, artifacts and demo traces (not credentials)" +paths = [ + '''^apps/web/\.env\.example$''', + '''^apps/web/src/demo/demo-trace\.generated\.ts$''', + '''^apps/web/src/lib/config\.test\.ts$''', + '''^packages/sdk/fixtures/mainnet-readiness\.json$''', + '''^packages/sdk/mainnet-artifacts\.json$''', + '''^packages/sdk/src/mainnet-readiness\.test\.ts$''', +] +regexes = [ + '''\bC[A-Z2-7]{55}\b''', + '''\bG[A-Z2-7]{55}\b''', + '''\b[0-9a-f]{64}\b''', +] diff --git a/docs/SECRET_PROTECTION.md b/docs/SECRET_PROTECTION.md new file mode 100644 index 00000000..0bf096eb --- /dev/null +++ b/docs/SECRET_PROTECTION.md @@ -0,0 +1,144 @@ +# Secret protection + +This repository treats leaked credentials as a first-class incident. Two +independent layers keep them out: + +1. **Repository settings on GitHub** — secret scanning, push protection, + non-provider pattern detection and validity checks. These live in GitHub's + configuration for the repository, not in the tree, so they cannot be + committed; they are verified with a script (see below). +2. **An in-repo CI gate** — `.github/workflows/secret-scan.yml` scans the + history and the working tree with gitleaks on every push to `main` and on + every incoming pull request. + +The two layers fail differently on purpose: the settings stop a credential +before it lands in the history, and the CI gate stops it from landing in a +merge. + +## Settings that must be enabled + +| Setting | `security_and_analysis` field | Required | +| --- | --- | --- | +| Secret scanning | `secret_scanning` | yes | +| Push protection | `secret_scanning_push_protection` | yes | +| Non-provider pattern detection | `secret_scanning_non_provider_patterns` | where available | +| Validity checks | `secret_scanning_validity_checks` | where available | + +The last two depend on what the repository's plan exposes. The API omits the +fields it does not offer, and this repository treats "not offered" as +"nothing to enable" — but it never treats "offered and off" as acceptable. + +## Enabling them (repository admin) + +In the web UI: **Settings → Code security and analysis → Secret scanning → +Enable**, and the same for **Push protection**. + +From the command line, with a token that has **Administration: write** on the +repository: + +```bash +export GITHUB_TOKEN= +pnpm secrets:enable +``` + +`pnpm secrets:enable` runs `node scripts/check-secret-protection.mjs --enable`, +which enables one protection per request, ignores the ones the API reports as +unavailable (HTTP 422) and then re-reads the settings so the result is shown +from the API rather than from the request that was sent. + +## Verifying them + +```bash +export GITHUB_TOKEN= +pnpm secrets:check +``` + +Expected output (one line per protection, then a summary): + +``` +[PASS] Secret scanning (secret_scanning) — enabled +[PASS] Push protection (secret_scanning_push_protection) — enabled +[PASS] Non-provider pattern detection (secret_scanning_non_provider_patterns) — enabled +[PASS] Validity checks (secret_scanning_validity_checks) — enabled +PASS: secret protection is enabled for Sub-Rosa-Issue/sub-rosa-issue +``` + +The command exits non-zero when a protection is disabled, when a required +protection is not reported by the API (usually a token without +**Administration: read**), or when the API call fails. `--json` prints the +same result as a single machine-readable line. + +## What each protection covers + +| Protection | Scope | +| --- | --- | +| Secret scanning | Scans the history of the default branch and every new push, and opens one alert per detected credential. | +| Push protection | Blocks a push that would introduce a credential — on any branch, including the branch behind an incoming pull request — and lets an admin review or override the block. | +| Non-provider pattern detection | Adds patterns for credentials that have no provider partner (generic API keys, private keys, and similar). | +| Validity checks | Marks each alert as active, inactive or unknown, so a live credential can be told apart from a revoked one. | + +Because push protection blocks the push itself, it protects `main` and every +incoming pull request before the code is merged. Secret scanning then covers +what is already in the history. + +## The CI gate + +`.github/workflows/secret-scan.yml` runs on pushes to `main` and on pull +requests, and: + +- downloads a pinned gitleaks release and verifies it against the published + checksum before running it; +- scans the full history and the working tree with the default gitleaks rule + set, so provider patterns and generic patterns are both covered; +- runs with `--redact`, so no secret value is ever written to the job log or + to the SARIF report that gets uploaded to code scanning — reviewers see the + rule, the file and the line, never the value; +- uploads the SARIF results to code scanning, so the findings show up in + the repository's **Security** tab like native secret scanning alerts. For a + pull request from a fork the token is read-only, so the upload is skipped + there (the scan itself still runs and still fails on a finding); this keeps + a clean fork PR from failing on a permission error. + +`.gitleaks.toml` keeps the default rules and allowlists only the values in +this repository that look like credentials but are not: Stellar contract IDs +(`C…`), Stellar account IDs (`G…`) and SHA-256 hashes in fixtures, mainnet +artifacts and demo traces. The allowlist pairs those file paths with those +value shapes, so a real credential dropped into one of those files does not +match it and still fails the job. + +## Reviewing alerts without exposing values + +- Review alerts in **Security → Secret scanning**. Do not copy the value into + an issue, a pull request, a comment or a log. +- To list alerts from the API without the literal secret in the response: + `gh api "repos/OWNER/REPO/secret-scanning/alerts?hide_secret=true"`. +- When an alert turns out to be a real credential: revoke or rotate it first, + then resolve the alert as `revoked`. Resolve non-credentials as + `false_positive` (or `used_in_tests` when they are test values). +- Record the alert number, the secret type and the location — never the value. + +## Result of the initial scan + +The initial scan of the complete history reachable from `main` at the time of +writing (403 commits) with the rules used by the CI gate found no credential. +The only matches were `generic-api-key` hits on public, non-secret values — Stellar contract IDs, +Stellar account IDs and SHA-256 hashes — in fixtures, mainnet artifacts and +demo traces. Those are exactly the values allowlisted in `.gitleaks.toml`, so +no rotation and no history rewrite are needed. + +Native GitHub secret scanning will raise its own alerts for the same values, +because they look like high-entropy strings to a generic pattern. They can be +resolved as false positives; their values are public on-chain identifiers, but +they still do not belong in an issue or a comment. + +## Commands + +| Command | What it does | +| --- | --- | +| `pnpm secrets:check` | Read the repository settings and report every protection | +| `pnpm secrets:enable` | Enable the settings (needs **Administration: write**) | +| `pnpm secrets:test` | Unit tests for the check/enable script | + +See also [CI and quality gates](./CI.md) for the rest of the automated checks +and [DEPLOY.md](./DEPLOY.md) for how runtime secrets are handled in the +deployed app. diff --git a/scripts/check-links.js b/scripts/check-links.js index 73d6ab4c..0349f0ca 100644 --- a/scripts/check-links.js +++ b/scripts/check-links.js @@ -17,6 +17,7 @@ const FILES = [ 'docs/THREAT_MODEL.md', 'docs/DEPLOY.md', 'docs/DEMO_SCRIPT.md', + 'docs/SECRET_PROTECTION.md', 'docs/INTEGRATION.md', 'docs/RECEIPTS.md', 'docs/SCF_TRANCHE_PLAN.md', diff --git a/scripts/check-secret-protection.mjs b/scripts/check-secret-protection.mjs new file mode 100644 index 00000000..f1764319 --- /dev/null +++ b/scripts/check-secret-protection.mjs @@ -0,0 +1,346 @@ +#!/usr/bin/env node +// Copyright (c) 2026 Sub Rosa contributors +import { createLogger, writeData } from '../packages/logging/src/index.cjs'; +import { readFileSync } from 'node:fs'; +import { dirname, resolve } from 'node:path'; +import { fileURLToPath } from 'node:url'; + +const diagnostics = createLogger('scripts.check-secret-protection'); + +// scripts/check-secret-protection.mjs +// +// Comprueba (y, con --enable, activa) las protecciones de secretos de GitHub +// para un repositorio: +// +// - secret_scanning escaneo de secretos +// - secret_scanning_push_protection push protection +// - secret_scanning_non_provider_patterns deteccion de patrones no-proveedor +// - secret_scanning_validity_checks comprobaciones de validez +// +// El estado vive en la configuracion del repositorio (Settings > Code +// security), no en el arbol de ficheros, asi que este script es la forma +// reproducible de confirmarlo y de activarlo. +// +// Solo imprime estados. Nunca imprime el token ni ningun valor de secreto. + +const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..'); + +const FEATURES = [ + { key: 'secret_scanning', label: 'Secret scanning', required: true }, + { key: 'secret_scanning_push_protection', label: 'Push protection', required: true }, + { + key: 'secret_scanning_non_provider_patterns', + label: 'Non-provider pattern detection', + required: false, + }, + { key: 'secret_scanning_validity_checks', label: 'Validity checks', required: false }, +]; + +const DEFAULT_API_BASE = 'https://api.github.com'; + +function defaultRepo() { + try { + const pkg = JSON.parse(readFileSync(resolve(ROOT, 'package.json'), 'utf-8')); + const url = String(pkg.repository?.url ?? ''); + const match = url.match(/github\.com[:/]([^/]+)\/([^/]+?)(?:\.git)?$/); + if (match) return { owner: match[1], repo: match[2] }; + } catch { + // Sin package.json legible se cae al repositorio por defecto de abajo. + } + return { owner: 'Sub-Rosa-Issue', repo: 'sub-rosa-issue' }; +} + +function parseRepo(value) { + const match = String(value).match(/^([^/]+)\/([^/]+)$/); + if (!match) return null; + return { owner: match[1], repo: match[2] }; +} + +function parseArgs(argv) { + const options = { + repo: parseRepo(process.env.SECRET_PROTECTION_REPO ?? '') ?? defaultRepo(), + token: process.env.SECRET_PROTECTION_TOKEN ?? process.env.GITHUB_TOKEN ?? process.env.GH_TOKEN ?? null, + apiBase: process.env.SECRET_PROTECTION_API_BASE ?? DEFAULT_API_BASE, + enable: false, + json: false, + help: false, + }; + + for (let i = 0; i < argv.length; i += 1) { + const arg = argv[i]; + const next = () => { + const value = argv[i + 1]; + if (value === undefined) { + diagnostics.error('usage', `Missing value for ${arg}`); + process.exit(2); + } + i += 1; + return value; + }; + + switch (arg) { + case '--repo': { + const value = next(); + const repo = parseRepo(value); + if (!repo) { + diagnostics.error('usage', `--repo expects owner/name, got "${value}"`); + process.exit(2); + } + options.repo = repo; + break; + } + case '--token': + options.token = next(); + break; + case '--api-base': + options.apiBase = next(); + break; + case '--enable': + options.enable = true; + break; + case '--json': + options.json = true; + break; + case '--help': + case '-h': + options.help = true; + break; + default: + diagnostics.error('usage', `Unknown argument: ${arg}`); + process.exit(2); + } + } + + return options; +} + +function usage() { + return [ + 'Usage: node scripts/check-secret-protection.mjs [options]', + '', + 'Options:', + ' --repo Repository to inspect (default: from package.json)', + ' --token Token with Administration read (and write with --enable)', + ' --api-base GitHub API base URL (default: https://api.github.com)', + ' --enable Enable the settings instead of only reporting them', + ' --json Print a machine-readable summary', + '', + 'Environment: SECRET_PROTECTION_TOKEN, GITHUB_TOKEN, GH_TOKEN,', + ' SECRET_PROTECTION_REPO, SECRET_PROTECTION_API_BASE', + ].join('\n'); +} + +async function apiRequest({ apiBase, token, method, path, body }) { + const response = await fetch(`${apiBase}${path}`, { + method, + headers: { + accept: 'application/vnd.github+json', + 'x-github-api-version': '2022-11-28', + authorization: `Bearer ${token}`, + ...(body ? { 'content-type': 'application/json' } : {}), + }, + body: body ? JSON.stringify(body) : undefined, + }); + + const text = await response.text(); + let json = null; + try { + json = text ? JSON.parse(text) : null; + } catch { + // Cuerpo no-JSON (por ejemplo, un error de proxy). Se conserva el texto. + } + + return { status: response.status, ok: response.ok, json, text }; +} + +function describeApiError(response) { + const message = response.json?.message ?? response.text?.slice(0, 200) ?? 'sin detalle'; + if (response.status === 403) { + return `403 ${message}. The token needs "Administration: read" (check) or "Administration: write" (--enable) on the repository.`; + } + if (response.status === 404) { + return `404 ${message}. The repository does not exist or the token cannot see it.`; + } + if (response.status === 422) { + return `422 ${message}.`; + } + return `${response.status} ${message}`; +} + +// Evalua el estado de cada proteccion a partir del bloque +// security_and_analysis que devuelve la API. +// +// enabled -> activo +// disabled -> existe pero esta apagado (fallo) +// unavailable -> la API no expone la proteccion (no disponible en este plan) +// unknown -> la proteccion es obligatoria pero la API no informo de ella +function evaluateFeatures(securityAndAnalysis) { + return FEATURES.map((feature) => { + const entry = securityAndAnalysis?.[feature.key]; + const status = typeof entry?.status === 'string' ? entry.status : null; + + if (status === 'enabled') { + return { ...feature, status, state: 'enabled' }; + } + if (status === 'disabled') { + return { ...feature, status, state: 'disabled' }; + } + if (!feature.required) { + return { ...feature, status, state: 'unavailable' }; + } + return { ...feature, status, state: 'unknown' }; + }); +} + +function isProtected(features) { + return features.every( + (feature) => feature.state === 'enabled' || (!feature.required && feature.state === 'unavailable'), + ); +} + +function reportFeatures(features, { owner, repo }) { + diagnostics.info('repository', `Repository: ${owner}/${repo}`); + for (const feature of features) { + const tag = + feature.state === 'enabled' + ? 'PASS' + : feature.state === 'unavailable' + ? 'N/A ' + : 'FAIL'; + const detail = + feature.state === 'enabled' + ? 'enabled' + : feature.state === 'unavailable' + ? 'not available for this repository/plan' + : feature.state === 'disabled' + ? 'disabled' + : 'not reported by the API (insufficient permissions?)'; + diagnostics.info('feature', ` [${tag}] ${feature.label} (${feature.key}) — ${detail}`); + } +} + +async function enableFeature({ apiBase, token, owner, repo, feature }) { + const response = await apiRequest({ + apiBase, + token, + method: 'PATCH', + path: `/repos/${owner}/${repo}`, + body: { security_and_analysis: { [feature.key]: { status: 'enabled' } } }, + }); + + if (response.ok) { + return { feature, outcome: 'enabled' }; + } + if (response.status === 422) { + // La API rechaza la proteccion cuando no esta disponible para este + // repositorio o plan (por ejemplo, patrones no-proveedor sin GitHub + // Advanced Security). No es un fallo del repositorio. + return { feature, outcome: 'unavailable', detail: describeApiError(response) }; + } + return { feature, outcome: 'error', detail: describeApiError(response) }; +} + +async function main() { + const options = parseArgs(process.argv.slice(2)); + + if (options.help) { + writeData(usage()); + return 0; + } + + if (!options.token) { + diagnostics.error('usage', 'No token found. Pass --token or set SECRET_PROTECTION_TOKEN / GITHUB_TOKEN / GH_TOKEN.'); + return 2; + } + + const { owner, repo } = options.repo; + + if (options.enable) { + diagnostics.info('enable', `Enabling secret protection on ${owner}/${repo}`); + for (const feature of FEATURES) { + const result = await enableFeature({ ...options, owner, repo, feature }); + if (result.outcome === 'enabled') { + diagnostics.info('enable-ok', ` [OK] ${feature.label} (${feature.key}) — enabled`); + } else if (result.outcome === 'unavailable') { + diagnostics.info('enable-na', ` [N/A] ${feature.label} (${feature.key}) — not available for this repository/plan`); + } else { + diagnostics.error('enable-fail', ` [FAIL] ${feature.label} (${feature.key}) — ${result.detail}`); + } + } + } + + const response = await apiRequest({ + apiBase: options.apiBase, + token: options.token, + method: 'GET', + path: `/repos/${owner}/${repo}`, + }); + + if (!response.ok) { + diagnostics.error('api', `Could not read repository settings: ${describeApiError(response)}`); + return 1; + } + + const securityAndAnalysis = response.json?.security_and_analysis; + if (!securityAndAnalysis || typeof securityAndAnalysis !== 'object') { + diagnostics.error( + 'api', + 'The API response does not include security_and_analysis. The token cannot read repository settings, ' + + 'or this repository does not expose secret-protection settings. A token with Administration read is required.', + ); + return 1; + } + + const features = evaluateFeatures(securityAndAnalysis); + reportFeatures(features, { owner, repo }); + + const ok = isProtected(features); + const unavailable = features.filter((feature) => feature.state === 'unavailable').map((feature) => feature.key); + + if (options.json) { + writeData( + JSON.stringify({ + repository: `${owner}/${repo}`, + ok, + features: features.map((feature) => ({ + key: feature.key, + label: feature.label, + required: feature.required, + status: feature.status, + state: feature.state, + })), + }), + ); + } + + if (ok) { + diagnostics.info( + 'ok', + `PASS: secret protection is enabled for ${owner}/${repo}` + + (unavailable.length > 0 ? ` (not available here: ${unavailable.join(', ')})` : ''), + ); + return 0; + } + + const failing = features + .filter((feature) => feature.state === 'disabled' || feature.state === 'unknown') + .map((feature) => feature.key); + diagnostics.error('fail', `FAIL: secret protection is incomplete for ${owner}/${repo} — ${failing.join(', ')}`); + return 1; +} + +const invokedDirectly = + process.argv[1] && resolve(process.argv[1]) === resolve(fileURLToPath(import.meta.url)); + +if (invokedDirectly) { + main() + .then((code) => { + process.exitCode = code; + }) + .catch((error) => { + diagnostics.error('unexpected', `Unexpected failure: ${error?.message ?? String(error)}`); + process.exitCode = 1; + }); +} + +export { evaluateFeatures, isProtected, parseArgs, FEATURES }; diff --git a/scripts/check-secret-protection.test.mjs b/scripts/check-secret-protection.test.mjs new file mode 100644 index 00000000..366c4f5a --- /dev/null +++ b/scripts/check-secret-protection.test.mjs @@ -0,0 +1,265 @@ +// Copyright (c) 2026 Sub Rosa contributors +import { execFile } from "node:child_process"; +import { createServer } from "node:http"; +import { describe, it } from "node:test"; +import assert from "node:assert/strict"; +import { promisify } from "node:util"; + +const execFileAsync = promisify(execFile); + +const SCRIPT_PATH = new URL("check-secret-protection.mjs", import.meta.url).pathname; +const CWD = new URL("..", import.meta.url).pathname; + +// Servidor de mentira que imita las respuestas de la API de GitHub que usa +// el script. Devuelve { url, requests, close }. +async function startFakeApi(responder) { + const requests = []; + const server = createServer((req, res) => { + let body = ""; + req.on("data", (chunk) => { + body += chunk; + }); + req.on("end", () => { + requests.push({ + method: req.method, + url: req.url, + body: body ? JSON.parse(body) : null, + authorization: req.headers.authorization, + }); + const reply = responder(req, body ? JSON.parse(body) : null) ?? { status: 200, json: {} }; + res.writeHead(reply.status, { "content-type": "application/json" }); + res.end(JSON.stringify(reply.json ?? {})); + }); + }); + + await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); + const { port } = server.address(); + + return { + url: `http://127.0.0.1:${port}`, + requests, + close: () => new Promise((resolve) => server.close(resolve)), + }; +} + +function runScript(args) { + return execFileAsync("node", [SCRIPT_PATH, ...args], { + cwd: CWD, + encoding: "utf-8", + env: { ...process.env, GITHUB_TOKEN: "", GH_TOKEN: "" }, + }).then( + (result) => ({ code: 0, output: `${result.stdout}${result.stderr}` }), + (error) => ({ + code: error.code ?? 1, + output: `${error.stdout ?? ""}${error.stderr ?? ""}`, + }), + ); +} + +const ALL_ENABLED = { + secret_scanning: { status: "enabled" }, + secret_scanning_push_protection: { status: "enabled" }, + secret_scanning_non_provider_patterns: { status: "enabled" }, + secret_scanning_validity_checks: { status: "enabled" }, +}; + +describe("check-secret-protection", () => { + it("passes when every secret-protection feature is enabled", async () => { + const api = await startFakeApi(() => ({ + status: 200, + json: { full_name: "acme/widgets", security_and_analysis: ALL_ENABLED }, + })); + + try { + const result = await runScript(["--repo", "acme/widgets", "--token", "t", "--api-base", api.url]); + assert.equal(result.code, 0, result.output); + assert.match(result.output, /PASS: secret protection is enabled/); + assert.match(result.output, /Push protection/); + } finally { + await api.close(); + } + }); + + it("fails when secret scanning is disabled", async () => { + const api = await startFakeApi(() => ({ + status: 200, + json: { + security_and_analysis: { + ...ALL_ENABLED, + secret_scanning: { status: "disabled" }, + }, + }, + })); + + try { + const result = await runScript(["--repo", "acme/widgets", "--token", "t", "--api-base", api.url]); + assert.equal(result.code, 1, result.output); + assert.match(result.output, /FAIL: secret protection is incomplete/); + assert.match(result.output, /secret_scanning/); + } finally { + await api.close(); + } + }); + + it("treats optional features that the API does not expose as not available", async () => { + const api = await startFakeApi(() => ({ + status: 200, + json: { + security_and_analysis: { + secret_scanning: { status: "enabled" }, + secret_scanning_push_protection: { status: "enabled" }, + }, + }, + })); + + try { + const result = await runScript(["--repo", "acme/widgets", "--token", "t", "--api-base", api.url]); + assert.equal(result.code, 0, result.output); + assert.match(result.output, /not available for this repository\/plan/); + assert.match(result.output, /not available here: secret_scanning_non_provider_patterns/); + } finally { + await api.close(); + } + }); + + it("fails when the API does not return the settings at all", async () => { + const api = await startFakeApi(() => ({ status: 200, json: { full_name: "acme/widgets" } })); + + try { + const result = await runScript(["--repo", "acme/widgets", "--token", "t", "--api-base", api.url]); + assert.equal(result.code, 1, result.output); + assert.match(result.output, /does not include security_and_analysis/); + } finally { + await api.close(); + } + }); + + it("explains a 403 as a permissions problem", async () => { + const api = await startFakeApi(() => ({ + status: 403, + json: { message: "Resource not accessible by integration" }, + })); + + try { + const result = await runScript(["--repo", "acme/widgets", "--token", "t", "--api-base", api.url]); + assert.equal(result.code, 1, result.output); + assert.match(result.output, /Administration: read/); + } finally { + await api.close(); + } + }); + + it("enables every feature and re-reads the settings", async () => { + const api = await startFakeApi((req) => { + if (req.method === "PATCH") { + return { status: 200, json: { security_and_analysis: ALL_ENABLED } }; + } + return { status: 200, json: { security_and_analysis: ALL_ENABLED } }; + }); + + try { + const result = await runScript([ + "--repo", + "acme/widgets", + "--token", + "t", + "--api-base", + api.url, + "--enable", + ]); + assert.equal(result.code, 0, result.output); + + const patches = api.requests.filter((request) => request.method === "PATCH"); + assert.equal(patches.length, 4); + for (const patch of patches) { + const [key, value] = Object.entries(patch.body.security_and_analysis)[0]; + assert.equal(value.status, "enabled"); + assert.ok(key.startsWith("secret_scanning"), key); + } + assert.match(result.output, /PASS: secret protection is enabled/); + } finally { + await api.close(); + } + }); + + it("keeps going when a feature is rejected as unavailable (422)", async () => { + const api = await startFakeApi((req, body) => { + if (req.method === "PATCH") { + const key = Object.keys(body.security_and_analysis)[0]; + if (key === "secret_scanning_non_provider_patterns") { + return { status: 422, json: { message: "not available for this repository" } }; + } + return { status: 200, json: { security_and_analysis: ALL_ENABLED } }; + } + return { + status: 200, + json: { + security_and_analysis: { + secret_scanning: { status: "enabled" }, + secret_scanning_push_protection: { status: "enabled" }, + secret_scanning_validity_checks: { status: "enabled" }, + }, + }, + }; + }); + + try { + const result = await runScript([ + "--repo", + "acme/widgets", + "--token", + "t", + "--api-base", + api.url, + "--enable", + ]); + assert.equal(result.code, 0, result.output); + assert.match(result.output, /not available for this repository\/plan/); + assert.equal(api.requests.filter((request) => request.method === "PATCH").length, 4); + } finally { + await api.close(); + } + }); + + it("exits 2 with usage text when no token is available", async () => { + const result = await runScript(["--repo", "acme/widgets"]); + assert.equal(result.code, 2, result.output); + assert.match(result.output, /No token found/); + }); + + it("prints a machine-readable summary with --json", async () => { + const api = await startFakeApi(() => ({ + status: 200, + json: { security_and_analysis: ALL_ENABLED }, + })); + + try { + const result = await runScript([ + "--repo", + "acme/widgets", + "--token", + "t", + "--api-base", + api.url, + "--json", + ]); + assert.equal(result.code, 0, result.output); + const jsonLine = result.output + .split("\n") + .map((line) => { + try { + return JSON.parse(line); + } catch { + return null; + } + }) + .find((value) => value && value.repository === "acme/widgets"); + assert.ok(jsonLine, result.output); + assert.equal(jsonLine.features.filter((feature) => feature.state === "enabled").length, 4); + assert.equal(jsonLine.ok, true); + assert.equal(jsonLine.features.length, 4); + } finally { + await api.close(); + } + }); +});