Skip to content

alexgreensh/repo-forensics / skills/repo-forensics

repo-forensics

Flagged

Security forensics for git repos, AI skills, and MCP servers. Audits dependencies, detects prompt injection, credential theft, runtime dynamism, manifest drift, known CVEs, CISA KEV (actively exploited) vulns, and 2026 attack patterns. Not for fixing vulnerabilities or pentesting.

FileKindSize
.gitignoreother193 B
SKILL.mdskill md43.4 KB
checksums.jsonconfig10.8 KB
checksums.json.sigother64 B
data/README.mdmarkdown1.3 KB
data/compromised_versions.jsonconfig188.3 KB
data/rule_ids.csvother35.3 KB
data/rulepacks/.gitkeepother221 B
data/rulepacks/dead_anchors.jsonconfig9.0 KB
data/rulepacks/mcp_security.jsonconfig31.2 KB
data/rulepacks/runtime_dynamism.jsonconfig46.7 KB
data/rulepacks/sast.jsonconfig107.6 KB
data/rulepacks/secrets.jsonconfig30.4 KB
data/rulepacks/shared.jsonconfig4.4 KB
data/rulepacks/skill_threats.jsonconfig95.4 KB
data/runtime_floors.jsonconfig2.3 KB
data/yara/cryptominers.yarother1.8 KB
data/yara/hacktools.yarother2.2 KB
data/yara/malware.yarother2.2 KB
data/yara/manifest.jsonconfig8.0 KB
data/yara/webshells.yarother2.5 KB
references/cursor-hook-contract.mdmarkdown5.6 KB
references/kernel_privesc_sandbox_pack.mdmarkdown5.0 KB
references/mcp-attack-patterns.mdmarkdown8.7 KB
references/research_sources.mdmarkdown8.0 KB
references/threat_patterns.mdmarkdown20.3 KB
scripts/_context_gate.pyscript21.7 KB
scripts/_ed25519.pyscript5.1 KB
scripts/_pyc_unmarshal.pyscript17.1 KB
scripts/_shared_patterns.pyscript4.8 KB
scripts/adjudication.pyscript16.4 KB
scripts/adjudication_bridge.pyscript1.0 KB
scripts/aggregate_json.pyscript69.2 KB
scripts/auto_scan.pyexecutablescript152.1 KB
scripts/corpus_sync.pyscript10.0 KB
scripts/cursor_pre_scan.pyscript22.5 KB
scripts/dast_sandbox.sbother1.6 KB
scripts/dead_anchors_extract.pyscript14.8 KB
scripts/dead_anchors_probe.pyscript27.1 KB
scripts/forensics_core.pyscript176.5 KB
scripts/gen_rule_ids.pyscript8.6 KB
scripts/hook_adapter.pyscript19.4 KB
scripts/ioc_manager.pyscript49.6 KB
scripts/parse_pnpm_lock.pyscript7.9 KB
scripts/pre_scan.pyscript143.5 KB
scripts/pypi_pins.pyscript8.1 KB
scripts/refresh_controller.pyexecutablescript48.4 KB
scripts/refresh_threat_dbs.pyexecutablescript19.4 KB
scripts/rule_loader.pyscript44.8 KB
scripts/rulepack_feed.pyscript26.4 KB
scripts/run_forensics.shexecutablescript20.3 KB
scripts/sarif_export.pyscript18.6 KB
scripts/scan_agent_skills.pyscript33.2 KB
scripts/scan_archive.pyscript29.1 KB
scripts/scan_ast.pyscript44.9 KB
scripts/scan_binary.pyscript10.9 KB
scripts/scan_bytecode.pyscript28.2 KB
scripts/scan_dast.pyscript28.8 KB
scripts/scan_dataflow.pyscript15.4 KB
scripts/scan_dead_anchors.pyscript15.9 KB
scripts/scan_decode.pyscript37.5 KB
scripts/scan_dependencies.pyscript124.5 KB
scripts/scan_devcontainer.pyscript8.5 KB
scripts/scan_entropy.pyscript15.6 KB
scripts/scan_entrypoint.pyscript34.3 KB
scripts/scan_git_config.pyscript96.3 KB
scripts/scan_git_forensics.pyscript24.1 KB
scripts/scan_history.pyscript14.5 KB
scripts/scan_infra.pyscript54.3 KB
scripts/scan_integrity.pyscript41.0 KB
scripts/scan_lifecycle.pyscript65.1 KB
scripts/scan_manifest_drift.pyscript47.0 KB
scripts/scan_mcp_security.pyscript42.3 KB
scripts/scan_oversize.pyscript11.7 KB
scripts/scan_post_incident.pyscript36.9 KB
scripts/scan_provenance.pyscript19.4 KB
scripts/scan_runtime_dynamism.pyscript23.5 KB
scripts/scan_runtime_floors.pyscript33.5 KB
scripts/scan_sast.pyscript59.1 KB
scripts/scan_secrets.pyscript11.9 KB
scripts/scan_skill_threats.pyscript102.4 KB
scripts/scan_splitstream.pyscript29.5 KB
scripts/scan_yara.pyscript19.7 KB
scripts/session_scan.pyscript54.1 KB
scripts/suppressions.pyscript15.4 KB
scripts/validate_manifests.pyscript13.7 KB
scripts/verify_install.pyscript26.2 KB
scripts/vuln_feed.pyscript31.1 KB
tests/conftest.pyscript13.4 KB
tests/corpus/DEAD_ANCHORS_CORPUS.mdmarkdown2.3 KB
tests/corpus/budgets.jsonconfig5.6 KB
tests/cursor_helpers.pyscript12.6 KB
tests/fixtures/legacy_main_blocks.jsonconfig10.3 KB
tests/fixtures/powershell_verdict_corpus.jsonconfig114.9 KB
tests/golden/parity_mcp_security.jsonconfig17.5 KB
tests/golden/parity_runtime_dynamism.jsonconfig31.7 KB
tests/golden/parity_sast.jsonconfig59.8 KB
tests/golden/parity_secrets.jsonconfig18.8 KB
tests/golden/parity_skill_threats.jsonconfig48.8 KB
tests/parity_corpus.pyscript6.3 KB
tests/powershell_hook.pyscript8.2 KB
tests/report_builders.pyscript5.0 KB
tests/schemas/sarif-schema-2.1.0.jsonconfig109.1 KB
tests/shell_compat.pyscript2.2 KB
tests/test_adjudication_bridge.pyscript832 B
tests/test_adjudication_containment.pyscript1.4 KB
tests/test_adjudication_output.pyscript20.0 KB
tests/test_adjudication_suppressions.pyscript18.7 KB
tests/test_advisory_adjudication.pyscript1.3 KB
tests/test_agent_relay_rules.pyscript7.8 KB
tests/test_aggregate_json.pyscript10.0 KB
tests/test_auto_scan_patterns.pyscript10.5 KB
tests/test_benign_corpus.pyscript16.4 KB
tests/test_benign_new_scanners.pyscript6.1 KB
tests/test_build_output_skip.pyscript10.6 KB
tests/test_capability_ledger.pyscript18.8 KB
tests/test_codex_install.pyscript10.0 KB
tests/test_codex_marketplace.pyscript3.3 KB
tests/test_comment_false_positives.pyscript2.2 KB
tests/test_composer_dependencies.pyscript4.0 KB
tests/test_compromised_versions.pyscript51.2 KB
tests/test_context_gate.pyscript32.4 KB
tests/test_coverage_status.pyscript7.6 KB
tests/test_css_compounding_shrink.pyscript20.8 KB
tests/test_cursor_adapter.pyscript7.8 KB
tests/test_cursor_benign.pyscript3.4 KB
tests/test_cursor_degrade.pyscript12.7 KB
tests/test_cursor_install.pyscript17.1 KB
tests/test_cursor_latency.pyscript7.2 KB
tests/test_cursor_parity.pyscript5.8 KB
tests/test_cursor_redteam_fn.pyscript4.9 KB
tests/test_cursor_tamper_modify.pyscript14.2 KB
tests/test_cursor_wiring.pyscript32.3 KB
tests/test_d1_yara_correlation.pyscript9.2 KB
tests/test_dead_anchors_extract.pyscript7.6 KB
tests/test_dead_anchors_probe.pyscript19.7 KB
tests/test_evidence_engine_parity.pyscript8.1 KB
tests/test_evidence_model.pyscript11.4 KB
tests/test_forensics_core.pyscript79.2 KB
tests/test_fp_hardening_r3.pyscript9.7 KB
tests/test_fp_hardening_r4.pyscript18.8 KB
tests/test_fp_regression_pairs.pyscript62.5 KB
tests/test_fp_structural.pyscript21.2 KB
tests/test_freshness.pyscript6.2 KB
tests/test_frontmatter_validity.pyscript7.0 KB
tests/test_gpg_rce_hotfix.pyscript4.8 KB
tests/test_hook_inert_data.pyscript6.1 KB
tests/test_hook_scripts.pyscript14.0 KB
tests/test_inspection_cpu_budget.pyscript11.6 KB
tests/test_ioc_manager.pyscript55.4 KB
tests/test_kernel_privesc_rules.pyscript27.8 KB
tests/test_legit_precision_regressions.pyscript6.8 KB
tests/test_lethal_trifecta.pyscript20.7 KB
tests/test_manifest_signature.pyscript1.5 KB
tests/test_manifest_validity.pyscript2.9 KB
tests/test_monotonic_trust_e2e.pyscript4.4 KB
tests/test_non_breaking_contract.pyscript22.7 KB
tests/test_openclaw_install.pyscript6.6 KB
tests/test_pack_parity.pyscript24.8 KB
tests/test_parse_pnpm_lock.pyscript10.7 KB
tests/test_plugin_checkout_provenance.pyscript11.1 KB
tests/test_powershell_hook_wire.pyscript10.6 KB
tests/test_powershell_verdict_corpus.pyscript6.2 KB
tests/test_pr44_hardening.pyscript6.5 KB
tests/test_pre_scan.pyscript19.6 KB
tests/test_pre_scan_composer.pyscript7.4 KB
tests/test_precondition_fields.pyscript4.6 KB
tests/test_provenance_offline.pyscript2.5 KB
tests/test_published_rulepack_feed_current.pyscript1.4 KB
tests/test_py38_compat.pyscript3.3 KB
tests/test_pypi_pinned_versions.pyscript19.3 KB
tests/test_pyproject_string_forms.pyscript2.2 KB
tests/test_redteam_fn_regression.pyscript32.5 KB
tests/test_reflective_fetch_execute.pyscript23.5 KB
tests/test_reflective_review_fixes.pyscript17.8 KB
tests/test_refresh_controller.pyscript19.9 KB
tests/test_refresh_rulepacks.pyscript12.4 KB
tests/test_review_gate_regressions.pyscript9.3 KB
tests/test_rule_loader.pyscript23.2 KB
tests/test_rulepack_feed.pyscript38.1 KB
tests/test_run_forensics_json.pyscript1012 B
tests/test_run_scanner_fail_loud.pyscript6.5 KB
tests/test_runtime_floors.pyscript19.8 KB
tests/test_sandbox_probing_rules.pyscript9.6 KB
tests/test_sarif_export.pyscript19.9 KB
tests/test_scan_agent_skills.pyscript31.3 KB
tests/test_scan_archive.pyscript11.6 KB
tests/test_scan_ast.pyscript12.8 KB
tests/test_scan_binary.pyscript15.3 KB
tests/test_scan_bytecode.pyscript21.5 KB
tests/test_scan_dast.pyscript32.1 KB
tests/test_scan_dataflow.pyscript7.1 KB
tests/test_scan_dead_anchors.pyscript11.5 KB
tests/test_scan_decode.pyscript28.0 KB
tests/test_scan_dependencies.pyscript37.8 KB
tests/test_scan_devcontainer.pyscript8.5 KB
tests/test_scan_entropy.pyscript11.2 KB
tests/test_scan_entrypoint.pyscript19.5 KB
tests/test_scan_git_config.pyscript58.5 KB
tests/test_scan_git_config_review_fixes.pyscript33.3 KB

