mirror of
https://github.com/norandom/OpenUltraSAST.git
synced 2026-12-03 02:08:18 +00:00
feat(valid-detection-benchmark): enforce permanent reservation guard
This commit is contained in:
@@ -64,7 +64,7 @@
|
|||||||
- Done when duplicate equal events are idempotent, forks and missing predecessors fail, terminal states cannot be undone, and only an active replacement-complete projection is admission eligible.
|
- Done when duplicate equal events are idempotent, forks and missing predecessors fail, terminal states cannot be undone, and only an active replacement-complete projection is admission eligible.
|
||||||
- _Requirements: 3.6, 4.7, 4.9, 5.1, 5.2, 5.6, 7.7_
|
- _Requirements: 3.6, 4.7, 4.9, 5.1, 5.2, 5.6, 7.7_
|
||||||
- _Boundary: Baseline Lifecycle Authority_
|
- _Boundary: Baseline Lifecycle Authority_
|
||||||
- [ ] 2.4 Route the permanent-reservation guard through exact reviewed authority
|
- [x] 2.4 Route the permanent-reservation guard through exact reviewed authority
|
||||||
- Replace test-owned exception logic with the reservation census and exact historical authorization contracts.
|
- Replace test-owned exception logic with the reservation census and exact historical authorization contracts.
|
||||||
- Require the replacement population to pass canonical identity, alias/fork, influence, and historical-file checks before acceptance.
|
- Require the replacement population to pass canonical identity, alias/fork, influence, and historical-file checks before acceptance.
|
||||||
- Preserve the guard's nonzero repository census and report every forbidden reference without treating an unread tree as zero.
|
- Preserve the guard's nonzero repository census and report every forbidden reference without treating an unread tree as zero.
|
||||||
@@ -417,3 +417,4 @@
|
|||||||
- Task 2.1 projects independently reviewed influence and explicit authoritative legacy sources through canonical alias/former-name/redirect/fork networks; enumeration remains recorded but non-reserving, and the legacy test-owned guard remains pending Task 2.4 migration.
|
- Task 2.1 projects independently reviewed influence and explicit authoritative legacy sources through canonical alias/former-name/redirect/fork networks; enumeration remains recorded but non-reserving, and the legacy test-owned guard remains pending Task 2.4 migration.
|
||||||
- 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.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.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.
|
||||||
|
|||||||
@@ -390,6 +390,17 @@ class ReservationAuthority:
|
|||||||
return False
|
return False
|
||||||
return network.network_identity_digest in census.reserved_network_digests
|
return network.network_identity_digest in census.reserved_network_digests
|
||||||
|
|
||||||
|
def resolve_repository(self, repository: str) -> RepositoryNetworkIdentity:
|
||||||
|
"""Resolve a candidate through the reviewed canonical network registry."""
|
||||||
|
return self._resolver.resolve(repository)
|
||||||
|
|
||||||
|
def legacy_source_network_digest(self, legacy_source_digest: str) -> str:
|
||||||
|
"""Resolve one accepted legacy-source identity to its canonical network."""
|
||||||
|
try:
|
||||||
|
return self._legacy_by_digest[legacy_source_digest].network_identity_digest
|
||||||
|
except KeyError as error:
|
||||||
|
raise ReservationError("legacy source identity is not accepted") from error
|
||||||
|
|
||||||
|
|
||||||
__all__ = [
|
__all__ = [
|
||||||
"InfluenceDisposition",
|
"InfluenceDisposition",
|
||||||
|
|||||||
@@ -0,0 +1,438 @@
|
|||||||
|
"""Production permanent-reservation guard over exact reviewed authority."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import re
|
||||||
|
from dataclasses import dataclass
|
||||||
|
from hashlib import sha256
|
||||||
|
from pathlib import Path, PurePosixPath
|
||||||
|
|
||||||
|
from benchmarks.valid.historical_authorization import (
|
||||||
|
HistoricalAuthorizationError,
|
||||||
|
HistoricalWithdrawalV1,
|
||||||
|
authorize_historical_path,
|
||||||
|
withdrawal_bytes,
|
||||||
|
)
|
||||||
|
from benchmarks.valid.lifecycle import PopulationLifecycleProjectionV1, PopulationLifecycleState
|
||||||
|
from benchmarks.valid.lifecycle_projection import projection_bytes
|
||||||
|
from benchmarks.valid.replacement_artifact_contract import canonical_json_bytes
|
||||||
|
from benchmarks.valid.reservation import (
|
||||||
|
ReservationAuthority,
|
||||||
|
ReservationCensusV1,
|
||||||
|
ReservationError,
|
||||||
|
census_bytes,
|
||||||
|
)
|
||||||
|
from benchmarks.valid.reservation_guard_sources import PINNED_LEGACY_RESERVATION_SOURCE_DIGESTS
|
||||||
|
from openultrasast.core.canonical import JsonValue, content_digest
|
||||||
|
|
||||||
|
GUARD_REPORT_SCHEMA = "openultrasast.valid-detection-benchmark.reservation-guard.v1"
|
||||||
|
REPLACEMENT_ACCEPTANCE_SCHEMA = "openultrasast.valid-detection-benchmark.reservation-acceptance.v1"
|
||||||
|
PRODUCTION_GUARD_SCAN_ROOTS = ("benchmarks", "plane", "src", "tests")
|
||||||
|
_DIGEST = re.compile(r"[0-9a-f]{64}")
|
||||||
|
_REPOSITORY = re.compile(
|
||||||
|
rb"github\.com/([A-Za-z0-9_.-]*[A-Za-z0-9_-]/[A-Za-z0-9_.-]*[A-Za-z0-9_-])(?:\.git)?"
|
||||||
|
rb"(?=[./?\#\s\"'<>),;:\]\}]|$)",
|
||||||
|
re.IGNORECASE,
|
||||||
|
)
|
||||||
|
_SKIPPED_SUFFIXES = frozenset({".bin", ".gz", ".pyc"})
|
||||||
|
|
||||||
|
|
||||||
|
class ReservationGuardError(ValueError):
|
||||||
|
"""The permanent-reservation guard could not establish a clean result."""
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class ExactReservationSourceV1:
|
||||||
|
path: str
|
||||||
|
byte_length: int
|
||||||
|
content_digest: str
|
||||||
|
legacy_source_digests: tuple[str, ...]
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True, order=True)
|
||||||
|
class ForbiddenReservationReferenceV1:
|
||||||
|
path: str
|
||||||
|
repository: str
|
||||||
|
network_identity_digest: str
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class ReservationGuardReportV1:
|
||||||
|
files_read: int
|
||||||
|
bytes_read: int
|
||||||
|
reserved_network_count: int
|
||||||
|
census_digest: str
|
||||||
|
scan_roots: tuple[str, ...]
|
||||||
|
input_receipt_digest: str
|
||||||
|
reservation_source_digests: tuple[str, ...]
|
||||||
|
historical_withdrawal_digest: str | None
|
||||||
|
violations: tuple[ForbiddenReservationReferenceV1, ...]
|
||||||
|
report_digest: str
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class ReplacementReservationAcceptanceV1:
|
||||||
|
population_digest: str
|
||||||
|
freeze_digest: str
|
||||||
|
census_digest: str
|
||||||
|
guard_report_digest: str
|
||||||
|
lifecycle_projection_digest: str
|
||||||
|
network_identity_digests: tuple[str, ...]
|
||||||
|
historical_paths: tuple[str, ...]
|
||||||
|
acceptance_digest: str
|
||||||
|
|
||||||
|
|
||||||
|
def _path(value: str) -> str:
|
||||||
|
candidate = PurePosixPath(value)
|
||||||
|
if not value or candidate.is_absolute() or str(candidate) != value or ".." in candidate.parts:
|
||||||
|
raise ReservationGuardError("guard path must be canonical repository-relative POSIX")
|
||||||
|
return value
|
||||||
|
|
||||||
|
|
||||||
|
def _digest(value: str, field: str) -> str:
|
||||||
|
if not isinstance(value, str) or _DIGEST.fullmatch(value) is None:
|
||||||
|
raise ReservationGuardError(f"{field} must be a full lowercase SHA-256 digest")
|
||||||
|
return value
|
||||||
|
|
||||||
|
|
||||||
|
def _read(root: Path, relative: str) -> bytes:
|
||||||
|
path = _path(relative)
|
||||||
|
resolved_root = root.resolve()
|
||||||
|
target = root / path
|
||||||
|
if target.is_symlink() or not target.is_file() or not target.resolve().is_relative_to(resolved_root):
|
||||||
|
raise ReservationGuardError("guard input must resolve to a regular repository file")
|
||||||
|
try:
|
||||||
|
content = target.read_bytes()
|
||||||
|
except OSError as error:
|
||||||
|
raise ReservationGuardError("guard input is unreadable") from error
|
||||||
|
return content
|
||||||
|
|
||||||
|
|
||||||
|
def exact_reservation_source(
|
||||||
|
root: Path,
|
||||||
|
relative_path: str,
|
||||||
|
legacy_source_digests: tuple[str, ...],
|
||||||
|
) -> ExactReservationSourceV1:
|
||||||
|
"""Bind one exact source file to census-carried legacy authorities."""
|
||||||
|
content = _read(root, relative_path)
|
||||||
|
if not content:
|
||||||
|
raise ReservationGuardError("reservation source read zero bytes")
|
||||||
|
digests = tuple(sorted(set(legacy_source_digests)))
|
||||||
|
if not digests:
|
||||||
|
raise ReservationGuardError("reservation source lacks legacy authorities")
|
||||||
|
for digest in digests:
|
||||||
|
_digest(digest, "legacy source digest")
|
||||||
|
return ExactReservationSourceV1(relative_path, len(content), sha256(content).hexdigest(), digests)
|
||||||
|
|
||||||
|
|
||||||
|
def _validate_sources(
|
||||||
|
root: Path,
|
||||||
|
authority: ReservationAuthority,
|
||||||
|
census: ReservationCensusV1,
|
||||||
|
sources: tuple[ExactReservationSourceV1, ...],
|
||||||
|
) -> tuple[dict[str, frozenset[str]], tuple[str, ...]]:
|
||||||
|
allowed: dict[str, frozenset[str]] = {}
|
||||||
|
identities: list[str] = []
|
||||||
|
for source in sources:
|
||||||
|
path = _path(source.path)
|
||||||
|
if path in allowed:
|
||||||
|
raise ReservationGuardError("reservation source path is duplicated")
|
||||||
|
content = _read(root, path)
|
||||||
|
if not content or len(content) != source.byte_length or sha256(content).hexdigest() != source.content_digest:
|
||||||
|
raise ReservationGuardError("reservation source bytes changed")
|
||||||
|
if not source.legacy_source_digests or not set(source.legacy_source_digests) <= set(census.legacy_source_digests):
|
||||||
|
raise ReservationGuardError("reservation source is not bound to the census")
|
||||||
|
try:
|
||||||
|
networks = frozenset(authority.legacy_source_network_digest(digest) for digest in source.legacy_source_digests)
|
||||||
|
except ReservationError as error:
|
||||||
|
raise ReservationGuardError("reservation source identity is not accepted") from error
|
||||||
|
allowed[path] = networks
|
||||||
|
identities.append(
|
||||||
|
content_digest(
|
||||||
|
{
|
||||||
|
"path": path,
|
||||||
|
"byte_length": source.byte_length,
|
||||||
|
"content_digest": source.content_digest,
|
||||||
|
"legacy_source_digests": source.legacy_source_digests,
|
||||||
|
}
|
||||||
|
)
|
||||||
|
)
|
||||||
|
return allowed, tuple(sorted(identities))
|
||||||
|
|
||||||
|
|
||||||
|
def _historical_paths(root: Path, withdrawal: HistoricalWithdrawalV1 | None) -> tuple[frozenset[str], str | None]:
|
||||||
|
if withdrawal is None:
|
||||||
|
return frozenset(), None
|
||||||
|
withdrawal_bytes(withdrawal)
|
||||||
|
allowed: set[str] = set()
|
||||||
|
for entry in withdrawal.candidate.entries:
|
||||||
|
try:
|
||||||
|
authorize_historical_path(root, entry.path, entry.content_digest, withdrawal)
|
||||||
|
except HistoricalAuthorizationError as error:
|
||||||
|
raise ReservationGuardError("reviewed historical path or digest changed") from error
|
||||||
|
allowed.add(entry.path)
|
||||||
|
return frozenset(allowed), withdrawal.withdrawal_digest
|
||||||
|
|
||||||
|
|
||||||
|
def _repository_matches(content: bytes) -> tuple[str, ...]:
|
||||||
|
values = {match.group(1).decode("ascii").removesuffix(".git") for match in _REPOSITORY.finditer(content)}
|
||||||
|
return tuple(sorted(f"https://github.com/{value}" for value in values))
|
||||||
|
|
||||||
|
|
||||||
|
def _scan_scope(roots: tuple[str, ...]) -> tuple[str, ...]:
|
||||||
|
canonical = tuple(sorted({_path(root) for root in roots}))
|
||||||
|
if canonical != PRODUCTION_GUARD_SCAN_ROOTS:
|
||||||
|
raise ReservationGuardError("production guard scan scope is incomplete or unsupported")
|
||||||
|
return PRODUCTION_GUARD_SCAN_ROOTS
|
||||||
|
|
||||||
|
|
||||||
|
def _scan_files(root: Path, roots: tuple[str, ...]) -> tuple[tuple[str, bytes], ...]:
|
||||||
|
collected: list[tuple[str, bytes]] = []
|
||||||
|
seen: set[str] = set()
|
||||||
|
for relative_root in roots:
|
||||||
|
base = root / _path(relative_root)
|
||||||
|
if base.is_symlink() or not base.is_dir():
|
||||||
|
raise ReservationGuardError("guard scan root is unreadable or not a directory")
|
||||||
|
for path in sorted(base.rglob("*")):
|
||||||
|
if path.is_symlink():
|
||||||
|
raise ReservationGuardError("guard scan contains a symlink")
|
||||||
|
if not path.is_file() or path.suffix in _SKIPPED_SUFFIXES:
|
||||||
|
continue
|
||||||
|
relative = path.relative_to(root).as_posix()
|
||||||
|
if relative in seen:
|
||||||
|
raise ReservationGuardError("guard scan roots overlap")
|
||||||
|
seen.add(relative)
|
||||||
|
collected.append((relative, _read(root, relative)))
|
||||||
|
if not collected or sum(len(content) for _, content in collected) <= 0:
|
||||||
|
raise ReservationGuardError("guard scan read zero repository bytes")
|
||||||
|
return tuple(collected)
|
||||||
|
|
||||||
|
|
||||||
|
def _input_receipt_digest(files: tuple[tuple[str, bytes], ...]) -> str:
|
||||||
|
receipts: tuple[JsonValue, ...] = tuple(
|
||||||
|
{"path": path, "byte_length": len(content), "content_digest": sha256(content).hexdigest()}
|
||||||
|
for path, content in sorted(files, key=lambda item: item[0])
|
||||||
|
)
|
||||||
|
return content_digest({"files": receipts})
|
||||||
|
|
||||||
|
|
||||||
|
def _report_value(report: ReservationGuardReportV1, *, include_digest: bool) -> dict[str, JsonValue]:
|
||||||
|
value: dict[str, JsonValue] = {
|
||||||
|
"schema_version": GUARD_REPORT_SCHEMA,
|
||||||
|
"files_read": report.files_read,
|
||||||
|
"bytes_read": report.bytes_read,
|
||||||
|
"reserved_network_count": report.reserved_network_count,
|
||||||
|
"census_digest": report.census_digest,
|
||||||
|
"scan_roots": report.scan_roots,
|
||||||
|
"input_receipt_digest": report.input_receipt_digest,
|
||||||
|
"reservation_source_digests": report.reservation_source_digests,
|
||||||
|
"historical_withdrawal_digest": report.historical_withdrawal_digest,
|
||||||
|
"violations": tuple(
|
||||||
|
{
|
||||||
|
"path": item.path,
|
||||||
|
"repository": item.repository,
|
||||||
|
"network_identity_digest": item.network_identity_digest,
|
||||||
|
}
|
||||||
|
for item in report.violations
|
||||||
|
),
|
||||||
|
}
|
||||||
|
if include_digest:
|
||||||
|
value["report_digest"] = report.report_digest
|
||||||
|
return value
|
||||||
|
|
||||||
|
|
||||||
|
def guard_report_bytes(report: ReservationGuardReportV1) -> bytes:
|
||||||
|
if report.files_read <= 0 or report.bytes_read <= 0 or report.reserved_network_count <= 0:
|
||||||
|
raise ReservationGuardError("guard report lacks nonzero instrument proof")
|
||||||
|
_digest(report.census_digest, "guard census digest")
|
||||||
|
if report.scan_roots != _scan_scope(report.scan_roots):
|
||||||
|
raise ReservationGuardError("guard scan roots are not canonical")
|
||||||
|
_digest(report.input_receipt_digest, "guard input receipt digest")
|
||||||
|
if report.reservation_source_digests != tuple(sorted(set(report.reservation_source_digests))):
|
||||||
|
raise ReservationGuardError("guard source identities are not canonical")
|
||||||
|
for digest in report.reservation_source_digests:
|
||||||
|
_digest(digest, "guard source identity")
|
||||||
|
if report.historical_withdrawal_digest is not None:
|
||||||
|
_digest(report.historical_withdrawal_digest, "guard historical withdrawal digest")
|
||||||
|
if report.violations != tuple(sorted(set(report.violations))):
|
||||||
|
raise ReservationGuardError("guard violations are not canonical")
|
||||||
|
if report.report_digest != content_digest(_report_value(report, include_digest=False)):
|
||||||
|
raise ReservationGuardError("guard report digest does not match")
|
||||||
|
return canonical_json_bytes(_report_value(report, include_digest=True))
|
||||||
|
|
||||||
|
|
||||||
|
def scan_permanent_reservations(
|
||||||
|
root: Path,
|
||||||
|
*,
|
||||||
|
scan_roots: tuple[str, ...],
|
||||||
|
authority: ReservationAuthority,
|
||||||
|
census: ReservationCensusV1,
|
||||||
|
reservation_sources: tuple[ExactReservationSourceV1, ...] = (),
|
||||||
|
historical_withdrawal: HistoricalWithdrawalV1 | None = None,
|
||||||
|
) -> ReservationGuardReportV1:
|
||||||
|
"""Report every reserved reference outside exact authority-bearing files."""
|
||||||
|
census_content = census_bytes(census)
|
||||||
|
if not census_content or not census.reserved_network_digests:
|
||||||
|
raise ReservationGuardError("guard reservation census is empty")
|
||||||
|
roots = _scan_scope(scan_roots)
|
||||||
|
source_networks, source_digests = _validate_sources(root, authority, census, reservation_sources)
|
||||||
|
historical_paths, historical_digest = _historical_paths(root, historical_withdrawal)
|
||||||
|
files = _scan_files(root, roots)
|
||||||
|
violations: set[ForbiddenReservationReferenceV1] = set()
|
||||||
|
for path, content in files:
|
||||||
|
for repository in _repository_matches(content):
|
||||||
|
if authority.is_reserved(repository, census):
|
||||||
|
network = authority.resolve_repository(repository)
|
||||||
|
if path in historical_paths or network.network_identity_digest in source_networks.get(path, frozenset()):
|
||||||
|
continue
|
||||||
|
violations.add(ForbiddenReservationReferenceV1(path, repository, network.network_identity_digest))
|
||||||
|
draft = ReservationGuardReportV1(
|
||||||
|
files_read=len(files),
|
||||||
|
bytes_read=sum(len(content) for _, content in files),
|
||||||
|
reserved_network_count=len(census.reserved_network_digests),
|
||||||
|
census_digest=census.census_digest,
|
||||||
|
scan_roots=roots,
|
||||||
|
input_receipt_digest=_input_receipt_digest(files),
|
||||||
|
reservation_source_digests=source_digests,
|
||||||
|
historical_withdrawal_digest=historical_digest,
|
||||||
|
violations=tuple(sorted(violations)),
|
||||||
|
report_digest="",
|
||||||
|
)
|
||||||
|
report = ReservationGuardReportV1(**{**vars(draft), "report_digest": content_digest(_report_value(draft, include_digest=False))})
|
||||||
|
guard_report_bytes(report)
|
||||||
|
return report
|
||||||
|
|
||||||
|
|
||||||
|
def require_clean_guard(report: ReservationGuardReportV1) -> None:
|
||||||
|
guard_report_bytes(report)
|
||||||
|
if report.violations:
|
||||||
|
raise ReservationGuardError(f"permanent reservation references forbidden: count={len(report.violations)}")
|
||||||
|
|
||||||
|
|
||||||
|
def _acceptance_value(value: ReplacementReservationAcceptanceV1, *, include_digest: bool) -> dict[str, JsonValue]:
|
||||||
|
result: dict[str, JsonValue] = {
|
||||||
|
"schema_version": REPLACEMENT_ACCEPTANCE_SCHEMA,
|
||||||
|
"population_digest": value.population_digest,
|
||||||
|
"freeze_digest": value.freeze_digest,
|
||||||
|
"census_digest": value.census_digest,
|
||||||
|
"guard_report_digest": value.guard_report_digest,
|
||||||
|
"lifecycle_projection_digest": value.lifecycle_projection_digest,
|
||||||
|
"network_identity_digests": value.network_identity_digests,
|
||||||
|
"historical_paths": value.historical_paths,
|
||||||
|
}
|
||||||
|
if include_digest:
|
||||||
|
result["acceptance_digest"] = value.acceptance_digest
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
def _replacement_networks(repositories: tuple[str, ...], authority: ReservationAuthority, census: ReservationCensusV1) -> tuple[str, ...]:
|
||||||
|
if not repositories:
|
||||||
|
raise ReservationGuardError("replacement repository census is empty")
|
||||||
|
networks: set[str] = set()
|
||||||
|
for repository in repositories:
|
||||||
|
try:
|
||||||
|
network = authority.resolve_repository(repository)
|
||||||
|
except ReservationError as error:
|
||||||
|
raise ReservationGuardError("replacement repository identity is unresolved") from error
|
||||||
|
if network.network_identity_digest in census.reserved_network_digests:
|
||||||
|
raise ReservationGuardError("replacement repository resolves to permanent reservation")
|
||||||
|
networks.add(network.network_identity_digest)
|
||||||
|
return tuple(sorted(networks))
|
||||||
|
|
||||||
|
|
||||||
|
def _replacement_history(
|
||||||
|
root: Path,
|
||||||
|
withdrawal: HistoricalWithdrawalV1,
|
||||||
|
requests: tuple[tuple[str, str], ...],
|
||||||
|
) -> tuple[str, ...]:
|
||||||
|
paths: set[str] = set()
|
||||||
|
for path, digest in requests:
|
||||||
|
try:
|
||||||
|
authorize_historical_path(root, path, digest, withdrawal)
|
||||||
|
except HistoricalAuthorizationError as error:
|
||||||
|
raise ReservationGuardError("replacement historical reference is not exactly authorized") from error
|
||||||
|
paths.add(_path(path))
|
||||||
|
return tuple(sorted(paths))
|
||||||
|
|
||||||
|
|
||||||
|
def _require_current_report(
|
||||||
|
root: Path,
|
||||||
|
report: ReservationGuardReportV1,
|
||||||
|
authority: ReservationAuthority,
|
||||||
|
census: ReservationCensusV1,
|
||||||
|
sources: tuple[ExactReservationSourceV1, ...],
|
||||||
|
withdrawal: HistoricalWithdrawalV1,
|
||||||
|
) -> None:
|
||||||
|
current = scan_permanent_reservations(
|
||||||
|
root,
|
||||||
|
scan_roots=PRODUCTION_GUARD_SCAN_ROOTS,
|
||||||
|
authority=authority,
|
||||||
|
census=census,
|
||||||
|
reservation_sources=sources,
|
||||||
|
historical_withdrawal=withdrawal,
|
||||||
|
)
|
||||||
|
if current != report:
|
||||||
|
raise ReservationGuardError("replacement guard report is stale or the scanned authority changed")
|
||||||
|
require_clean_guard(current)
|
||||||
|
|
||||||
|
|
||||||
|
def validate_replacement_population(
|
||||||
|
root: Path,
|
||||||
|
*,
|
||||||
|
repositories: tuple[str, ...],
|
||||||
|
population_digest: str,
|
||||||
|
freeze_digest: str,
|
||||||
|
lifecycle: PopulationLifecycleProjectionV1,
|
||||||
|
guard_report: ReservationGuardReportV1,
|
||||||
|
authority: ReservationAuthority,
|
||||||
|
census: ReservationCensusV1,
|
||||||
|
historical_withdrawal: HistoricalWithdrawalV1,
|
||||||
|
reservation_sources: tuple[ExactReservationSourceV1, ...] = (),
|
||||||
|
historical_requests: tuple[tuple[str, str], ...] = (),
|
||||||
|
) -> ReplacementReservationAcceptanceV1:
|
||||||
|
"""Accept only one resolved, unreserved, lifecycle-eligible replacement."""
|
||||||
|
census_bytes(census)
|
||||||
|
require_clean_guard(guard_report)
|
||||||
|
if guard_report.census_digest != census.census_digest:
|
||||||
|
raise ReservationGuardError("replacement guard report does not bind the census")
|
||||||
|
if guard_report.reserved_network_count != len(census.reserved_network_digests):
|
||||||
|
raise ReservationGuardError("replacement guard report census count does not match")
|
||||||
|
_require_current_report(root, guard_report, authority, census, reservation_sources, historical_withdrawal)
|
||||||
|
projection_bytes(lifecycle)
|
||||||
|
population = _digest(population_digest, "population digest")
|
||||||
|
freeze = _digest(freeze_digest, "freeze digest")
|
||||||
|
if lifecycle.state is not PopulationLifecycleState.REPLACEMENT_COMPLETE or not lifecycle.admission_eligible:
|
||||||
|
raise ReservationGuardError("replacement lifecycle is not admission eligible")
|
||||||
|
if (lifecycle.population_digest, lifecycle.freeze_digest) != (population, freeze):
|
||||||
|
raise ReservationGuardError("replacement lifecycle identity does not match")
|
||||||
|
networks = _replacement_networks(repositories, authority, census)
|
||||||
|
paths = _replacement_history(root, historical_withdrawal, historical_requests)
|
||||||
|
draft = ReplacementReservationAcceptanceV1(
|
||||||
|
population,
|
||||||
|
freeze,
|
||||||
|
census.census_digest,
|
||||||
|
guard_report.report_digest,
|
||||||
|
lifecycle.projection_digest,
|
||||||
|
networks,
|
||||||
|
paths,
|
||||||
|
"",
|
||||||
|
)
|
||||||
|
return ReplacementReservationAcceptanceV1(
|
||||||
|
**{**vars(draft), "acceptance_digest": content_digest(_acceptance_value(draft, include_digest=False))}
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
__all__ = [
|
||||||
|
"PINNED_LEGACY_RESERVATION_SOURCE_DIGESTS",
|
||||||
|
"PRODUCTION_GUARD_SCAN_ROOTS",
|
||||||
|
"ExactReservationSourceV1",
|
||||||
|
"ForbiddenReservationReferenceV1",
|
||||||
|
"ReplacementReservationAcceptanceV1",
|
||||||
|
"ReservationGuardError",
|
||||||
|
"ReservationGuardReportV1",
|
||||||
|
"exact_reservation_source",
|
||||||
|
"guard_report_bytes",
|
||||||
|
"require_clean_guard",
|
||||||
|
"scan_permanent_reservations",
|
||||||
|
"validate_replacement_population",
|
||||||
|
]
|
||||||
@@ -0,0 +1,51 @@
|
|||||||
|
"""Frozen exact identities for retained legacy reservation source files."""
|
||||||
|
|
||||||
|
from types import MappingProxyType
|
||||||
|
|
||||||
|
PINNED_LEGACY_RESERVATION_SOURCE_DIGESTS = MappingProxyType(
|
||||||
|
{
|
||||||
|
"benchmarks/independent/candidates-v3-php.json": "38f818c058d5d67e7c2861225bb37f29d1f279f213bed3d363f9eaf695cfd04e",
|
||||||
|
"benchmarks/independent/freeze-v1.json": "2c9ca1be6386a2053b34532e573195201c4bbd5db1cdf0f6b8678c311246e330",
|
||||||
|
"benchmarks/independent/freeze-v2.json": "83335e0ee49dd88f6e7c2b7d856b20da22e0572e5fe360d30f0ff7552c518b07",
|
||||||
|
"benchmarks/independent/freeze-v3-php.json": "ad372911ee90b2437f777ff4db128421028d7c0c6eafab7da768e97cb25163f2",
|
||||||
|
"benchmarks/independent/research-2026-09-24.md": "2c24df48d93f4cd6bdc71b1b990afacd0de5314127041a9b786baf5c33b4810a",
|
||||||
|
"benchmarks/independent/research-2026-09-26.md": "905da0feae5fa1d5e5c71dfc7bca9d6a2ca208fbe30a82345a8209c81d0ab3b6",
|
||||||
|
"benchmarks/independent/research-2026-09-30-php.md": "8b87fef5a7d73ff71c23e9b7fb64a0756124ad2429fbffa8df54e87abb8e8feb",
|
||||||
|
"benchmarks/measurements/2026-10-12-valid-benchmark-pilot/catalog.toml": (
|
||||||
|
"32d1353325c475826fde62008225779032cc2f4750a2c7550fc1b7fc933fcdd4"
|
||||||
|
),
|
||||||
|
"benchmarks/measurements/2026-10-12-valid-benchmark-pilot/sources.json": (
|
||||||
|
"c867d7cbb45948de48fb359cdf864085d9c7fdd333a2077d1a79c4f62ef59b7f"
|
||||||
|
),
|
||||||
|
"benchmarks/pairs/advisory-fixes/catalog.toml": "dc2a34db001e02294d43b25183b0e04ff91497beb48e7c50d0945791e4ea7e86",
|
||||||
|
"benchmarks/pairs/advisory-fixes/research-2026-10-01.md": "095fadc612fdc9d9a269bf36998c5b6bc694fa718b90d739180aae451d247e9a",
|
||||||
|
"plane/tasks/validation-46.yaml": "3ff9607cc6aa8c769caa816966b68d8506c3b21f342e3e9f7a84c53b42bb8139",
|
||||||
|
"plane/workspaces/budibase-mongo-template-nosqli-vulnerable.yaml": (
|
||||||
|
"ce45f9a4eade0695205a26dff4c3c3a060f2818dab5d764615040ad7bea9db57"
|
||||||
|
),
|
||||||
|
"plane/workspaces/cct-studio-server-cmdi-vulnerable.yaml": "7759599f0097ef9d90ed7eafdec1193c0eac0460ee06c20d932622c5adf30590",
|
||||||
|
"plane/workspaces/contextforge-prompt-ssti-vulnerable.yaml": "7d81b46da34a501a1ce280845649720a5df74e9269dcd400311ed9a0666d42d0",
|
||||||
|
"plane/workspaces/froxlor-admin-ip-second-order-sqli-vulnerable.yaml": (
|
||||||
|
"f7c0b9570c679e5a451e44f8e44720fabf8db3ec7bc401e224e983ef176ff760"
|
||||||
|
),
|
||||||
|
"plane/workspaces/fuxa-tdengine-escape-sqli-vulnerable.yaml": "a6453130ab9c3ab27b81414568ba70e61161aead0d84953d8344141317c87351",
|
||||||
|
"plane/workspaces/lmdeploy-media-url-ssrf-vulnerable.yaml": "e42aad434cce797949d14ab0368f87eb23985fb4b44feaec0c4f6c4b95f03fd9",
|
||||||
|
"plane/workspaces/medplum-external-auth-open-redirect-vulnerable.yaml": (
|
||||||
|
"6228e5cb9aa2ddb9c0b33c9775ee094eb026a1cff1e3dbfff4a28b2ab7b3a64d"
|
||||||
|
),
|
||||||
|
"plane/workspaces/pgadmin-maintenance-sqli-vulnerable.yaml": "fc64de599a0ef123bb01d63691aa7d3602596c81b419942252aee656e90257f0",
|
||||||
|
"plane/workspaces/qwed-sympy-eval-vulnerable.yaml": "4a0d29e8e73cf71d0fafbd36b828426b345b94d380dc875d1daa9df000aa1c61",
|
||||||
|
"plane/workspaces/reactpress-findall-column-sqli-vulnerable.yaml": (
|
||||||
|
"d4f9701723e91049437bd1f42067bc638e342752e2d71eaf23dcbc070274e265"
|
||||||
|
),
|
||||||
|
"plane/workspaces/unleash-addon-webhook-ssrf-vulnerable.yaml": "82467a84cdd231a0aacf4919b3a3009f83ea5e023fa50197a80d0a19f455ded5",
|
||||||
|
"plane/workspaces/winml-cli-serve-cors-vulnerable.yaml": "cab02c399c98f2f8916642535c8ac918d90457dbff5a3860008be98bd2a20357",
|
||||||
|
"plane/workspaces/wp-directorist-avatar-ssrf-vulnerable.yaml": "abc7eeb27297bc43a955c1d4fdfe8b1aa35e161fdf423a25ff22200bd781068b",
|
||||||
|
"plane/workspaces/wp-gopay-log-filter-sqli-vulnerable.yaml": "160f69b6d9c379563ee384a807f6ebffe8733c1557a04a4768a8585673fd41be",
|
||||||
|
"plane/workspaces/wp-groundhogg-confirm-redirect-vulnerable.yaml": (
|
||||||
|
"f93ab3a76791535392e2350ce7914815417faad1fb755990a551fc25650c08a1"
|
||||||
|
),
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
__all__ = ["PINNED_LEGACY_RESERVATION_SOURCE_DIGESTS"]
|
||||||
@@ -11,11 +11,19 @@ from __future__ import annotations
|
|||||||
import hashlib
|
import hashlib
|
||||||
import json
|
import json
|
||||||
import re
|
import re
|
||||||
|
import sys
|
||||||
import tomllib
|
import tomllib
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
import pytest
|
import pytest
|
||||||
|
|
||||||
|
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
||||||
|
|
||||||
|
from benchmarks.valid import historical_authorization as historical
|
||||||
|
from benchmarks.valid import reservation, reservation_guard
|
||||||
|
from benchmarks.valid.replacement_artifact_contract import canonical_json_bytes
|
||||||
|
from openultrasast.core.canonical import content_digest
|
||||||
|
|
||||||
ROOT = Path(__file__).resolve().parents[1]
|
ROOT = Path(__file__).resolve().parents[1]
|
||||||
POPULATIONS = sorted((ROOT / "benchmarks" / "independent").glob("population-v*.toml"))
|
POPULATIONS = sorted((ROOT / "benchmarks" / "independent").glob("population-v*.toml"))
|
||||||
POPULATION = POPULATIONS[0]
|
POPULATION = POPULATIONS[0]
|
||||||
@@ -72,10 +80,13 @@ def _pool_manifests() -> list[Path]:
|
|||||||
|
|
||||||
|
|
||||||
def _pool_names() -> set[str]:
|
def _pool_names() -> set[str]:
|
||||||
names = set()
|
names: set[str] = set()
|
||||||
for path in _pool_manifests():
|
for path in _pool_manifests():
|
||||||
text = path.read_text().lower()
|
data = tomllib.loads(path.read_text())
|
||||||
names.update(m.rstrip("/").removesuffix(".git") for m in re.findall(r"github\.com/([\w.-]+/[\w.-]+)", text))
|
for row in data.get("repository", []):
|
||||||
|
value = row.get("repository")
|
||||||
|
if isinstance(value, str) and value:
|
||||||
|
names.add(value.lower().removeprefix("https://github.com/").rstrip("/").removesuffix(".git"))
|
||||||
return names
|
return names
|
||||||
|
|
||||||
|
|
||||||
@@ -84,30 +95,100 @@ def _population_names() -> set[str]:
|
|||||||
return {url.rsplit("/", 2)[-2] + "/" + url.rsplit("/", 1)[-1] for url in reserved}
|
return {url.rsplit("/", 2)[-2] + "/" + url.rsplit("/", 1)[-1] for url in reserved}
|
||||||
|
|
||||||
|
|
||||||
|
def _source_repositories() -> dict[Path, set[str]]:
|
||||||
|
sources: dict[Path, set[str]] = {}
|
||||||
|
for path in POPULATIONS:
|
||||||
|
sources[path] = {case["repo"].lower() for case in _population(path)["case"]}
|
||||||
|
for path in _pool_manifests():
|
||||||
|
data = tomllib.loads(path.read_text())
|
||||||
|
names = {
|
||||||
|
value.lower().removeprefix("https://github.com/").rstrip("/").removesuffix(".git")
|
||||||
|
for row in data.get("repository", [])
|
||||||
|
if isinstance((value := row.get("repository")), str) and value
|
||||||
|
}
|
||||||
|
if names:
|
||||||
|
sources[path] = {f"https://github.com/{name}" for name in names}
|
||||||
|
reserved = {repository for values in sources.values() for repository in values}
|
||||||
|
for relative, expected_digest in reservation_guard.PINNED_LEGACY_RESERVATION_SOURCE_DIGESTS.items():
|
||||||
|
path = ROOT / relative
|
||||||
|
if not path.is_file():
|
||||||
|
continue
|
||||||
|
assert hashlib.sha256(path.read_bytes()).hexdigest() == expected_digest
|
||||||
|
names = {
|
||||||
|
match.rstrip("/").removesuffix(".git")
|
||||||
|
for match in re.findall(r"github\.com/([\w.-]+/[\w.-]+)", path.read_text(errors="ignore").lower())
|
||||||
|
if f"https://github.com/{match.rstrip('/').removesuffix('.git')}" in reserved
|
||||||
|
}
|
||||||
|
if names:
|
||||||
|
sources[path] = {f"https://github.com/{name}" for name in names}
|
||||||
|
return sources
|
||||||
|
|
||||||
|
|
||||||
|
def _reviewed_history() -> historical.HistoricalWithdrawalV1:
|
||||||
|
inventory = historical.pinned_historical_inventory(ROOT)
|
||||||
|
candidate = historical.build_withdrawal_candidate(inventory)
|
||||||
|
value: dict[str, object] = {
|
||||||
|
"schema_version": historical.HISTORICAL_REVIEW_SCHEMA,
|
||||||
|
"subject_digest": candidate.candidate_digest,
|
||||||
|
"decision": "authorize_exact_historical_audit",
|
||||||
|
"producer_identity": "benchmark-custodian",
|
||||||
|
"reviewer_identity": "independent-guard-reviewer",
|
||||||
|
"conflict_disclosed": True,
|
||||||
|
"policy_digest": content_digest({"policy": "permanent-reservation-guard-v1"}),
|
||||||
|
}
|
||||||
|
value["review_digest"] = content_digest(value)
|
||||||
|
return historical.accept_reviewed_withdrawal(candidate, canonical_json_bytes(value))
|
||||||
|
|
||||||
|
|
||||||
|
def _production_guard_report() -> reservation_guard.ReservationGuardReportV1:
|
||||||
|
sources = _source_repositories()
|
||||||
|
repositories = sorted({repository for values in sources.values() for repository in values})
|
||||||
|
networks = tuple(reservation.build_network_identity(repository) for repository in repositories)
|
||||||
|
resolver = reservation.RepositoryIdentityResolver(networks)
|
||||||
|
legacy_by_path: dict[Path, tuple[reservation.LegacyReservationSourceV1, ...]] = {}
|
||||||
|
all_legacy: list[reservation.LegacyReservationSourceV1] = []
|
||||||
|
source_owner: dict[str, str] = {}
|
||||||
|
for path, values in sources.items():
|
||||||
|
owner = "independent" if ROOT / "benchmarks/independent" in path.parents else "unseen"
|
||||||
|
relative = path.relative_to(ROOT).as_posix()
|
||||||
|
pinned_source = relative in reservation_guard.PINNED_LEGACY_RESERVATION_SOURCE_DIGESTS
|
||||||
|
source_digest = hashlib.sha256(path.read_bytes()).hexdigest()
|
||||||
|
records = tuple(
|
||||||
|
reservation.legacy_reservation_source(resolver, repository=repository, source_digest=source_digest)
|
||||||
|
for repository in sorted(values)
|
||||||
|
if pinned_source or source_owner.get(repository, owner) == owner
|
||||||
|
)
|
||||||
|
for repository in values:
|
||||||
|
source_owner.setdefault(repository, owner)
|
||||||
|
if records:
|
||||||
|
legacy_by_path[path] = records
|
||||||
|
all_legacy.extend(records)
|
||||||
|
authority = reservation.ReservationAuthority(resolver, legacy_sources=all_legacy)
|
||||||
|
census = authority.project_census(())
|
||||||
|
exact_sources = tuple(
|
||||||
|
reservation_guard.exact_reservation_source(
|
||||||
|
ROOT,
|
||||||
|
path.relative_to(ROOT).as_posix(),
|
||||||
|
tuple(record.legacy_source_digest for record in records),
|
||||||
|
)
|
||||||
|
for path, records in sorted(legacy_by_path.items())
|
||||||
|
)
|
||||||
|
return reservation_guard.scan_permanent_reservations(
|
||||||
|
ROOT,
|
||||||
|
scan_roots=tuple(name for name in ("benchmarks", "src", "tests", "plane") if (ROOT / name).is_dir()),
|
||||||
|
authority=authority,
|
||||||
|
census=census,
|
||||||
|
reservation_sources=exact_sources,
|
||||||
|
historical_withdrawal=(
|
||||||
|
_reviewed_history() if all((ROOT / relative).is_file() for relative in historical.PINNED_HISTORICAL_DIGESTS) else None
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
def test_no_reserved_repository_is_referenced_by_the_development_tree() -> None:
|
def test_no_reserved_repository_is_referenced_by_the_development_tree() -> None:
|
||||||
reservations = [(ROOT / "benchmarks/independent", _population_names()), (ROOT / "benchmarks/unseen", _pool_names())]
|
report = _production_guard_report()
|
||||||
offenders = 0
|
reservation_guard.require_clean_guard(report)
|
||||||
counts = {}
|
assert report.files_read > 0 and report.bytes_read > 0 and report.reserved_network_count > 0
|
||||||
for top in ("benchmarks", "src", "tests", "plane"):
|
|
||||||
for path in (ROOT / top).rglob("*"):
|
|
||||||
if not path.is_file() or path == Path(__file__) or path.suffix in {".pyc", ".bin", ".gz"}:
|
|
||||||
continue
|
|
||||||
# Preserve the population guard's existing scope; plane is newly reserved for pools.
|
|
||||||
active = [
|
|
||||||
(directory, names)
|
|
||||||
for directory, names in reservations
|
|
||||||
if directory not in path.parents and names and not (top == "plane" and directory == ROOT / "benchmarks/independent")
|
|
||||||
]
|
|
||||||
if not active:
|
|
||||||
continue
|
|
||||||
try:
|
|
||||||
text = path.read_text(errors="ignore").lower()
|
|
||||||
except OSError:
|
|
||||||
continue
|
|
||||||
count = sum(1 for _, names in active for name in names if f"github.com/{name}" in text)
|
|
||||||
offenders += count
|
|
||||||
counts[top] = counts.get(top, 0) + count
|
|
||||||
assert not offenders, f"reserved repository referenced outside its reservation: count={offenders}, sources={counts}"
|
|
||||||
|
|
||||||
|
|
||||||
def test_pool_and_population_names_are_disjoint() -> None:
|
def test_pool_and_population_names_are_disjoint() -> None:
|
||||||
@@ -145,30 +226,33 @@ def test_pool_guard_controls(tmp_path, monkeypatch) -> None:
|
|||||||
pool = tmp_path / "benchmarks/unseen/pool-p1.toml"
|
pool = tmp_path / "benchmarks/unseen/pool-p1.toml"
|
||||||
population.parent.mkdir(parents=True)
|
population.parent.mkdir(parents=True)
|
||||||
pool.parent.mkdir(parents=True)
|
pool.parent.mkdir(parents=True)
|
||||||
|
for name in reservation_guard.PRODUCTION_GUARD_SCAN_ROOTS:
|
||||||
|
(tmp_path / name).mkdir(exist_ok=True)
|
||||||
prefix = "https://" + "github.com/"
|
prefix = "https://" + "github.com/"
|
||||||
population.write_text('[[case]]\nrepo = "' + prefix + 'synthetic/population"\n')
|
population.write_text('[[case]]\nrepo = "' + prefix + 'synthetic/population"\n')
|
||||||
pool.write_text('[[repository]]\nrepo = "' + prefix + 'synthetic/pool"\n')
|
pool.write_text('[[repository]]\nrepository = "synthetic/pool"\n')
|
||||||
monkeypatch.setattr(__import__(__name__), "ROOT", tmp_path)
|
monkeypatch.setattr(__import__(__name__), "ROOT", tmp_path)
|
||||||
monkeypatch.setattr(__import__(__name__), "POPULATIONS", [population])
|
monkeypatch.setattr(__import__(__name__), "POPULATIONS", [population])
|
||||||
test_no_reserved_repository_is_referenced_by_the_development_tree()
|
test_no_reserved_repository_is_referenced_by_the_development_tree()
|
||||||
leak = tmp_path / "benchmarks/measurements/fixture.txt"
|
leak = tmp_path / "benchmarks/measurements/fixture.txt"
|
||||||
leak.parent.mkdir(parents=True)
|
leak.parent.mkdir(parents=True)
|
||||||
leak.write_text(prefix + "synthetic/pool")
|
leak.write_text(prefix + "synthetic/pool")
|
||||||
with pytest.raises(AssertionError, match="count=1"):
|
with pytest.raises(reservation_guard.ReservationGuardError, match="count=1"):
|
||||||
test_no_reserved_repository_is_referenced_by_the_development_tree()
|
test_no_reserved_repository_is_referenced_by_the_development_tree()
|
||||||
leak.unlink()
|
leak.unlink()
|
||||||
plane = tmp_path / "plane/fixture.txt"
|
plane = tmp_path / "plane/fixture.txt"
|
||||||
plane.parent.mkdir()
|
plane.parent.mkdir(exist_ok=True)
|
||||||
plane.write_text(prefix + "synthetic/pool")
|
plane.write_text(prefix + "synthetic/pool")
|
||||||
with pytest.raises(AssertionError, match="count=1"):
|
with pytest.raises(reservation_guard.ReservationGuardError, match="count=1"):
|
||||||
test_no_reserved_repository_is_referenced_by_the_development_tree()
|
test_no_reserved_repository_is_referenced_by_the_development_tree()
|
||||||
plane.write_text(prefix + "synthetic/population")
|
plane.write_text(prefix + "synthetic/population")
|
||||||
test_no_reserved_repository_is_referenced_by_the_development_tree()
|
with pytest.raises(reservation_guard.ReservationGuardError, match="count=1"):
|
||||||
|
test_no_reserved_repository_is_referenced_by_the_development_tree()
|
||||||
plane.unlink()
|
plane.unlink()
|
||||||
private = pool.parent / "private/draft-p1.toml"
|
private = pool.parent / "private/draft-p1.toml"
|
||||||
private.parent.mkdir()
|
private.parent.mkdir()
|
||||||
private.write_text('[[repository]]\nrepo = "' + prefix + 'synthetic/population"\n')
|
private.write_text('[[repository]]\nrepo = "' + prefix + 'synthetic/population"\n')
|
||||||
with pytest.raises(AssertionError, match="count=2"):
|
with pytest.raises(reservation_guard.ReservationGuardError, match="count=1"):
|
||||||
test_no_reserved_repository_is_referenced_by_the_development_tree()
|
test_no_reserved_repository_is_referenced_by_the_development_tree()
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,422 @@
|
|||||||
|
"""Production-backed permanent-reservation guard integration."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import shutil
|
||||||
|
import sys
|
||||||
|
from dataclasses import replace
|
||||||
|
from hashlib import sha256
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
||||||
|
|
||||||
|
from benchmarks.valid import historical_authorization as historical # noqa: E402
|
||||||
|
from benchmarks.valid import lifecycle, reservation, reservation_guard # noqa: E402
|
||||||
|
from benchmarks.valid.replacement_artifact_contract import canonical_json_bytes # noqa: E402
|
||||||
|
from openultrasast.core.canonical import content_digest # noqa: E402
|
||||||
|
|
||||||
|
ROOT = Path(__file__).resolve().parents[1]
|
||||||
|
POLICY = content_digest({"policy": "guard-review-v1"})
|
||||||
|
POPULATION = content_digest({"population": "replacement"})
|
||||||
|
FREEZE = content_digest({"freeze": "replacement"})
|
||||||
|
|
||||||
|
|
||||||
|
def _network(canonical: str, *, alias: str | None = None, fork: str | None = None):
|
||||||
|
return reservation.build_network_identity(
|
||||||
|
canonical,
|
||||||
|
aliases=(alias,) if alias else (),
|
||||||
|
forks=(fork,) if fork else (),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _authority(tmp_path: Path):
|
||||||
|
reserved = _network(
|
||||||
|
"https://github.com/acme/reserved",
|
||||||
|
alias="https://github.com/acme/old-reserved",
|
||||||
|
fork="https://github.com/fork/reserved",
|
||||||
|
)
|
||||||
|
fresh = _network("https://github.com/fresh/project")
|
||||||
|
resolver = reservation.RepositoryIdentityResolver((reserved, fresh))
|
||||||
|
source_path = "benchmarks/reservations/source.txt"
|
||||||
|
target = tmp_path / source_path
|
||||||
|
target.parent.mkdir(parents=True)
|
||||||
|
target.write_text("https://github.com/acme/reserved\n")
|
||||||
|
source_digest = sha256(target.read_bytes()).hexdigest()
|
||||||
|
legacy = reservation.legacy_reservation_source(
|
||||||
|
resolver,
|
||||||
|
repository=reserved.canonical_repository,
|
||||||
|
source_digest=source_digest,
|
||||||
|
)
|
||||||
|
authority = reservation.ReservationAuthority(resolver, legacy_sources=(legacy,))
|
||||||
|
census = authority.project_census(())
|
||||||
|
source = reservation_guard.exact_reservation_source(tmp_path, source_path, (legacy.legacy_source_digest,))
|
||||||
|
return authority, census, source
|
||||||
|
|
||||||
|
|
||||||
|
def _historical_review(subject: str) -> bytes:
|
||||||
|
value: dict[str, object] = {
|
||||||
|
"schema_version": historical.HISTORICAL_REVIEW_SCHEMA,
|
||||||
|
"subject_digest": subject,
|
||||||
|
"decision": "authorize_exact_historical_audit",
|
||||||
|
"producer_identity": "custodian",
|
||||||
|
"reviewer_identity": "reviewer",
|
||||||
|
"conflict_disclosed": True,
|
||||||
|
"policy_digest": POLICY,
|
||||||
|
}
|
||||||
|
value["review_digest"] = content_digest(value)
|
||||||
|
return canonical_json_bytes(value)
|
||||||
|
|
||||||
|
|
||||||
|
def _copy_history(destination: Path) -> historical.HistoricalWithdrawalV1:
|
||||||
|
for relative in historical.PINNED_HISTORICAL_DIGESTS:
|
||||||
|
target = destination / relative
|
||||||
|
target.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
shutil.copyfile(ROOT / relative, target)
|
||||||
|
inventory = historical.pinned_historical_inventory(destination)
|
||||||
|
candidate = historical.build_withdrawal_candidate(inventory)
|
||||||
|
return historical.accept_reviewed_withdrawal(candidate, _historical_review(candidate.candidate_digest))
|
||||||
|
|
||||||
|
|
||||||
|
def _active_lifecycle(withdrawal: historical.HistoricalWithdrawalV1):
|
||||||
|
root = lifecycle.withdrawn_event(withdrawal)
|
||||||
|
withdrawn = lifecycle.decode_lifecycle_event(root)
|
||||||
|
replacement = lifecycle.reviewed_replacement_event(
|
||||||
|
predecessor_digest=withdrawn.event_digest,
|
||||||
|
historical_withdrawal_digest=withdrawn.historical_withdrawal_digest,
|
||||||
|
population_digest=POPULATION,
|
||||||
|
freeze_digest=FREEZE,
|
||||||
|
producer_identity="producer",
|
||||||
|
reviewer_identity="reviewer",
|
||||||
|
conflict_disclosed=True,
|
||||||
|
policy_digest=POLICY,
|
||||||
|
)
|
||||||
|
return lifecycle.BaselineLifecycleAuthority().project((root, replacement))
|
||||||
|
|
||||||
|
|
||||||
|
def _scan_roots(root: Path) -> None:
|
||||||
|
for name in ("benchmarks", "src", "tests", "plane"):
|
||||||
|
(root / name).mkdir(exist_ok=True)
|
||||||
|
|
||||||
|
|
||||||
|
def _clean_report(tmp_path, authority, census, source, withdrawal):
|
||||||
|
return reservation_guard.scan_permanent_reservations(
|
||||||
|
tmp_path,
|
||||||
|
scan_roots=("benchmarks", "src", "tests", "plane"),
|
||||||
|
authority=authority,
|
||||||
|
census=census,
|
||||||
|
reservation_sources=(source,),
|
||||||
|
historical_withdrawal=withdrawal,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _partial_src_report(report: reservation_guard.ReservationGuardReportV1, path: Path) -> reservation_guard.ReservationGuardReportV1:
|
||||||
|
content = path.read_bytes()
|
||||||
|
receipt = content_digest(
|
||||||
|
{
|
||||||
|
"files": (
|
||||||
|
{
|
||||||
|
"path": path.parent.name + "/" + path.name,
|
||||||
|
"byte_length": len(content),
|
||||||
|
"content_digest": sha256(content).hexdigest(),
|
||||||
|
},
|
||||||
|
)
|
||||||
|
}
|
||||||
|
)
|
||||||
|
draft = replace(
|
||||||
|
report,
|
||||||
|
files_read=1,
|
||||||
|
bytes_read=len(content),
|
||||||
|
scan_roots=("src",),
|
||||||
|
input_receipt_digest=receipt,
|
||||||
|
violations=(),
|
||||||
|
report_digest="",
|
||||||
|
)
|
||||||
|
value = {
|
||||||
|
"schema_version": reservation_guard.GUARD_REPORT_SCHEMA,
|
||||||
|
"files_read": draft.files_read,
|
||||||
|
"bytes_read": draft.bytes_read,
|
||||||
|
"reserved_network_count": draft.reserved_network_count,
|
||||||
|
"census_digest": draft.census_digest,
|
||||||
|
"scan_roots": draft.scan_roots,
|
||||||
|
"input_receipt_digest": draft.input_receipt_digest,
|
||||||
|
"reservation_source_digests": draft.reservation_source_digests,
|
||||||
|
"historical_withdrawal_digest": draft.historical_withdrawal_digest,
|
||||||
|
"violations": (),
|
||||||
|
}
|
||||||
|
return replace(draft, report_digest=content_digest(value))
|
||||||
|
|
||||||
|
|
||||||
|
def test_exact_source_is_allowed_but_alias_and_fork_leaks_are_all_reported(tmp_path: Path) -> None:
|
||||||
|
_scan_roots(tmp_path)
|
||||||
|
authority, census, source = _authority(tmp_path)
|
||||||
|
leak = tmp_path / "src/leak.txt"
|
||||||
|
leak.write_text("github.com/acme/old-reserved\ngithub.com/fork/reserved\n")
|
||||||
|
|
||||||
|
report = reservation_guard.scan_permanent_reservations(
|
||||||
|
tmp_path,
|
||||||
|
scan_roots=("benchmarks", "src", "tests", "plane"),
|
||||||
|
authority=authority,
|
||||||
|
census=census,
|
||||||
|
reservation_sources=(source,),
|
||||||
|
)
|
||||||
|
|
||||||
|
assert report.files_read == 2
|
||||||
|
assert report.bytes_read > 0
|
||||||
|
assert report.reserved_network_count == 1
|
||||||
|
assert tuple(item.path for item in report.violations) == ("src/leak.txt", "src/leak.txt")
|
||||||
|
assert {item.repository for item in report.violations} == {
|
||||||
|
"https://github.com/acme/old-reserved",
|
||||||
|
"https://github.com/fork/reserved",
|
||||||
|
}
|
||||||
|
with pytest.raises(reservation_guard.ReservationGuardError, match="count=2"):
|
||||||
|
reservation_guard.require_clean_guard(report)
|
||||||
|
|
||||||
|
|
||||||
|
def test_changed_source_bytes_and_empty_or_unreadable_inputs_fail_loudly(tmp_path: Path) -> None:
|
||||||
|
_scan_roots(tmp_path)
|
||||||
|
authority, census, source = _authority(tmp_path)
|
||||||
|
(tmp_path / source.path).write_text("github.com/acme/reserved\nchanged\n")
|
||||||
|
with pytest.raises(reservation_guard.ReservationGuardError, match="source bytes changed"):
|
||||||
|
reservation_guard.scan_permanent_reservations(
|
||||||
|
tmp_path,
|
||||||
|
scan_roots=("benchmarks", "src", "tests", "plane"),
|
||||||
|
authority=authority,
|
||||||
|
census=census,
|
||||||
|
reservation_sources=(source,),
|
||||||
|
)
|
||||||
|
with pytest.raises(reservation_guard.ReservationGuardError, match="scan"):
|
||||||
|
reservation_guard.scan_permanent_reservations(
|
||||||
|
tmp_path,
|
||||||
|
scan_roots=("missing",),
|
||||||
|
authority=authority,
|
||||||
|
census=census,
|
||||||
|
reservation_sources=(),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def test_exact_source_authority_is_scoped_to_its_bound_network(tmp_path: Path) -> None:
|
||||||
|
_scan_roots(tmp_path)
|
||||||
|
first = _network("https://github.com/acme/first")
|
||||||
|
second = _network("https://github.com/acme/second")
|
||||||
|
resolver = reservation.RepositoryIdentityResolver((first, second))
|
||||||
|
path = "benchmarks/reservations/source.txt"
|
||||||
|
target = tmp_path / path
|
||||||
|
target.parent.mkdir(parents=True)
|
||||||
|
target.write_text("github.com/acme/first, github.com/acme/second.\n")
|
||||||
|
source_digest = sha256(target.read_bytes()).hexdigest()
|
||||||
|
first_legacy = reservation.legacy_reservation_source(resolver, repository=first.canonical_repository, source_digest=source_digest)
|
||||||
|
second_legacy = reservation.legacy_reservation_source(
|
||||||
|
resolver,
|
||||||
|
repository=second.canonical_repository,
|
||||||
|
source_digest=content_digest({"other": "source"}),
|
||||||
|
)
|
||||||
|
authority = reservation.ReservationAuthority(resolver, legacy_sources=(first_legacy, second_legacy))
|
||||||
|
census = authority.project_census(())
|
||||||
|
source = reservation_guard.exact_reservation_source(tmp_path, path, (first_legacy.legacy_source_digest,))
|
||||||
|
|
||||||
|
report = reservation_guard.scan_permanent_reservations(
|
||||||
|
tmp_path,
|
||||||
|
scan_roots=("benchmarks", "src", "tests", "plane"),
|
||||||
|
authority=authority,
|
||||||
|
census=census,
|
||||||
|
reservation_sources=(source,),
|
||||||
|
)
|
||||||
|
|
||||||
|
assert tuple(item.repository for item in report.violations) == ("https://github.com/acme/second",)
|
||||||
|
|
||||||
|
|
||||||
|
def test_only_reviewed_exact_historical_files_are_allowed(tmp_path: Path) -> None:
|
||||||
|
_scan_roots(tmp_path)
|
||||||
|
authority, census, source = _authority(tmp_path)
|
||||||
|
withdrawal = _copy_history(tmp_path)
|
||||||
|
historical_path = tmp_path / "benchmarks/valid/pilot/pool-valid.toml"
|
||||||
|
historical_path.write_bytes(historical_path.read_bytes() + b"\n# github.com/acme/reserved\n")
|
||||||
|
with pytest.raises(reservation_guard.ReservationGuardError, match="historical|digest"):
|
||||||
|
reservation_guard.scan_permanent_reservations(
|
||||||
|
tmp_path,
|
||||||
|
scan_roots=("benchmarks", "src", "tests", "plane"),
|
||||||
|
authority=authority,
|
||||||
|
census=census,
|
||||||
|
reservation_sources=(source,),
|
||||||
|
historical_withdrawal=withdrawal,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def test_unchanged_reviewed_historical_file_is_exactly_allowed(tmp_path: Path) -> None:
|
||||||
|
_scan_roots(tmp_path)
|
||||||
|
authority, census, source = _authority(tmp_path)
|
||||||
|
withdrawal = _copy_history(tmp_path)
|
||||||
|
report = reservation_guard.scan_permanent_reservations(
|
||||||
|
tmp_path,
|
||||||
|
scan_roots=("benchmarks", "src", "tests", "plane"),
|
||||||
|
authority=authority,
|
||||||
|
census=census,
|
||||||
|
reservation_sources=(source,),
|
||||||
|
historical_withdrawal=withdrawal,
|
||||||
|
)
|
||||||
|
reservation_guard.require_clean_guard(report)
|
||||||
|
assert report.scan_roots == ("benchmarks", "plane", "src", "tests")
|
||||||
|
assert report.input_receipt_digest and report.reservation_source_digests
|
||||||
|
assert report.historical_withdrawal_digest == withdrawal.withdrawal_digest
|
||||||
|
assert b"github.com/acme/reserved" not in reservation_guard.guard_report_bytes(report)
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
"repository",
|
||||||
|
(
|
||||||
|
"https://github.com/acme/reserved",
|
||||||
|
"https://github.com/acme/old-reserved",
|
||||||
|
"https://github.com/fork/reserved",
|
||||||
|
),
|
||||||
|
)
|
||||||
|
def test_replacement_rejects_reserved_canonical_alias_and_fork(tmp_path: Path, repository: str) -> None:
|
||||||
|
_scan_roots(tmp_path)
|
||||||
|
authority, census, source = _authority(tmp_path)
|
||||||
|
withdrawal = _copy_history(tmp_path)
|
||||||
|
projection = _active_lifecycle(withdrawal)
|
||||||
|
report = _clean_report(tmp_path, authority, census, source, withdrawal)
|
||||||
|
with pytest.raises(reservation_guard.ReservationGuardError, match="permanent reservation"):
|
||||||
|
reservation_guard.validate_replacement_population(
|
||||||
|
tmp_path,
|
||||||
|
repositories=(repository,),
|
||||||
|
population_digest=POPULATION,
|
||||||
|
freeze_digest=FREEZE,
|
||||||
|
lifecycle=projection,
|
||||||
|
guard_report=report,
|
||||||
|
authority=authority,
|
||||||
|
census=census,
|
||||||
|
historical_withdrawal=withdrawal,
|
||||||
|
reservation_sources=(source,),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def test_replacement_accepts_resolved_fresh_identity_and_exact_historical_audit(tmp_path: Path) -> None:
|
||||||
|
_scan_roots(tmp_path)
|
||||||
|
authority, census, source = _authority(tmp_path)
|
||||||
|
withdrawal = _copy_history(tmp_path)
|
||||||
|
projection = _active_lifecycle(withdrawal)
|
||||||
|
report = _clean_report(tmp_path, authority, census, source, withdrawal)
|
||||||
|
path = "benchmarks/valid/pilot/freeze-valid.json"
|
||||||
|
accepted = reservation_guard.validate_replacement_population(
|
||||||
|
tmp_path,
|
||||||
|
repositories=("https://github.com/fresh/project",),
|
||||||
|
population_digest=POPULATION,
|
||||||
|
freeze_digest=FREEZE,
|
||||||
|
lifecycle=projection,
|
||||||
|
guard_report=report,
|
||||||
|
authority=authority,
|
||||||
|
census=census,
|
||||||
|
historical_withdrawal=withdrawal,
|
||||||
|
reservation_sources=(source,),
|
||||||
|
historical_requests=((path, historical.PINNED_HISTORICAL_DIGESTS[path]),),
|
||||||
|
)
|
||||||
|
assert accepted.network_identity_digests
|
||||||
|
assert accepted.historical_paths == (path,)
|
||||||
|
assert accepted.acceptance_digest
|
||||||
|
|
||||||
|
(tmp_path / "src/leak.txt").write_text("github.com/acme/reserved\n")
|
||||||
|
with pytest.raises(reservation_guard.ReservationGuardError, match="stale|changed"):
|
||||||
|
reservation_guard.validate_replacement_population(
|
||||||
|
tmp_path,
|
||||||
|
repositories=("https://github.com/fresh/project",),
|
||||||
|
population_digest=POPULATION,
|
||||||
|
freeze_digest=FREEZE,
|
||||||
|
lifecycle=projection,
|
||||||
|
guard_report=report,
|
||||||
|
authority=authority,
|
||||||
|
census=census,
|
||||||
|
historical_withdrawal=withdrawal,
|
||||||
|
reservation_sources=(source,),
|
||||||
|
)
|
||||||
|
dirty = _clean_report(tmp_path, authority, census, source, withdrawal)
|
||||||
|
with pytest.raises(reservation_guard.ReservationGuardError, match="count=1"):
|
||||||
|
reservation_guard.validate_replacement_population(
|
||||||
|
tmp_path,
|
||||||
|
repositories=("https://github.com/fresh/project",),
|
||||||
|
population_digest=POPULATION,
|
||||||
|
freeze_digest=FREEZE,
|
||||||
|
lifecycle=projection,
|
||||||
|
guard_report=dirty,
|
||||||
|
authority=authority,
|
||||||
|
census=census,
|
||||||
|
historical_withdrawal=withdrawal,
|
||||||
|
reservation_sources=(source,),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def test_replacement_refuses_unresolved_identity_wrong_lifecycle_and_broad_history(tmp_path: Path) -> None:
|
||||||
|
_scan_roots(tmp_path)
|
||||||
|
authority, census, source = _authority(tmp_path)
|
||||||
|
withdrawal = _copy_history(tmp_path)
|
||||||
|
projection = _active_lifecycle(withdrawal)
|
||||||
|
report = _clean_report(tmp_path, authority, census, source, withdrawal)
|
||||||
|
with pytest.raises(reservation_guard.ReservationGuardError, match="unresolved"):
|
||||||
|
reservation_guard.validate_replacement_population(
|
||||||
|
tmp_path,
|
||||||
|
repositories=("https://github.com/unknown/project",),
|
||||||
|
population_digest=POPULATION,
|
||||||
|
freeze_digest=FREEZE,
|
||||||
|
lifecycle=projection,
|
||||||
|
guard_report=report,
|
||||||
|
authority=authority,
|
||||||
|
census=census,
|
||||||
|
historical_withdrawal=withdrawal,
|
||||||
|
reservation_sources=(source,),
|
||||||
|
)
|
||||||
|
with pytest.raises(reservation_guard.ReservationGuardError, match="identity"):
|
||||||
|
reservation_guard.validate_replacement_population(
|
||||||
|
tmp_path,
|
||||||
|
repositories=("https://github.com/fresh/project",),
|
||||||
|
population_digest="0" * 64,
|
||||||
|
freeze_digest=FREEZE,
|
||||||
|
lifecycle=projection,
|
||||||
|
guard_report=report,
|
||||||
|
authority=authority,
|
||||||
|
census=census,
|
||||||
|
historical_withdrawal=withdrawal,
|
||||||
|
reservation_sources=(source,),
|
||||||
|
)
|
||||||
|
with pytest.raises(reservation_guard.ReservationGuardError, match="historical"):
|
||||||
|
reservation_guard.validate_replacement_population(
|
||||||
|
tmp_path,
|
||||||
|
repositories=("https://github.com/fresh/project",),
|
||||||
|
population_digest=POPULATION,
|
||||||
|
freeze_digest=FREEZE,
|
||||||
|
lifecycle=projection,
|
||||||
|
guard_report=report,
|
||||||
|
authority=authority,
|
||||||
|
census=census,
|
||||||
|
historical_withdrawal=withdrawal,
|
||||||
|
reservation_sources=(source,),
|
||||||
|
historical_requests=(("benchmarks/valid/pilot", "0" * 64),),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def test_partial_scope_report_and_replacement_acceptance_are_refused(tmp_path: Path) -> None:
|
||||||
|
_scan_roots(tmp_path)
|
||||||
|
authority, census, source = _authority(tmp_path)
|
||||||
|
withdrawal = _copy_history(tmp_path)
|
||||||
|
projection = _active_lifecycle(withdrawal)
|
||||||
|
clean = tmp_path / "src/clean.txt"
|
||||||
|
clean.write_text("clean-ok")
|
||||||
|
report = _clean_report(tmp_path, authority, census, source, withdrawal)
|
||||||
|
partial = _partial_src_report(report, clean)
|
||||||
|
(tmp_path / "tests/leak.txt").write_text("github.com/acme/reserved\n")
|
||||||
|
|
||||||
|
with pytest.raises(reservation_guard.ReservationGuardError, match="scope"):
|
||||||
|
reservation_guard.guard_report_bytes(partial)
|
||||||
|
with pytest.raises(reservation_guard.ReservationGuardError, match="scope"):
|
||||||
|
reservation_guard.validate_replacement_population(
|
||||||
|
tmp_path,
|
||||||
|
repositories=("https://github.com/fresh/project",),
|
||||||
|
population_digest=POPULATION,
|
||||||
|
freeze_digest=FREEZE,
|
||||||
|
lifecycle=projection,
|
||||||
|
guard_report=partial,
|
||||||
|
authority=authority,
|
||||||
|
census=census,
|
||||||
|
historical_withdrawal=withdrawal,
|
||||||
|
reservation_sources=(source,),
|
||||||
|
)
|
||||||
Reference in New Issue
Block a user