mirror of
https://github.com/norandom/OpenUltraSAST.git
synced 2026-12-03 10:18:18 +00:00
feat(valid-detection-benchmark): 10.5 ingest fourth cohort and close positive set
This commit is contained in:
@@ -62,6 +62,8 @@ 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")
|
||||
FOURTH_PYTHON_NAMES = tuple(f"py4-{index:02d}" for index in range(12))
|
||||
FOURTH_JAVASCRIPT_NAMES = (*(f"js4-{index:02d}" for index in range(10)), "ts4-00", "ts4-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))
|
||||
|
||||
@@ -210,12 +212,60 @@ for _name, _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):
|
||||
_family = "file_disclosure" if _index % 2 == 0 else "open_redirect"
|
||||
_apps_key = f"py4-{_index:02d}"
|
||||
_APPS[_apps_key] = {
|
||||
"url": f"https://github.com/fixture/cohort-{_apps_key}",
|
||||
"repo": f"fixture/cohort-{_apps_key}",
|
||||
"path": f"app/fourth_{_index:02d}.py",
|
||||
"function": f"serve_{_index:02d}",
|
||||
"language": "python",
|
||||
"hint": "python",
|
||||
"family": _family,
|
||||
"cwe": "CWE-200" if _family == "file_disclosure" else "CWE-601",
|
||||
"vulnerable": f"def serve_{_index:02d}(target):\n return eval(target)\n",
|
||||
"fixed": f"def serve_{_index:02d}(target):\n return str(target)\n",
|
||||
}
|
||||
for _index in range(10):
|
||||
_family = "redos" if _index % 2 == 0 else "type_confusion"
|
||||
_apps_key = f"js4-{_index:02d}"
|
||||
_APPS[_apps_key] = {
|
||||
"url": f"https://github.com/fixture/cohort-{_apps_key}",
|
||||
"repo": f"fixture/cohort-{_apps_key}",
|
||||
"path": f"lib/fourth_{_index:02d}.js",
|
||||
"function": f"match_{_index:02d}",
|
||||
"language": "javascript",
|
||||
"hint": "javascript",
|
||||
"family": _family,
|
||||
"cwe": "CWE-400" if _family == "redos" else "CWE-843",
|
||||
"vulnerable": f"function match_{_index:02d}(input) {{\n return eval(input);\n}}\n",
|
||||
"fixed": f"function match_{_index:02d}(input) {{\n return String(input);\n}}\n",
|
||||
}
|
||||
for _name, _function, _family, _cwe in (
|
||||
("ts4-00", "scanPattern", "redos", "CWE-400"),
|
||||
("ts4-01", "coerceValue", "type_confusion", "CWE-843"),
|
||||
):
|
||||
_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)})
|
||||
_FOURTH_ORDER = (*FOURTH_PYTHON_NAMES, *FOURTH_JAVASCRIPT_NAMES)
|
||||
_REVISIONS.update({name: (f"{9000 + index * 2:040x}", f"{9001 + index * 2:040x}") for index, name in enumerate(_FOURTH_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")
|
||||
@@ -600,6 +650,8 @@ __all__ = [
|
||||
"ENUMERATION_REVIEWER",
|
||||
"GROUND_TRUTH_POLICY",
|
||||
"FakeReader",
|
||||
"FOURTH_JAVASCRIPT_NAMES",
|
||||
"FOURTH_PYTHON_NAMES",
|
||||
"JAVASCRIPT_COUNT",
|
||||
"JAVASCRIPT_NAMES",
|
||||
"PYTHON_COUNT",
|
||||
|
||||
@@ -0,0 +1,371 @@
|
||||
"""Bounded ingestion of the fourth independently reviewed cohort closes the positive set."""
|
||||
|
||||
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_JAVASCRIPT_NAMES,
|
||||
COMBINED_PYTHON_NAMES,
|
||||
ECOSYSTEM_POLICY,
|
||||
FOURTH_JAVASCRIPT_NAMES,
|
||||
FOURTH_PYTHON_NAMES,
|
||||
GROUND_TRUTH_POLICY,
|
||||
SINGLE_FAMILY_JAVASCRIPT_NAMES,
|
||||
SINGLE_FAMILY_PYTHON_NAMES,
|
||||
THIRD_PYTHON_NAMES,
|
||||
authority,
|
||||
candidate_for,
|
||||
ingested_replacement_ledger,
|
||||
replacement_cohort_state,
|
||||
resolver,
|
||||
reviewed_record,
|
||||
)
|
||||
|
||||
from benchmarks.valid.cohort_ingestion import ( # noqa: E402
|
||||
COHORT_BATCH_CAP,
|
||||
MINIMUM_ACCEPTED_POSITIVES,
|
||||
CohortBatchStatus,
|
||||
CohortInsufficientReason,
|
||||
)
|
||||
from benchmarks.valid.cohort_selection import ( # noqa: E402
|
||||
CohortSelectionReason,
|
||||
CohortSelectionStateError,
|
||||
CohortSelectionStateReason,
|
||||
CohortSelectionStatus,
|
||||
cohort_selection,
|
||||
cohort_selection_bytes,
|
||||
ingest_fourth_cohort_batch,
|
||||
ingest_third_cohort_batch,
|
||||
select_fourth_cohort_batch,
|
||||
select_third_cohort_batch,
|
||||
)
|
||||
from benchmarks.valid.cohort_selection_store import decode_cohort_selection # noqa: E402
|
||||
from benchmarks.valid.positive_set_closure import ( # noqa: E402
|
||||
COMBINED_POSITIVE_FLOOR,
|
||||
PositiveSetClosureReason,
|
||||
PositiveSetClosureStatus,
|
||||
positive_set_closure_bytes,
|
||||
project_positive_set_closure,
|
||||
)
|
||||
from benchmarks.valid.reservation import legacy_reservation_source # noqa: E402
|
||||
from openultrasast.core.canonical import content_digest # noqa: E402
|
||||
|
||||
CLOSED_PYTHON_NAMES = (*COMBINED_PYTHON_NAMES, *THIRD_PYTHON_NAMES)
|
||||
CLOSED_JAVASCRIPT_NAMES = (*COMBINED_JAVASCRIPT_NAMES, *FOURTH_JAVASCRIPT_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 _select_fourth(state, ledger, *, eco=ECOSYSTEM_POLICY, gt=GROUND_TRUTH_POLICY):
|
||||
return select_fourth_cohort_batch(
|
||||
state=state,
|
||||
accepted_batches=ledger,
|
||||
expected_ecosystem_policy_digest=eco,
|
||||
expected_ground_truth_policy_digest=gt,
|
||||
)
|
||||
|
||||
|
||||
def _candidates(resolved, names):
|
||||
candidates = {}
|
||||
for name in names:
|
||||
candidate = candidate_for(name, resolved)
|
||||
candidates[candidate.candidate_digest] = candidate
|
||||
return 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_fourth(records, selection, state, candidates):
|
||||
return ingest_fourth_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 _prepared():
|
||||
state, resolved = replacement_cohort_state(python_names=CLOSED_PYTHON_NAMES, javascript_names=CLOSED_JAVASCRIPT_NAMES)
|
||||
candidates = _candidates(resolved, (*CLOSED_PYTHON_NAMES, *CLOSED_JAVASCRIPT_NAMES))
|
||||
first_two = ingested_replacement_ledger(state, resolved)
|
||||
third_selection = select_third_cohort_batch(
|
||||
state=state,
|
||||
accepted_batches=first_two,
|
||||
expected_ecosystem_policy_digest=ECOSYSTEM_POLICY,
|
||||
expected_ground_truth_policy_digest=GROUND_TRUTH_POLICY,
|
||||
)
|
||||
entries = _selected_entries(state, third_selection)
|
||||
records = [reviewed_record(entry, candidates[entry.candidate_digest])[0] for entry in entries]
|
||||
third = ingest_third_cohort_batch(
|
||||
records,
|
||||
selection=third_selection,
|
||||
state=state,
|
||||
candidates_by_digest=candidates,
|
||||
expected_ecosystem_policy_digest=ECOSYSTEM_POLICY,
|
||||
expected_ground_truth_policy_digest=GROUND_TRUTH_POLICY,
|
||||
)
|
||||
return state, resolved, (*first_two, third), candidates
|
||||
|
||||
|
||||
def test_fourth_cohort_closes_the_combined_positive_set():
|
||||
state, resolved, ledger, candidates = _prepared()
|
||||
selection = _select_fourth(state, ledger)
|
||||
|
||||
assert selection.status is CohortSelectionStatus.SELECTED
|
||||
assert selection.ecosystem == "javascript"
|
||||
assert selection.reason is CohortSelectionReason.BALANCED_PROGRESS_SELECTED
|
||||
assert dict(selection.accepted_by_ecosystem) == {"javascript": 12, "python": 24}
|
||||
assert selection.targeted_families == ("redos", "type_confusion")
|
||||
entries = _selected_entries(state, selection)
|
||||
assert MINIMUM_ACCEPTED_POSITIVES <= len(entries) <= COHORT_BATCH_CAP
|
||||
records = [reviewed_record(entry, candidates[entry.candidate_digest], ecosystem="javascript")[0] for entry in entries]
|
||||
|
||||
outcome = _ingest_fourth(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(
|
||||
scope.ecosystem.value == "javascript" for positive in outcome.accepted_positives for scope in positive.verified_scopes
|
||||
)
|
||||
assert all(positive.verified_scopes for positive in outcome.accepted_positives)
|
||||
|
||||
closure = project_positive_set_closure((*ledger, outcome))
|
||||
assert closure.status is PositiveSetClosureStatus.CLOSED
|
||||
assert closure.reason is PositiveSetClosureReason.ALL_GAPS_CLOSED
|
||||
assert closure.total_accepted_positives == 48 >= COMBINED_POSITIVE_FLOOR
|
||||
assert dict(closure.positives_by_ecosystem) == {"javascript": 24, "python": 24}
|
||||
assert {"injection", "path_traversal", "output_encoding", "deserialization", "ssrf"} <= set(closure.accepted_families)
|
||||
assert closure.accepted_batch_digests == tuple(sorted(batch.batch_digest for batch in (*ledger, outcome)))
|
||||
|
||||
replayed = _ingest_fourth(list(reversed(records)), selection, state, candidates)
|
||||
assert replayed == outcome
|
||||
assert replayed.batch_digest == outcome.batch_digest
|
||||
assert project_positive_set_closure((*ledger, replayed)) == closure
|
||||
|
||||
|
||||
def test_fourth_cohort_stays_pending_without_external_records():
|
||||
state, resolved, ledger, candidates = _prepared()
|
||||
selection = _select_fourth(state, ledger)
|
||||
entries = _selected_entries(state, selection)
|
||||
records = [reviewed_record(entry, candidates[entry.candidate_digest], ecosystem="javascript")[0] for entry in entries]
|
||||
|
||||
empty = _ingest_fourth([], 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
|
||||
empty_closure = project_positive_set_closure((*ledger, empty))
|
||||
assert empty_closure.status is PositiveSetClosureStatus.INSUFFICIENT
|
||||
assert empty_closure.reason is PositiveSetClosureReason.INSUFFICIENT_TOTAL_POSITIVES
|
||||
assert empty_closure.total_accepted_positives == 36 < COMBINED_POSITIVE_FLOOR
|
||||
assert empty_closure.accepted_batch_digests == tuple(sorted(batch.batch_digest for batch in ledger))
|
||||
|
||||
partial = _ingest_fourth(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))
|
||||
partial_closure = project_positive_set_closure((*ledger, partial))
|
||||
assert partial_closure.status is PositiveSetClosureStatus.INSUFFICIENT
|
||||
assert partial_closure.reason is PositiveSetClosureReason.INSUFFICIENT_TOTAL_POSITIVES
|
||||
assert partial_closure.total_accepted_positives == 36
|
||||
|
||||
|
||||
def test_fourth_selection_refuses_a_gap_it_cannot_close():
|
||||
state, resolved = replacement_cohort_state(
|
||||
python_names=("py-01", *SINGLE_FAMILY_PYTHON_NAMES),
|
||||
javascript_names=("js-01", *SINGLE_FAMILY_JAVASCRIPT_NAMES),
|
||||
)
|
||||
ledger = ingested_replacement_ledger(
|
||||
state,
|
||||
resolved,
|
||||
python_names=SINGLE_FAMILY_PYTHON_NAMES,
|
||||
javascript_names=SINGLE_FAMILY_JAVASCRIPT_NAMES,
|
||||
)
|
||||
selection = _select_fourth(state, ledger)
|
||||
assert selection.status is CohortSelectionStatus.REFUSED
|
||||
assert selection.reason is CohortSelectionReason.GAP_UNCLOSABLE
|
||||
assert selection.ecosystem is None
|
||||
assert selection.selected_entries == () and selection.targeted_families == ()
|
||||
assert decode_cohort_selection(cohort_selection_bytes(selection)) == selection
|
||||
closure = project_positive_set_closure(ledger)
|
||||
assert closure.status is PositiveSetClosureStatus.INSUFFICIENT
|
||||
assert closure.accepted_families == ("injection",)
|
||||
assert closure.total_accepted_positives == 24 < COMBINED_POSITIVE_FLOOR
|
||||
|
||||
unbalanced, resolved_two = replacement_cohort_state(
|
||||
python_names=(*COMBINED_PYTHON_NAMES, *THIRD_PYTHON_NAMES),
|
||||
javascript_names=("js-00", "js-01", "js-02", "js-03"),
|
||||
)
|
||||
python_ledger = ingested_replacement_ledger(unbalanced, resolved_two, javascript_names=())
|
||||
refused = _select_fourth(unbalanced, python_ledger)
|
||||
assert refused.status is CohortSelectionStatus.REFUSED
|
||||
assert refused.reason is CohortSelectionReason.GAP_UNCLOSABLE
|
||||
assert refused.selected_entries == () and refused.targeted_families == ()
|
||||
|
||||
|
||||
def test_fourth_selection_closes_a_remaining_family_gap():
|
||||
state, resolved = replacement_cohort_state(
|
||||
python_names=("py-01", *SINGLE_FAMILY_PYTHON_NAMES, *THIRD_PYTHON_NAMES),
|
||||
javascript_names=("js-01", *SINGLE_FAMILY_JAVASCRIPT_NAMES),
|
||||
)
|
||||
ledger = ingested_replacement_ledger(
|
||||
state,
|
||||
resolved,
|
||||
python_names=SINGLE_FAMILY_PYTHON_NAMES,
|
||||
javascript_names=SINGLE_FAMILY_JAVASCRIPT_NAMES,
|
||||
)
|
||||
candidates = _candidates(resolved, ("py-01", *SINGLE_FAMILY_PYTHON_NAMES, *THIRD_PYTHON_NAMES))
|
||||
|
||||
selection = _select_fourth(state, ledger)
|
||||
|
||||
assert selection.status is CohortSelectionStatus.SELECTED
|
||||
assert selection.ecosystem == "python"
|
||||
assert selection.reason is CohortSelectionReason.CLOSURE_GAP_SELECTED
|
||||
entries = _selected_entries(state, selection)
|
||||
assert len(entries) == 13
|
||||
assert {entry.family.vulnerability_family for entry in entries} == {"path_traversal", "deserialization", "ssrf"}
|
||||
assert selection.targeted_families == ("deserialization", "path_traversal", "ssrf")
|
||||
|
||||
records = [reviewed_record(entry, candidates[entry.candidate_digest])[0] for entry in entries]
|
||||
outcome = _ingest_fourth(records, selection, state, candidates)
|
||||
assert outcome.status is CohortBatchStatus.ACCEPTED
|
||||
assert len(outcome.accepted_positives) == 13 >= MINIMUM_ACCEPTED_POSITIVES
|
||||
|
||||
closure = project_positive_set_closure((*ledger, outcome))
|
||||
assert closure.status is PositiveSetClosureStatus.INSUFFICIENT
|
||||
assert closure.reason is PositiveSetClosureReason.INSUFFICIENT_TOTAL_POSITIVES
|
||||
assert closure.total_accepted_positives == 37 < COMBINED_POSITIVE_FLOOR
|
||||
assert {"injection", "path_traversal", "deserialization", "ssrf"} <= set(closure.accepted_families)
|
||||
|
||||
|
||||
def test_fourth_selection_targets_a_missing_ecosystem_to_close_it():
|
||||
state, resolved = replacement_cohort_state()
|
||||
ledger = ingested_replacement_ledger(state, resolved, javascript_names=())
|
||||
|
||||
selection = _select_fourth(state, ledger)
|
||||
|
||||
assert selection.status is CohortSelectionStatus.SELECTED
|
||||
assert selection.ecosystem == "javascript"
|
||||
assert selection.reason is CohortSelectionReason.MISSING_ECOSYSTEM_SELECTED
|
||||
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])
|
||||
|
||||
|
||||
def test_fourth_selection_ignores_how_many_reviews_passed():
|
||||
state, resolved = replacement_cohort_state()
|
||||
full = ingested_replacement_ledger(state, resolved, javascript_names=())
|
||||
thinned = ingested_replacement_ledger(state, resolved, javascript_names=(), weakened_python=2)
|
||||
assert len(thinned[0].accepted_positives) < len(full[0].accepted_positives)
|
||||
|
||||
chosen = _select_fourth(state, full)
|
||||
other = _select_fourth(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_fourth_selection_refuses_reweighted_policy_and_stale_census():
|
||||
state, resolved = replacement_cohort_state()
|
||||
ledger = ingested_replacement_ledger(state, resolved, javascript_names=())
|
||||
|
||||
changed = _select_fourth(state, ledger, eco=content_digest({"policy": "reweighted-after-outcomes"}))
|
||||
assert changed.status is CohortSelectionStatus.REFUSED
|
||||
assert changed.reason is CohortSelectionReason.POLICY_MISMATCH
|
||||
|
||||
reserved = legacy_reservation_source(
|
||||
resolved, repository="https://github.com/fixture/cohort-py4-00", source_digest="c" * 64
|
||||
)
|
||||
stale_state, _ = replacement_cohort_state(
|
||||
python_names=(*COMBINED_PYTHON_NAMES, *FOURTH_PYTHON_NAMES),
|
||||
javascript_names=(),
|
||||
authority_=authority(resolver(), legacy=(reserved,)),
|
||||
)
|
||||
assert stale_state.census_digest != state.census_digest
|
||||
stale = _select_fourth(stale_state, ledger)
|
||||
assert stale.status is CohortSelectionStatus.REFUSED
|
||||
assert stale.reason is CohortSelectionReason.CENSUS_MISMATCH
|
||||
assert decode_cohort_selection(cohort_selection_bytes(stale)) == stale
|
||||
|
||||
|
||||
def test_fourth_binding_guard_refuses_mismatched_selections():
|
||||
state, resolved, ledger, candidates = _prepared()
|
||||
selection = _select_fourth(state, ledger)
|
||||
assert selection.status is CohortSelectionStatus.SELECTED
|
||||
|
||||
other, _ = replacement_cohort_state(python_names=(*COMBINED_PYTHON_NAMES,))
|
||||
with pytest.raises(CohortSelectionStateError) as error:
|
||||
_ingest_fourth([], selection, other, candidates)
|
||||
assert error.value.reason is CohortSelectionStateReason.STATE_MISMATCH
|
||||
|
||||
refused = _select_fourth(state, ledger, gt=content_digest({"policy": "changed"}))
|
||||
with pytest.raises(CohortSelectionStateError) as error:
|
||||
_ingest_fourth([], refused, state, candidates)
|
||||
assert error.value.reason is CohortSelectionStateReason.STATE_MISMATCH
|
||||
|
||||
forged = cohort_selection(
|
||||
ecosystem=selection.ecosystem,
|
||||
selected_entries=(*selection.selected_entries[:-1], "f" * 64),
|
||||
targeted_families=selection.targeted_families,
|
||||
queue_digest=selection.queue_digest,
|
||||
census_digest=selection.census_digest,
|
||||
ecosystem_policy_digest=selection.ecosystem_policy_digest,
|
||||
ground_truth_policy_digest=selection.ground_truth_policy_digest,
|
||||
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,
|
||||
)
|
||||
with pytest.raises(CohortSelectionStateError) as error:
|
||||
_ingest_fourth([], forged, state, candidates)
|
||||
assert error.value.reason is CohortSelectionStateReason.STATE_MISMATCH
|
||||
|
||||
|
||||
def test_fourth_round_modules_and_outputs_carry_no_out_of_scope_machinery():
|
||||
root = Path(__file__).resolve().parents[1]
|
||||
for name in (
|
||||
"benchmarks/valid/cohort_selection.py",
|
||||
"benchmarks/valid/positive_set_closure.py",
|
||||
"benchmarks/valid/positive_set_closure_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, candidates = _prepared()
|
||||
selection = _select_fourth(state, ledger)
|
||||
closure = project_positive_set_closure(ledger)
|
||||
for content in (cohort_selection_bytes(selection), positive_set_closure_bytes(closure)):
|
||||
for forbidden in (b"admission", b"detector", b"observation", b"label", b"verdict", b"score"):
|
||||
assert forbidden not in content
|
||||
@@ -0,0 +1,260 @@
|
||||
"""Combined closure of the replacement positive set over durable accepted ledgers."""
|
||||
|
||||
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_PYTHON_NAMES,
|
||||
FOURTH_PYTHON_NAMES,
|
||||
READ_POLICY,
|
||||
SINGLE_FAMILY_PYTHON_NAMES,
|
||||
THIRD_PYTHON_NAMES,
|
||||
_Client,
|
||||
_read_authority,
|
||||
_settings,
|
||||
ingested_replacement_ledger,
|
||||
replacement_cohort_state,
|
||||
)
|
||||
|
||||
from benchmarks.valid.artifact_repository import S3ArtifactRepository # noqa: E402
|
||||
from benchmarks.valid.cohort_ingestion import ( # noqa: E402
|
||||
CohortBatchStatus,
|
||||
cohort_batch,
|
||||
ingest_python_cohort_batch,
|
||||
)
|
||||
from benchmarks.valid.cohort_ingestion_store import ( # noqa: E402
|
||||
persist_cohort_batch,
|
||||
resume_cohort_batch,
|
||||
)
|
||||
from benchmarks.valid.positive_set_closure import ( # noqa: E402
|
||||
COMBINED_POSITIVE_FLOOR,
|
||||
PositiveSetClosureReason,
|
||||
PositiveSetClosureStateError,
|
||||
PositiveSetClosureStateReason,
|
||||
PositiveSetClosureStatus,
|
||||
positive_set_closure,
|
||||
positive_set_closure_bytes,
|
||||
project_positive_set_closure,
|
||||
)
|
||||
from benchmarks.valid.positive_set_closure_store import ( # noqa: E402
|
||||
decode_positive_set_closure,
|
||||
persist_positive_set_closure,
|
||||
resume_positive_set_closure,
|
||||
)
|
||||
from benchmarks.valid.replacement_artifact_contract import ( # noqa: E402
|
||||
ArtifactAccessClass,
|
||||
ArtifactKind,
|
||||
validate_artifact,
|
||||
)
|
||||
|
||||
|
||||
@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 _python_rounds(rounds):
|
||||
names = tuple(name for round_names in rounds for name in round_names)
|
||||
state, resolved = replacement_cohort_state(python_names=names, javascript_names=())
|
||||
ledger = ()
|
||||
for round_names in rounds:
|
||||
ledger = (*ledger, *ingested_replacement_ledger(state, resolved, python_names=round_names, javascript_names=()))
|
||||
return state, resolved, ledger
|
||||
|
||||
|
||||
def _py_only_batches():
|
||||
return _python_rounds((COMBINED_PYTHON_NAMES, THIRD_PYTHON_NAMES, FOURTH_PYTHON_NAMES, SINGLE_FAMILY_PYTHON_NAMES))[2]
|
||||
|
||||
|
||||
def test_closure_is_deterministic_across_ledger_permutations():
|
||||
batches = _py_only_batches()
|
||||
assert len(batches) == 4
|
||||
|
||||
closure = project_positive_set_closure(batches)
|
||||
permuted = project_positive_set_closure(tuple(reversed(batches)))
|
||||
|
||||
assert closure == permuted
|
||||
assert closure.closure_digest == permuted.closure_digest
|
||||
assert closure.status is PositiveSetClosureStatus.INSUFFICIENT
|
||||
assert closure.reason is PositiveSetClosureReason.MISSING_ECOSYSTEM
|
||||
assert closure.total_accepted_positives == 48 >= COMBINED_POSITIVE_FLOOR
|
||||
assert dict(closure.positives_by_ecosystem) == {"javascript": 0, "python": 48}
|
||||
assert closure.batch_digests == tuple(sorted(batch.batch_digest for batch in batches))
|
||||
assert closure.accepted_batch_digests == closure.batch_digests
|
||||
assert len(closure.accepted_families) >= 2
|
||||
assert decode_positive_set_closure(positive_set_closure_bytes(closure)) == closure
|
||||
|
||||
|
||||
def test_closure_refuses_closed_below_the_floor():
|
||||
batches = _python_rounds((COMBINED_PYTHON_NAMES, THIRD_PYTHON_NAMES, FOURTH_PYTHON_NAMES))[2]
|
||||
assert len(batches) == 3
|
||||
|
||||
closure = project_positive_set_closure(batches)
|
||||
|
||||
assert closure.status is PositiveSetClosureStatus.INSUFFICIENT
|
||||
assert closure.reason is PositiveSetClosureReason.INSUFFICIENT_TOTAL_POSITIVES
|
||||
assert closure.total_accepted_positives == 36 < COMBINED_POSITIVE_FLOOR
|
||||
assert len(closure.accepted_batch_digests) == 3
|
||||
|
||||
|
||||
def test_closure_reports_no_accepted_batches_and_fails_closed_on_malformed_ledgers():
|
||||
empty = project_positive_set_closure(())
|
||||
assert empty.status is PositiveSetClosureStatus.INSUFFICIENT
|
||||
assert empty.reason is PositiveSetClosureReason.NO_ACCEPTED_BATCHES
|
||||
assert empty.total_accepted_positives == 0
|
||||
assert empty.accepted_batch_digests == () and empty.batch_digests == ()
|
||||
assert decode_positive_set_closure(positive_set_closure_bytes(empty)) == empty
|
||||
|
||||
state, resolved = replacement_cohort_state(python_names=COMBINED_PYTHON_NAMES, javascript_names=())
|
||||
pending_only = ingest_python_cohort_batch(
|
||||
[],
|
||||
state=state,
|
||||
candidates_by_digest={},
|
||||
expected_ecosystem_policy_digest="a" * 64,
|
||||
expected_ground_truth_policy_digest="b" * 64,
|
||||
)
|
||||
assert pending_only.status is CohortBatchStatus.INSUFFICIENT
|
||||
unanswered = project_positive_set_closure((pending_only,))
|
||||
assert unanswered.status is PositiveSetClosureStatus.INSUFFICIENT
|
||||
assert unanswered.reason is PositiveSetClosureReason.NO_ACCEPTED_BATCHES
|
||||
assert unanswered.total_accepted_positives == 0
|
||||
|
||||
batches = _py_only_batches()
|
||||
first = batches[0]
|
||||
second = batches[1]
|
||||
conflicted = cohort_batch(
|
||||
ecosystem=second.ecosystem,
|
||||
queue_digest=second.queue_digest,
|
||||
census_digest=second.census_digest,
|
||||
ecosystem_policy_digest=second.ecosystem_policy_digest,
|
||||
ground_truth_policy_digest=second.ground_truth_policy_digest,
|
||||
record_outcomes=second.record_outcomes,
|
||||
pending_entries=second.pending_entries,
|
||||
accepted_positives=(
|
||||
replace(second.accepted_positives[0], change_identity_digest=first.accepted_positives[0].change_identity_digest),
|
||||
*second.accepted_positives[1:],
|
||||
),
|
||||
status=second.status,
|
||||
insufficient_reason=second.insufficient_reason,
|
||||
)
|
||||
for bad in (
|
||||
None,
|
||||
{"ecosystem": "python"},
|
||||
replace(first, ecosystem="typescript"),
|
||||
replace(first, batch_digest="z" * 64),
|
||||
replace(first, accepted_positives=()),
|
||||
replace(first, accepted_positives=(replace(first.accepted_positives[0], ground_truth_review_digest="y" * 64),)),
|
||||
replace(first, accepted_positives=(replace(first.accepted_positives[0], verified_scopes=()),)),
|
||||
(first, conflicted),
|
||||
):
|
||||
with pytest.raises(PositiveSetClosureStateError) as error:
|
||||
project_positive_set_closure(bad if isinstance(bad, tuple) else (bad,))
|
||||
assert error.value.reason is PositiveSetClosureStateReason.STATE_MISMATCH
|
||||
|
||||
|
||||
def test_closure_assembler_fails_closed_on_impossible_combinations():
|
||||
based = {
|
||||
"batch_digests": ("a" * 64, "b" * 64),
|
||||
"accepted_batch_digests": ("a" * 64,),
|
||||
"total_accepted_positives": 45,
|
||||
"positives_by_ecosystem": {"javascript": 21, "python": 24},
|
||||
"accepted_families": ("injection", "path_traversal"),
|
||||
"status": PositiveSetClosureStatus.CLOSED,
|
||||
"reason": PositiveSetClosureReason.ALL_GAPS_CLOSED,
|
||||
}
|
||||
valid = positive_set_closure(**based)
|
||||
assert valid.status is PositiveSetClosureStatus.CLOSED
|
||||
assert positive_set_closure_bytes(valid)
|
||||
|
||||
short = positive_set_closure(
|
||||
**{**based, "total_accepted_positives": 39, "positives_by_ecosystem": {"javascript": 21, "python": 18},
|
||||
"status": PositiveSetClosureStatus.INSUFFICIENT,
|
||||
"reason": PositiveSetClosureReason.INSUFFICIENT_TOTAL_POSITIVES}
|
||||
)
|
||||
assert short.total_accepted_positives == 39
|
||||
|
||||
mutations = (
|
||||
{"total_accepted_positives": 39},
|
||||
{"positives_by_ecosystem": {"python": 45}},
|
||||
{"accepted_families": ("injection",)},
|
||||
{"accepted_batch_digests": ()},
|
||||
{"total_accepted_positives": 44, "positives_by_ecosystem": {"javascript": 21, "python": 24}},
|
||||
{"status": PositiveSetClosureStatus.INSUFFICIENT, "reason": PositiveSetClosureReason.MISSING_ECOSYSTEM},
|
||||
)
|
||||
for changes in mutations:
|
||||
with pytest.raises(PositiveSetClosureStateError) as error:
|
||||
positive_set_closure(**{**based, **changes})
|
||||
assert error.value.reason is PositiveSetClosureStateReason.STATE_MISMATCH
|
||||
|
||||
with pytest.raises(PositiveSetClosureStateError) as error:
|
||||
positive_set_closure(
|
||||
**{**based, "status": PositiveSetClosureStatus.INSUFFICIENT, "reason": PositiveSetClosureReason.NO_ACCEPTED_BATCHES}
|
||||
)
|
||||
assert error.value.reason is PositiveSetClosureStateReason.STATE_MISMATCH
|
||||
|
||||
|
||||
def test_closure_decodes_hostile_bytes_and_persists_durably():
|
||||
batches = _py_only_batches()
|
||||
closure = project_positive_set_closure(batches)
|
||||
content = positive_set_closure_bytes(closure)
|
||||
assert content and decode_positive_set_closure(content) == closure
|
||||
|
||||
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": "insufficient_families"}, 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(PositiveSetClosureStateError):
|
||||
decode_positive_set_closure(bad)
|
||||
|
||||
client = _Client()
|
||||
store = S3ArtifactRepository(_settings(), client)
|
||||
reference = persist_positive_set_closure(store, closure)
|
||||
assert persist_positive_set_closure(store, closure) == 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
|
||||
|
||||
batch_references = [persist_cohort_batch(store, batch) for batch in batches]
|
||||
resumed_batches = [
|
||||
resume_cohort_batch(
|
||||
S3ArtifactRepository(_settings(), client), item, authority=_read_authority(), expected_access_policy_digest=READ_POLICY
|
||||
)
|
||||
for item in batch_references
|
||||
]
|
||||
assert project_positive_set_closure(tuple(resumed_batches)) == closure
|
||||
|
||||
resumed = resume_positive_set_closure(
|
||||
S3ArtifactRepository(_settings(), client), reference, authority=_read_authority(), expected_access_policy_digest=READ_POLICY
|
||||
)
|
||||
assert resumed == closure
|
||||
assert positive_set_closure_bytes(resumed) == content
|
||||
Reference in New Issue
Block a user