scripts/scan_provenance.py

View on GitHub
#!/usr/bin/env python3
"""
scan_provenance.py - Artifact Provenance / Attestation Scanner (U4, Gap 5)

Closes the "no artifact provenance check" gap from the 2026-06 audit:
scan_git_forensics verifies commit GPG signatures, but nothing checks whether
the SHIPPED artifact (a published npm package, a PyPI dist, or a generic
skill/repo) is signed by a trusted publisher (sigstore/SLSA/cosign, npm/PyPI
attestation). An attacker who can publish an unsigned (or tampered) artifact to
a registry slips past every other scanner.

Expert posture (repo-forensics makes the call, the user does not):
  - signature PRESENT but verification FAILS  -> CRITICAL "signature
    verification failed" (tampering signal). This is the one actionable,
    alarm-worthy verdict, and it always fires.
  - signature valid / NO signature found / tooling absent or inconclusive
                                              -> NOT a finding. An unsigned
    third-party artifact is the normal state of the world today; alarming on it
    would fire on nearly every scan, flip every clean repo off the exit-0
    contract, and only train users to ignore alarms. The scanner decides this
    is not worth surfacing, like `integrity` only firing on drift. No user
    flag, no opt-in toggle — the expert tool owns the judgment.

User-safety north star: NEVER raise, NEVER hard-fail, NEVER require network.
Every subprocess call is time-bounded and wrapped so a missing tool / timeout /
OSError degrades to "couldn't verify" — which, being non-actionable, stays
silent.

Zero non-stdlib deps (KTD7): shell out to external CLIs (cosign / gh / npm /
pip) via subprocess ONLY when found on PATH (shutil.which). No third-party
Python package is imported — stdlib + forensics_core only.

Created by Alex Greenshpun
"""

