# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-peer-s-signed-revocation-status-as-authoritative-across-a-federation-boundary-and-when-does-crl-gossip.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-peer-s-signed-revocation-status-as-authoritative-across-a-federation-boundary-and-when-does-crl-gossip.warrant.json
# Markdown SHA-256:   70df576bb151b0253b6b260c267f89fb0b74f0dfd251134c6c417e7b7f27b3c7
# Code AST SHA-256:   0892b802b6de238565db75e1b21238cdb9691d262e945d8b8c5196c6a2f454b6
# Verified Classes:   RevocationConvergenceError, StatusList, HighWaterMark, FederationStatusValidator
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from __future__ import annotations

import hashlib
import time
from dataclasses import dataclass, field
from typing import Optional


class RevocationConvergenceError(RuntimeError):
    """Raised when a status list cannot be trusted as authoritative."""


@dataclass(frozen=True)
class StatusList:
    issuer_domain: str
    version: int
    this_update: float
    next_update: float
    revoked_subjects: frozenset[str]
    signature: bytes
    content_hash: str = field(init=False)

    def __post_init__(self) -> None:
        h = hashlib.sha256(
            f"{self.issuer_domain}|{self.version}|{self.this_update}|"
            f"{sorted(self.revoked_subjects)}".encode()
        ).hexdigest()
        object.__setattr__(self, "content_hash", h)


@dataclass
class HighWaterMark:
    version: int
    content_hash: str


class FederationStatusValidator:
    """
    Enforces authority locality, monotonic version integrity, and
    fail-closed freshness for cross-domain revocation status.
    """

    def __init__(self, own_domain: str) -> None:
        self.own_domain = own_domain
        # Durable in production; in-memory here for illustration only.
        self._hwm: dict[str, HighWaterMark] = {}

    def _check_monotonic(self, sl: StatusList) -> None:
        prev = self._hwm.get(sl.issuer_domain)
        if prev is None:
            return
        if sl.version < prev.version:
            raise RevocationConvergenceError(
                f"version regression from {sl.issuer_domain}: "
                f"got v={sl.version}, high-water v={prev.version}"
            )
        if sl.version == prev.version and sl.content_hash != prev.content_hash:
            raise RevocationConvergenceError(
                f"status list split at v={sl.version} from {sl.issuer_domain}: "
                f"{sl.content_hash} != {prev.content_hash}"
            )

    def _check_freshness_for_positive(self, sl: StatusList, subject: str) -> None:
        # Stale lists may maintain a revocation, never clear one.
        if subject in sl.revoked_subjects:
            return
        if time.time() >= sl.next_update:
            raise RevocationConvergenceError(
                f"stale status list from {sl.issuer_domain} used to assert "
                f"{subject} is valid; next_update={sl.next_update}"
            )

    def decide(
        self,
        subject: str,
        subject_domain: str,
        candidate: StatusList,
        *,
        relayed_by_peer: bool,
    ) -> bool:
        """
        Returns True iff the subject may be admitted.
        Raises RevocationConvergenceError when the candidate is not
        authoritative; caller must deny on raise.
        """
        # Authority locality: a peer's relay is a hint, not a fact.
        if relayed_by_peer and candidate.issuer_domain != self.own_domain:
            raise RevocationConvergenceError(
                f"cross-domain status for {subject} relayed by peer; "
                f"issuer={candidate.issuer_domain} must be queried directly"
            )
        if candidate.issuer_domain != subject_domain:
            raise RevocationConvergenceError(
                f"issuer {candidate.issuer_domain} has no authority over "
                f"subject {subject} in domain {subject_domain}"
            )

        self._check_monotonic(candidate)
        self._check_freshness_for_positive(candidate, subject)

        # Commit high-water mark only after all checks pass.
        self._hwm[candidate.issuer_domain] = HighWaterMark(
            version=candidate.version, content_hash=candidate.content_hash
        )

        return subject not in candidate.revoked_subjects
