mirror of
https://github.com/norandom/OpenUltraSAST.git
synced 2026-12-03 02:08:18 +00:00
feat(valid-detection-benchmark): 10.5 ingest fourth cohort and close positive set
This commit is contained in:
@@ -337,7 +337,7 @@
|
|||||||
- _Requirements: 1.1, 1.2, 1.3, 1.5, 1.6, 2.3, 2.4, 2.5, 2.6, 4.1, 4.2, 4.10_
|
- _Requirements: 1.1, 1.2, 1.3, 1.5, 1.6, 2.3, 2.4, 2.5, 2.6, 4.1, 4.2, 4.10_
|
||||||
- _Boundary: Review Authority, Replacement Population Sourcing_
|
- _Boundary: Review Authority, Replacement Population Sourcing_
|
||||||
- _Depends: 10.2, 10.3_
|
- _Depends: 10.2, 10.3_
|
||||||
- [ ] 10.5 Ingest a fourth bounded independently reviewed cohort and close the positive set
|
- [x] 10.5 Ingest a fourth bounded independently reviewed cohort and close the positive set
|
||||||
- Accept one externally supplied batch of at most twenty candidate review records under the unchanged review and reservation policy.
|
- Accept one externally supplied batch of at most twenty candidate review records under the unchanged review and reservation policy.
|
||||||
- Require its accepted records to close any remaining ecosystem or family gap without granting an unverified scope.
|
- Require its accepted records to close any remaining ecosystem or family gap without granting an unverified scope.
|
||||||
- Do not fabricate or self-approve missing reviews; leave this bounded cohort pending when its external records are unavailable.
|
- Do not fabricate or self-approve missing reviews; leave this bounded cohort pending when its external records are unavailable.
|
||||||
|
|||||||
@@ -18,10 +18,13 @@ from benchmarks.valid.cohort_ingestion import (
|
|||||||
COHORT_BATCH_CAP,
|
COHORT_BATCH_CAP,
|
||||||
MINIMUM_ACCEPTED_POSITIVES,
|
MINIMUM_ACCEPTED_POSITIVES,
|
||||||
CohortBatchOutcomeV1,
|
CohortBatchOutcomeV1,
|
||||||
|
CohortRecordOutcomeV1,
|
||||||
|
CohortRecordStatus,
|
||||||
ingest_javascript_cohort_batch,
|
ingest_javascript_cohort_batch,
|
||||||
ingest_python_cohort_batch,
|
ingest_python_cohort_batch,
|
||||||
)
|
)
|
||||||
from benchmarks.valid.fix_site_catalog import FixSiteCandidateV1
|
from benchmarks.valid.fix_site_catalog import FixSiteCandidateV1
|
||||||
|
from benchmarks.valid.ground_truth_review import GroundTruthExclusionReason
|
||||||
from benchmarks.valid.sourcing_queue import (
|
from benchmarks.valid.sourcing_queue import (
|
||||||
EcosystemReviewQueueV1,
|
EcosystemReviewQueueV1,
|
||||||
ReviewQueueEntryV1,
|
ReviewQueueEntryV1,
|
||||||
@@ -49,9 +52,11 @@ class CohortSelectionReason(StrEnum):
|
|||||||
MISSING_ECOSYSTEM_SELECTED = "missing_ecosystem_selected"
|
MISSING_ECOSYSTEM_SELECTED = "missing_ecosystem_selected"
|
||||||
FAMILY_GAP_SELECTED = "family_gap_selected"
|
FAMILY_GAP_SELECTED = "family_gap_selected"
|
||||||
BALANCED_PROGRESS_SELECTED = "balanced_progress_selected"
|
BALANCED_PROGRESS_SELECTED = "balanced_progress_selected"
|
||||||
|
CLOSURE_GAP_SELECTED = "closure_gap_selected"
|
||||||
NO_PENDING_ENTRIES = "no_pending_entries"
|
NO_PENDING_ENTRIES = "no_pending_entries"
|
||||||
CENSUS_MISMATCH = "census_mismatch"
|
CENSUS_MISMATCH = "census_mismatch"
|
||||||
POLICY_MISMATCH = "policy_mismatch"
|
POLICY_MISMATCH = "policy_mismatch"
|
||||||
|
GAP_UNCLOSABLE = "gap_unclosable"
|
||||||
|
|
||||||
|
|
||||||
class CohortSelectionStateReason(StrEnum):
|
class CohortSelectionStateReason(StrEnum):
|
||||||
@@ -64,6 +69,7 @@ _REFUSAL_REASONS = frozenset(
|
|||||||
CohortSelectionReason.NO_PENDING_ENTRIES,
|
CohortSelectionReason.NO_PENDING_ENTRIES,
|
||||||
CohortSelectionReason.CENSUS_MISMATCH,
|
CohortSelectionReason.CENSUS_MISMATCH,
|
||||||
CohortSelectionReason.POLICY_MISMATCH,
|
CohortSelectionReason.POLICY_MISMATCH,
|
||||||
|
CohortSelectionReason.GAP_UNCLOSABLE,
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -479,6 +485,241 @@ def select_third_cohort_batch(
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
_REVIEW_RESOLVED_REASONS = frozenset(item.value for item in GroundTruthExclusionReason)
|
||||||
|
|
||||||
|
|
||||||
|
def _review_resolved(outcome: CohortRecordOutcomeV1) -> bool:
|
||||||
|
"""True when one external record resolved its queue entry through review."""
|
||||||
|
if outcome.queue_entry_digest is None:
|
||||||
|
return False
|
||||||
|
if outcome.status is CohortRecordStatus.ACCEPTED:
|
||||||
|
return True
|
||||||
|
return outcome.reason in _REVIEW_RESOLVED_REASONS
|
||||||
|
|
||||||
|
|
||||||
|
def _pending_by_ecosystem(
|
||||||
|
state: SourcingQueueStateV1,
|
||||||
|
batches: Sequence[CohortBatchOutcomeV1],
|
||||||
|
) -> dict[str, tuple[ReviewQueueEntryV1, ...]]:
|
||||||
|
"""Pending entries per ecosystem from every batch's resolved records.
|
||||||
|
|
||||||
|
A record resolves its entry only through the committed review machinery:
|
||||||
|
accepted positives and review-level exclusions answer the entry, while
|
||||||
|
unreadable or evidence-invalid records leave it pending. A narrowed
|
||||||
|
selection batch therefore surrenders exactly the entries its records
|
||||||
|
resolved, never the whole shared queue.
|
||||||
|
"""
|
||||||
|
queued = {
|
||||||
|
ecosystem: {entry.entry_digest for entry in _queue_for(state, ecosystem).entries}
|
||||||
|
for ecosystem in COHORT_SELECTION_ECOSYSTEMS
|
||||||
|
}
|
||||||
|
answered: dict[str, set[str]] = {ecosystem: set() for ecosystem in COHORT_SELECTION_ECOSYSTEMS}
|
||||||
|
for batch in batches:
|
||||||
|
ecosystem = batch.ecosystem
|
||||||
|
if ecosystem not in answered:
|
||||||
|
continue
|
||||||
|
for outcome in batch.record_outcomes:
|
||||||
|
if _review_resolved(outcome) and outcome.queue_entry_digest in queued[ecosystem]:
|
||||||
|
answered[ecosystem].add(outcome.queue_entry_digest)
|
||||||
|
return {
|
||||||
|
ecosystem: tuple(
|
||||||
|
entry for entry in _queue_for(state, ecosystem).entries if entry.entry_digest not in answered[ecosystem]
|
||||||
|
)
|
||||||
|
for ecosystem in COHORT_SELECTION_ECOSYSTEMS
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _ecosystem_gap(facts: _LedgerFacts) -> tuple[str, ...]:
|
||||||
|
"""Canonical ecosystems with no accepted positive recorded yet."""
|
||||||
|
return tuple(
|
||||||
|
ecosystem for ecosystem in COHORT_SELECTION_ECOSYSTEMS if facts.accepted_by_ecosystem.get(ecosystem, 0) == 0
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _fourth_ecosystem(
|
||||||
|
pending_by: Mapping[str, Sequence[ReviewQueueEntryV1]],
|
||||||
|
facts: _LedgerFacts,
|
||||||
|
ecosystem_gap: Sequence[str],
|
||||||
|
) -> str | None:
|
||||||
|
"""One ecosystem whose pending batch can close the remaining gap, else None.
|
||||||
|
|
||||||
|
A gap-closing batch must be able to contribute the per-batch minimum of
|
||||||
|
accepted positives; a family gap additionally needs a pending entry from a
|
||||||
|
family no accepted review has recorded yet.
|
||||||
|
"""
|
||||||
|
for ecosystem in ecosystem_gap or COHORT_SELECTION_ECOSYSTEMS:
|
||||||
|
pending = pending_by[ecosystem]
|
||||||
|
if len(pending) < MINIMUM_ACCEPTED_POSITIVES:
|
||||||
|
continue
|
||||||
|
if not ecosystem_gap and all(entry.family.vulnerability_family in facts.families for entry in pending):
|
||||||
|
continue
|
||||||
|
return ecosystem
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def _fourth_selected(
|
||||||
|
state: SourcingQueueStateV1,
|
||||||
|
ecosystem: str,
|
||||||
|
reason: CohortSelectionReason,
|
||||||
|
pending: Sequence[ReviewQueueEntryV1],
|
||||||
|
facts: _LedgerFacts,
|
||||||
|
*,
|
||||||
|
family_gap: bool,
|
||||||
|
census: str,
|
||||||
|
eco_policy: str,
|
||||||
|
gt_policy: str,
|
||||||
|
) -> CohortSelectionV1:
|
||||||
|
"""Bind one selected fourth-round batch to the gap facts it serves."""
|
||||||
|
base = facts.families_by_ecosystem.get(ecosystem, frozenset())
|
||||||
|
represented = frozenset(facts.families) if family_gap else frozenset(base)
|
||||||
|
chosen, targeted = _selected_entries(pending, represented)
|
||||||
|
return cohort_selection(
|
||||||
|
ecosystem=ecosystem,
|
||||||
|
selected_entries=chosen,
|
||||||
|
targeted_families=targeted,
|
||||||
|
queue_digest=_queue_for(state, ecosystem).queue_digest,
|
||||||
|
census_digest=census,
|
||||||
|
ecosystem_policy_digest=eco_policy,
|
||||||
|
ground_truth_policy_digest=gt_policy,
|
||||||
|
prior_batch_digests=facts.batch_digests,
|
||||||
|
accepted_families=facts.families,
|
||||||
|
accepted_by_ecosystem=facts.accepted_by_ecosystem,
|
||||||
|
status=CohortSelectionStatus.SELECTED,
|
||||||
|
reason=reason,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _gap_closing_selection(
|
||||||
|
state: SourcingQueueStateV1,
|
||||||
|
pending_by: Mapping[str, Sequence[ReviewQueueEntryV1]],
|
||||||
|
facts: _LedgerFacts,
|
||||||
|
*,
|
||||||
|
census: str,
|
||||||
|
eco_policy: str,
|
||||||
|
gt_policy: str,
|
||||||
|
) -> CohortSelectionV1 | None:
|
||||||
|
"""Selection closing a remaining ecosystem or family gap, or a closed refusal."""
|
||||||
|
ecosystem_gap = _ecosystem_gap(facts)
|
||||||
|
family_gap = len(facts.families) < REQUIRED_DISTINCT_FAMILIES
|
||||||
|
if not (ecosystem_gap or family_gap):
|
||||||
|
return None
|
||||||
|
ecosystem = _fourth_ecosystem(pending_by, facts, ecosystem_gap)
|
||||||
|
if ecosystem is None:
|
||||||
|
return _refused(
|
||||||
|
CohortSelectionReason.GAP_UNCLOSABLE,
|
||||||
|
facts,
|
||||||
|
census_digest=census,
|
||||||
|
ecosystem_policy_digest=eco_policy,
|
||||||
|
ground_truth_policy_digest=gt_policy,
|
||||||
|
)
|
||||||
|
reason = (
|
||||||
|
CohortSelectionReason.MISSING_ECOSYSTEM_SELECTED if ecosystem_gap else CohortSelectionReason.CLOSURE_GAP_SELECTED
|
||||||
|
)
|
||||||
|
return _fourth_selected(
|
||||||
|
state,
|
||||||
|
ecosystem,
|
||||||
|
reason,
|
||||||
|
pending_by[ecosystem],
|
||||||
|
facts,
|
||||||
|
family_gap=family_gap,
|
||||||
|
census=census,
|
||||||
|
eco_policy=eco_policy,
|
||||||
|
gt_policy=gt_policy,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _fourth_decision(
|
||||||
|
state: SourcingQueueStateV1,
|
||||||
|
accepted_batches: Sequence[CohortBatchOutcomeV1],
|
||||||
|
facts: _LedgerFacts,
|
||||||
|
*,
|
||||||
|
census: str,
|
||||||
|
eco_policy: str,
|
||||||
|
gt_policy: str,
|
||||||
|
) -> CohortSelectionV1:
|
||||||
|
try:
|
||||||
|
pending_by = _pending_by_ecosystem(state, accepted_batches)
|
||||||
|
if not any(pending_by.values()):
|
||||||
|
return _refused(
|
||||||
|
CohortSelectionReason.NO_PENDING_ENTRIES,
|
||||||
|
facts,
|
||||||
|
census_digest=census,
|
||||||
|
ecosystem_policy_digest=eco_policy,
|
||||||
|
ground_truth_policy_digest=gt_policy,
|
||||||
|
)
|
||||||
|
closing = _gap_closing_selection(state, pending_by, facts, census=census, eco_policy=eco_policy, gt_policy=gt_policy)
|
||||||
|
if closing is not None:
|
||||||
|
return closing
|
||||||
|
ranked = sorted(
|
||||||
|
_ecosystem_rank(pending_by[ecosystem], ecosystem, facts) for ecosystem in COHORT_SELECTION_ECOSYSTEMS
|
||||||
|
)
|
||||||
|
for rank in ranked:
|
||||||
|
ecosystem = rank[4]
|
||||||
|
if pending_by[ecosystem]:
|
||||||
|
return _fourth_selected(
|
||||||
|
state,
|
||||||
|
ecosystem,
|
||||||
|
CohortSelectionReason.BALANCED_PROGRESS_SELECTED,
|
||||||
|
pending_by[ecosystem],
|
||||||
|
facts,
|
||||||
|
family_gap=False,
|
||||||
|
census=census,
|
||||||
|
eco_policy=eco_policy,
|
||||||
|
gt_policy=gt_policy,
|
||||||
|
)
|
||||||
|
except CohortSelectionStateError:
|
||||||
|
raise
|
||||||
|
except (AttributeError, TypeError, ValueError) as error:
|
||||||
|
raise CohortSelectionStateError(CohortSelectionStateReason.STATE_MISMATCH) from error
|
||||||
|
return _refused(
|
||||||
|
CohortSelectionReason.NO_PENDING_ENTRIES,
|
||||||
|
facts,
|
||||||
|
census_digest=census,
|
||||||
|
ecosystem_policy_digest=eco_policy,
|
||||||
|
ground_truth_policy_digest=gt_policy,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def select_fourth_cohort_batch(
|
||||||
|
*,
|
||||||
|
state: SourcingQueueStateV1,
|
||||||
|
accepted_batches: Sequence[CohortBatchOutcomeV1],
|
||||||
|
expected_ecosystem_policy_digest: str,
|
||||||
|
expected_ground_truth_policy_digest: str,
|
||||||
|
) -> CohortSelectionV1:
|
||||||
|
"""Select the gap-closing fourth cohort batch from one shared reservation snapshot.
|
||||||
|
|
||||||
|
The fourth round must close any remaining ecosystem or family gap: it
|
||||||
|
targets the gap when a feasible pending batch exists and refuses with a
|
||||||
|
closed reason when no pending batch can close it, never substituting a
|
||||||
|
batch that would leave the gap open.
|
||||||
|
"""
|
||||||
|
facts = _ledger_facts(accepted_batches)
|
||||||
|
try:
|
||||||
|
census = _closed_digest(state.census_digest)
|
||||||
|
eco_policy = _closed_digest(expected_ecosystem_policy_digest)
|
||||||
|
gt_policy = _closed_digest(expected_ground_truth_policy_digest)
|
||||||
|
except (AttributeError, TypeError, ValueError) as error:
|
||||||
|
raise CohortSelectionStateError(CohortSelectionStateReason.STATE_MISMATCH) from error
|
||||||
|
if _census_refused(facts, census):
|
||||||
|
return _refused(
|
||||||
|
CohortSelectionReason.CENSUS_MISMATCH,
|
||||||
|
facts,
|
||||||
|
census_digest=census,
|
||||||
|
ecosystem_policy_digest=eco_policy,
|
||||||
|
ground_truth_policy_digest=gt_policy,
|
||||||
|
)
|
||||||
|
if _policy_refused(facts, (eco_policy, gt_policy)):
|
||||||
|
return _refused(
|
||||||
|
CohortSelectionReason.POLICY_MISMATCH,
|
||||||
|
facts,
|
||||||
|
census_digest=census,
|
||||||
|
ecosystem_policy_digest=eco_policy,
|
||||||
|
ground_truth_policy_digest=gt_policy,
|
||||||
|
)
|
||||||
|
return _fourth_decision(state, accepted_batches, facts, census=census, eco_policy=eco_policy, gt_policy=gt_policy)
|
||||||
|
|
||||||
|
|
||||||
def _require_selection_binding(
|
def _require_selection_binding(
|
||||||
selection: CohortSelectionV1,
|
selection: CohortSelectionV1,
|
||||||
state: SourcingQueueStateV1,
|
state: SourcingQueueStateV1,
|
||||||
@@ -535,7 +776,7 @@ def _selection_state(
|
|||||||
raise CohortSelectionStateError(CohortSelectionStateReason.STATE_MISMATCH) from error
|
raise CohortSelectionStateError(CohortSelectionStateReason.STATE_MISMATCH) from error
|
||||||
|
|
||||||
|
|
||||||
def ingest_third_cohort_batch(
|
def _ingest_selected_cohort_batch(
|
||||||
records: Sequence[bytes],
|
records: Sequence[bytes],
|
||||||
*,
|
*,
|
||||||
selection: CohortSelectionV1,
|
selection: CohortSelectionV1,
|
||||||
@@ -544,7 +785,7 @@ def ingest_third_cohort_batch(
|
|||||||
expected_ecosystem_policy_digest: str,
|
expected_ecosystem_policy_digest: str,
|
||||||
expected_ground_truth_policy_digest: str,
|
expected_ground_truth_policy_digest: str,
|
||||||
) -> CohortBatchOutcomeV1:
|
) -> CohortBatchOutcomeV1:
|
||||||
"""Ingest the selected bounded third cohort through the committed machinery."""
|
"""Ingest one selected bounded cohort batch through the committed machinery."""
|
||||||
narrowed = _selection_state(
|
narrowed = _selection_state(
|
||||||
selection,
|
selection,
|
||||||
state,
|
state,
|
||||||
@@ -561,6 +802,50 @@ def ingest_third_cohort_batch(
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def ingest_third_cohort_batch(
|
||||||
|
records: Sequence[bytes],
|
||||||
|
*,
|
||||||
|
selection: CohortSelectionV1,
|
||||||
|
state: SourcingQueueStateV1,
|
||||||
|
candidates_by_digest: Mapping[str, FixSiteCandidateV1],
|
||||||
|
expected_ecosystem_policy_digest: str,
|
||||||
|
expected_ground_truth_policy_digest: str,
|
||||||
|
) -> CohortBatchOutcomeV1:
|
||||||
|
"""Ingest the selected bounded third cohort through the committed machinery."""
|
||||||
|
return _ingest_selected_cohort_batch(
|
||||||
|
records,
|
||||||
|
selection=selection,
|
||||||
|
state=state,
|
||||||
|
candidates_by_digest=candidates_by_digest,
|
||||||
|
expected_ecosystem_policy_digest=expected_ecosystem_policy_digest,
|
||||||
|
expected_ground_truth_policy_digest=expected_ground_truth_policy_digest,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def ingest_fourth_cohort_batch(
|
||||||
|
records: Sequence[bytes],
|
||||||
|
*,
|
||||||
|
selection: CohortSelectionV1,
|
||||||
|
state: SourcingQueueStateV1,
|
||||||
|
candidates_by_digest: Mapping[str, FixSiteCandidateV1],
|
||||||
|
expected_ecosystem_policy_digest: str,
|
||||||
|
expected_ground_truth_policy_digest: str,
|
||||||
|
) -> CohortBatchOutcomeV1:
|
||||||
|
"""Ingest the selected bounded fourth cohort under the unchanged review policy.
|
||||||
|
|
||||||
|
Scope verification never moves: acceptance still flows only through the
|
||||||
|
committed review authorities over the narrowed selected queue.
|
||||||
|
"""
|
||||||
|
return _ingest_selected_cohort_batch(
|
||||||
|
records,
|
||||||
|
selection=selection,
|
||||||
|
state=state,
|
||||||
|
candidates_by_digest=candidates_by_digest,
|
||||||
|
expected_ecosystem_policy_digest=expected_ecosystem_policy_digest,
|
||||||
|
expected_ground_truth_policy_digest=expected_ground_truth_policy_digest,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
__all__ = [
|
__all__ = [
|
||||||
"COHORT_SELECTION_ECOSYSTEMS",
|
"COHORT_SELECTION_ECOSYSTEMS",
|
||||||
"COHORT_SELECTION_SCHEMA",
|
"COHORT_SELECTION_SCHEMA",
|
||||||
@@ -573,6 +858,8 @@ __all__ = [
|
|||||||
"cohort_selection",
|
"cohort_selection",
|
||||||
"cohort_selection_bytes",
|
"cohort_selection_bytes",
|
||||||
"cohort_selection_value",
|
"cohort_selection_value",
|
||||||
|
"ingest_fourth_cohort_batch",
|
||||||
"ingest_third_cohort_batch",
|
"ingest_third_cohort_batch",
|
||||||
|
"select_fourth_cohort_batch",
|
||||||
"select_third_cohort_batch",
|
"select_third_cohort_batch",
|
||||||
]
|
]
|
||||||
|
|||||||
@@ -0,0 +1,329 @@
|
|||||||
|
"""Combined closure of the replacement positive set over durable cohort ledgers.
|
||||||
|
|
||||||
|
The closure projection reads only accepted review evidence already recorded on
|
||||||
|
cohort batch outcomes: families, ecosystems, and positive counts are facts of
|
||||||
|
recorded human reviews. Every accepted positive is reachable by construction
|
||||||
|
because acceptance exists only through the committed review machinery, which
|
||||||
|
requires the in-repository reachability judgment; no scope is granted here and
|
||||||
|
an unverified family or ecosystem stays impossible without a new external
|
||||||
|
review record.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import re
|
||||||
|
from collections.abc import Iterable, Mapping, Sequence
|
||||||
|
from dataclasses import dataclass, replace
|
||||||
|
from enum import StrEnum
|
||||||
|
|
||||||
|
from benchmarks.valid.cohort_ingestion import (
|
||||||
|
CohortBatchOutcomeV1,
|
||||||
|
CohortBatchStatus,
|
||||||
|
CohortStateError,
|
||||||
|
cohort_batch_bytes,
|
||||||
|
)
|
||||||
|
from benchmarks.valid.cohort_selection import COHORT_SELECTION_ECOSYSTEMS, REQUIRED_DISTINCT_FAMILIES
|
||||||
|
from benchmarks.valid.ground_truth_review import AcceptedGroundTruthV1
|
||||||
|
from openultrasast.core.canonical import JsonValue, canonical_bytes, content_digest
|
||||||
|
|
||||||
|
POSITIVE_SET_CLOSURE_SCHEMA = "openultrasast.valid-detection-benchmark.positive-set-closure.v1"
|
||||||
|
COMBINED_POSITIVE_FLOOR = 40
|
||||||
|
_DIGEST = re.compile(r"[0-9a-f]{64}")
|
||||||
|
_FAMILY = re.compile(r"[a-z0-9][a-z0-9_]{0,127}")
|
||||||
|
|
||||||
|
|
||||||
|
class PositiveSetClosureStatus(StrEnum):
|
||||||
|
CLOSED = "closed"
|
||||||
|
INSUFFICIENT = "insufficient"
|
||||||
|
|
||||||
|
|
||||||
|
class PositiveSetClosureReason(StrEnum):
|
||||||
|
"""Closed decision vocabulary naming which closure gate closed or failed."""
|
||||||
|
|
||||||
|
ALL_GAPS_CLOSED = "all_gaps_closed"
|
||||||
|
NO_ACCEPTED_BATCHES = "no_accepted_batches"
|
||||||
|
INSUFFICIENT_TOTAL_POSITIVES = "insufficient_total_positives"
|
||||||
|
MISSING_ECOSYSTEM = "missing_ecosystem"
|
||||||
|
INSUFFICIENT_FAMILIES = "insufficient_families"
|
||||||
|
|
||||||
|
|
||||||
|
_INSUFFICIENCY_REASONS = frozenset(
|
||||||
|
{
|
||||||
|
PositiveSetClosureReason.NO_ACCEPTED_BATCHES,
|
||||||
|
PositiveSetClosureReason.INSUFFICIENT_TOTAL_POSITIVES,
|
||||||
|
PositiveSetClosureReason.MISSING_ECOSYSTEM,
|
||||||
|
PositiveSetClosureReason.INSUFFICIENT_FAMILIES,
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class PositiveSetClosureStateReason(StrEnum):
|
||||||
|
STATE_UNREADABLE = "state_unreadable"
|
||||||
|
STATE_MISMATCH = "state_mismatch"
|
||||||
|
|
||||||
|
|
||||||
|
_STATE_REASON_TEXT = {
|
||||||
|
PositiveSetClosureStateReason.STATE_UNREADABLE: "positive set closure bytes are unreadable",
|
||||||
|
PositiveSetClosureStateReason.STATE_MISMATCH: "positive set closure state does not match its canonical schema",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
class PositiveSetClosureStateError(ValueError):
|
||||||
|
"""Closed closure refusal carrying one structural reason."""
|
||||||
|
|
||||||
|
def __init__(self, reason: PositiveSetClosureStateReason) -> None:
|
||||||
|
self.reason = reason
|
||||||
|
super().__init__(_STATE_REASON_TEXT[reason])
|
||||||
|
|
||||||
|
|
||||||
|
def _mismatch() -> PositiveSetClosureStateError:
|
||||||
|
return PositiveSetClosureStateError(PositiveSetClosureStateReason.STATE_MISMATCH)
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class PositiveSetClosureV1:
|
||||||
|
batch_digests: tuple[str, ...]
|
||||||
|
accepted_batch_digests: tuple[str, ...]
|
||||||
|
total_accepted_positives: int
|
||||||
|
positives_by_ecosystem: tuple[tuple[str, int], ...]
|
||||||
|
accepted_families: tuple[str, ...]
|
||||||
|
status: PositiveSetClosureStatus
|
||||||
|
reason: PositiveSetClosureReason
|
||||||
|
closure_digest: str
|
||||||
|
|
||||||
|
def __post_init__(self) -> None:
|
||||||
|
_validate_closure(self)
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class _ClosureFacts:
|
||||||
|
batch_digests: tuple[str, ...]
|
||||||
|
accepted_batch_digests: tuple[str, ...]
|
||||||
|
families: tuple[str, ...]
|
||||||
|
counts: tuple[tuple[str, int], ...]
|
||||||
|
total: int
|
||||||
|
|
||||||
|
|
||||||
|
def _closed_digest(value: object) -> str:
|
||||||
|
if not isinstance(value, str) or _DIGEST.fullmatch(value) is None:
|
||||||
|
raise _mismatch()
|
||||||
|
return value
|
||||||
|
|
||||||
|
|
||||||
|
def _closed_vocabulary(values: object, pattern: re.Pattern[str]) -> tuple[str, ...]:
|
||||||
|
if not isinstance(values, tuple) or not all(isinstance(item, str) for item in values):
|
||||||
|
raise _mismatch()
|
||||||
|
ordered = tuple(sorted(set(values)))
|
||||||
|
if ordered != values or any(pattern.fullmatch(item) is None for item in ordered):
|
||||||
|
raise _mismatch()
|
||||||
|
return values
|
||||||
|
|
||||||
|
|
||||||
|
def _closed_counts(pairs: object) -> tuple[tuple[str, int], ...]:
|
||||||
|
if not isinstance(pairs, tuple) or tuple(ecosystem for ecosystem, _ in pairs) != COHORT_SELECTION_ECOSYSTEMS:
|
||||||
|
raise _mismatch()
|
||||||
|
for _, count in pairs:
|
||||||
|
if type(count) is not int or count < 0:
|
||||||
|
raise _mismatch()
|
||||||
|
return pairs
|
||||||
|
|
||||||
|
|
||||||
|
def _gates(item: PositiveSetClosureV1) -> tuple[bool, bool, bool]:
|
||||||
|
total_ok = item.total_accepted_positives >= COMBINED_POSITIVE_FLOOR
|
||||||
|
ecosystems_ok = all(count > 0 for _, count in item.positives_by_ecosystem)
|
||||||
|
families_ok = len(item.accepted_families) >= REQUIRED_DISTINCT_FAMILIES
|
||||||
|
return total_ok, ecosystems_ok, families_ok
|
||||||
|
|
||||||
|
|
||||||
|
def _validate_closure(item: PositiveSetClosureV1) -> None:
|
||||||
|
if not isinstance(item.status, PositiveSetClosureStatus) or not isinstance(item.reason, PositiveSetClosureReason):
|
||||||
|
raise _mismatch()
|
||||||
|
if item.closure_digest:
|
||||||
|
_closed_digest(item.closure_digest)
|
||||||
|
_closed_vocabulary(item.batch_digests, _DIGEST)
|
||||||
|
_closed_vocabulary(item.accepted_batch_digests, _DIGEST)
|
||||||
|
if not set(item.accepted_batch_digests) <= set(item.batch_digests):
|
||||||
|
raise _mismatch()
|
||||||
|
_closed_vocabulary(item.accepted_families, _FAMILY)
|
||||||
|
_closed_counts(item.positives_by_ecosystem)
|
||||||
|
if item.total_accepted_positives < 0 or item.total_accepted_positives != sum(
|
||||||
|
count for _, count in item.positives_by_ecosystem
|
||||||
|
):
|
||||||
|
raise _mismatch()
|
||||||
|
if bool(item.accepted_batch_digests) != (item.total_accepted_positives > 0):
|
||||||
|
raise _mismatch()
|
||||||
|
total_ok, ecosystems_ok, families_ok = _gates(item)
|
||||||
|
if item.status is PositiveSetClosureStatus.CLOSED:
|
||||||
|
if item.reason is not PositiveSetClosureReason.ALL_GAPS_CLOSED or not (total_ok and ecosystems_ok and families_ok):
|
||||||
|
raise _mismatch()
|
||||||
|
else:
|
||||||
|
if item.reason not in _INSUFFICIENCY_REASONS or (total_ok and ecosystems_ok and families_ok):
|
||||||
|
raise _mismatch()
|
||||||
|
if item.reason is PositiveSetClosureReason.NO_ACCEPTED_BATCHES and item.total_accepted_positives != 0:
|
||||||
|
raise _mismatch()
|
||||||
|
|
||||||
|
|
||||||
|
def _count_value(pairs: tuple[tuple[str, int], ...]) -> tuple[dict[str, JsonValue], ...]:
|
||||||
|
return tuple({"ecosystem": ecosystem, "accepted_positives": count} for ecosystem, count in pairs)
|
||||||
|
|
||||||
|
|
||||||
|
def _closure_value(item: PositiveSetClosureV1, *, include_digest: bool) -> dict[str, JsonValue]:
|
||||||
|
value: dict[str, JsonValue] = {
|
||||||
|
"schema_version": POSITIVE_SET_CLOSURE_SCHEMA,
|
||||||
|
"batch_digests": item.batch_digests,
|
||||||
|
"accepted_batch_digests": item.accepted_batch_digests,
|
||||||
|
"total_accepted_positives": item.total_accepted_positives,
|
||||||
|
"positives_by_ecosystem": _count_value(item.positives_by_ecosystem),
|
||||||
|
"accepted_families": item.accepted_families,
|
||||||
|
"status": item.status.value,
|
||||||
|
"reason": item.reason.value,
|
||||||
|
}
|
||||||
|
if include_digest:
|
||||||
|
value["closure_digest"] = item.closure_digest
|
||||||
|
return value
|
||||||
|
|
||||||
|
|
||||||
|
def positive_set_closure_value(item: PositiveSetClosureV1) -> dict[str, JsonValue]:
|
||||||
|
"""Canonical closure payload used for durable persistence and exact rereads."""
|
||||||
|
return _closure_value(item, include_digest=True)
|
||||||
|
|
||||||
|
|
||||||
|
def positive_set_closure_bytes(item: PositiveSetClosureV1) -> bytes:
|
||||||
|
"""Encode a digest-consistent closure decision as canonical bytes."""
|
||||||
|
if item.closure_digest != content_digest(_closure_value(item, include_digest=False)):
|
||||||
|
raise _mismatch()
|
||||||
|
return canonical_bytes(positive_set_closure_value(item))
|
||||||
|
|
||||||
|
|
||||||
|
def positive_set_closure(
|
||||||
|
*,
|
||||||
|
batch_digests: Iterable[str],
|
||||||
|
accepted_batch_digests: Iterable[str],
|
||||||
|
total_accepted_positives: int,
|
||||||
|
positives_by_ecosystem: Mapping[str, int],
|
||||||
|
accepted_families: Iterable[str],
|
||||||
|
status: PositiveSetClosureStatus,
|
||||||
|
reason: PositiveSetClosureReason,
|
||||||
|
) -> PositiveSetClosureV1:
|
||||||
|
"""Assemble one durable closure decision bound to its exact ledger facts."""
|
||||||
|
try:
|
||||||
|
counts = tuple((ecosystem, positives_by_ecosystem[ecosystem]) for ecosystem in COHORT_SELECTION_ECOSYSTEMS)
|
||||||
|
draft = PositiveSetClosureV1(
|
||||||
|
tuple(sorted(set(batch_digests))),
|
||||||
|
tuple(sorted(set(accepted_batch_digests))),
|
||||||
|
total_accepted_positives,
|
||||||
|
counts,
|
||||||
|
tuple(sorted(set(accepted_families))),
|
||||||
|
status,
|
||||||
|
reason,
|
||||||
|
"",
|
||||||
|
)
|
||||||
|
except PositiveSetClosureStateError:
|
||||||
|
raise
|
||||||
|
except (AttributeError, KeyError, TypeError, ValueError) as error:
|
||||||
|
raise PositiveSetClosureStateError(PositiveSetClosureStateReason.STATE_MISMATCH) from error
|
||||||
|
return replace(draft, closure_digest=content_digest(_closure_value(draft, include_digest=False)))
|
||||||
|
|
||||||
|
|
||||||
|
def _require_replayable(batch: CohortBatchOutcomeV1) -> None:
|
||||||
|
"""Prove one ledger batch re-encodes to its recorded digest before use."""
|
||||||
|
try:
|
||||||
|
cohort_batch_bytes(batch)
|
||||||
|
for positive in batch.accepted_positives:
|
||||||
|
if not positive.verified_scopes:
|
||||||
|
raise _mismatch()
|
||||||
|
for scope in positive.verified_scopes:
|
||||||
|
if scope.ecosystem.value != batch.ecosystem:
|
||||||
|
raise _mismatch()
|
||||||
|
except PositiveSetClosureStateError:
|
||||||
|
raise
|
||||||
|
except (CohortStateError, AttributeError, KeyError, TypeError, ValueError) as error:
|
||||||
|
raise PositiveSetClosureStateError(PositiveSetClosureStateReason.STATE_MISMATCH) from error
|
||||||
|
|
||||||
|
|
||||||
|
def _closure_facts(batches: Sequence[CohortBatchOutcomeV1]) -> _ClosureFacts:
|
||||||
|
"""Derive combined facts from replay-verified accepted cohort evidence."""
|
||||||
|
digests: set[str] = set()
|
||||||
|
accepted_digests: set[str] = set()
|
||||||
|
families: set[str] = set()
|
||||||
|
counts = {ecosystem: 0 for ecosystem in COHORT_SELECTION_ECOSYSTEMS}
|
||||||
|
by_change: dict[str, AcceptedGroundTruthV1] = {}
|
||||||
|
for batch in batches:
|
||||||
|
_require_replayable(batch)
|
||||||
|
digests.add(_closed_digest(batch.batch_digest))
|
||||||
|
if batch.status is not CohortBatchStatus.ACCEPTED:
|
||||||
|
continue
|
||||||
|
accepted_digests.add(batch.batch_digest)
|
||||||
|
for positive in batch.accepted_positives:
|
||||||
|
existing = by_change.get(positive.change_identity_digest)
|
||||||
|
if existing is not None and existing != positive:
|
||||||
|
raise _mismatch()
|
||||||
|
if existing is None:
|
||||||
|
by_change[positive.change_identity_digest] = positive
|
||||||
|
counts[batch.ecosystem] += 1
|
||||||
|
for scope in positive.verified_scopes:
|
||||||
|
families.add(scope.vulnerability_family)
|
||||||
|
return _ClosureFacts(
|
||||||
|
tuple(sorted(digests)),
|
||||||
|
tuple(sorted(accepted_digests)),
|
||||||
|
tuple(sorted(families)),
|
||||||
|
tuple((ecosystem, counts[ecosystem]) for ecosystem in COHORT_SELECTION_ECOSYSTEMS),
|
||||||
|
len(by_change),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _closure_reason(facts: _ClosureFacts) -> PositiveSetClosureReason:
|
||||||
|
if not facts.accepted_batch_digests:
|
||||||
|
return PositiveSetClosureReason.NO_ACCEPTED_BATCHES
|
||||||
|
if facts.total < COMBINED_POSITIVE_FLOOR:
|
||||||
|
return PositiveSetClosureReason.INSUFFICIENT_TOTAL_POSITIVES
|
||||||
|
if any(count == 0 for _, count in facts.counts):
|
||||||
|
return PositiveSetClosureReason.MISSING_ECOSYSTEM
|
||||||
|
if len(facts.families) < REQUIRED_DISTINCT_FAMILIES:
|
||||||
|
return PositiveSetClosureReason.INSUFFICIENT_FAMILIES
|
||||||
|
return PositiveSetClosureReason.ALL_GAPS_CLOSED
|
||||||
|
|
||||||
|
|
||||||
|
def project_positive_set_closure(batches: Sequence[CohortBatchOutcomeV1]) -> PositiveSetClosureV1:
|
||||||
|
"""Close the combined positive set over durable accepted cohort ledgers.
|
||||||
|
|
||||||
|
Only accepted ingestion units contribute positives: an insufficient batch
|
||||||
|
is a refused unit whose partial records never lower the closure bar. A
|
||||||
|
gap-remaining set stays insufficient with a closed reason instead of being
|
||||||
|
reported closed.
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
facts = _closure_facts(batches)
|
||||||
|
except PositiveSetClosureStateError:
|
||||||
|
raise
|
||||||
|
except (AttributeError, TypeError, ValueError) as error:
|
||||||
|
raise PositiveSetClosureStateError(PositiveSetClosureStateReason.STATE_MISMATCH) from error
|
||||||
|
reason = _closure_reason(facts)
|
||||||
|
if reason is PositiveSetClosureReason.ALL_GAPS_CLOSED:
|
||||||
|
status = PositiveSetClosureStatus.CLOSED
|
||||||
|
else:
|
||||||
|
status = PositiveSetClosureStatus.INSUFFICIENT
|
||||||
|
return positive_set_closure(
|
||||||
|
batch_digests=facts.batch_digests,
|
||||||
|
accepted_batch_digests=facts.accepted_batch_digests,
|
||||||
|
total_accepted_positives=facts.total,
|
||||||
|
positives_by_ecosystem=dict(facts.counts),
|
||||||
|
accepted_families=facts.families,
|
||||||
|
status=status,
|
||||||
|
reason=reason,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
__all__ = [
|
||||||
|
"COMBINED_POSITIVE_FLOOR",
|
||||||
|
"POSITIVE_SET_CLOSURE_SCHEMA",
|
||||||
|
"PositiveSetClosureReason",
|
||||||
|
"PositiveSetClosureStateError",
|
||||||
|
"PositiveSetClosureStateReason",
|
||||||
|
"PositiveSetClosureStatus",
|
||||||
|
"PositiveSetClosureV1",
|
||||||
|
"positive_set_closure",
|
||||||
|
"positive_set_closure_bytes",
|
||||||
|
"positive_set_closure_value",
|
||||||
|
"project_positive_set_closure",
|
||||||
|
]
|
||||||
@@ -0,0 +1,137 @@
|
|||||||
|
"""Durable persistence, hostile decode, and replay for positive-set closure decisions."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
import math
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from benchmarks.valid.artifact_repository import ArtifactReadAuthority, S3ArtifactRepository
|
||||||
|
from benchmarks.valid.positive_set_closure import (
|
||||||
|
POSITIVE_SET_CLOSURE_SCHEMA,
|
||||||
|
PositiveSetClosureReason,
|
||||||
|
PositiveSetClosureStateError,
|
||||||
|
PositiveSetClosureStateReason,
|
||||||
|
PositiveSetClosureStatus,
|
||||||
|
PositiveSetClosureV1,
|
||||||
|
positive_set_closure,
|
||||||
|
positive_set_closure_bytes,
|
||||||
|
positive_set_closure_value,
|
||||||
|
)
|
||||||
|
from benchmarks.valid.replacement_artifact_contract import (
|
||||||
|
ArtifactAccessClass,
|
||||||
|
ArtifactKind,
|
||||||
|
ArtifactReference,
|
||||||
|
artifact_reference,
|
||||||
|
canonical_artifact_bytes,
|
||||||
|
)
|
||||||
|
from openultrasast.core.canonical import canonical_bytes
|
||||||
|
|
||||||
|
_CLOSURE_KEYS = frozenset(
|
||||||
|
{
|
||||||
|
"schema_version",
|
||||||
|
"batch_digests",
|
||||||
|
"accepted_batch_digests",
|
||||||
|
"total_accepted_positives",
|
||||||
|
"positives_by_ecosystem",
|
||||||
|
"accepted_families",
|
||||||
|
"status",
|
||||||
|
"reason",
|
||||||
|
"closure_digest",
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _reject_constant(name: str) -> None:
|
||||||
|
raise ValueError(name)
|
||||||
|
|
||||||
|
|
||||||
|
def _finite_float(text: str) -> float:
|
||||||
|
value = float(text)
|
||||||
|
if not math.isfinite(value):
|
||||||
|
raise ValueError(text)
|
||||||
|
return value
|
||||||
|
|
||||||
|
|
||||||
|
def _converted(value: Any) -> Any:
|
||||||
|
if isinstance(value, list):
|
||||||
|
return tuple(_converted(item) for item in value)
|
||||||
|
if isinstance(value, dict):
|
||||||
|
return {str(key): _converted(item) for key, item in value.items()}
|
||||||
|
return value
|
||||||
|
|
||||||
|
|
||||||
|
def _decoded_value(content: bytes) -> dict[str, Any]:
|
||||||
|
"""Hostile decode: no constants, finite floats, bounded recursion, canonical bytes."""
|
||||||
|
if not isinstance(content, bytes) or not content:
|
||||||
|
raise PositiveSetClosureStateError(PositiveSetClosureStateReason.STATE_UNREADABLE)
|
||||||
|
try:
|
||||||
|
parsed = json.loads(content, parse_constant=_reject_constant, parse_float=_finite_float)
|
||||||
|
value = _converted(parsed)
|
||||||
|
canonical = canonical_bytes(value)
|
||||||
|
except (UnicodeError, json.JSONDecodeError, ValueError, RecursionError):
|
||||||
|
raise PositiveSetClosureStateError(PositiveSetClosureStateReason.STATE_UNREADABLE) from None
|
||||||
|
if not isinstance(value, dict) or canonical != content:
|
||||||
|
raise PositiveSetClosureStateError(PositiveSetClosureStateReason.STATE_UNREADABLE)
|
||||||
|
return value
|
||||||
|
|
||||||
|
|
||||||
|
def decode_positive_set_closure(content: bytes) -> PositiveSetClosureV1:
|
||||||
|
"""Rebuild one closure decision only from canonical, digest-consistent bytes."""
|
||||||
|
value = _decoded_value(content)
|
||||||
|
if set(value) != _CLOSURE_KEYS or value["schema_version"] != POSITIVE_SET_CLOSURE_SCHEMA:
|
||||||
|
raise PositiveSetClosureStateError(PositiveSetClosureStateReason.STATE_MISMATCH)
|
||||||
|
try:
|
||||||
|
closure = positive_set_closure(
|
||||||
|
batch_digests=tuple(value["batch_digests"]),
|
||||||
|
accepted_batch_digests=tuple(value["accepted_batch_digests"]),
|
||||||
|
total_accepted_positives=value["total_accepted_positives"],
|
||||||
|
positives_by_ecosystem={item["ecosystem"]: item["accepted_positives"] for item in value["positives_by_ecosystem"]},
|
||||||
|
accepted_families=tuple(value["accepted_families"]),
|
||||||
|
status=PositiveSetClosureStatus(value["status"]),
|
||||||
|
reason=PositiveSetClosureReason(value["reason"]),
|
||||||
|
)
|
||||||
|
except (AttributeError, KeyError, TypeError, ValueError) as error:
|
||||||
|
raise PositiveSetClosureStateError(PositiveSetClosureStateReason.STATE_MISMATCH) from error
|
||||||
|
if positive_set_closure_bytes(closure) != content:
|
||||||
|
raise PositiveSetClosureStateError(PositiveSetClosureStateReason.STATE_MISMATCH)
|
||||||
|
return closure
|
||||||
|
|
||||||
|
|
||||||
|
def persist_positive_set_closure(store: S3ArtifactRepository, closure: PositiveSetClosureV1) -> ArtifactReference:
|
||||||
|
"""Persist one durable closure decision bound to the ledger facts it examined."""
|
||||||
|
content = canonical_artifact_bytes(
|
||||||
|
ArtifactKind.POPULATION,
|
||||||
|
positive_set_closure_value(closure),
|
||||||
|
access_class=ArtifactAccessClass.OPERATOR_SAFE,
|
||||||
|
provenance_digest=closure.closure_digest,
|
||||||
|
)
|
||||||
|
return store.put_if_absent(content, reference=artifact_reference(content))
|
||||||
|
|
||||||
|
|
||||||
|
def resume_positive_set_closure(
|
||||||
|
store: S3ArtifactRepository,
|
||||||
|
reference: ArtifactReference,
|
||||||
|
*,
|
||||||
|
authority: ArtifactReadAuthority,
|
||||||
|
expected_access_policy_digest: str,
|
||||||
|
) -> PositiveSetClosureV1:
|
||||||
|
"""Resume one closure decision from the durable store after restart."""
|
||||||
|
accepted = store.get(
|
||||||
|
reference,
|
||||||
|
expected_kind=ArtifactKind.POPULATION,
|
||||||
|
authority=authority,
|
||||||
|
expected_access_policy_digest=expected_access_policy_digest,
|
||||||
|
)
|
||||||
|
try:
|
||||||
|
content = canonical_bytes(_converted(accepted.artifact.payload))
|
||||||
|
except (TypeError, ValueError, RecursionError):
|
||||||
|
raise PositiveSetClosureStateError(PositiveSetClosureStateReason.STATE_UNREADABLE) from None
|
||||||
|
return decode_positive_set_closure(content)
|
||||||
|
|
||||||
|
|
||||||
|
__all__ = [
|
||||||
|
"decode_positive_set_closure",
|
||||||
|
"persist_positive_set_closure",
|
||||||
|
"resume_positive_set_closure",
|
||||||
|
]
|
||||||
@@ -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)
|
COMBINED_JAVASCRIPT_NAMES = (*JAVASCRIPT_NAMES, *TYPESCRIPT_NAMES)
|
||||||
THIRD_PYTHON_NAMES = tuple(f"py3-{index:02d}" for index in range(12))
|
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")
|
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_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))
|
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",
|
"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",
|
"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)))
|
_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)
|
_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 = {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)})
|
_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)
|
_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)})
|
_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)
|
_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)})
|
_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")
|
READ_POLICY = bytes_digest(b"cohort-ingestion-read-policy-fixture")
|
||||||
@@ -600,6 +650,8 @@ __all__ = [
|
|||||||
"ENUMERATION_REVIEWER",
|
"ENUMERATION_REVIEWER",
|
||||||
"GROUND_TRUTH_POLICY",
|
"GROUND_TRUTH_POLICY",
|
||||||
"FakeReader",
|
"FakeReader",
|
||||||
|
"FOURTH_JAVASCRIPT_NAMES",
|
||||||
|
"FOURTH_PYTHON_NAMES",
|
||||||
"JAVASCRIPT_COUNT",
|
"JAVASCRIPT_COUNT",
|
||||||
"JAVASCRIPT_NAMES",
|
"JAVASCRIPT_NAMES",
|
||||||
"PYTHON_COUNT",
|
"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