import os
import sys
import time
import json
import shutil
import subprocess
import tempfile

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import forensics_core as core

SCANNER_NAME = "provenance"

# Per-tool wall-clock cap. The scanner runs inside the auto_scan hook (SIGKILL
# at ~15s -> silent zero), so a hung cosign/gh/npm/pip must never stall us.
SUBPROCESS_TIMEOUT_SEC = 8

# TOTAL subprocess wall-clock budget across ALL probes in one scan. Probes run
# sequentially; each per-tool 8s timeout summed over 2-3 tools (npm+cosign+gh)
# could reach 16-24s and trip the auto_scan ~15s SIGKILL -> silent zero, which
# would suppress even a real tampering CRITICAL. We budget the SUM well under 15s
# and stop probing once it is exhausted (an unprobed tool = unchecked = silent,
# which is safe; getting SIGKILLed is not).
TOTAL_BUDGET_SEC = 12.0


class _Deadline:
    """Tracks remaining wall-clock against the single shared TOTAL_BUDGET_SEC so
    the sequential probes can never sum past it. `remaining()` returns seconds
    left (>=0); `expired()` is True once the budget is spent. TOTAL_BUDGET_SEC is
    read at construction (not import) so a test can monkeypatch it.

    Uses time.perf_counter (highest-resolution monotonic clock) rather than
    time.monotonic: on Windows time.monotonic has ~15.6 ms granularity
    (GetTickCount64), coarse enough that a sub-second budget could under-count
    elapsed time and let extra probes run past the point they should have been
    skipped. perf_counter (QueryPerformanceCounter on Windows) is monotonic
    within the process and sub-microsecond, so the clamp/early-stop is precise
    on every platform. Both reads below use the same clock, so the deadline is
    self-consistent."""

    def __init__(self):
        self._end = time.perf_counter() + TOTAL_BUDGET_SEC

    def remaining(self):
        return max(0.0, self._end - time.perf_counter())

    def expired(self):
        return self.remaining() <= 0.0

