From 408a562c413b6baf01f1f4be3c5854f00623ed08 Mon Sep 17 00:00:00 2001 From: Marius Ciepluch <11855163+norandom@users.noreply.github.com> Date: Sun, 22 Nov 2026 18:42:51 +0100 Subject: [PATCH] feat(valid-detection-benchmark): 10.3 ingest bounded reviewed JavaScript/TypeScript cohort --- .../specs/valid-detection-benchmark/tasks.md | 2 +- benchmarks/valid/cohort_ingestion.py | 173 +++++-- benchmarks/valid/cohort_ingestion_store.py | 8 +- tests/cohort_ingestion_fixtures.py | 91 +++- ...d_benchmark_cohort_ingestion_javascript.py | 421 ++++++++++++++++++ 5 files changed, 644 insertions(+), 51 deletions(-) create mode 100644 tests/test_valid_benchmark_cohort_ingestion_javascript.py diff --git a/.kiro/specs/valid-detection-benchmark/tasks.md b/.kiro/specs/valid-detection-benchmark/tasks.md index 6f0feee4..6db04cb2 100644 --- a/.kiro/specs/valid-detection-benchmark/tasks.md +++ b/.kiro/specs/valid-detection-benchmark/tasks.md @@ -320,7 +320,7 @@ - _Requirements: 1.1, 1.5, 1.6, 2.3, 2.4, 2.5, 2.6, 4.1, 4.2_ - _Boundary: Review Authority, Replacement Population Sourcing_ - _Depends: 10.1_ -- [ ] 10.3 Ingest the first bounded independently reviewed JavaScript/TypeScript cohort +- [x] 10.3 Ingest the first bounded independently reviewed JavaScript/TypeScript cohort - Apply the same independent-review, conflict-disclosure, reachability, exact-scope, reservation, and exclusion rules to the canonical `javascript` ecosystem. - Limit this ingestion unit to one supplied batch of at most twenty candidate review records. - Preserve TypeScript as observed language evidence without creating a separate ecosystem or detector requirement. diff --git a/benchmarks/valid/cohort_ingestion.py b/benchmarks/valid/cohort_ingestion.py index df9c979a..fac5898c 100644 --- a/benchmarks/valid/cohort_ingestion.py +++ b/benchmarks/valid/cohort_ingestion.py @@ -1,10 +1,11 @@ -"""Bounded ingestion of externally reviewed Python cohort batches. +"""Bounded ingestion of externally reviewed cohort batches. One ingestion unit consumes a single supplied batch of at most twenty external -review records against the pending Python review queue. Every acceptance comes -only from the committed review authorities revalidating the external -attestations; missing, partial, or refused reviews are recorded as closed -per-record exclusions or pending entries and are never self-approved. +review records against one pending canonical-ecosystem review queue (Python or +JavaScript; TypeScript arrives as observed language evidence under javascript). +Every acceptance comes only from the committed review authorities revalidating +the external attestations; missing, partial, or refused reviews are recorded as +closed per-record exclusions or pending entries and are never self-approved. """ from __future__ import annotations @@ -36,11 +37,14 @@ from benchmarks.valid.ground_truth_review import ( project_accepted_ground_truth, review_ground_truth, ) -from benchmarks.valid.sourcing_queue import ReviewQueueEntryV1, SourcingQueueStateV1 +from benchmarks.valid.sourcing_queue import EcosystemReviewQueueV1, ReviewQueueEntryV1, SourcingQueueStateV1 from openultrasast.core.canonical import JsonValue, bytes_digest, canonical_bytes, content_digest EXTERNAL_REVIEW_RECORD_SCHEMA = "openultrasast.valid-detection-benchmark.external-review-record.v1" COHORT_BATCH_SCHEMA = "openultrasast.valid-detection-benchmark.python-cohort-batch.v1" +JAVASCRIPT_COHORT_BATCH_SCHEMA = "openultrasast.valid-detection-benchmark.javascript-cohort-batch.v1" +_BATCH_SCHEMA_BY_ECOSYSTEM = {"python": COHORT_BATCH_SCHEMA, "javascript": JAVASCRIPT_COHORT_BATCH_SCHEMA} +_ECOSYSTEM_BY_BATCH_SCHEMA = {schema: ecosystem for ecosystem, schema in _BATCH_SCHEMA_BY_ECOSYSTEM.items()} COHORT_BATCH_CAP = 20 MINIMUM_ACCEPTED_POSITIVES = 10 _DIGEST = re.compile(r"[0-9a-f]{64}") @@ -81,6 +85,7 @@ class CohortInsufficientReason(StrEnum): BATCH_EMPTY = "batch_empty" BATCH_CAP_EXCEEDED = "batch_cap_exceeded" PYTHON_QUEUE_EMPTY = "python_queue_empty" + JAVASCRIPT_QUEUE_EMPTY = "javascript_queue_empty" INSUFFICIENT_ACCEPTED_POSITIVES = "insufficient_accepted_positives" @@ -138,6 +143,9 @@ class CohortRecordOutcomeV1: def __post_init__(self) -> None: if not isinstance(self.record_digest, str) or _DIGEST.fullmatch(self.record_digest) is None: raise CohortStateError(CohortStateReason.STATE_MISMATCH) + for digest_value in (self.queue_entry_digest, self.ground_truth_review_digest): + if digest_value is not None and (not isinstance(digest_value, str) or _DIGEST.fullmatch(digest_value) is None): + raise CohortStateError(CohortStateReason.STATE_MISMATCH) if not isinstance(self.status, CohortRecordStatus): raise CohortStateError(CohortStateReason.STATE_MISMATCH) if self.status is CohortRecordStatus.ACCEPTED: @@ -373,9 +381,10 @@ def _batch_status( record_count: int, accepted_count: int, queue_entry_count: int, + queue_empty_reason: CohortInsufficientReason, ) -> tuple[CohortBatchStatus, CohortInsufficientReason | None]: if queue_entry_count == 0: - return CohortBatchStatus.INSUFFICIENT, CohortInsufficientReason.PYTHON_QUEUE_EMPTY + return CohortBatchStatus.INSUFFICIENT, queue_empty_reason if record_count == 0: return CohortBatchStatus.INSUFFICIENT, CohortInsufficientReason.BATCH_EMPTY if accepted_count < MINIMUM_ACCEPTED_POSITIVES: @@ -389,8 +398,21 @@ def _closed_digest(value: object) -> str: return value +def _batch_schema(ecosystem: object) -> str: + schema = _BATCH_SCHEMA_BY_ECOSYSTEM.get(ecosystem) if isinstance(ecosystem, str) else None + if schema is None: + raise CohortStateError(CohortStateReason.STATE_MISMATCH) + return schema + + +def cohort_batch_ecosystem(schema_version: object) -> str | None: + """Map one committed cohort batch schema onto its canonical ecosystem, else None.""" + return _ECOSYSTEM_BY_BATCH_SCHEMA.get(schema_version) if isinstance(schema_version, str) else None + + def cohort_batch( *, + ecosystem: str = "python", queue_digest: str, census_digest: str, ecosystem_policy_digest: str, @@ -401,7 +423,13 @@ def cohort_batch( status: CohortBatchStatus, insufficient_reason: CohortInsufficientReason | None, ) -> CohortBatchOutcomeV1: - """Assemble one bounded Python cohort batch bound to its exact queue and census.""" + """Assemble one bounded cohort batch bound to its exact queue and census. + + The ecosystem must be one of the canonical cohort ecosystems; a batch for + an observed language such as TypeScript is a javascript-ecosystem batch. + """ + if not isinstance(ecosystem, str) or ecosystem not in _BATCH_SCHEMA_BY_ECOSYSTEM: + raise CohortStateError(CohortStateReason.STATE_MISMATCH) if not isinstance(status, CohortBatchStatus): raise CohortStateError(CohortStateReason.STATE_MISMATCH) accepted_tuple = tuple(accepted_positives) @@ -411,13 +439,13 @@ def cohort_batch( raise CohortStateError(CohortStateReason.STATE_MISMATCH) accepted = tuple(sorted(accepted_tuple, key=lambda item: item.change_identity_digest)) draft = CohortBatchOutcomeV1( - "python", + ecosystem, _closed_digest(queue_digest), _closed_digest(census_digest), _closed_digest(ecosystem_policy_digest), _closed_digest(ground_truth_policy_digest), tuple(sorted(record_outcomes, key=lambda item: item.record_digest)), - tuple(sorted(set(pending_entries))), + tuple(sorted({_closed_digest(item) for item in pending_entries})), accepted, MINIMUM_ACCEPTED_POSITIVES, status, @@ -456,7 +484,7 @@ def _accepted_value(item: AcceptedGroundTruthV1) -> dict[str, JsonValue]: def cohort_batch_value(outcome: CohortBatchOutcomeV1) -> dict[str, JsonValue]: """Canonical batch payload used for durable persistence and exact rereads.""" return { - "schema_version": COHORT_BATCH_SCHEMA, + "schema_version": _batch_schema(outcome.ecosystem), "ecosystem": outcome.ecosystem, "queue_digest": outcome.queue_digest, "census_digest": outcome.census_digest, @@ -486,7 +514,13 @@ def cohort_batch_bytes(outcome: CohortBatchOutcomeV1) -> bytes: return canonical_bytes(cohort_batch_value(outcome)) -def _refused_batch(state: SourcingQueueStateV1, ordered: Sequence[bytes], batch: _BatchState) -> CohortBatchOutcomeV1: +def _refused_batch( + queue: EcosystemReviewQueueV1, + census_digest: str, + ecosystem: str, + ordered: Sequence[bytes], + batch: _BatchState, +) -> CohortBatchOutcomeV1: outcomes = [ CohortRecordOutcomeV1( bytes_digest(content), None, None, CohortRecordStatus.EXCLUDED, CohortRecordExclusionReason.BATCH_UNIT_REFUSED.value @@ -494,8 +528,9 @@ def _refused_batch(state: SourcingQueueStateV1, ordered: Sequence[bytes], batch: for content in ordered ] return cohort_batch( - queue_digest=state.python_queue.queue_digest, - census_digest=state.census_digest, + ecosystem=ecosystem, + queue_digest=queue.queue_digest, + census_digest=census_digest, ecosystem_policy_digest=batch.ecosystem_policy_digest, ground_truth_policy_digest=batch.ground_truth_policy_digest, record_outcomes=outcomes, @@ -506,6 +541,57 @@ def _refused_batch(state: SourcingQueueStateV1, ordered: Sequence[bytes], batch: ) +def _ingest_cohort_batch( + records: Sequence[bytes], + *, + queue: EcosystemReviewQueueV1, + census_digest: str, + ecosystem: str, + queue_empty_reason: CohortInsufficientReason, + candidates_by_digest: Mapping[str, FixSiteCandidateV1], + expected_ecosystem_policy_digest: str, + expected_ground_truth_policy_digest: str, +) -> CohortBatchOutcomeV1: + """Ingest one supplied batch of at most twenty external review records.""" + for content in records: + if not isinstance(content, bytes): + raise ValueError("external review records must be supplied as bytes") + batch = _BatchState( + {entry.entry_digest: entry for entry in queue.entries}, + candidates_by_digest, + expected_ecosystem_policy_digest, + expected_ground_truth_policy_digest, + ) + ordered = tuple(sorted(records, key=bytes_digest)) + if len(ordered) > COHORT_BATCH_CAP: + return _refused_batch(queue, census_digest, ecosystem, ordered, batch) + for content in ordered: + batch.outcomes.append(_review_record(content, batch).outcome) + try: + accepted_positives = project_accepted_ground_truth( + batch.accepted_reviews, + candidates_by_digest=candidates_by_digest, + ecosystem_reviews_by_digest=dict(batch.ecosystem_reviews), + expected_ecosystem_policy_digest=expected_ecosystem_policy_digest, + expected_ground_truth_policy_digest=expected_ground_truth_policy_digest, + ) + except GroundTruthReviewError: + raise CohortStateError(CohortStateReason.STATE_MISMATCH) from None + status, reason = _batch_status(len(ordered), len(accepted_positives), len(batch.entries), queue_empty_reason) + return cohort_batch( + ecosystem=ecosystem, + queue_digest=queue.queue_digest, + census_digest=census_digest, + ecosystem_policy_digest=expected_ecosystem_policy_digest, + ground_truth_policy_digest=expected_ground_truth_policy_digest, + record_outcomes=batch.outcomes, + pending_entries=sorted(batch.entries.keys() - batch.answered), + accepted_positives=accepted_positives, + status=status, + insufficient_reason=reason, + ) + + def ingest_python_cohort_batch( records: Sequence[bytes], *, @@ -515,38 +601,40 @@ def ingest_python_cohort_batch( expected_ground_truth_policy_digest: str, ) -> CohortBatchOutcomeV1: """Ingest one supplied batch of at most twenty external Python review records.""" - for content in records: - if not isinstance(content, bytes): - raise ValueError("external review records must be supplied as bytes") - batch = _BatchState( - {entry.entry_digest: entry for entry in state.python_queue.entries}, - candidates_by_digest, - expected_ecosystem_policy_digest, - expected_ground_truth_policy_digest, - ) - ordered = tuple(sorted(records, key=bytes_digest)) - if len(ordered) > COHORT_BATCH_CAP: - return _refused_batch(state, ordered, batch) - for content in ordered: - batch.outcomes.append(_review_record(content, batch).outcome) - accepted_positives = project_accepted_ground_truth( - batch.accepted_reviews, + return _ingest_cohort_batch( + records, + queue=state.python_queue, + census_digest=state.census_digest, + ecosystem="python", + queue_empty_reason=CohortInsufficientReason.PYTHON_QUEUE_EMPTY, candidates_by_digest=candidates_by_digest, - ecosystem_reviews_by_digest=dict(batch.ecosystem_reviews), expected_ecosystem_policy_digest=expected_ecosystem_policy_digest, expected_ground_truth_policy_digest=expected_ground_truth_policy_digest, ) - status, reason = _batch_status(len(ordered), len(accepted_positives), len(batch.entries)) - return cohort_batch( - queue_digest=state.python_queue.queue_digest, + + +def ingest_javascript_cohort_batch( + records: Sequence[bytes], + *, + state: SourcingQueueStateV1, + candidates_by_digest: Mapping[str, FixSiteCandidateV1], + expected_ecosystem_policy_digest: str, + expected_ground_truth_policy_digest: str, +) -> CohortBatchOutcomeV1: + """Ingest one supplied JavaScript/TypeScript review batch under the canonical javascript ecosystem. + + TypeScript arrives only as observed language evidence on queue entries; the + cohort itself stays bound to the javascript ecosystem and its batch schema. + """ + return _ingest_cohort_batch( + records, + queue=state.javascript_queue, census_digest=state.census_digest, - ecosystem_policy_digest=expected_ecosystem_policy_digest, - ground_truth_policy_digest=expected_ground_truth_policy_digest, - record_outcomes=batch.outcomes, - pending_entries=sorted(batch.entries.keys() - batch.answered), - accepted_positives=accepted_positives, - status=status, - insufficient_reason=reason, + ecosystem="javascript", + queue_empty_reason=CohortInsufficientReason.JAVASCRIPT_QUEUE_EMPTY, + candidates_by_digest=candidates_by_digest, + expected_ecosystem_policy_digest=expected_ecosystem_policy_digest, + expected_ground_truth_policy_digest=expected_ground_truth_policy_digest, ) @@ -563,10 +651,13 @@ __all__ = [ "CohortStateError", "CohortStateReason", "EXTERNAL_REVIEW_RECORD_SCHEMA", + "JAVASCRIPT_COHORT_BATCH_SCHEMA", "MINIMUM_ACCEPTED_POSITIVES", "cohort_batch", "cohort_batch_bytes", + "cohort_batch_ecosystem", "cohort_batch_value", "decode_external_record", + "ingest_javascript_cohort_batch", "ingest_python_cohort_batch", ] diff --git a/benchmarks/valid/cohort_ingestion_store.py b/benchmarks/valid/cohort_ingestion_store.py index dd4a026a..2b944042 100644 --- a/benchmarks/valid/cohort_ingestion_store.py +++ b/benchmarks/valid/cohort_ingestion_store.py @@ -9,7 +9,6 @@ from typing import Any from benchmarks.valid.artifact_repository import ArtifactReadAuthority, S3ArtifactRepository from benchmarks.valid.cohort_ingestion import ( - COHORT_BATCH_SCHEMA, CohortBatchOutcomeV1, CohortBatchStatus, CohortInsufficientReason, @@ -19,6 +18,7 @@ from benchmarks.valid.cohort_ingestion import ( CohortStateReason, cohort_batch, cohort_batch_bytes, + cohort_batch_ecosystem, cohort_batch_value, decode_external_record, ) @@ -98,11 +98,15 @@ def _accepted_from_value(item: Any) -> AcceptedGroundTruthV1: def decode_cohort_batch(content: bytes) -> CohortBatchOutcomeV1: """Rebuild one batch outcome only from canonical, digest-consistent bytes.""" value = _decoded_value(content) - if set(value) != _BATCH_KEYS or value["schema_version"] != COHORT_BATCH_SCHEMA: + if set(value) != _BATCH_KEYS: + raise CohortStateError(CohortStateReason.STATE_MISMATCH) + ecosystem = cohort_batch_ecosystem(value["schema_version"]) + if ecosystem is None or value["ecosystem"] != ecosystem: raise CohortStateError(CohortStateReason.STATE_MISMATCH) try: reason = None if value["insufficient_reason"] is None else CohortInsufficientReason(value["insufficient_reason"]) outcome = cohort_batch( + ecosystem=ecosystem, queue_digest=value["queue_digest"], census_digest=value["census_digest"], ecosystem_policy_digest=value["ecosystem_policy_digest"], diff --git a/tests/cohort_ingestion_fixtures.py b/tests/cohort_ingestion_fixtures.py index d05a2738..aaffa55c 100644 --- a/tests/cohort_ingestion_fixtures.py +++ b/tests/cohort_ingestion_fixtures.py @@ -50,6 +50,9 @@ ENUMERATION_REVIEWER = "cohort-enumeration-reviewer@example.invalid" ECOSYSTEM_PRODUCER = "ecosystem-producer@example.invalid" ECOSYSTEM_REVIEWER = "ecosystem-reviewer@example.invalid" PYTHON_COUNT = 12 +JAVASCRIPT_NAMES = tuple(f"js-{index:02d}" for index in range(10)) +TYPESCRIPT_NAMES = ("ts-00", "ts-01") +JAVASCRIPT_COUNT = len(JAVASCRIPT_NAMES) + len(TYPESCRIPT_NAMES) _APPS: dict[str, dict[str, Any]] = {} for _index in range(PYTHON_COUNT): @@ -91,7 +94,41 @@ _APPS["js-01"] = { "vulnerable": "function validate(input) {\n return eval(input);\n}\n", "fixed": "function validate(input) {\n return String(input);\n}\n", } -_REVISIONS = {name: (f"{5000 + index * 2:040x}", f"{5001 + index * 2:040x}") for index, name in enumerate(sorted(_APPS))} +for _index in range(2, 10): + _family = "injection" if _index % 2 == 0 else "path_traversal" + _apps_key = f"js-{_index:02d}" + _APPS[_apps_key] = { + "url": f"https://github.com/fixture/cohort-{_apps_key}", + "repo": f"fixture/cohort-{_apps_key}", + "path": f"lib/module{_index:02d}.js", + "function": f"transform_{_index:02d}", + "language": "javascript", + "hint": "javascript", + "family": _family, + "cwe": "CWE-94" if _family == "injection" else "CWE-22", + "vulnerable": f"function transform_{_index:02d}(input) {{\n return eval(input);\n}}\n", + "fixed": f"function transform_{_index:02d}(input) {{\n return String(input);\n}}\n", + } +for _name, _path, _function, _family, _cwe in ( + ("ts-00", "src/paths.ts", "resolveTarget", "path_traversal", "CWE-22"), + ("ts-01", "src/config.ts", "parseValue", "injection", "CWE-94"), +): + _APPS[_name] = { + "url": f"https://github.com/fixture/cohort-{_name}", + "repo": f"fixture/cohort-{_name}", + "path": _path, + "function": _function, + "language": "typescript", + "hint": "javascript", + "family": _family, + "cwe": _cwe, + "vulnerable": f"export function {_function}(input: string) {{\n return eval(input);\n}}\n", + "fixed": f"export function {_function}(input: string) {{\n return String(input);\n}}\n", + } +_STABLE_APP_ORDER = ("js-00", "js-01", *(f"py-{index:02d}" for index in range(PYTHON_COUNT))) +_NEW_APP_ORDER = (*JAVASCRIPT_NAMES[2:], *TYPESCRIPT_NAMES) +_REVISIONS = {name: (f"{5000 + index * 2:040x}", f"{5001 + index * 2:040x}") for index, name in enumerate(_STABLE_APP_ORDER)} +_REVISIONS.update({name: (f"{6000 + index * 2:040x}", f"{6001 + index * 2:040x}") for index, name in enumerate(_NEW_APP_ORDER)}) READ_POLICY = bytes_digest(b"cohort-ingestion-read-policy-fixture") @@ -249,6 +286,34 @@ def python_entries(state: SourcingQueueStateV1) -> list[ReviewQueueEntryV1]: return [*state.python_queue.entries] +def javascript_request_names() -> tuple[str, ...]: + return (*JAVASCRIPT_NAMES, *TYPESCRIPT_NAMES) + + +def javascript_cohort_state( + requests: list | None = None, + *, + resolver_: RepositoryIdentityResolver | None = None, + authority_: ReservationAuthority | None = None, + per_ecosystem_cap: int = 20, +) -> tuple[SourcingQueueStateV1, RepositoryIdentityResolver]: + resolved = resolver_ or resolver() + state = build_sourcing_queue( + requests or [request_for(name) for name in javascript_request_names()], + reader=FakeReader(), + resolver=resolved, + authority=authority_ or authority(resolved), + policy=sourcing_queue_policy(per_ecosystem_cap=per_ecosystem_cap, required_families=2), + enumeration_actor=ENUMERATION_ACTOR, + enumeration_reviewer=ENUMERATION_REVIEWER, + ) + return state, resolved + + +def javascript_entries(state: SourcingQueueStateV1) -> list[ReviewQueueEntryV1]: + return [*state.javascript_queue.entries] + + def _eco_value(att: EcosystemReviewAttestationV1) -> dict[str, Any]: return { "candidate_digest": att.candidate_digest, @@ -285,13 +350,19 @@ def reviewed_record( entry: ReviewQueueEntryV1, candidate: FixSiteCandidateV1, *, + ecosystem: str = "python", eco_changes: dict[str, Any] | None = None, gt_changes: dict[str, Any] | None = None, entry_digest: str | None = None, record_extra: dict[str, Any] | None = None, derive_review: bool = True, ) -> tuple[bytes, GroundTruthReviewV1 | None]: - """Build one external review record and the review the authorities derive from it.""" + """Build one external review record and the review the authorities derive from it. + + The ecosystem parameter stays inside the closed canonical vocabulary; a + TypeScript-language repository is reviewed as observed evidence under the + canonical javascript ecosystem, never as its own ecosystem. + """ locator = entry.family.advisory_locator eco = replace( EcosystemReviewAttestationV1( @@ -302,15 +373,15 @@ def reviewed_record( conflict_disclosed=True, policy_digest=ECOSYSTEM_POLICY, policy_satisfied=True, - decision=EcosystemReviewDecision.PYTHON, + decision=EcosystemReviewDecision(ecosystem), ), **(eco_changes or {}), ) - ecosystem = review_repository_ecosystem(candidate, eco, expected_policy_digest=ECOSYSTEM_POLICY) + ecosystem_review = review_repository_ecosystem(candidate, eco, expected_policy_digest=ECOSYSTEM_POLICY) ground_truth = replace( GroundTruthAttestationV1( candidate_digest=candidate.candidate_digest, - ecosystem_review_digest=ecosystem.review_digest, + ecosystem_review_digest=ecosystem_review.review_digest, producer_identity=f"producer-{locator}@example.invalid", reviewer_identity=f"reviewer-{locator}@example.invalid", conflict_disclosed=True, @@ -319,7 +390,7 @@ def reviewed_record( defect_present=True, fix_addresses=True, in_repository_reachable=True, - verified_scopes=(VerifiedScope(entry.family.vulnerability_family, "python"),), + verified_scopes=(VerifiedScope(entry.family.vulnerability_family, ecosystem),), model_assistance_digest=None, ), **(gt_changes or {}), @@ -328,7 +399,7 @@ def reviewed_record( if derive_review: review = review_ground_truth( candidate, - ecosystem, + ecosystem_review, ground_truth, expected_ecosystem_policy_digest=ECOSYSTEM_POLICY, expected_ground_truth_policy_digest=GROUND_TRUTH_POLICY, @@ -367,12 +438,18 @@ __all__ = [ "ENUMERATION_REVIEWER", "GROUND_TRUTH_POLICY", "FakeReader", + "JAVASCRIPT_COUNT", + "JAVASCRIPT_NAMES", "PYTHON_COUNT", "READ_POLICY", "RepositoryEcosystemReviewV1", + "TYPESCRIPT_NAMES", "authority", "candidates_for", "case_for", + "javascript_cohort_state", + "javascript_entries", + "javascript_request_names", "model_only_assistance_digest", "python_cohort_state", "python_entries", diff --git a/tests/test_valid_benchmark_cohort_ingestion_javascript.py b/tests/test_valid_benchmark_cohort_ingestion_javascript.py new file mode 100644 index 00000000..412da90f --- /dev/null +++ b/tests/test_valid_benchmark_cohort_ingestion_javascript.py @@ -0,0 +1,421 @@ +"""Bounded ingestion of the first independently reviewed JavaScript/TypeScript cohort.""" + +from __future__ import annotations + +import json +import sys +from pathlib import Path + +import pytest + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) + +from cohort_ingestion_fixtures import ( # noqa: E402 + ECOSYSTEM_POLICY, + GROUND_TRUTH_POLICY, + JAVASCRIPT_COUNT, + JAVASCRIPT_NAMES, + PYTHON_COUNT, + READ_POLICY, + TYPESCRIPT_NAMES, + _Client, + _read_authority, + _settings, + authority, + candidates_for, + javascript_cohort_state, + javascript_entries, + python_cohort_state, + request_for, + resolver, + reviewed_record, +) + +from benchmarks.valid import ( + cohort_ingestion, # noqa: E402 + cohort_ingestion_store, # noqa: E402 +) +from benchmarks.valid.artifact_repository import S3ArtifactRepository # noqa: E402 +from benchmarks.valid.cohort_ingestion import ( # noqa: E402 + COHORT_BATCH_CAP, + JAVASCRIPT_COHORT_BATCH_SCHEMA, + MINIMUM_ACCEPTED_POSITIVES, + CohortBatchStatus, + CohortInsufficientReason, + CohortStateError, + CohortStateReason, + cohort_batch, + cohort_batch_bytes, + cohort_batch_value, + ingest_javascript_cohort_batch, +) +from benchmarks.valid.ecosystem_review import EcosystemReviewDecision # noqa: E402 +from benchmarks.valid.ground_truth_review import GroundTruthReviewError, GroundTruthStatus, VerifiedScope # noqa: E402 +from benchmarks.valid.replacement_artifact_contract import ArtifactKind # noqa: E402 +from benchmarks.valid.reservation import legacy_reservation_source # noqa: E402 +from openultrasast.core.canonical import bytes_digest # noqa: E402 + +JAVASCRIPT_REQUEST_NAMES = (*JAVASCRIPT_NAMES, *TYPESCRIPT_NAMES) + + +@pytest.fixture(autouse=True) +def offline(monkeypatch): + def forbidden(*args, **kwargs): + pytest.fail("network or SZZ was invoked") + + import socket + + from benchmarks.unseen import extract + + monkeypatch.setattr(socket, "create_connection", forbidden) + monkeypatch.setattr(socket.socket, "connect", forbidden) + monkeypatch.setattr(extract, "introducing", forbidden) + monkeypatch.setattr(extract.Git, "blame", forbidden) + + +def _ingest(records, state, candidates): + return ingest_javascript_cohort_batch( + records, + state=state, + candidates_by_digest=candidates, + expected_ecosystem_policy_digest=ECOSYSTEM_POLICY, + expected_ground_truth_policy_digest=GROUND_TRUTH_POLICY, + ) + + +def _prepared(): + state, resolved = javascript_cohort_state() + requests = [request_for(name) for name in JAVASCRIPT_REQUEST_NAMES] + return state, candidates_for(requests, resolved) + + +def _js_records(state, candidates): + return [ + reviewed_record(entry, candidates[entry.candidate_digest], ecosystem="javascript")[0] + for entry in javascript_entries(state) + ] + + +def _by_reason(outcome): + return {item.reason: item for item in outcome.record_outcomes if item.reason is not None} + + +def _tampered_bytes(payload): + return json.dumps(payload, sort_keys=True, separators=(",", ":"), ensure_ascii=False).encode("utf-8") + + +def test_first_bounded_javascript_batch_reaches_ten_accepted_reachable_positives(): + state, candidates = _prepared() + records = _js_records(state, candidates) + + assert len(records) == JAVASCRIPT_COUNT <= COHORT_BATCH_CAP + assert all(records) + outcome = _ingest(records, state, candidates) + + assert outcome.status is CohortBatchStatus.ACCEPTED + assert outcome.insufficient_reason is None + assert outcome.ecosystem == "javascript" + assert len(outcome.accepted_positives) == JAVASCRIPT_COUNT >= MINIMUM_ACCEPTED_POSITIVES + assert outcome.pending_entries == () + assert all(item.status.value == "accepted" for item in outcome.record_outcomes) + families = {scope.vulnerability_family for positive in outcome.accepted_positives for scope in positive.verified_scopes} + assert len(families) >= 2 + assert all(scope.ecosystem.value == "javascript" for positive in outcome.accepted_positives for scope in positive.verified_scopes) + assert outcome.census_digest == state.census_digest + assert outcome.queue_digest == state.javascript_queue.queue_digest + assert cohort_batch_value(outcome)["schema_version"] == JAVASCRIPT_COHORT_BATCH_SCHEMA + + shuffled = list(reversed(records)) + replayed = _ingest(shuffled, state, candidates) + assert replayed == outcome + assert replayed.batch_digest == outcome.batch_digest + + +def test_typescript_stays_observed_language_evidence_under_the_javascript_ecosystem(): + state, candidates = _prepared() + entries = javascript_entries(state) + typescript_entries = [entry for entry in entries if entry.observed_language == "typescript"] + assert len(typescript_entries) == len(TYPESCRIPT_NAMES) >= 1 + assert {entry.canonical_ecosystem for entry in typescript_entries} == {"javascript"} + assert {entry.observed_language for entry in entries} == {"javascript", "typescript"} + + records = _js_records(state, candidates) + outcome = _ingest(records, state, candidates) + assert outcome.status is CohortBatchStatus.ACCEPTED + + by_entry = {item.queue_entry_digest: item for item in outcome.record_outcomes} + assert all(by_entry[entry.entry_digest].status.value == "accepted" for entry in typescript_entries) + typescript_candidates = {entry.candidate_digest for entry in typescript_entries} + for positive in outcome.accepted_positives: + if positive.candidate_digest in typescript_candidates: + assert all(scope.ecosystem.value == "javascript" for scope in positive.verified_scopes) + + index = entries.index(typescript_entries[0]) + minted_payload = json.loads(records[index]) + minted_payload["ground_truth_attestation"]["verified_scopes"] = [ + {"vulnerability_family": typescript_entries[0].family.vulnerability_family, "ecosystem": "typescript"} + ] + minted = list(records) + minted[index] = _tampered_bytes(minted_payload) + refused = _ingest(minted, state, candidates) + item = next(item for item in refused.record_outcomes if item.queue_entry_digest == typescript_entries[0].entry_digest) + assert item.status.value == "excluded" + assert item.reason == "record_schema_mismatch" + assert typescript_entries[0].entry_digest in refused.pending_entries + + with pytest.raises(CohortStateError) as error: + cohort_batch( + ecosystem="typescript", + queue_digest="0" * 64, + census_digest="0" * 64, + ecosystem_policy_digest="0" * 64, + ground_truth_policy_digest="0" * 64, + record_outcomes=(), + pending_entries=(), + accepted_positives=(), + status=CohortBatchStatus.INSUFFICIENT, + insufficient_reason=CohortInsufficientReason.BATCH_EMPTY, + ) + assert error.value.reason is CohortStateReason.STATE_MISMATCH + + +def test_every_accepted_and_excluded_javascript_candidate_replays_from_external_review_evidence(): + state, candidates = _prepared() + entries = javascript_entries(state) + cases = [ + ({"decision": EcosystemReviewDecision.PYTHON}, lambda entry: {}), + (None, lambda entry: {"reviewer_identity": f"producer-{entry.family.advisory_locator}@example.invalid"}), + (None, lambda entry: {"conflict_disclosed": False}), + (None, lambda entry: {"policy_satisfied": False}), + (None, lambda entry: {"defect_present": None}), + (None, lambda entry: {"in_repository_reachable": False}), + (None, lambda entry: {"verified_scopes": ()}), + (None, lambda entry: {"verified_scopes": (VerifiedScope("injection", "python"),)}), + ] + records = [] + expected = {} + for index, entry in enumerate(entries): + eco_changes, gt_builder = cases[index] if index < len(cases) else (None, None) + content, review = reviewed_record( + entry, + candidates[entry.candidate_digest], + ecosystem="javascript", + eco_changes=eco_changes, + gt_changes=gt_builder(entry) if index < len(cases) else None, + ) + records.append(content) + expected[entry.entry_digest] = review + unknown = reviewed_record( + entries[0], candidates[entries[0].candidate_digest], ecosystem="javascript", entry_digest="3" * 64 + )[0] + records.append(unknown) + + outcome = _ingest(records, state, candidates) + replayed = _ingest(list(reversed(records)), state, candidates) + assert replayed == outcome + assert replayed.batch_digest == outcome.batch_digest + assert any(item.record_digest == bytes_digest(unknown) for item in outcome.record_outcomes) + + by_entry = {item.queue_entry_digest: item for item in outcome.record_outcomes if item.queue_entry_digest is not None} + for entry in entries: + review = expected[entry.entry_digest] + item = by_entry[entry.entry_digest] + assert item.ground_truth_review_digest == review.review_digest + if review.status is GroundTruthStatus.ACCEPTED: + assert item.status.value == "accepted" + assert review.in_repository_reachable is True + else: + assert item.status.value == "excluded" + assert item.reason == review.exclusion_reason.value + + +def test_missing_external_decisions_leave_the_javascript_cohort_pending(): + state, candidates = _prepared() + entries = javascript_entries(state) + + empty = _ingest([], state, candidates) + assert empty.status is CohortBatchStatus.INSUFFICIENT + assert empty.insufficient_reason is CohortInsufficientReason.BATCH_EMPTY + assert empty.record_outcomes == () and empty.accepted_positives == () + assert empty.pending_entries == tuple(sorted(entry.entry_digest for entry in entries)) + + partial = _js_records(state, candidates)[: MINIMUM_ACCEPTED_POSITIVES - 1] + outcome = _ingest(partial, state, candidates) + assert outcome.status is CohortBatchStatus.INSUFFICIENT + assert outcome.insufficient_reason is CohortInsufficientReason.INSUFFICIENT_ACCEPTED_POSITIVES + assert all(item.status.value == "accepted" for item in outcome.record_outcomes) + assert outcome.pending_entries == tuple(sorted(entry.entry_digest for entry in entries[MINIMUM_ACCEPTED_POSITIVES - 1 :])) + + python_requests = [request_for(f"py-{index:02d}") for index in range(PYTHON_COUNT)] + python_only, python_resolver = python_cohort_state(python_requests) + assert python_only.javascript_queue.entries == () + python_candidates = candidates_for(python_requests, python_resolver) + python_entry = python_only.python_queue.entries[0] + python_record = reviewed_record(python_entry, python_candidates[python_entry.candidate_digest])[0] + refused = _ingest([python_record], python_only, python_candidates) + assert refused.status is CohortBatchStatus.INSUFFICIENT + assert refused.insufficient_reason is CohortInsufficientReason.JAVASCRIPT_QUEUE_EMPTY + assert refused.accepted_positives == () + + +def test_javascript_records_are_hostile_decoded_and_label_blind(): + state, candidates = _prepared() + entries = javascript_entries(state) + good, _ = reviewed_record(entries[0], candidates[entries[0].candidate_digest], ecosystem="javascript") + spaced = json.dumps(json.loads(good), sort_keys=True, indent=1).encode("utf-8") + wrong_schema = json.dumps({**json.loads(good), "schema_version": "other.v1"}, sort_keys=True, separators=(",", ":")).encode("utf-8") + labeled = json.dumps({**json.loads(good), "verdict": "accepted"}, sort_keys=True, separators=(",", ":")).encode("utf-8") + + outcome = _ingest( + [b"", b"not json at all", b'{"x":NaN}', b'{"x":1e999}', b'{"k":' + b"[" * 20000 + b"]" * 20000 + b"}", + spaced, wrong_schema, labeled], + state, + candidates, + ) + + assert outcome.record_outcomes and all(item.status.value == "excluded" for item in outcome.record_outcomes) + assert sum(1 for item in outcome.record_outcomes if item.reason == "record_unreadable") == 6 + assert sum(1 for item in outcome.record_outcomes if item.reason == "record_schema_mismatch") == 2 + assert outcome.pending_entries == tuple(sorted(entry.entry_digest for entry in entries)) + assert outcome.status is CohortBatchStatus.INSUFFICIENT + assert outcome.insufficient_reason is CohortInsufficientReason.INSUFFICIENT_ACCEPTED_POSITIVES + content = cohort_batch_bytes(outcome) + for forbidden in (b"admission", b"detector", b"observation", b"label", b"verdict", b"score"): + assert forbidden not in content + + +def test_unknown_duplicate_missing_and_reserved_javascript_records_stay_closed(): + state, candidates = _prepared() + entries = javascript_entries(state) + unknown = reviewed_record( + entries[0], candidates[entries[0].candidate_digest], ecosystem="javascript", entry_digest="4" * 64 + )[0] + good, _ = reviewed_record(entries[1], candidates[entries[1].candidate_digest], ecosystem="javascript") + thinned = dict(candidates) + del thinned[entries[2].candidate_digest] + missing, _ = reviewed_record(entries[2], candidates[entries[2].candidate_digest], ecosystem="javascript") + + outcome = _ingest([unknown, good, good, missing], state, thinned) + + reasons = _by_reason(outcome) + assert reasons["duplicate_record"].queue_entry_digest == entries[1].entry_digest + assert reasons["candidate_evidence_missing"].queue_entry_digest == entries[2].entry_digest + assert entries[0].entry_digest in outcome.pending_entries + assert len(outcome.pending_entries) == len(entries) - 1 + + resolved = resolver() + js_url = "https://github.com/fixture/cohort-js-00" + legacy = (legacy_reservation_source(resolved, repository=js_url, source_digest="b" * 64),) + reserved_authority = authority(resolved, legacy=legacy) + names = [name for name in JAVASCRIPT_REQUEST_NAMES if name != "js-00"] + reserved_requests = [request_for(name) for name in names] + reserved_state, _ = javascript_cohort_state( + reserved_requests, resolver_=resolved, authority_=reserved_authority + ) + reserved_candidates = candidates_for(reserved_requests, resolved) + assert js_url not in {entry.canonical_repository for entry in javascript_entries(reserved_state)} + reserved_candidate = next(iter(candidates_for([request_for("js-00")], resolved).values())) + entry = javascript_entries(reserved_state)[0] + forged, _ = reviewed_record(entry, reserved_candidate, ecosystem="javascript") + good_without_entry = [ + reviewed_record(item, reserved_candidates[item.candidate_digest], ecosystem="javascript")[0] + for item in javascript_entries(reserved_state)[1:] + ] + reserved_outcome = _ingest([forged, *good_without_entry], reserved_state, reserved_candidates) + + assert reserved_outcome.status is CohortBatchStatus.ACCEPTED + assert len(reserved_outcome.accepted_positives) == JAVASCRIPT_COUNT - 2 + assert all(positive.candidate_digest != reserved_candidate.candidate_digest for positive in reserved_outcome.accepted_positives) + assert _by_reason(reserved_outcome)["review_evidence_invalid"].queue_entry_digest == entry.entry_digest + assert entry.entry_digest in reserved_outcome.pending_entries + + +def test_javascript_batch_cap_refuses_over_twenty_records_with_every_record_ledgered(): + state, candidates = _prepared() + records = _js_records(state, candidates) + while len(records) <= COHORT_BATCH_CAP: + records.append(records[0]) + records = records[: COHORT_BATCH_CAP + 1] + + outcome = _ingest(records, state, candidates) + + assert outcome.status is CohortBatchStatus.INSUFFICIENT + assert outcome.insufficient_reason is CohortInsufficientReason.BATCH_CAP_EXCEEDED + assert len(outcome.record_outcomes) == COHORT_BATCH_CAP + 1 + assert {item.reason for item in outcome.record_outcomes} == {"batch_unit_refused"} + assert outcome.accepted_positives == () + assert outcome.pending_entries == tuple(sorted(entry.entry_digest for entry in javascript_entries(state))) + + +def test_javascript_batch_persists_resumes_and_replays_from_durable_evidence(): + client = _Client() + store = S3ArtifactRepository(_settings(), client) + state, candidates = _prepared() + records = _js_records(state, candidates) + outcome = _ingest(records, state, candidates) + assert outcome.status is CohortBatchStatus.ACCEPTED + + record_references = cohort_ingestion_store.publish_external_review_records(store, records) + reference = cohort_ingestion_store.persist_cohort_batch(store, outcome) + assert cohort_ingestion_store.persist_cohort_batch(store, outcome) == reference + accepted = store.get( + reference, expected_kind=ArtifactKind.REVIEW, authority=_read_authority(), expected_access_policy_digest=READ_POLICY + ) + assert accepted.artifact.payload["ecosystem"] == "javascript" + + restarted = S3ArtifactRepository(_settings(), client) + resumed = cohort_ingestion_store.resume_cohort_batch( + restarted, reference, authority=_read_authority(), expected_access_policy_digest=READ_POLICY + ) + assert resumed == outcome + assert cohort_batch_bytes(resumed) == cohort_batch_bytes(outcome) + + reread = cohort_ingestion_store.read_external_review_records( + restarted, record_references, authority=_read_authority(), expected_access_policy_digest=READ_POLICY + ) + replayed = _ingest(reread, state, candidates) + assert replayed == outcome + assert replayed.batch_digest == outcome.batch_digest + + +def test_decode_cohort_batch_closes_forged_digest_and_ecosystem_fields(): + state, candidates = _prepared() + partial = _js_records(state, candidates)[: JAVASCRIPT_COUNT - 2] + outcome = _ingest(partial, state, candidates) + content = cohort_batch_bytes(outcome) + decode = cohort_ingestion_store.decode_cohort_batch + + forged_pending = json.loads(content) + forged_pending["pending_entries"] = ["not-a-digest"] + with pytest.raises(CohortStateError): + decode(_tampered_bytes(forged_pending)) + + forged_entry_digest = json.loads(content) + forged_entry_digest["record_outcomes"][0]["queue_entry_digest"] = "typescript" + with pytest.raises(CohortStateError): + decode(_tampered_bytes(forged_entry_digest)) + + forged_review_digest = json.loads(content) + forged_review_digest["record_outcomes"][0]["ground_truth_review_digest"] = "javascript" + with pytest.raises(CohortStateError): + decode(_tampered_bytes(forged_review_digest)) + + minted_ecosystem = json.loads(content) + minted_ecosystem["ecosystem"] = "typescript" + with pytest.raises(CohortStateError): + decode(_tampered_bytes(minted_ecosystem)) + + assert decode(content) == outcome + + +def test_projection_failure_is_a_closed_state_refusal(monkeypatch): + state, candidates = _prepared() + records = _js_records(state, candidates)[:1] + + def refusing(*args, **kwargs): + raise GroundTruthReviewError("projection diverged from the reviewed inputs") + + monkeypatch.setattr(cohort_ingestion, "project_accepted_ground_truth", refusing) + with pytest.raises(CohortStateError) as error: + _ingest(records, state, candidates) + assert error.value.reason is CohortStateReason.STATE_MISMATCH