feat(valid-detection-benchmark): preserve exact fix-site evidence

This commit is contained in:
Marius Ciepluch
2026-11-16 17:08:05 +01:00
parent 731eb8d24a
commit 00b584a1ac
4 changed files with 529 additions and 10 deletions
@@ -74,7 +74,7 @@
- _Depends: 2.1, 2.2, 2.3_
- [ ] 3. Produce independently reviewed ecosystem and fix-derived ground truth
- [ ] 3.1 Preserve fix-site, repository, ecosystem, language, license, and provenance evidence
- [x] 3.1 Preserve fix-site, repository, ecosystem, language, license, and provenance evidence
- Derive vulnerable and fixed locations from the security-fix file and function at the vulnerable parent and fixed revision without blame walk-back or SZZ introducing-commit inference.
- Retain canonical repository identity, observed language, package ecosystem evidence, license evidence, source evidence, change inputs, and nonzero function bytes.
- Treat concrete frameworks and repositories as evidence only and add no detector vocabulary or implementation behavior.
@@ -418,3 +418,4 @@
- Task 2.2 centralizes the unchanged ten-file historical inventory, records the 2026-10-12 pilot as withdrawn/non-admissible and replacement-pending, and grants audit authority only after external review of exact live path/digest/length bytes; no real review identity is fabricated.
- Task 2.3 projects one immutable reviewed lifecycle chain from the exact withdrawal through replacement completion; retirement and development opening are terminal, with the latter emitting reviewed permanent-reservation influence for every opened network.
- Task 2.4 replaces directory exceptions with a production guard over the fixed `benchmarks`/`plane`/`src`/`tests` scope; reports bind exact read receipts and authorities, and replacement acceptance reruns the complete scope to reject stale or narrowed clean reports.
- Task 3.1 builds non-authoritative fix-site candidates from only the fixed revision and its exact parent, binding nonzero pre/post function bytes and repository/package/language/license/source/change provenance without blame or introducing-commit inference.
+50 -9
View File
@@ -8,13 +8,28 @@ import json
import os
import re
import subprocess
from collections.abc import Callable, Mapping, Sequence
from dataclasses import asdict, is_dataclass
from functools import cache
from pathlib import Path
from typing import Any
from benchmarks.unseen import extract
from benchmarks.unseen.draft import toml
from benchmarks.unseen.eligibility import normalize
from benchmarks.valid.fix_site_catalog import (
EvidenceRef,
FixSiteCandidateV1,
FixSiteCatalogError,
FixSiteReader,
FixSiteRequest,
FunctionSnapshot,
LicenseEvidence,
PackageEcosystemEvidence,
SourceEvidence,
build_fix_site_candidate,
fix_site_candidate_bytes,
)
LANGUAGES = {
".py": "python",
@@ -29,17 +44,17 @@ LANGUAGES = {
}
def local_git(path: Path):
def local_git(path: Path) -> extract.Git:
"""Disable partial-clone lazy fetches while reading existing local objects."""
def runner(argv, **kwargs):
def runner(argv: Sequence[str], **kwargs: Any) -> Any:
return subprocess.run(argv, env={**os.environ, "GIT_NO_LAZY_FETCH": "1", "GIT_TERMINAL_PROMPT": "0"}, **kwargs)
return extract.Git(path, runner=runner)
@cache
def pair_builder():
def pair_builder() -> Any:
path = Path(__file__).resolve().parents[1] / "pairs/advisory-fixes/materialize.py"
spec = importlib.util.spec_from_file_location("valid_pair_builder", path)
if spec is None or spec.loader is None:
@@ -49,9 +64,14 @@ def pair_builder():
return module
def read_functions(git, case: dict, *, report=None) -> dict:
def read_functions(
git: Any,
case: Mapping[str, Any],
*,
report: Callable[[str, int], None] | None = None,
) -> dict[str, Any]:
"""Use the pair builder's function_bounds cutter on both pinned snapshots."""
result = {}
result: dict[str, Any] = {}
for side, sha in (("pre_fix", case["parent"]), ("post_fix", case["commit"])):
source = git.blob(sha, case["path"])
cut = pair_builder().extract(source, case["language"], case["function"]) if source else None
@@ -71,9 +91,9 @@ def read_functions(git, case: dict, *, report=None) -> dict:
return result
def build_cases(git, source, *, cwe: str | None = None, advisory_text: str = "") -> list[dict]:
def build_cases(git: Any, source: Any, *, cwe: str | None = None, advisory_text: str = "") -> list[dict[str, Any]]:
"""Accept source.Candidate or its resolved dictionary, with advisory metadata."""
source = asdict(source) if is_dataclass(source) else dict(source)
source = asdict(source) if is_dataclass(source) and not isinstance(source, type) else dict(source)
repo = normalize(source.get("repository") or source["repo"])
fix, parent = source.get("fix") or source["commit"], source["parent"]
if not extract.SHA.fullmatch(fix) or not extract.SHA.fullmatch(parent) or fix == parent:
@@ -120,7 +140,7 @@ def build_cases(git, source, *, cwe: str | None = None, advisory_text: str = "")
return sorted(rows, key=lambda row: row["id"])
def write_catalog(path: Path, cases: list[dict]) -> None:
def write_catalog(path: Path, cases: list[dict[str, Any]]) -> None:
if len({row["id"] for row in cases}) != len(cases):
raise ValueError("duplicate case id")
text = "\n".join(
@@ -130,7 +150,7 @@ def write_catalog(path: Path, cases: list[dict]) -> None:
path.write_text(text, encoding="utf-8")
def main(argv=None):
def main(argv: Sequence[str] | None = None) -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("sources", type=Path, help="JSON array of resolved Candidate dictionaries with CWE and advisory_text")
parser.add_argument("--repos", type=Path, required=True, help="JSON map of repository names to local Git directories")
@@ -148,3 +168,24 @@ def main(argv=None):
if __name__ == "__main__":
raise SystemExit(main())
__all__ = [
"EvidenceRef",
"FixSiteCandidateV1",
"FixSiteCatalogError",
"FixSiteReader",
"FixSiteRequest",
"FunctionSnapshot",
"LicenseEvidence",
"PackageEcosystemEvidence",
"SourceEvidence",
"build_cases",
"build_fix_site_candidate",
"fix_site_candidate_bytes",
"local_git",
"main",
"pair_builder",
"read_functions",
"write_catalog",
]
+305
View File
@@ -0,0 +1,305 @@
"""Replacement fix-site candidates anchored only to the security-fix pair."""
from __future__ import annotations
import re
from collections.abc import Sequence
from dataclasses import dataclass
from pathlib import PurePosixPath
from typing import Protocol
from benchmarks.unseen.extract import Rejected, functions
from benchmarks.valid.reservation_identity import RepositoryNetworkIdentity
from openultrasast.core.canonical import JsonValue, bytes_digest, canonical_bytes, content_digest
FIX_SITE_CANDIDATE_SCHEMA = "openultrasast.valid-detection-benchmark.fix-site-candidate.v1"
_DIGEST = re.compile(r"[0-9a-f]{64}")
_REVISION = re.compile(r"(?:[0-9a-f]{40}|[0-9a-f]{64})")
_LANGUAGE_BY_SUFFIX = {
".py": "python",
".js": "javascript",
".jsx": "javascript",
".mjs": "javascript",
".cjs": "javascript",
".ts": "typescript",
".tsx": "typescript",
}
class FixSiteCatalogError(ValueError):
"""Fix-site evidence is absent, ambiguous, or inconsistent."""
class FixSiteReader(Protocol):
def parents(self, revision: str) -> Sequence[str]: ...
def blob(self, revision: str, path: str) -> str | None: ...
@dataclass(frozen=True)
class EvidenceRef:
path: str
content_digest: str
byte_length: int
@dataclass(frozen=True)
class PackageEcosystemEvidence:
ecosystem_hint: str
manifest: EvidenceRef
@dataclass(frozen=True)
class LicenseEvidence:
expression: str
source: EvidenceRef
@dataclass(frozen=True)
class SourceEvidence:
source_kind: str
source_locator: str
evidence_digest: str
@dataclass(frozen=True)
class FixSiteRequest:
repository: RepositoryNetworkIdentity
vulnerable_parent: str
fixed_revision: str
path: str
function: str
observed_language: str
package_evidence: PackageEcosystemEvidence
license_evidence: LicenseEvidence
source_evidence: SourceEvidence
change_inputs_digest: str
@dataclass(frozen=True)
class FunctionSnapshot:
revision: str
path: str
function: str
start_line: int
end_line: int
byte_length: int
content_digest: str
content: str
@dataclass(frozen=True)
class FixSiteCandidateV1:
canonical_repository: str
network_identity_digest: str
observed_language: str
package_evidence: PackageEcosystemEvidence
license_evidence: LicenseEvidence
source_evidence: SourceEvidence
change_inputs_digest: str
vulnerable: FunctionSnapshot
fixed: FunctionSnapshot
provenance_digest: str
candidate_digest: str
def _text(value: object, field: str) -> str:
if not isinstance(value, str) or not value.strip():
raise FixSiteCatalogError(f"{field} must be nonempty text")
return value.strip()
def _digest(value: object, field: str) -> str:
if not isinstance(value, str) or _DIGEST.fullmatch(value) is None:
raise FixSiteCatalogError(f"{field} must be a full lowercase SHA-256 digest")
return value
def _revision(value: object, field: str) -> str:
if not isinstance(value, str) or _REVISION.fullmatch(value) is None:
raise FixSiteCatalogError(f"{field} must be a full Git object identity")
return value
def _path(value: object, field: str) -> str:
text = _text(value, field)
path = PurePosixPath(text)
if path.is_absolute() or str(path) != text or any(part in {"", ".", ".."} for part in path.parts):
raise FixSiteCatalogError(f"{field} must be a canonical repository-relative path")
return text
def _evidence_value(reference: EvidenceRef) -> dict[str, JsonValue]:
path = _path(reference.path, "evidence path")
digest = _digest(reference.content_digest, "evidence content digest")
if isinstance(reference.byte_length, bool) or not isinstance(reference.byte_length, int) or reference.byte_length <= 0:
raise FixSiteCatalogError("evidence byte length must be positive")
return {"path": path, "content_digest": digest, "byte_length": reference.byte_length}
def _package_value(evidence: PackageEcosystemEvidence) -> dict[str, JsonValue]:
hint = _text(evidence.ecosystem_hint, "package ecosystem hint")
if hint not in {"python", "javascript", "unresolved"}:
raise FixSiteCatalogError("package ecosystem hint is unsupported")
return {"ecosystem_hint": hint, "manifest": _evidence_value(evidence.manifest)}
def _license_value(evidence: LicenseEvidence) -> dict[str, JsonValue]:
return {"expression": _text(evidence.expression, "license expression"), "source": _evidence_value(evidence.source)}
def _source_value(evidence: SourceEvidence) -> dict[str, JsonValue]:
return {
"source_kind": _text(evidence.source_kind, "source evidence kind"),
"source_locator": _text(evidence.source_locator, "source evidence locator"),
"evidence_digest": _digest(evidence.evidence_digest, "source evidence digest"),
}
def _snapshot_value(snapshot: FunctionSnapshot) -> dict[str, JsonValue]:
if snapshot.start_line <= 0 or snapshot.end_line < snapshot.start_line:
raise FixSiteCatalogError("function line range is invalid")
content = _text(snapshot.content, "function content")
encoded = content.encode("utf-8")
if snapshot.byte_length != len(encoded) or snapshot.content_digest != bytes_digest(encoded):
raise FixSiteCatalogError("function byte receipt does not match content")
return {
"revision": _revision(snapshot.revision, "function revision"),
"path": _path(snapshot.path, "function path"),
"function": _text(snapshot.function, "function name"),
"start_line": snapshot.start_line,
"end_line": snapshot.end_line,
"byte_length": snapshot.byte_length,
"content_digest": snapshot.content_digest,
"content": content,
}
def _provenance_value(candidate: FixSiteCandidateV1) -> dict[str, JsonValue]:
canonical_repository = _text(candidate.canonical_repository, "canonical repository")
network_digest = _digest(candidate.network_identity_digest, "repository network identity digest")
observed_language = _text(candidate.observed_language, "observed language")
vulnerable = _snapshot_value(candidate.vulnerable)
fixed = _snapshot_value(candidate.fixed)
if (candidate.vulnerable.path, candidate.vulnerable.function) != (
candidate.fixed.path,
candidate.fixed.function,
):
raise FixSiteCatalogError("fix-site snapshots do not identify the same file and function")
if candidate.vulnerable.revision == candidate.fixed.revision:
raise FixSiteCatalogError("fix-site revisions must differ")
if _LANGUAGE_BY_SUFFIX.get(PurePosixPath(candidate.vulnerable.path).suffix) != observed_language:
raise FixSiteCatalogError("observed language does not match the fix-site path")
return {
"canonical_repository": canonical_repository,
"network_identity_digest": network_digest,
"observed_language": observed_language,
"package_evidence": _package_value(candidate.package_evidence),
"license_evidence": _license_value(candidate.license_evidence),
"source_evidence": _source_value(candidate.source_evidence),
"change_inputs_digest": _digest(candidate.change_inputs_digest, "change inputs digest"),
"vulnerable": vulnerable,
"fixed": fixed,
}
def _candidate_value(candidate: FixSiteCandidateV1, *, include_digest: bool) -> dict[str, JsonValue]:
value = {"schema_version": FIX_SITE_CANDIDATE_SCHEMA, **_provenance_value(candidate)}
value["provenance_digest"] = candidate.provenance_digest
if include_digest:
value["candidate_digest"] = candidate.candidate_digest
return value
def _snapshot(reader: FixSiteReader, revision: str, path: str, function: str) -> FunctionSnapshot:
source = reader.blob(revision, path)
if source is None:
raise FixSiteCatalogError("fix-site function is unreadable at the exact revision and path")
if not source.strip():
raise FixSiteCatalogError("fix-site source bytes are empty")
try:
matches = [span for span in functions(path, source) if span[0] == function]
except Rejected as error:
raise FixSiteCatalogError("fix-site function is unreadable") from error
if not matches:
raise FixSiteCatalogError("fix-site function is not present at the exact revision and path")
if len(matches) != 1:
raise FixSiteCatalogError("fix-site function is ambiguous")
_, start, end = matches[0]
content = "\n".join(source.splitlines()[start - 1 : end])
if not content.strip():
raise FixSiteCatalogError("fix-site function bytes are empty")
encoded = content.encode("utf-8")
return FunctionSnapshot(revision, path, function, start, end, len(encoded), bytes_digest(encoded), content)
def _validate_request(request: FixSiteRequest) -> tuple[str, str, str, str]:
parent = _revision(request.vulnerable_parent, "vulnerable parent")
fixed = _revision(request.fixed_revision, "fixed revision")
if parent == fixed:
raise FixSiteCatalogError("vulnerable parent and fixed revision must differ")
path = _path(request.path, "fix-site path")
function = _text(request.function, "fix-site function")
language = _text(request.observed_language, "observed language")
if _LANGUAGE_BY_SUFFIX.get(PurePosixPath(path).suffix) != language:
raise FixSiteCatalogError("observed language does not match the fix-site path")
_package_value(request.package_evidence)
_license_value(request.license_evidence)
_source_value(request.source_evidence)
_digest(request.change_inputs_digest, "change inputs digest")
return parent, fixed, path, function
def build_fix_site_candidate(reader: FixSiteReader, request: FixSiteRequest) -> FixSiteCandidateV1:
"""Build evidence from only the exact fix and its supplied parent."""
parent, fixed, path, function = _validate_request(request)
if tuple(reader.parents(fixed)) != (parent,):
raise FixSiteCatalogError("fixed revision does not have the exact vulnerable parent")
vulnerable = _snapshot(reader, parent, path, function)
repaired = _snapshot(reader, fixed, path, function)
if vulnerable.content_digest == repaired.content_digest:
raise FixSiteCatalogError("fix-site function is unchanged across the security fix")
draft = FixSiteCandidateV1(
request.repository.canonical_repository,
request.repository.network_identity_digest,
request.observed_language,
request.package_evidence,
request.license_evidence,
request.source_evidence,
request.change_inputs_digest,
vulnerable,
repaired,
"",
"",
)
provenance = content_digest(_provenance_value(draft))
reviewed = FixSiteCandidateV1(**{**vars(draft), "provenance_digest": provenance})
candidate = FixSiteCandidateV1(
**{**vars(reviewed), "candidate_digest": content_digest(_candidate_value(reviewed, include_digest=False))}
)
fix_site_candidate_bytes(candidate)
return candidate
def fix_site_candidate_bytes(candidate: FixSiteCandidateV1) -> bytes:
"""Validate and encode a candidate for later independent review."""
if candidate.provenance_digest != content_digest(_provenance_value(candidate)):
raise FixSiteCatalogError("fix-site provenance digest does not match")
if candidate.candidate_digest != content_digest(_candidate_value(candidate, include_digest=False)):
raise FixSiteCatalogError("fix-site candidate digest does not match")
return canonical_bytes(_candidate_value(candidate, include_digest=True))
__all__ = [
"EvidenceRef",
"FixSiteCandidateV1",
"FixSiteCatalogError",
"FixSiteReader",
"FixSiteRequest",
"FunctionSnapshot",
"LicenseEvidence",
"PackageEcosystemEvidence",
"SourceEvidence",
"build_fix_site_candidate",
"fix_site_candidate_bytes",
]
@@ -0,0 +1,172 @@
"""Replacement fix-site catalog remains anchored to the exact security fix."""
from __future__ import annotations
import subprocess
import sys
from dataclasses import replace
from pathlib import Path
import pytest
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from benchmarks.valid import catalog as catalog_facade # noqa: E402
from benchmarks.valid import fix_site_catalog as catalog # noqa: E402
from benchmarks.valid.reservation import build_network_identity # noqa: E402
from openultrasast.core.canonical import content_digest # noqa: E402
PARENT = "1" * 40
FIX = "2" * 40
class FixtureReader:
def __init__(self, blobs: dict[tuple[str, str], str | None], parents: tuple[str, ...] = (PARENT,)) -> None:
self.blobs = blobs
self.fixed_parents = parents
self.calls: list[tuple[str, ...]] = []
def parents(self, revision: str) -> tuple[str, ...]:
self.calls.append(("parents", revision))
return self.fixed_parents
def blob(self, revision: str, path: str) -> str | None:
self.calls.append(("blob", revision, path))
return self.blobs.get((revision, path))
def blame(self, *_args: object) -> None:
raise AssertionError("SZZ/blame is outside the fix-site catalog boundary")
def _ref(path: str, text: str) -> catalog.EvidenceRef:
return catalog.EvidenceRef(path, content_digest(text), len(text.encode()))
def _request(**changes: object) -> catalog.FixSiteRequest:
value = catalog.FixSiteRequest(
repository=build_network_identity("https://github.com/example/application"),
vulnerable_parent=PARENT,
fixed_revision=FIX,
path="src/service.py",
function="handle",
observed_language="python",
package_evidence=catalog.PackageEcosystemEvidence("python", _ref("pyproject.toml", "[project]")),
license_evidence=catalog.LicenseEvidence("Apache-2.0", _ref("LICENSE", "license text")),
source_evidence=catalog.SourceEvidence("advisory", "GHSA-test-test-test", content_digest("advisory")),
change_inputs_digest=content_digest("exact diff inputs"),
)
return replace(value, **changes)
def _reader(pre: str | None = None, post: str | None = None) -> FixtureReader:
pre = pre if pre is not None else "def handle(value):\n return dangerous(value)\n"
post = post if post is not None else "def handle(value):\n return safe(value)\n"
return FixtureReader({(PARENT, "src/service.py"): pre, (FIX, "src/service.py"): post})
def test_candidate_preserves_exact_fix_pair_and_provenance() -> None:
reader = _reader()
candidate = catalog.build_fix_site_candidate(reader, _request())
assert candidate.vulnerable.revision == PARENT
assert candidate.fixed.revision == FIX
assert candidate.vulnerable.content == "def handle(value):\n return dangerous(value)"
assert candidate.fixed.content == "def handle(value):\n return safe(value)"
assert candidate.canonical_repository == "https://github.com/example/application"
assert candidate.package_evidence.ecosystem_hint == "python"
assert candidate.license_evidence.expression == "Apache-2.0"
assert candidate.source_evidence.source_kind == "advisory"
assert candidate.provenance_digest and candidate.candidate_digest
assert reader.calls == [
("parents", FIX),
("blob", PARENT, "src/service.py"),
("blob", FIX, "src/service.py"),
]
def test_local_git_fixture_reads_exact_parent_and_fix_objects(tmp_path: Path) -> None:
subprocess.run(["git", "init", "-q", str(tmp_path)], check=True)
subprocess.run(["git", "-C", str(tmp_path), "config", "user.email", "[email protected]"], check=True)
subprocess.run(["git", "-C", str(tmp_path), "config", "user.name", "Fixture"], check=True)
source = tmp_path / "src/service.py"
source.parent.mkdir()
source.write_text("def handle(value):\n return dangerous(value)\n")
subprocess.run(["git", "-C", str(tmp_path), "add", "src/service.py"], check=True)
subprocess.run(["git", "-C", str(tmp_path), "commit", "-qm", "vulnerable"], check=True)
parent = subprocess.run(["git", "-C", str(tmp_path), "rev-parse", "HEAD"], check=True, capture_output=True, text=True).stdout.strip()
source.write_text("def handle(value):\n return safe(value)\n")
subprocess.run(["git", "-C", str(tmp_path), "commit", "-qam", "security fix"], check=True)
fixed = subprocess.run(["git", "-C", str(tmp_path), "rev-parse", "HEAD"], check=True, capture_output=True, text=True).stdout.strip()
reader = catalog_facade.local_git(tmp_path)
candidate = catalog.build_fix_site_candidate(
reader,
_request(vulnerable_parent=parent, fixed_revision=fixed),
)
assert candidate.vulnerable.content.endswith("dangerous(value)")
assert candidate.fixed.content.endswith("safe(value)")
assert reader.files_read == 2
assert reader.bytes_read > 0
def test_equal_inputs_produce_equal_candidate_identity() -> None:
first = catalog.build_fix_site_candidate(_reader(), _request())
second = catalog.build_fix_site_candidate(_reader(), _request())
assert first == second
assert catalog.fix_site_candidate_bytes(first) == catalog.fix_site_candidate_bytes(second)
def test_changed_function_bytes_cannot_reuse_candidate_identity() -> None:
candidate = catalog.build_fix_site_candidate(_reader(), _request())
changed = replace(candidate.vulnerable, content=candidate.vulnerable.content + "\n# changed")
with pytest.raises(catalog.FixSiteCatalogError, match="receipt"):
catalog.fix_site_candidate_bytes(replace(candidate, vulnerable=changed))
@pytest.mark.parametrize(
"reader,fix_request,message",
(
(_reader(), _request(vulnerable_parent="3" * 40), "parent"),
(_reader(pre=""), _request(), "empty"),
(FixtureReader({(FIX, "src/service.py"): "def handle():\n pass\n"}), _request(), "unreadable"),
(_reader(pre="def handle():\n pass\ndef handle():\n pass\n"), _request(), "ambiguous"),
(_reader(), _request(path="../service.py"), "path"),
(_reader(), _request(function="missing"), "function"),
),
)
def test_invalid_or_unreadable_fix_sites_are_refused(reader: FixtureReader, fix_request: catalog.FixSiteRequest, message: str) -> None:
with pytest.raises(catalog.FixSiteCatalogError, match=message):
catalog.build_fix_site_candidate(reader, fix_request)
def test_rename_is_not_inferred_across_the_fix() -> None:
reader = FixtureReader(
{
(PARENT, "src/old.py"): "def handle():\n return 1\n",
(FIX, "src/service.py"): "def handle():\n return 2\n",
}
)
with pytest.raises(catalog.FixSiteCatalogError, match="unreadable"):
catalog.build_fix_site_candidate(reader, _request())
def test_typescript_is_observed_language_with_javascript_package_evidence() -> None:
request = _request(
path="src/service.ts",
function="handle",
observed_language="typescript",
package_evidence=catalog.PackageEcosystemEvidence("javascript", _ref("package.json", "{}")),
)
reader = FixtureReader(
{
(PARENT, "src/service.ts"): "function handle(value) { return dangerous(value); }\n",
(FIX, "src/service.ts"): "function handle(value) { return safe(value); }\n",
}
)
assert catalog.build_fix_site_candidate(reader, request).observed_language == "typescript"
def test_catalog_surface_has_no_szz_or_introducing_commit_operation() -> None:
assert not {"blame", "introducing", "introducing_revision"} & set(catalog.FixSiteReader.__dict__)