# Hardened env for every shell-out: never prompt, never page, isolated config.
_SAFE_ENV = {
    "PATH": os.environ.get("PATH", "/usr/bin:/bin"),
    "HOME": os.environ.get("HOME", "/tmp"),
    "LANG": "C.UTF-8",
    "GIT_TERMINAL_PROMPT": "0",
    "GH_PROMPT_DISABLED": "1",
    "NO_COLOR": "1",
    "CI": "1",
}


def _run(cmd, cwd=None, deadline=None, env=None):
    """Run an external CLI with a timeout and a hardened env. Returns a dict:
        {"ran": bool, "code": int|None, "out": str, "err": str}
    `ran` is False (and code None) when the tool is missing / timed out / OSError
    — the caller treats that as `unchecked`, which is non-actionable and stays
    SILENT (no finding), never a crash. NEVER raises; NEVER requires network
    (offline tools just return non-zero or time out, both of which degrade to the
    silent unchecked verdict).

    The effective timeout is min(per-tool cap, remaining shared budget): a single
    tool can never burn more than the time left in the scanner-wide budget, so the
    sum of all probes stays under TOTAL_BUDGET_SEC (no SIGKILL / silent zero)."""
    timeout = SUBPROCESS_TIMEOUT_SEC
    if deadline is not None:
        timeout = min(SUBPROCESS_TIMEOUT_SEC, deadline.remaining())
        if timeout <= 0.0:
            # Budget already exhausted; do not even start the process.
            return {"ran": False, "code": None, "out": "", "err": ""}
    try:
        result = subprocess.run(
            cmd,
            cwd=cwd,
            capture_output=True,
            text=True,
            timeout=timeout,
            env=_SAFE_ENV if env is None else env,
            check=False,
        )
        return {
            "ran": True,
            "code": result.returncode,
            "out": (result.stdout or ""),
            "err": (result.stderr or ""),
        }
    except (subprocess.TimeoutExpired, FileNotFoundError, OSError, ValueError):
        # TimeoutExpired -> tool hung; FileNotFoundError/OSError -> tool vanished
        # between which() and run(); all degrade to "couldn't check".
        return {"ran": False, "code": None, "out": "", "err": ""}


