mirror of
https://github.com/norandom/OpenUltraSAST.git
synced 2026-12-04 02:38:18 +00:00
feat(valid-detection-benchmark): 10.4 select and ingest third reviewed cohort
This commit is contained in:
@@ -15,7 +15,12 @@ from dataclasses import replace
|
||||
from typing import Any
|
||||
|
||||
from benchmarks.valid.catalog import candidate_request
|
||||
from benchmarks.valid.cohort_ingestion import EXTERNAL_REVIEW_RECORD_SCHEMA
|
||||
from benchmarks.valid.cohort_ingestion import (
|
||||
EXTERNAL_REVIEW_RECORD_SCHEMA,
|
||||
CohortBatchOutcomeV1,
|
||||
ingest_javascript_cohort_batch,
|
||||
ingest_python_cohort_batch,
|
||||
)
|
||||
from benchmarks.valid.ecosystem_review import (
|
||||
EcosystemReviewAttestationV1,
|
||||
EcosystemReviewDecision,
|
||||
@@ -53,6 +58,12 @@ 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)
|
||||
COMBINED_PYTHON_NAMES = tuple(f"py-{index:02d}" for index in range(PYTHON_COUNT))
|
||||
COMBINED_JAVASCRIPT_NAMES = (*JAVASCRIPT_NAMES, *TYPESCRIPT_NAMES)
|
||||
THIRD_PYTHON_NAMES = tuple(f"py3-{index:02d}" for index in range(12))
|
||||
THIRD_JAVASCRIPT_NAMES = (*(f"js3-{index:02d}" for index in range(10)), "ts3-00", "ts3-01")
|
||||
SINGLE_FAMILY_PYTHON_NAMES = tuple(f"pyinj-{index:02d}" for index in range(12))
|
||||
SINGLE_FAMILY_JAVASCRIPT_NAMES = tuple(f"jsinj-{index:02d}" for index in range(12))
|
||||
|
||||
_APPS: dict[str, dict[str, Any]] = {}
|
||||
for _index in range(PYTHON_COUNT):
|
||||
@@ -125,10 +136,88 @@ for _name, _path, _function, _family, _cwe in (
|
||||
"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",
|
||||
}
|
||||
for _index in range(12):
|
||||
_apps_key = f"pyinj-{_index:02d}"
|
||||
_APPS[_apps_key] = {
|
||||
"url": f"https://github.com/fixture/cohort-{_apps_key}",
|
||||
"repo": f"fixture/cohort-{_apps_key}",
|
||||
"path": f"pkg/inj_{_index:02d}.py",
|
||||
"function": f"invoke_{_index:02d}",
|
||||
"language": "python",
|
||||
"hint": "python",
|
||||
"family": "injection",
|
||||
"cwe": "CWE-94",
|
||||
"vulnerable": f"def invoke_{_index:02d}(query):\n return eval(query)\n",
|
||||
"fixed": f"def invoke_{_index:02d}(query):\n return str(query)\n",
|
||||
}
|
||||
for _index in range(12):
|
||||
_apps_key = f"jsinj-{_index:02d}"
|
||||
_APPS[_apps_key] = {
|
||||
"url": f"https://github.com/fixture/cohort-{_apps_key}",
|
||||
"repo": f"fixture/cohort-{_apps_key}",
|
||||
"path": f"lib/inj_{_index:02d}.js",
|
||||
"function": f"render_{_index:02d}",
|
||||
"language": "javascript",
|
||||
"hint": "javascript",
|
||||
"family": "injection",
|
||||
"cwe": "CWE-94",
|
||||
"vulnerable": f"function render_{_index:02d}(input) {{\n return eval(input);\n}}\n",
|
||||
"fixed": f"function render_{_index:02d}(input) {{\n return String(input);\n}}\n",
|
||||
}
|
||||
for _index in range(12):
|
||||
_family = "deserialization" if _index % 2 == 0 else "ssrf"
|
||||
_apps_key = f"py3-{_index:02d}"
|
||||
_APPS[_apps_key] = {
|
||||
"url": f"https://github.com/fixture/cohort-{_apps_key}",
|
||||
"repo": f"fixture/cohort-{_apps_key}",
|
||||
"path": f"app/third_{_index:02d}.py",
|
||||
"function": f"dispatch_{_index:02d}",
|
||||
"language": "python",
|
||||
"hint": "python",
|
||||
"family": _family,
|
||||
"cwe": "CWE-502" if _family == "deserialization" else "CWE-918",
|
||||
"vulnerable": f"def dispatch_{_index:02d}(payload):\n return eval(payload)\n",
|
||||
"fixed": f"def dispatch_{_index:02d}(payload):\n return str(payload)\n",
|
||||
}
|
||||
for _index in range(10):
|
||||
_family = "prototype_pollution" if _index % 2 == 0 else "output_encoding"
|
||||
_apps_key = f"js3-{_index:02d}"
|
||||
_APPS[_apps_key] = {
|
||||
"url": f"https://github.com/fixture/cohort-{_apps_key}",
|
||||
"repo": f"fixture/cohort-{_apps_key}",
|
||||
"path": f"lib/third_{_index:02d}.js",
|
||||
"function": f"merge_{_index:02d}",
|
||||
"language": "javascript",
|
||||
"hint": "javascript",
|
||||
"family": _family,
|
||||
"cwe": "CWE-1321" if _family == "prototype_pollution" else "CWE-79",
|
||||
"vulnerable": f"function merge_{_index:02d}(input) {{\n return eval(input);\n}}\n",
|
||||
"fixed": f"function merge_{_index:02d}(input) {{\n return String(input);\n}}\n",
|
||||
}
|
||||
for _name, _function, _family, _cwe in (
|
||||
("ts3-00", "loadPayload", "deserialization", "CWE-502"),
|
||||
("ts3-01", "fetchTarget", "ssrf", "CWE-918"),
|
||||
):
|
||||
_APPS[_name] = {
|
||||
"url": f"https://github.com/fixture/cohort-{_name}",
|
||||
"repo": f"fixture/cohort-{_name}",
|
||||
"path": f"src/{_name}.ts",
|
||||
"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)})
|
||||
_THIRD_ORDER = (*THIRD_PYTHON_NAMES, *THIRD_JAVASCRIPT_NAMES)
|
||||
_REVISIONS.update({name: (f"{7000 + index * 2:040x}", f"{7001 + index * 2:040x}") for index, name in enumerate(_THIRD_ORDER)})
|
||||
_SINGLE_FAMILY_ORDER = (*SINGLE_FAMILY_PYTHON_NAMES, *SINGLE_FAMILY_JAVASCRIPT_NAMES)
|
||||
_REVISIONS.update({name: (f"{8000 + index * 2:040x}", f"{8001 + index * 2:040x}") for index, name in enumerate(_SINGLE_FAMILY_ORDER)})
|
||||
READ_POLICY = bytes_digest(b"cohort-ingestion-read-policy-fixture")
|
||||
|
||||
|
||||
@@ -430,7 +519,80 @@ def model_only_assistance_digest() -> str:
|
||||
return verify.model_assistance_digest(record)
|
||||
|
||||
|
||||
def candidate_for(name: str, resolver_: RepositoryIdentityResolver) -> FixSiteCandidateV1:
|
||||
"""Build one fix-site candidate for a named fixture app."""
|
||||
return next(iter(candidates_for([request_for(name)], resolver_).values()))
|
||||
|
||||
|
||||
def replacement_cohort_state(
|
||||
python_names: tuple[str, ...] = (*COMBINED_PYTHON_NAMES, *THIRD_PYTHON_NAMES),
|
||||
javascript_names: tuple[str, ...] = (*COMBINED_JAVASCRIPT_NAMES, *THIRD_JAVASCRIPT_NAMES),
|
||||
*,
|
||||
per_ecosystem_cap: int | None = None,
|
||||
resolver_: RepositoryIdentityResolver | None = None,
|
||||
authority_: ReservationAuthority | None = None,
|
||||
) -> tuple[SourcingQueueStateV1, RepositoryIdentityResolver]:
|
||||
"""One shared queue state carrying the ingested cohorts and the pending third.
|
||||
|
||||
Every cohort round reads this same state, so the accepted ledger and the
|
||||
pending queues always share one reservation-census snapshot.
|
||||
"""
|
||||
resolved = resolver_ or resolver()
|
||||
cap = per_ecosystem_cap or max(len(python_names), len(javascript_names))
|
||||
state = build_sourcing_queue(
|
||||
[request_for(name) for name in (*python_names, *javascript_names)],
|
||||
reader=FakeReader(),
|
||||
resolver=resolved,
|
||||
authority=authority_ or authority(resolved),
|
||||
policy=sourcing_queue_policy(per_ecosystem_cap=cap, required_families=2),
|
||||
enumeration_actor=ENUMERATION_ACTOR,
|
||||
enumeration_reviewer=ENUMERATION_REVIEWER,
|
||||
)
|
||||
return state, resolved
|
||||
|
||||
|
||||
def ingested_replacement_ledger(
|
||||
state: SourcingQueueStateV1,
|
||||
resolved: RepositoryIdentityResolver,
|
||||
*,
|
||||
python_names: tuple[str, ...] = COMBINED_PYTHON_NAMES,
|
||||
javascript_names: tuple[str, ...] = COMBINED_JAVASCRIPT_NAMES,
|
||||
weakened_python: int = 0,
|
||||
weakened_javascript: int = 0,
|
||||
) -> tuple[CohortBatchOutcomeV1, ...]:
|
||||
"""Ingest the committed first cohorts against one shared queue state."""
|
||||
batches: list[CohortBatchOutcomeV1] = []
|
||||
rounds = (
|
||||
("python", python_names, weakened_python, ingest_python_cohort_batch),
|
||||
("javascript", javascript_names, weakened_javascript, ingest_javascript_cohort_batch),
|
||||
)
|
||||
for ecosystem, names, weakened, ingest in rounds:
|
||||
if not names:
|
||||
continue
|
||||
queue = state.python_queue if ecosystem == "python" else state.javascript_queue
|
||||
by_candidate = {entry.candidate_digest: entry for entry in queue.entries}
|
||||
candidates = {name: candidate_for(name, resolved) for name in names}
|
||||
records = []
|
||||
for index, name in enumerate(names):
|
||||
candidate = candidates[name]
|
||||
entry = by_candidate[candidate.candidate_digest]
|
||||
changes = {"in_repository_reachable": False} if index < weakened else None
|
||||
records.append(reviewed_record(entry, candidate, ecosystem=ecosystem, gt_changes=changes)[0])
|
||||
batches.append(
|
||||
ingest(
|
||||
records,
|
||||
state=state,
|
||||
candidates_by_digest={item.candidate_digest: item for item in candidates.values()},
|
||||
expected_ecosystem_policy_digest=ECOSYSTEM_POLICY,
|
||||
expected_ground_truth_policy_digest=GROUND_TRUTH_POLICY,
|
||||
)
|
||||
)
|
||||
return tuple(batches)
|
||||
|
||||
|
||||
__all__ = [
|
||||
"COMBINED_JAVASCRIPT_NAMES",
|
||||
"COMBINED_PYTHON_NAMES",
|
||||
"ECOSYSTEM_POLICY",
|
||||
"ECOSYSTEM_PRODUCER",
|
||||
"ECOSYSTEM_REVIEWER",
|
||||
@@ -443,16 +605,23 @@ __all__ = [
|
||||
"PYTHON_COUNT",
|
||||
"READ_POLICY",
|
||||
"RepositoryEcosystemReviewV1",
|
||||
"SINGLE_FAMILY_JAVASCRIPT_NAMES",
|
||||
"SINGLE_FAMILY_PYTHON_NAMES",
|
||||
"THIRD_JAVASCRIPT_NAMES",
|
||||
"THIRD_PYTHON_NAMES",
|
||||
"TYPESCRIPT_NAMES",
|
||||
"authority",
|
||||
"candidate_for",
|
||||
"candidates_for",
|
||||
"case_for",
|
||||
"ingested_replacement_ledger",
|
||||
"javascript_cohort_state",
|
||||
"javascript_entries",
|
||||
"javascript_request_names",
|
||||
"model_only_assistance_digest",
|
||||
"python_cohort_state",
|
||||
"python_entries",
|
||||
"replacement_cohort_state",
|
||||
"request_for",
|
||||
"resolver",
|
||||
"reviewed_record",
|
||||
|
||||
@@ -0,0 +1,367 @@
|
||||
"""Outcome-blind selection of the third bounded cohort batch over pending queues."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import sys
|
||||
from dataclasses import replace
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
||||
|
||||
from cohort_ingestion_fixtures import ( # noqa: E402
|
||||
COMBINED_JAVASCRIPT_NAMES,
|
||||
COMBINED_PYTHON_NAMES,
|
||||
ECOSYSTEM_POLICY,
|
||||
GROUND_TRUTH_POLICY,
|
||||
READ_POLICY,
|
||||
SINGLE_FAMILY_JAVASCRIPT_NAMES,
|
||||
SINGLE_FAMILY_PYTHON_NAMES,
|
||||
THIRD_JAVASCRIPT_NAMES,
|
||||
THIRD_PYTHON_NAMES,
|
||||
_Client,
|
||||
_read_authority,
|
||||
_settings,
|
||||
authority,
|
||||
ingested_replacement_ledger,
|
||||
replacement_cohort_state,
|
||||
resolver,
|
||||
)
|
||||
|
||||
from benchmarks.valid.artifact_repository import S3ArtifactRepository # noqa: E402
|
||||
from benchmarks.valid.cohort_selection import ( # noqa: E402
|
||||
COHORT_BATCH_CAP,
|
||||
CohortSelectionReason,
|
||||
CohortSelectionStateError,
|
||||
CohortSelectionStateReason,
|
||||
CohortSelectionStatus,
|
||||
cohort_selection,
|
||||
cohort_selection_bytes,
|
||||
select_third_cohort_batch,
|
||||
)
|
||||
from benchmarks.valid.cohort_selection_store import ( # noqa: E402
|
||||
decode_cohort_selection,
|
||||
persist_cohort_selection,
|
||||
resume_cohort_selection,
|
||||
)
|
||||
from benchmarks.valid.replacement_artifact_contract import ArtifactAccessClass, ArtifactKind, validate_artifact # noqa: E402
|
||||
from benchmarks.valid.reservation import legacy_reservation_source # noqa: E402
|
||||
from benchmarks.valid.sourcing_queue import ecosystem_review_queue, sourcing_queue_policy, sourcing_queue_state # noqa: E402
|
||||
from openultrasast.core.canonical import content_digest # noqa: E402
|
||||
|
||||
THIRD_PYTHON_FAMILIES = {"deserialization", "ssrf"}
|
||||
|
||||
|
||||
@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 _select(state, ledger, *, eco=ECOSYSTEM_POLICY, gt=GROUND_TRUTH_POLICY):
|
||||
return select_third_cohort_batch(
|
||||
state=state,
|
||||
accepted_batches=ledger,
|
||||
expected_ecosystem_policy_digest=eco,
|
||||
expected_ground_truth_policy_digest=gt,
|
||||
)
|
||||
|
||||
|
||||
def _prepared():
|
||||
state, resolved = replacement_cohort_state()
|
||||
ledger = ingested_replacement_ledger(state, resolved)
|
||||
return state, resolved, ledger
|
||||
|
||||
|
||||
def test_selection_balances_family_coverage_across_both_ecosystems():
|
||||
state, resolved, ledger = _prepared()
|
||||
assert {batch.ecosystem for batch in ledger} == {"python", "javascript"}
|
||||
|
||||
selection = _select(state, ledger)
|
||||
|
||||
assert selection.status is CohortSelectionStatus.SELECTED
|
||||
assert selection.ecosystem == "python"
|
||||
assert selection.reason is CohortSelectionReason.BALANCED_PROGRESS_SELECTED
|
||||
expected = sorted(
|
||||
entry.entry_digest for entry in state.python_queue.entries if entry.family.vulnerability_family in THIRD_PYTHON_FAMILIES
|
||||
)
|
||||
assert selection.selected_entries == tuple(expected)
|
||||
assert selection.targeted_families == ("deserialization", "ssrf")
|
||||
assert selection.accepted_families == ("injection", "output_encoding", "path_traversal")
|
||||
assert dict(selection.accepted_by_ecosystem) == {"javascript": 12, "python": 12}
|
||||
assert selection.census_digest == state.census_digest
|
||||
assert selection.queue_digest == state.python_queue.queue_digest
|
||||
assert selection.prior_batch_digests == tuple(sorted(batch.batch_digest for batch in ledger))
|
||||
assert decode_cohort_selection(cohort_selection_bytes(selection)) == selection
|
||||
|
||||
|
||||
def test_selection_targets_a_missing_ecosystem_to_preserve_both():
|
||||
state, resolved = replacement_cohort_state()
|
||||
ledger = ingested_replacement_ledger(state, resolved, javascript_names=())
|
||||
|
||||
selection = _select(state, ledger)
|
||||
|
||||
assert selection.status is CohortSelectionStatus.SELECTED
|
||||
assert selection.ecosystem == "javascript"
|
||||
assert selection.reason is CohortSelectionReason.MISSING_ECOSYSTEM_SELECTED
|
||||
assert dict(selection.accepted_by_ecosystem) == {"python": 12}
|
||||
pending = sorted(state.javascript_queue.entries, key=lambda entry: entry.entry_digest)
|
||||
assert selection.selected_entries == tuple(entry.entry_digest for entry in pending[:COHORT_BATCH_CAP])
|
||||
assert selection.targeted_families == tuple(
|
||||
sorted({entry.family.vulnerability_family for entry in pending[:COHORT_BATCH_CAP]})
|
||||
)
|
||||
|
||||
|
||||
def test_selection_targets_the_second_vulnerability_family_gap():
|
||||
state, resolved = replacement_cohort_state(
|
||||
python_names=("py-01", "py-03", *SINGLE_FAMILY_PYTHON_NAMES, *THIRD_PYTHON_NAMES),
|
||||
javascript_names=("js-01", *SINGLE_FAMILY_JAVASCRIPT_NAMES, *THIRD_JAVASCRIPT_NAMES),
|
||||
)
|
||||
ledger = ingested_replacement_ledger(
|
||||
state,
|
||||
resolved,
|
||||
python_names=("py-01", "py-03", *SINGLE_FAMILY_PYTHON_NAMES),
|
||||
javascript_names=("js-01", *SINGLE_FAMILY_JAVASCRIPT_NAMES),
|
||||
weakened_python=2,
|
||||
weakened_javascript=1,
|
||||
)
|
||||
ledger_families = {
|
||||
scope.vulnerability_family
|
||||
for batch in ledger
|
||||
for item in batch.accepted_positives
|
||||
for scope in item.verified_scopes
|
||||
}
|
||||
assert ledger_families == {"injection"}
|
||||
|
||||
selection = _select(state, ledger)
|
||||
|
||||
assert selection.status is CohortSelectionStatus.SELECTED
|
||||
assert selection.reason is CohortSelectionReason.FAMILY_GAP_SELECTED
|
||||
assert selection.ecosystem == "javascript"
|
||||
assert selection.targeted_families == ("deserialization", "output_encoding", "prototype_pollution", "ssrf")
|
||||
js_batch = next(batch for batch in ledger if batch.ecosystem == "javascript")
|
||||
pending = set(js_batch.pending_entries)
|
||||
assert set(selection.selected_entries) == pending
|
||||
typescript = [entry for entry in state.javascript_queue.entries if entry.observed_language == "typescript"]
|
||||
assert typescript and all(entry.entry_digest in pending for entry in typescript)
|
||||
assert all(entry.canonical_ecosystem == "javascript" for entry in typescript)
|
||||
|
||||
|
||||
def test_selection_ignores_how_many_reviews_passed():
|
||||
state, resolved = replacement_cohort_state()
|
||||
full = ingested_replacement_ledger(state, resolved)
|
||||
thinned = ingested_replacement_ledger(state, resolved, weakened_python=2)
|
||||
assert len(thinned[0].accepted_positives) < len(full[0].accepted_positives)
|
||||
|
||||
chosen = _select(state, full)
|
||||
other = _select(state, thinned)
|
||||
|
||||
assert (chosen.status, chosen.reason, chosen.ecosystem) == (other.status, other.reason, other.ecosystem)
|
||||
assert chosen.selected_entries == other.selected_entries
|
||||
assert chosen.targeted_families == other.targeted_families
|
||||
assert chosen.selection_digest != other.selection_digest
|
||||
|
||||
|
||||
def test_selection_refuses_a_reweighted_policy_after_judgments():
|
||||
state, resolved, ledger = _prepared()
|
||||
|
||||
changed = _select(state, ledger, eco=content_digest({"policy": "reweighted-after-outcomes"}))
|
||||
frozen = _select(state, ledger)
|
||||
|
||||
assert changed.status is CohortSelectionStatus.REFUSED
|
||||
assert changed.reason is CohortSelectionReason.POLICY_MISMATCH
|
||||
assert changed.selected_entries == () and changed.targeted_families == ()
|
||||
assert frozen.status is CohortSelectionStatus.SELECTED
|
||||
|
||||
|
||||
def test_selection_refuses_a_stale_reservation_census():
|
||||
state, resolved, ledger = _prepared()
|
||||
reserved = legacy_reservation_source(
|
||||
resolved, repository="https://github.com/fixture/cohort-pyinj-00", source_digest="c" * 64
|
||||
)
|
||||
stale_state, _ = replacement_cohort_state(authority_=authority(resolver(), legacy=(reserved,)))
|
||||
assert stale_state.census_digest != state.census_digest
|
||||
assert [entry.entry_digest for entry in stale_state.python_queue.entries] == [
|
||||
entry.entry_digest for entry in state.python_queue.entries
|
||||
]
|
||||
|
||||
selection = _select(stale_state, ledger)
|
||||
|
||||
assert selection.status is CohortSelectionStatus.REFUSED
|
||||
assert selection.reason is CohortSelectionReason.CENSUS_MISMATCH
|
||||
assert selection.census_digest == stale_state.census_digest
|
||||
assert decode_cohort_selection(cohort_selection_bytes(selection)) == selection
|
||||
|
||||
|
||||
def test_selection_without_pending_entries_refuses_closed():
|
||||
state, _, ledger = _prepared()
|
||||
policy = sourcing_queue_policy(per_ecosystem_cap=1)
|
||||
empty = sourcing_queue_state(
|
||||
python_queue=ecosystem_review_queue("python", cap=1, policy_digest=policy.policy_digest, entries=()),
|
||||
javascript_queue=ecosystem_review_queue("javascript", cap=1, policy_digest=policy.policy_digest, entries=()),
|
||||
exclusions=(),
|
||||
census_digest=state.census_digest,
|
||||
policy_digest=policy.policy_digest,
|
||||
)
|
||||
|
||||
selection = _select(empty, ledger)
|
||||
|
||||
assert selection.status is CohortSelectionStatus.REFUSED
|
||||
assert selection.reason is CohortSelectionReason.NO_PENDING_ENTRIES
|
||||
assert selection.ecosystem is None and selection.queue_digest is None
|
||||
assert decode_cohort_selection(cohort_selection_bytes(selection)) == selection
|
||||
|
||||
|
||||
def test_selection_is_deterministic_across_permutations():
|
||||
forward, resolved = replacement_cohort_state()
|
||||
backward, _ = replacement_cohort_state(
|
||||
python_names=tuple(reversed((*COMBINED_PYTHON_NAMES, *THIRD_PYTHON_NAMES))),
|
||||
javascript_names=tuple(reversed((*COMBINED_JAVASCRIPT_NAMES, *THIRD_JAVASCRIPT_NAMES))),
|
||||
)
|
||||
assert forward.state_digest == backward.state_digest
|
||||
ledger = ingested_replacement_ledger(forward, resolved)
|
||||
|
||||
assert _select(forward, ledger) == _select(backward, ledger)
|
||||
|
||||
|
||||
def test_selection_caps_at_twenty_preferring_family_gaps():
|
||||
state, resolved = replacement_cohort_state(
|
||||
python_names=(*COMBINED_PYTHON_NAMES, *THIRD_PYTHON_NAMES, *SINGLE_FAMILY_PYTHON_NAMES),
|
||||
)
|
||||
ledger = ingested_replacement_ledger(state, resolved)
|
||||
|
||||
selection = _select(state, ledger)
|
||||
|
||||
assert selection.status is CohortSelectionStatus.SELECTED
|
||||
assert selection.ecosystem == "python"
|
||||
assert len(selection.selected_entries) == COHORT_BATCH_CAP
|
||||
gap_entries = {
|
||||
entry.entry_digest
|
||||
for entry in state.python_queue.entries
|
||||
if entry.family.vulnerability_family in {"deserialization", "ssrf"}
|
||||
}
|
||||
assert gap_entries <= set(selection.selected_entries)
|
||||
python_batch = next(batch for batch in ledger if batch.ecosystem == "python")
|
||||
unselected = [
|
||||
entry
|
||||
for entry in state.python_queue.entries
|
||||
if entry.entry_digest in set(python_batch.pending_entries)
|
||||
and entry.entry_digest not in set(selection.selected_entries)
|
||||
]
|
||||
assert len(unselected) == 4
|
||||
assert {entry.family.vulnerability_family for entry in unselected} == {"injection"}
|
||||
|
||||
|
||||
def test_selection_decodes_hostile_bytes_and_persists_durably():
|
||||
state, resolved, ledger = _prepared()
|
||||
selection = _select(state, ledger)
|
||||
content = cohort_selection_bytes(selection)
|
||||
assert content and decode_cohort_selection(content) == selection
|
||||
|
||||
good = json.loads(content)
|
||||
spaced = json.dumps(good, sort_keys=True, indent=1).encode("utf-8")
|
||||
wrong_schema = json.dumps({**good, "schema_version": "other.v1"}, sort_keys=True, separators=(",", ":")).encode("utf-8")
|
||||
tampered = json.dumps({**good, "reason": "no_pending_entries"}, sort_keys=True, separators=(",", ":")).encode("utf-8")
|
||||
for bad in (
|
||||
b"",
|
||||
b"not json at all",
|
||||
b'{"x":NaN}',
|
||||
b'{"x":1e999}',
|
||||
b'{"k":' + b"[" * 20000 + b"]" * 20000 + b"}",
|
||||
spaced,
|
||||
wrong_schema,
|
||||
tampered,
|
||||
):
|
||||
with pytest.raises(CohortSelectionStateError):
|
||||
decode_cohort_selection(bad)
|
||||
|
||||
client = _Client()
|
||||
store = S3ArtifactRepository(_settings(), client)
|
||||
reference = persist_cohort_selection(store, selection)
|
||||
assert persist_cohort_selection(store, selection) == reference
|
||||
accepted = store.get(
|
||||
reference, expected_kind=ArtifactKind.POPULATION, authority=_read_authority(), expected_access_policy_digest=READ_POLICY
|
||||
)
|
||||
validate_artifact(accepted.content, reference=reference)
|
||||
assert reference.access_class is ArtifactAccessClass.OPERATOR_SAFE
|
||||
|
||||
resumed = resume_cohort_selection(
|
||||
S3ArtifactRepository(_settings(), client), reference, authority=_read_authority(), expected_access_policy_digest=READ_POLICY
|
||||
)
|
||||
assert resumed == selection
|
||||
assert cohort_selection_bytes(resumed) == content
|
||||
|
||||
|
||||
def test_malformed_ledgers_and_states_fail_closed():
|
||||
state, _, ledger = _prepared()
|
||||
forged_census = replace(ledger[0], census_digest="z" * 64)
|
||||
wrong_ecosystem = replace(ledger[0], ecosystem="typescript")
|
||||
for bad in (None, {"ecosystem": "python"}, forged_census, wrong_ecosystem):
|
||||
with pytest.raises(CohortSelectionStateError) as error:
|
||||
_select(state, (bad,))
|
||||
assert error.value.reason is CohortSelectionStateReason.STATE_MISMATCH
|
||||
|
||||
with pytest.raises(CohortSelectionStateError):
|
||||
_select({"python_queue": ()}, ledger)
|
||||
|
||||
|
||||
def test_selection_module_and_outputs_avoid_out_of_scope_machinery():
|
||||
root = Path(__file__).resolve().parents[1]
|
||||
for name in ("benchmarks/valid/cohort_selection.py", "benchmarks/valid/cohort_selection_store.py"):
|
||||
source = (root / name).read_bytes()
|
||||
for forbidden in (b"admission", b"detector", b"observation", b"label", b"verdict", b"score"):
|
||||
assert forbidden not in source, f"{name} references out-of-scope machinery: {forbidden!r}"
|
||||
|
||||
state, resolved, ledger = _prepared()
|
||||
content = cohort_selection_bytes(_select(state, ledger))
|
||||
for forbidden in (b"admission", b"detector", b"observation", b"label", b"verdict", b"score"):
|
||||
assert forbidden not in content
|
||||
|
||||
stale = (root / "benchmarks/valid/cohort_ingestion.py").read_bytes()
|
||||
assert b"pending Python review queue entry" not in stale
|
||||
|
||||
|
||||
def test_refused_selections_never_carry_entries_or_families():
|
||||
state, resolved, ledger = _prepared()
|
||||
refused = _select(state, ledger, gt=content_digest({"policy": "changed"}))
|
||||
rebuilt = cohort_selection(
|
||||
ecosystem=refused.ecosystem,
|
||||
selected_entries=refused.selected_entries,
|
||||
targeted_families=refused.targeted_families,
|
||||
queue_digest=refused.queue_digest,
|
||||
census_digest=refused.census_digest,
|
||||
ecosystem_policy_digest=refused.ecosystem_policy_digest,
|
||||
ground_truth_policy_digest=refused.ground_truth_policy_digest,
|
||||
prior_batch_digests=refused.prior_batch_digests,
|
||||
accepted_families=refused.accepted_families,
|
||||
accepted_by_ecosystem=dict(refused.accepted_by_ecosystem),
|
||||
status=refused.status,
|
||||
reason=refused.reason,
|
||||
)
|
||||
assert rebuilt == refused
|
||||
with pytest.raises(CohortSelectionStateError):
|
||||
cohort_selection(
|
||||
ecosystem=None,
|
||||
selected_entries=(),
|
||||
targeted_families=(),
|
||||
queue_digest=None,
|
||||
census_digest=refused.census_digest,
|
||||
ecosystem_policy_digest=refused.ecosystem_policy_digest,
|
||||
ground_truth_policy_digest=refused.ground_truth_policy_digest,
|
||||
prior_batch_digests=refused.prior_batch_digests,
|
||||
accepted_families=refused.accepted_families,
|
||||
accepted_by_ecosystem=dict(refused.accepted_by_ecosystem),
|
||||
status=CohortSelectionStatus.SELECTED,
|
||||
reason=refused.reason,
|
||||
)
|
||||
@@ -0,0 +1,299 @@
|
||||
"""Bounded ingestion of the third independently reviewed replacement cohort."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
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
|
||||
COMBINED_PYTHON_NAMES,
|
||||
ECOSYSTEM_POLICY,
|
||||
GROUND_TRUTH_POLICY,
|
||||
SINGLE_FAMILY_PYTHON_NAMES,
|
||||
THIRD_JAVASCRIPT_NAMES,
|
||||
THIRD_PYTHON_NAMES,
|
||||
candidate_for,
|
||||
ingested_replacement_ledger,
|
||||
model_only_assistance_digest,
|
||||
replacement_cohort_state,
|
||||
reviewed_record,
|
||||
)
|
||||
|
||||
from benchmarks.valid.cohort_ingestion import ( # noqa: E402
|
||||
COHORT_BATCH_CAP,
|
||||
MINIMUM_ACCEPTED_POSITIVES,
|
||||
CohortBatchStatus,
|
||||
CohortInsufficientReason,
|
||||
cohort_batch_bytes,
|
||||
)
|
||||
from benchmarks.valid.cohort_selection import ( # noqa: E402
|
||||
CohortSelectionStateError,
|
||||
CohortSelectionStateReason,
|
||||
CohortSelectionStatus,
|
||||
cohort_selection,
|
||||
cohort_selection_bytes,
|
||||
ingest_third_cohort_batch,
|
||||
select_third_cohort_batch,
|
||||
)
|
||||
from benchmarks.valid.ground_truth_review import VerifiedScope # noqa: E402
|
||||
from openultrasast.core.canonical import bytes_digest # noqa: E402
|
||||
|
||||
|
||||
@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 _select(state, ledger):
|
||||
return select_third_cohort_batch(
|
||||
state=state,
|
||||
accepted_batches=ledger,
|
||||
expected_ecosystem_policy_digest=ECOSYSTEM_POLICY,
|
||||
expected_ground_truth_policy_digest=GROUND_TRUTH_POLICY,
|
||||
)
|
||||
|
||||
|
||||
def _candidates(resolved, names):
|
||||
candidates = {}
|
||||
for name in names:
|
||||
candidate = candidate_for(name, resolved)
|
||||
candidates[candidate.candidate_digest] = candidate
|
||||
return candidates
|
||||
|
||||
|
||||
def _prepared():
|
||||
state, resolved = replacement_cohort_state()
|
||||
ledger = ingested_replacement_ledger(state, resolved)
|
||||
selection = _select(state, ledger)
|
||||
candidates = _candidates(resolved, (*THIRD_PYTHON_NAMES, *THIRD_JAVASCRIPT_NAMES))
|
||||
return state, resolved, ledger, selection, candidates
|
||||
|
||||
|
||||
def _selected_entries(state, selection):
|
||||
wanted = set(selection.selected_entries)
|
||||
queue = state.python_queue if selection.ecosystem == "python" else state.javascript_queue
|
||||
return [entry for entry in queue.entries if entry.entry_digest in wanted]
|
||||
|
||||
|
||||
def _ingest(records, selection, state, candidates):
|
||||
return ingest_third_cohort_batch(
|
||||
records,
|
||||
selection=selection,
|
||||
state=state,
|
||||
candidates_by_digest=candidates,
|
||||
expected_ecosystem_policy_digest=ECOSYSTEM_POLICY,
|
||||
expected_ground_truth_policy_digest=GROUND_TRUTH_POLICY,
|
||||
)
|
||||
|
||||
|
||||
def test_third_cohort_contributes_ten_accepted_reachable_positives_and_replays():
|
||||
state, resolved, ledger, selection, candidates = _prepared()
|
||||
assert selection.status is CohortSelectionStatus.SELECTED
|
||||
entries = _selected_entries(state, selection)
|
||||
assert MINIMUM_ACCEPTED_POSITIVES <= len(entries) <= COHORT_BATCH_CAP
|
||||
records = [reviewed_record(entry, candidates[entry.candidate_digest])[0] for entry in entries]
|
||||
|
||||
outcome = _ingest(records, selection, state, candidates)
|
||||
|
||||
assert outcome.status is CohortBatchStatus.ACCEPTED
|
||||
assert outcome.insufficient_reason is None
|
||||
assert len(outcome.accepted_positives) == len(entries) >= MINIMUM_ACCEPTED_POSITIVES
|
||||
assert outcome.pending_entries == ()
|
||||
assert all(item.status.value == "accepted" for item in outcome.record_outcomes)
|
||||
assert all(
|
||||
scope.ecosystem.value == "python" for positive in outcome.accepted_positives for scope in positive.verified_scopes
|
||||
)
|
||||
assert {scope.vulnerability_family for p in outcome.accepted_positives for scope in p.verified_scopes} == {
|
||||
"deserialization",
|
||||
"ssrf",
|
||||
}
|
||||
assert outcome.census_digest == state.census_digest
|
||||
assert outcome.queue_digest != state.python_queue.queue_digest
|
||||
|
||||
replayed = _ingest(list(reversed(records)), selection, state, candidates)
|
||||
assert replayed == outcome
|
||||
assert replayed.batch_digest == outcome.batch_digest
|
||||
|
||||
combined = [*ledger[0].accepted_positives, *ledger[1].accepted_positives, *outcome.accepted_positives]
|
||||
assert {batch.ecosystem for batch in ledger} == {"python", "javascript"}
|
||||
assert len({item.change_identity_digest for item in combined}) == len(combined) == 36
|
||||
assert len(combined) < 40
|
||||
assert dict(selection.accepted_by_ecosystem) == {"javascript": 12, "python": 12}
|
||||
|
||||
|
||||
def test_third_cohort_stays_pending_without_external_records():
|
||||
state, resolved, ledger, selection, candidates = _prepared()
|
||||
entries = _selected_entries(state, selection)
|
||||
records = [reviewed_record(entry, candidates[entry.candidate_digest])[0] for entry in entries]
|
||||
|
||||
empty = _ingest([], selection, state, candidates)
|
||||
assert empty.status is CohortBatchStatus.INSUFFICIENT
|
||||
assert empty.insufficient_reason is CohortInsufficientReason.BATCH_EMPTY
|
||||
assert empty.accepted_positives == ()
|
||||
assert empty.pending_entries == selection.selected_entries
|
||||
|
||||
partial = _ingest(records[:3], selection, state, candidates)
|
||||
assert partial.status is CohortBatchStatus.INSUFFICIENT
|
||||
assert partial.insufficient_reason is CohortInsufficientReason.INSUFFICIENT_ACCEPTED_POSITIVES
|
||||
assert len(partial.accepted_positives) == 3
|
||||
answered = {item.queue_entry_digest for item in partial.record_outcomes if item.queue_entry_digest is not None}
|
||||
assert partial.pending_entries == tuple(sorted(set(selection.selected_entries) - answered))
|
||||
|
||||
|
||||
def test_records_outside_the_selected_batch_are_excluded_closed():
|
||||
python_names = (*COMBINED_PYTHON_NAMES, *THIRD_PYTHON_NAMES, *SINGLE_FAMILY_PYTHON_NAMES)
|
||||
state, resolved = replacement_cohort_state(python_names=python_names)
|
||||
ledger = ingested_replacement_ledger(state, resolved)
|
||||
selection = _select(state, ledger)
|
||||
candidates = _candidates(resolved, python_names)
|
||||
|
||||
entries = _selected_entries(state, selection)
|
||||
assert len(entries) == COHORT_BATCH_CAP
|
||||
python_batch = next(batch for batch in ledger if batch.ecosystem == "python")
|
||||
outside = [
|
||||
entry
|
||||
for entry in state.python_queue.entries
|
||||
if entry.entry_digest in set(python_batch.pending_entries)
|
||||
and entry.entry_digest not in set(selection.selected_entries)
|
||||
]
|
||||
assert len(outside) == 4
|
||||
assert {entry.family.vulnerability_family for entry in outside} == {"injection"}
|
||||
outsider = reviewed_record(outside[0], candidates[outside[0].candidate_digest])[0]
|
||||
records = [reviewed_record(entry, candidates[entry.candidate_digest])[0] for entry in entries[:-1]] + [outsider]
|
||||
|
||||
outcome = _ingest(records, selection, state, candidates)
|
||||
|
||||
assert outcome.status is CohortBatchStatus.ACCEPTED
|
||||
assert len(outcome.accepted_positives) == COHORT_BATCH_CAP - 1
|
||||
unknown = [item for item in outcome.record_outcomes if item.reason == "queue_entry_unknown"]
|
||||
assert len(unknown) == 1
|
||||
assert unknown[0].queue_entry_digest == outside[0].entry_digest
|
||||
assert unknown[0].record_digest == bytes_digest(outsider)
|
||||
assert outside[0].entry_digest not in outcome.pending_entries
|
||||
|
||||
|
||||
def test_every_accepted_and_excluded_record_replays_from_external_evidence():
|
||||
state, resolved, ledger, selection, candidates = _prepared()
|
||||
entries = _selected_entries(state, selection)
|
||||
weakened = [
|
||||
{"conflict_disclosed": False},
|
||||
{"defect_present": None},
|
||||
{"in_repository_reachable": False},
|
||||
{"verified_scopes": ()},
|
||||
{"policy_satisfied": False},
|
||||
{"reviewer_identity": f"producer-{entries[5].family.advisory_locator}@example.invalid"},
|
||||
{
|
||||
"defect_present": None,
|
||||
"fix_addresses": None,
|
||||
"in_repository_reachable": None,
|
||||
"model_assistance_digest": model_only_assistance_digest(),
|
||||
},
|
||||
{"verified_scopes": (VerifiedScope("injection", "javascript"),)},
|
||||
]
|
||||
records = []
|
||||
expected = {}
|
||||
for index, entry in enumerate(entries):
|
||||
changes = weakened[index] if index < len(weakened) else None
|
||||
if index == len(entries) - 1:
|
||||
own = entry.family.vulnerability_family
|
||||
second = "ssrf" if own != "ssrf" else "deserialization"
|
||||
changes = {"verified_scopes": (VerifiedScope(own, "python"), VerifiedScope(second, "python"))}
|
||||
content, review = reviewed_record(entry, candidates[entry.candidate_digest], gt_changes=changes)
|
||||
records.append(content)
|
||||
expected[entry.entry_digest] = review
|
||||
|
||||
outcome = _ingest(records, selection, state, candidates)
|
||||
replayed = _ingest(list(reversed(records)), selection, state, candidates)
|
||||
assert replayed == outcome
|
||||
assert replayed.batch_digest == outcome.batch_digest
|
||||
|
||||
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.verified_scopes:
|
||||
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
|
||||
|
||||
assert outcome.status is CohortBatchStatus.INSUFFICIENT
|
||||
assert outcome.insufficient_reason is CohortInsufficientReason.INSUFFICIENT_ACCEPTED_POSITIVES
|
||||
multi_scope = [positive for positive in outcome.accepted_positives if len(positive.verified_scopes) == 2]
|
||||
assert len(multi_scope) == 1
|
||||
families = {scope.vulnerability_family for scope in multi_scope[0].verified_scopes}
|
||||
assert len(families) == 2 and families <= {"deserialization", "ssrf"}
|
||||
assert all(scope.ecosystem.value == "python" for scope in multi_scope[0].verified_scopes)
|
||||
assert len({item.change_identity_digest for item in outcome.accepted_positives}) == len(outcome.accepted_positives)
|
||||
|
||||
|
||||
def test_selection_binding_guard_refuses_mismatched_selections():
|
||||
state, resolved, ledger, selection, candidates = _prepared()
|
||||
refused = _select(state, ledger)
|
||||
assert refused.status is CohortSelectionStatus.SELECTED
|
||||
|
||||
other, _ = replacement_cohort_state(python_names=(*COMBINED_PYTHON_NAMES,))
|
||||
with pytest.raises(CohortSelectionStateError) as error:
|
||||
_ingest([], selection, other, candidates)
|
||||
assert error.value.reason is CohortSelectionStateReason.STATE_MISMATCH
|
||||
|
||||
forged_entry = cohort_selection(
|
||||
ecosystem="python",
|
||||
selected_entries=("f" * 64,),
|
||||
targeted_families=("deserialization",),
|
||||
queue_digest=selection.queue_digest,
|
||||
census_digest=selection.census_digest,
|
||||
ecosystem_policy_digest=ECOSYSTEM_POLICY,
|
||||
ground_truth_policy_digest=GROUND_TRUTH_POLICY,
|
||||
prior_batch_digests=selection.prior_batch_digests,
|
||||
accepted_families=selection.accepted_families,
|
||||
accepted_by_ecosystem=dict(selection.accepted_by_ecosystem),
|
||||
status=CohortSelectionStatus.SELECTED,
|
||||
reason=selection.reason,
|
||||
)
|
||||
wrong_queue = cohort_selection(
|
||||
ecosystem="python",
|
||||
selected_entries=selection.selected_entries,
|
||||
targeted_families=selection.targeted_families,
|
||||
queue_digest="e" * 64,
|
||||
census_digest=selection.census_digest,
|
||||
ecosystem_policy_digest=ECOSYSTEM_POLICY,
|
||||
ground_truth_policy_digest=GROUND_TRUTH_POLICY,
|
||||
prior_batch_digests=selection.prior_batch_digests,
|
||||
accepted_families=selection.accepted_families,
|
||||
accepted_by_ecosystem=dict(selection.accepted_by_ecosystem),
|
||||
status=CohortSelectionStatus.SELECTED,
|
||||
reason=selection.reason,
|
||||
)
|
||||
for bad in (forged_entry, wrong_queue):
|
||||
with pytest.raises(CohortSelectionStateError) as error:
|
||||
_ingest([], bad, state, candidates)
|
||||
assert error.value.reason is CohortSelectionStateReason.STATE_MISMATCH
|
||||
|
||||
|
||||
def test_third_cohort_outputs_carry_no_out_of_scope_machinery():
|
||||
state, resolved, ledger, selection, candidates = _prepared()
|
||||
entries = _selected_entries(state, selection)
|
||||
records = [reviewed_record(entry, candidates[entry.candidate_digest])[0] for entry in entries]
|
||||
outcome = _ingest(records, selection, state, candidates)
|
||||
assert outcome.status is CohortBatchStatus.ACCEPTED
|
||||
|
||||
for content in (cohort_batch_bytes(outcome), cohort_selection_bytes(selection)):
|
||||
for forbidden in (b"admission", b"detector", b"observation", b"label", b"verdict", b"score"):
|
||||
assert forbidden not in content
|
||||
Reference in New Issue
Block a user