# --- Artifact-type detection (mirrors scan_dependencies.py manifest recognition) ---

def detect_artifact(repo_path):
    """Classify the scanned tree. Returns (artifact_type, marker_rel_path).

    artifact_type is one of: "npm", "pypi", "generic". marker_rel_path is the
    file/dir that anchored the classification (used as the finding's `file`)."""
    # npm: a package.json at the root.
    pkg = os.path.join(repo_path, "package.json")
    if os.path.isfile(pkg):
        return "npm", "package.json"

    # PyPI dist: a built/sdist marker or a project manifest.
    for name in ("PKG-INFO", "pyproject.toml", "setup.py", "setup.cfg"):
        if os.path.isfile(os.path.join(repo_path, name)):
            return "pypi", name
    try:
        for entry in os.listdir(repo_path):
            if entry.endswith(".dist-info") or entry.endswith(".egg-info"):
                return "pypi", entry
    except OSError:
        pass

    return "generic", "."


# --- Verification probes (each returns a verdict string) ---
#   "valid"     -> signature/attestation present and verified
#   "invalid"   -> signature present but verification FAILED (tampering)
#   "unsigned"  -> no signature/attestation found
#   "unchecked" -> tooling absent / timeout / couldn't determine
#
# THREE-TIER SIGNAL PARTITION (precedence, see _classify_output):
#
#   1. TAMPERING (definitive verification FAILURE) -> INVALID -> CRITICAL.
#      Scanned FIRST over the WHOLE output. If ANY tampering phrase is present
#      it WINS, regardless of any absent/ambiguous wording co-occurring. This is
#      the one alarm-worthy verdict and it must never be maskable.
#   2. ABSENT (definitively "nothing is signed") -> UNSIGNED -> silent.
#      Unambiguous "no signature is present" wording. Means absent, not failed.
#   3. AMBIGUOUS ("no matching" / "could not find" / "no valid"): dual-meaning —
#      could be absent OR a mismatch. With NO tampering phrase present, treated
#      as unchecked -> SILENT (conservative). NOT a CRITICAL (avoids the M2 false
#      positive on a clean unsigned repo) and NOT claimed unsigned-clean either.
#
# This replaces the earlier "UNSIGNED-before-INVALID, broad phrases first"
# ordering, which over-corrected the M2 false-CRITICAL into a false-NEGATIVE:
# cosign printing "no matching signatures" on a PRESENT-but-mismatched signature
# (real tampering) was masked as unsigned and went silent. Tampering now wins.

# TIER 1 — DEFINITIVE TAMPERING: a signature IS PRESENT but cryptographic
# verification FAILED (mismatch / untrusted key / modified after signing). Any
# of these phrases anywhere in the output forces a CRITICAL.
_TAMPERING_SIGNALS = (
    "verification failed",
    "signature verification failed",
    "cryptographic verification failed",
    "failed to verify",
    "signature failed",
    "invalid signature",
    "signature is invalid",
    "bad signature",
    "does not match",
    "doesn't match",
    "no matching signatures",  # cosign: signatures PRESENT, none match identity
    "tampered",
    "untrusted signer",
    "untrusted key",
    "untrusted certificate",
)

# TIER 2 — DEFINITIVE ABSENT: nothing is signed at all. Unambiguous "no
# signature is present" wording. These mean ABSENT (silent), not failed.
_ABSENT_SIGNALS = (
    "no signature found",
    "no signatures found",
    "no signatures present",
    "no signatures",
    "no attestation found",
    "no attestation",
    "no attestations",
    "no provenance",
    "missing signature",
    "not signed",
)

# TIER 3 — AMBIGUOUS: dual-meaning wording that could indicate either an absent
# signature OR a present-but-mismatched one. Without a Tier-1 tampering phrase we
# refuse to guess and stay SILENT (unchecked), so we neither raise a false
# CRITICAL nor falsely clear the artifact.
_AMBIGUOUS_SIGNALS = (
    "no matching",
    "could not find",
    "no valid",
)


def _classify_output(res):
    """Map a tool result dict to a verdict using exit code + stdout/stderr text.
    Shared by all probes so the severity ladder stays consistent.

    Precedence is the security-critical invariant:

      1. TAMPERING wins ALWAYS. The whole output is scanned for a definitive
         verification-failure phrase FIRST; if one is present we return
         "invalid" (CRITICAL) even if absent/ambiguous wording co-occurs. A
         present-but-failed signature is strictly more alarming than "no match",
         so tampering can never be masked by a co-occurring broad phrase.
      2. Else, a definitive ABSENT phrase -> "unsigned" (silent).
      3. Else exit 0 -> "valid".
      4. Else AMBIGUOUS-only wording (or anything unrecognized) -> "unchecked"
         (silent). We are deliberately conservative: ambiguous output never
         produces a false CRITICAL on a clean unsigned repo, and never falsely
         clears the artifact."""
    if not res["ran"]:
        return "unchecked"
    blob = (res["out"] + " " + res["err"]).lower()
    code = res["code"]

    # 1. Tampering wins regardless of any other co-occurring wording.
    if any(sig in blob for sig in _TAMPERING_SIGNALS):
        return "invalid"

    # 2. Definitively-absent signature -> unsigned (silent), on any exit code.
    if any(sig in blob for sig in _ABSENT_SIGNALS):
        return "unsigned"

    # 3. Clean exit with no absent/tampering notice -> a signature verified.
    if code == 0:
        return "valid"

    # 4. Non-zero with only ambiguous or unrecognized wording -> unchecked
    #    (silent). No tampering phrase was present, so we do NOT CRITICAL.
    return "unchecked"


def probe_npm(repo_path, deadline=None):
    """npm audit signatures: verifies registry signatures/attestations."""
    if not shutil.which("npm"):
        return "unchecked"
    res = _run(["npm", "audit", "signatures", "--json"], cwd=repo_path,
               deadline=deadline)
    if not res["ran"]:
        return "unchecked"
    # npm audit signatures emits structured JSON when it can; fall back to text.
    try:
        data = json.loads(res["out"]) if res["out"].strip() else {}
        invalid = data.get("invalid")
        missing = data.get("missing")
        if isinstance(invalid, list) and invalid:
            return "invalid"
        if isinstance(missing, list) and missing:
            return "unsigned"
        if data:
            return "valid"
    except (ValueError, AttributeError):
        pass
    return _classify_output(res)


def probe_pypi(repo_path, marker, deadline=None):
    """PyPI attestation presence. No network: we look for a local attestation
    sidecar (PEP 740 .publish.attestation) and, if cosign exists, let the
    generic cosign probe run. Absent any sidecar -> unsigned."""
    try:
        for entry in os.listdir(repo_path):
            if entry.endswith(".attestation") or entry.endswith(".publish.attestation"):
                # A present attestation sidecar; if cosign can verify it, great.
                if shutil.which("cosign"):
                    return probe_cosign(repo_path, deadline=deadline)
                return "valid"
    except OSError:
        return "unchecked"
    return "unsigned"


def probe_cosign(repo_path, deadline=None):
    """cosign verify over the artifact dir. Offline / keyless without a bundle
    will non-zero -> we read the message to classify."""
    if not shutil.which("cosign"):
        return "unchecked"
    res = _run(["cosign", "verify", "--offline", repo_path], cwd=repo_path,
               deadline=deadline)
    return _classify_output(res)


def probe_gh(repo_path, deadline=None):
    """gh attestation verify: GitHub artifact attestation (SLSA provenance)."""
    if not shutil.which("gh"):
        return "unchecked"

    def inside_target(path, target):
        try:
            return os.path.commonpath((target, os.path.realpath(path))) == target
        except ValueError:
            # Paths on different Windows drives cannot contain one another.
            return False

    verdict = "unchecked"
    try:
        target = os.path.realpath(repo_path)
        # Check before creating anything. A caller can place TMPDIR inside the
        # scanned tree; even a temporary directory there would mutate it.
        if inside_target(tempfile.gettempdir(), target):
            return "unchecked"
        with tempfile.TemporaryDirectory(prefix="repo-forensics-gh-") as state_dir:
            if inside_target(state_dir, target):
                return "unchecked"
            # gh may resolve config and state paths relative to cwd on Windows
            # when APPDATA/LOCALAPPDATA are absent. Keep every writable location
            # in this disposable directory, never in the scanned artifact.
            env = {**_SAFE_ENV, "HOME": state_dir, "USERPROFILE": state_dir,
                   "APPDATA": state_dir, "LOCALAPPDATA": state_dir,
                   "XDG_CONFIG_HOME": state_dir, "XDG_STATE_HOME": state_dir,
                   "XDG_CACHE_HOME": state_dir, "GH_CONFIG_DIR": state_dir,
                   "TEMP": state_dir, "TMP": state_dir}
            res = _run(["gh", "attestation", "verify", target], cwd=state_dir,
                       deadline=deadline, env=env)
            verdict = _classify_output(res)
    except OSError:
        # No writable isolation directory means no safe gh invocation.
        pass
    return verdict


def _verify(artifact_type, repo_path, marker, offline=False):
    """Run the appropriate probe(s) and collapse to a single verdict.

    Order of precedence across probes: invalid > valid > unsigned > unchecked.
    A CRITICAL-worthy 'invalid' from any probe wins; a single 'valid' clears
    the artifact; 'unsigned' only stands if no probe could verify.

    All probes share ONE wall-clock deadline (TOTAL_BUDGET_SEC). Each tool's
    timeout is clamped to the time remaining, and once the budget is spent we
    STOP probing further tools (they degrade to 'unchecked' = silent). This caps
    the SUM of sequential per-tool timeouts well under the auto_scan ~15s SIGKILL,
    so a hung/PATH-shimmed cosign/gh/npm can never drive us to a silent zero.

    offline=True skips every probe that contacts a registry (npm audit
    signatures, gh attestation verify); those degrade to 'unchecked'. cosign
    already runs with its own --offline flag, so it stays."""
    deadline = _Deadline()
    verdicts = []
    if artifact_type == "npm" and not offline:
        verdicts.append(probe_npm(repo_path, deadline=deadline))
    elif artifact_type == "pypi":
        verdicts.append(probe_pypi(repo_path, marker, deadline=deadline))

    # cosign / gh apply to any artifact type (sigstore/SLSA are ecosystem-wide).
    # Skip a probe outright once the shared budget is exhausted: an unprobed tool
    # is 'unchecked' (silent), which is safe — being SIGKILLed is not.
    if not deadline.expired():
        verdicts.append(probe_cosign(repo_path, deadline=deadline))
    if not offline and not deadline.expired():
        verdicts.append(probe_gh(repo_path, deadline=deadline))

    if "invalid" in verdicts:
        return "invalid"
    if "valid" in verdicts:
        return "valid"
    if "unsigned" in verdicts:
        return "unsigned"
    return "unchecked"


def scan_repo(repo_path, ignore_patterns=None, offline=False):
    """Verify artifact provenance; emit at most ONE finding.

    ignore_patterns is accepted for uniform registration (U5) but provenance is
    an artifact-level check, not a per-file walk, so it is unused.

    repo-forensics makes the expert call here rather than offloading a decision
    to the user: an unsigned third-party artifact is the *normal* state of the
    world today, so alarming on it would fire on nearly every scan and only
    train users to ignore alarms (and it would flip every clean repo off the
    exit-0 contract). The single actionable, expert-worthy signal is a signature
    that is PRESENT but FAILS verification — tampering — which always emits as a
    CRITICAL. Unsigned / verified / unverifiable states are deliberately NOT
    findings: the scanner decided they are not alarm-worthy, like `integrity`
    only firing on drift. No user flag, no opt-in toggle."""
    findings = []

    artifact_type, marker = detect_artifact(repo_path)
    verdict = _verify(artifact_type, repo_path, marker, offline=offline)

    if verdict == "invalid":
        findings.append(core.Finding(
            scanner=SCANNER_NAME, severity="critical",
            title="Artifact signature verification failed",
            description=(
                "A provenance signature/attestation is PRESENT on this "
                f"{artifact_type} artifact but verification FAILED. This is a "
                "tampering signal: the artifact may have been modified after "
                "signing, or signed by an untrusted key."
            ),
            file=marker, line=0,
            snippet="provenance verification failed",
            category="provenance",
        ))

    # verdict in {valid, unsigned, unchecked}: not alarm-worthy. The expert call
    # is to stay silent so clean repos keep a 0 verdict and users are not nagged
    # about the universal unsigned state. Capability is retained for the day
    # signing becomes common; only tampering surfaces today.
    return findings


def main():
    # --offline: skip the probes that contact a registry (npm, gh).
    offline = "--offline" in sys.argv[1:]
    argv = [a for a in sys.argv if a != "--offline"]
    args = core.parse_common_args(argv, "Artifact Provenance / Attestation Scanner")
    repo_path = args.repo_path

    core.emit_status(args.format, f"[*] Checking artifact provenance for {repo_path}...")

    ignore_patterns = core.load_ignore_patterns(repo_path)
    all_findings = scan_repo(repo_path, ignore_patterns, offline=offline)
    core.output_findings(all_findings, args.format, SCANNER_NAME)


if __name__ == "__main__":
    main()
rea-analysis-optimizationmorluto/reaOptimize REA providers and shared analysis workflows for agent context, latency, CPU, and memory while preserving correctness and Evidence. Use for analysis bottlenecks and cache or query design; CI/test-suite optimization belongs to rea-ci-tests-audit.Stars: 472kUpdated Claude CodeCodexVerifiedInstall
rea-ci-tests-auditmorluto/reaAudit REA CI and test suites for correctness, fixture drift, false passes, and measured performance; use for suite or workflow investigations and efficiency changes, rather than ordinary feature testing or a single test failure.Stars: 472kUpdated Claude CodeCodexVerifiedInstall
rea-tool-designmorluto/reaAudit, investigate, design, or change REA investigation tools, CLI/MCP contracts, provider capabilities, and Evidence semantics.Stars: 472kUpdated Claude CodeCodexVerifiedInstall
ponytail-auditDietrichGebert/ponytailQuality audit of the whole repo: bugs, security, real load, missing tests, speed, and what to delete. Most important first.Stars: 194kUpdated Claude CodeCodexVerifiedInstall