refactor(dr): preserve recovery contracts in bounded owners

This commit is contained in:
2026-10-24 19:08:27 +03:00
parent 05e664f245
commit fb293d229f
18 changed files with 1471 additions and 1070 deletions

View File

@@ -2,6 +2,8 @@
# #region Tooling.DrEvidenceCheck [C:4] [TYPE Module] [SEMANTICS dr,evidence,verification,offline,digest,scope]
# @ingroup Tooling
# @BRIEF Prove, offline and read-only, that every in-scope opaque evidence ref resolves to contained bytes whose sha256 matches.
# @RELATION DEPENDS_ON -> [Tooling.DrEvidenceCheck.TypedScope]
# @RELATION DEPENDS_ON -> [Tooling.DrEvidenceCheck.Containment]
# @PRE DATABASE_URL names the exact restored database and STORAGE_ROOT_PATH the archived evidence tree.
# @POST Nothing is written; the summary reports verified/out-of-scope counts and typed refusal codes without raw refs.
# @INVARIANT Scope comes from the typed catalog contract and typed columns, never from a prefix scan or a fallback.
@@ -31,14 +33,20 @@ Exit codes:
from __future__ import annotations
import argparse
import errno
import hashlib
import json
import os
import os as os
from pathlib import Path
import stat
import sys
from dr_evidence_scope import (
ScopeContractRefused as ScopeContractRefused, _entry_evidence_refs as _entry_evidence_refs, _authority_evidence_refs as _authority_evidence_refs, _merge_scope as _merge_scope,
_document_scope_rows as _document_scope_rows, _authority_scope_rows as _authority_scope_rows, _catalog_scope_rows as _catalog_scope_rows, _scope_from_database as _scope_from_database,
)
from dr_evidence_io import (
_resolve as _resolve, _open_root as _open_root, _classify_component as _classify_component, _open_contained as _open_contained, _sha256_descriptor as _sha256_descriptor, _archive_names as _archive_names,
)
EXIT_OK = 0
EXIT_FAILURES = 1
EXIT_EMPTY_SCOPE = 3
@@ -48,14 +56,6 @@ REFERENCE_PREFIXES = ("draft:", "handle:")
TERMINAL_RETENTION_STATES = ("deleted", "tombstoned")
class ScopeContractRefused(Exception):
"""Typed refusal raised when the reviewed scope contract cannot be read exactly."""
def __init__(self, code: str):
self.code = code
super().__init__(code)
# #region Tooling.DrEvidenceCheck.App [C:2] [TYPE Function]
def _app_modules():
"""Import the production owners; a missing owner is a typed refusal, never a fallback parser."""
@@ -74,290 +74,33 @@ def _app_modules():
# #endregion Tooling.DrEvidenceCheck.App
# #region Tooling.DrEvidenceCheck.TypedScope [C:4] [TYPE Function]
def _entry_evidence_refs(entry) -> list[dict]:
"""Extract DraftRef evidence fields from one typed catalog entry revision."""
refs = []
native = getattr(entry.entry, "native_result", None)
if native is not None:
record = native.authority_record
refs.append({"ref": record.capture_content_ref, "sha256": record.source_response_hash,
"source": "catalog_capture_content_ref"})
descriptor = record.descriptor.native_request
refs.append({"ref": descriptor.content_ref, "sha256": descriptor.sha256,
"source": "catalog_descriptor_content_ref"})
expected_image = getattr(entry.entry, "expected_image_content_ref", None)
if expected_image:
refs.append({"ref": expected_image, "sha256": expected_image.rsplit(":", 1)[-1],
"source": "catalog_expected_image_content_ref"})
return refs
def _authority_evidence_refs(authority) -> list[dict]:
"""Extract protected evidence from the typed entry authority, including nested security evidence."""
refs = []
protected = getattr(authority, "protected_evidence_ref", None)
if protected is not None:
# The authoring envelope has no separate digest column: the DraftRef itself carries the digest.
refs.append({"ref": protected, "sha256": None,
"source": "entry_authority_protected_evidence"})
security = getattr(authority, "security_authority", None)
if security is not None:
refs.append({"ref": security.protected_evidence_ref,
"sha256": security.protected_evidence_sha256,
"source": "entry_authority_security_evidence"})
return refs
def _merge_scope(rows: list[dict]) -> list[dict]:
"""One row per ref; conflicting digests for one ref are a typed refusal, never a silent pick."""
merged: dict[str, dict] = {}
for row in rows:
ref, digest = row["ref"], row.get("sha256")
existing = merged.get(ref)
if existing is None:
merged[ref] = row
continue
existing_digest = existing.get("sha256")
if existing_digest is None:
existing["sha256"] = digest
elif digest is not None and existing_digest != digest:
raise ScopeContractRefused("EVIDENCE_SCOPE_CONFLICT")
return list(merged.values())
def _document_scope_rows(payload, CatalogRevisionDocument, authority_kinds) -> list[dict]:
"""Validate one stored document through the typed contract, then extract its evidence fields."""
try:
document = CatalogRevisionDocument.model_validate_json(
json.dumps(payload), context={"entry_authority_kinds": authority_kinds})
except Exception: # noqa: BLE001 — the typed contract must validate, no fallback
raise ScopeContractRefused("EVIDENCE_CATALOG_PAYLOAD_INVALID") from None
rows: list[dict] = []
for entry in document.entry_revisions + document.observatory_entries:
rows.extend(_entry_evidence_refs(entry))
return rows
def _authority_scope_rows(payload, validate_authority) -> list[dict]:
"""Validate one stored authority envelope through the typed contract, then extract evidence."""
try:
authority = validate_authority(payload)
except Exception: # noqa: BLE001
raise ScopeContractRefused("EVIDENCE_ENTRY_AUTHORITY_INVALID") from None
return _authority_evidence_refs(authority)
def _catalog_scope_rows(engine, CatalogRevisionDocument, validate_authority) -> list[dict]:
from sqlalchemy import text
rows: list[dict] = []
with engine.connect() as connection:
payloads = connection.execute(text(
"SELECT payload FROM baseline_catalog_revisions")).scalars().all()
authorities = connection.execute(text(
"SELECT catalog_revision_id, baseline_revision_id, authority_kind, authority "
"FROM baseline_catalog_entry_authorities")).mappings().all()
kinds_by_revision: dict[str, dict[str, str]] = {}
for item in authorities:
kinds_by_revision.setdefault(item["catalog_revision_id"], {})[
item["baseline_revision_id"]] = item["authority_kind"]
for payload in payloads:
revision_id = payload.get("catalog_revision_id") if isinstance(payload, dict) else None
rows.extend(_document_scope_rows(payload, CatalogRevisionDocument,
kinds_by_revision.get(revision_id, {})))
for item in authorities:
rows.extend(_authority_scope_rows(item["authority"], validate_authority))
return rows
def _scope_from_database(CatalogRevisionDocument, validate_authority) -> tuple[list[dict], int]:
"""Return in-scope rows and the out-of-scope draft count; read-only queries only."""
from sqlalchemy import create_engine, text
database_url = os.environ.get("DATABASE_URL", "")
if not database_url:
raise ScopeContractRefused("DR_TARGET_UNRESOLVED")
schema = (os.environ.get("DB_SCHEMA") or "public").strip() or "public"
connect_args = {} if schema == "public" else {"options": f"-csearch_path={schema}"}
engine = create_engine(database_url, connect_args=connect_args)
try:
rows = _catalog_scope_rows(engine, CatalogRevisionDocument, validate_authority)
with engine.connect() as connection:
scenario_rows = connection.execute(text(
"SELECT a.content_ref AS ref, a.sha256 AS sha256 FROM scenario_artifacts a "
"LEFT JOIN scenario_retention_deletions d "
" ON d.target_type = 'artifact' AND d.target_id = a.id "
" AND d.state IN ('deleted', 'tombstoned') "
"WHERE a.is_active AND d.id IS NULL")).mappings().all()
known = {row["ref"] for row in rows}
for row in scenario_rows:
rows.append({"ref": row["ref"], "sha256": row["sha256"],
"source": "active_scenario_artifact"})
known.add(row["ref"])
out_of_scope = 0
for row in connection.execute(text(
"SELECT content_ref AS ref, sha256 AS sha256 FROM draft_artifacts")).mappings().all():
if row["ref"] in known:
rows.append({"ref": row["ref"], "sha256": row["sha256"],
"source": "referenced_draft_artifact"})
else:
out_of_scope += 1
finally:
engine.dispose()
return _merge_scope(rows), out_of_scope
# #endregion Tooling.DrEvidenceCheck.TypedScope
# #region Tooling.DrEvidenceCheck.Containment [C:5] [TYPE Function]
# Nonregular leaves must reach fstat without waiting for a FIFO writer/device peer. The same
# descriptor is still rejected below unless it is a regular file; no pathname type check replaces it.
_OPEN_FLAGS = os.O_RDONLY | os.O_NONBLOCK | getattr(os, "O_CLOEXEC", 0)
def _resolve(parse_draft, ref: str) -> tuple[tuple[str, ...], str]:
"""Map one opaque ref to (relative path components, digest); no filesystem access."""
if ref.startswith("draft:"):
run_id, digest = parse_draft(ref)
if run_id in {".", ".."}:
raise ValueError("DRAFT_OWNER_INVALID")
return ("drafts", run_id, digest), digest
# @INVARIANT A handle ref carries the explicit prefix: production HandleBlobStore.retrieve
# requires "handle:" and 64 hex digits (scenario/handles.py:46-49). A bare digest is
# not a handle ref and must be refused, never resolved by a prefix-stripping shortcut.
if not ref.startswith("handle:"):
raise ValueError("REF_SCHEME_INVALID")
digest = ref[len("handle:"):]
if len(digest) != 64 or any(character not in "0123456789abcdef" for character in digest):
raise ValueError("HANDLE_REF_INVALID")
return ("drafts", "handles", digest), digest
def _open_root(root_real: Path) -> int:
"""Pin every absolute directory component without following a symlink at any depth.
@RATIONALE O_NOFOLLOW on one absolute os.open only protects the final component; opening each
child relative to its pinned parent also rejects ancestor aliases and concurrent replacement.
@REJECTED resolve/lstat-only admission can follow a different root before the protected traversal.
"""
current = None
try:
root = Path(root_real)
if not root.is_absolute() or ".." in root.parts:
raise ValueError("absolute root required")
flags = _OPEN_FLAGS | os.O_DIRECTORY | os.O_NOFOLLOW
current = os.open(root.anchor, flags)
for part in root.parts[1:]:
child = os.open(part, flags, dir_fd=current)
os.close(current)
current = child
result = current
current = None # Transfer only the final owned directory descriptor to the caller.
return result
except (OSError, TypeError, ValueError):
raise ScopeContractRefused("EVIDENCE_STORAGE_ROOT_INVALID") from None
finally:
if current is not None:
os.close(current)
def _classify_component(part: str, parent_fd: int) -> str | None:
"""Name the reason a component is not a followable directory/file, or None when it is plain."""
try:
info = os.stat(part, dir_fd=parent_fd, follow_symlinks=False)
except OSError:
return "EVIDENCE_BYTES_MISSING"
if stat.S_ISLNK(info.st_mode):
return "EVIDENCE_PATH_SYMLINK"
return None
def _open_contained(root_fd: int, relative_parts: tuple[str, ...]):
"""Traverse pinned directory descriptors: each component opens O_NOFOLLOW relative to its parent.
@INVARIANT No pathname is ever opened again after being checked: the root fd is opened once and
every component is resolved with dir_fd=/O_NOFOLLOW, so replacing a verified parent
directory with a symlink cannot redirect the open to an external inode.
@POST The returned descriptor is the exact regular file inode that was fstat-ed; every helper fd
is closed before returning.
"""
opened: list[int] = []
current = root_fd
try:
for index, part in enumerate(relative_parts):
leaf = index == len(relative_parts) - 1
reason = _classify_component(part, current)
if reason is not None:
return None, reason
flags = _OPEN_FLAGS | getattr(os, "O_NOFOLLOW", 0)
if not leaf:
flags |= getattr(os, "O_DIRECTORY", 0)
try:
descriptor = os.open(part, flags, dir_fd=current)
except OSError as error:
# @RATIONALE A component swapped to a symlink between classify and open can surface
# as ELOOP or ENOTDIR; re-check the component without following it so the
# refusal names the symlink instead of a generic missing byte.
try:
info = os.stat(part, dir_fd=current, follow_symlinks=False)
if stat.S_ISLNK(info.st_mode):
return None, "EVIDENCE_PATH_SYMLINK"
except OSError:
pass
if error.errno == errno.ELOOP:
return None, "EVIDENCE_PATH_SYMLINK"
return None, "EVIDENCE_BYTES_MISSING"
opened.append(descriptor)
current = descriptor
file_info = os.fstat(current)
if not stat.S_ISREG(file_info.st_mode):
return None, "EVIDENCE_BYTES_MISSING"
if file_info.st_size <= 0:
return None, "EVIDENCE_BYTES_EMPTY"
return opened.pop(), None
finally:
for descriptor in opened:
os.close(descriptor)
def _sha256_descriptor(descriptor: int) -> str:
hasher = hashlib.sha256()
with os.fdopen(descriptor, "rb") as stream:
for chunk in iter(lambda: stream.read(1024 * 1024), b""):
hasher.update(chunk)
return hasher.hexdigest()
def _archive_names(path: str | None) -> set[str] | None:
if not path:
return None
names = set()
for line in Path(path).read_text(encoding="utf-8", errors="replace").splitlines():
name = line.strip()
if not name or name.endswith("/"):
continue
names.add(name[2:] if name.startswith("./") else name)
return names
# #endregion Tooling.DrEvidenceCheck.Containment
# #region Tooling.DrEvidenceCheck.Verify [C:4] [TYPE Function]
# #region Tooling.DrEvidenceCheck.Scheme [C:3] [TYPE Function] [SEMANTICS dr,recovery]
def _scheme(ref: str) -> str:
if ref.startswith("draft:"):
return "draft"
if ref.startswith("handle:"):
return "handle"
return "unsupported"
# #endregion Tooling.DrEvidenceCheck.Scheme
# #region Tooling.DrEvidenceCheck.Failure [C:3] [TYPE Function] [SEMANTICS dr,recovery]
def _failure(code: str, row: dict) -> dict:
"""Diagnostics carry only controlled identifiers and a ref digest; never the raw ref text."""
ref = row["ref"] if isinstance(row.get("ref"), str) else ""
return {"code": code, "source": row.get("source", "unknown"),
"scheme": _scheme(ref),
"ref_digest": hashlib.sha256(ref.encode("utf-8", "surrogatepass")).hexdigest()[:16]}
# #endregion Tooling.DrEvidenceCheck.Failure
# #region Tooling.DrEvidenceCheck.Verify [C:4] [TYPE Function]
def _verify(root, parse_draft, archive_names: set[str] | None,
rows: list[dict]) -> list[dict]:
root_real = _storage_root(str(root))
@@ -391,14 +134,16 @@ def _verify(root, parse_draft, archive_names: set[str] | None,
# #endregion Tooling.DrEvidenceCheck.Verify
# #region Tooling.DrEvidenceCheck.Main [C:3] [TYPE Function]
# #region Tooling.DrEvidenceCheck.StorageRoot [C:3] [TYPE Function] [SEMANTICS dr,recovery]
def _storage_root(value: str) -> Path:
candidate = Path(value)
if not candidate.is_absolute() or not candidate.is_dir():
raise ScopeContractRefused("EVIDENCE_STORAGE_ROOT_INVALID")
return candidate.resolve(strict=True)
# #endregion Tooling.DrEvidenceCheck.StorageRoot
# #region Tooling.DrEvidenceCheck.Main [C:3] [TYPE Function]
def main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser(description="Read-only DR evidence verifier (no DB or storage writes).")
parser.add_argument("--storage-root", default=os.environ.get("STORAGE_ROOT_PATH", "/app/storage"))

141
scripts/dr_evidence_io.py Normal file
View File

@@ -0,0 +1,141 @@
# #region Tooling.DrEvidenceCheck.Containment [C:5] [TYPE Module] [SEMANTICS dr,evidence,containment]
# @BRIEF Resolve typed evidence refs and open exact regular inodes through pinned directory descriptors.
import errno
import hashlib
import os
from pathlib import Path
import stat
from dr_evidence_scope import ScopeContractRefused
# Nonregular leaves must reach fstat without waiting for a FIFO writer/device peer. The same
# descriptor is still rejected below unless it is a regular file; no pathname type check replaces it.
_OPEN_FLAGS = os.O_RDONLY | os.O_NONBLOCK | getattr(os, "O_CLOEXEC", 0)
# #region Tooling.DrEvidenceCheck.Containment.Resolve [C:3] [TYPE Function] [SEMANTICS dr,recovery]
# @INVARIANT Handle refs require the explicit handle: prefix and 64 lowercase hexadecimal digits.
def _resolve(parse_draft, ref: str) -> tuple[tuple[str, ...], str]:
"""Map one opaque ref to (relative path components, digest); no filesystem access."""
if ref.startswith("draft:"):
run_id, digest = parse_draft(ref)
if run_id in {".", ".."}:
raise ValueError("DRAFT_OWNER_INVALID")
return ("drafts", run_id, digest), digest
if not ref.startswith("handle:"):
raise ValueError("REF_SCHEME_INVALID")
digest = ref[len("handle:"):]
if len(digest) != 64 or any(character not in "0123456789abcdef" for character in digest):
raise ValueError("HANDLE_REF_INVALID")
return ("drafts", "handles", digest), digest
# #endregion Tooling.DrEvidenceCheck.Containment.Resolve
# #region Tooling.DrEvidenceCheck.Containment.OpenRoot [C:5] [TYPE Function] [SEMANTICS dr,evidence,containment]
# @RATIONALE Opening each absolute component relative to its pinned parent rejects ancestor aliases and replacement races.
# @REJECTED One absolute O_NOFOLLOW open protects only the final component; resolve/lstat admission can select another root.
def _open_root(root_real: Path) -> int:
"""Pin every absolute directory component without following a symlink at any depth."""
current = None
try:
root = Path(root_real)
if not root.is_absolute() or ".." in root.parts:
raise ValueError("absolute root required")
flags = _OPEN_FLAGS | os.O_DIRECTORY | os.O_NOFOLLOW
current = os.open(root.anchor, flags)
for part in root.parts[1:]:
child = os.open(part, flags, dir_fd=current)
os.close(current)
current = child
result = current
current = None # Transfer only the final owned directory descriptor to the caller.
return result
except (OSError, TypeError, ValueError):
raise ScopeContractRefused("EVIDENCE_STORAGE_ROOT_INVALID") from None
finally:
if current is not None:
os.close(current)
# #endregion Tooling.DrEvidenceCheck.Containment.OpenRoot
# #region Tooling.DrEvidenceCheck.Containment.ClassifyComponent [C:3] [TYPE Function] [SEMANTICS dr,recovery]
def _classify_component(part: str, parent_fd: int) -> str | None:
"""Name the reason a component is not a followable directory/file, or None when it is plain."""
try:
info = os.stat(part, dir_fd=parent_fd, follow_symlinks=False)
except OSError:
return "EVIDENCE_BYTES_MISSING"
if stat.S_ISLNK(info.st_mode):
return "EVIDENCE_PATH_SYMLINK"
return None
# #endregion Tooling.DrEvidenceCheck.Containment.ClassifyComponent
# #region Tooling.DrEvidenceCheck.Containment.OpenFailure [C:3] [TYPE Function] [SEMANTICS dr,recovery]
# @RATIONALE A replacement symlink can yield ELOOP or ENOTDIR; nofollow reclassification preserves the typed symlink refusal.
def _open_failure(part, parent_fd, error):
"""Classify a classify/open race without following a replacement symlink."""
reason = _classify_component(part, parent_fd)
if reason == "EVIDENCE_PATH_SYMLINK" or error.errno == errno.ELOOP:
return "EVIDENCE_PATH_SYMLINK"
return "EVIDENCE_BYTES_MISSING"
# #endregion Tooling.DrEvidenceCheck.Containment.OpenFailure
# #region Tooling.DrEvidenceCheck.Containment.OpenContained [C:5] [TYPE Function] [SEMANTICS dr,evidence,containment]
# @INVARIANT Every component opens relative to its pinned parent with O_NOFOLLOW; a parent swap cannot redirect the leaf.
# @POST Returns the fstat-validated regular inode; all intermediate descriptors close on return or failure.
def _open_contained(root_fd: int, relative_parts: tuple[str, ...]):
"""Open the exact regular leaf through pinned parent descriptors; close all helper fds."""
opened: list[int] = []
current = root_fd
try:
for index, part in enumerate(relative_parts):
leaf = index == len(relative_parts) - 1
reason = _classify_component(part, current)
if reason is not None:
return None, reason
flags = _OPEN_FLAGS | getattr(os, "O_NOFOLLOW", 0)
if not leaf:
flags |= getattr(os, "O_DIRECTORY", 0)
try:
descriptor = os.open(part, flags, dir_fd=current)
except OSError as error:
return None, _open_failure(part, current, error)
opened.append(descriptor)
current = descriptor
file_info = os.fstat(current)
if not stat.S_ISREG(file_info.st_mode):
return None, "EVIDENCE_BYTES_MISSING"
if file_info.st_size <= 0:
return None, "EVIDENCE_BYTES_EMPTY"
return opened.pop(), None
finally:
for descriptor in opened:
os.close(descriptor)
# #endregion Tooling.DrEvidenceCheck.Containment.OpenContained
# #region Tooling.DrEvidenceCheck.Containment.Sha256Descriptor [C:3] [TYPE Function] [SEMANTICS dr,recovery]
def _sha256_descriptor(descriptor: int) -> str:
hasher = hashlib.sha256()
with os.fdopen(descriptor, "rb") as stream:
while chunk := stream.read(1024 * 1024):
hasher.update(chunk)
return hasher.hexdigest()
# #endregion Tooling.DrEvidenceCheck.Containment.Sha256Descriptor
# #region Tooling.DrEvidenceCheck.Containment.ArchiveNames [C:3] [TYPE Function] [SEMANTICS dr,recovery]
def _archive_names(path: str | None) -> set[str] | None:
if not path:
return None
names = set()
for line in Path(path).read_text(encoding="utf-8", errors="replace").splitlines():
name = line.strip()
if not name or name.endswith("/"):
continue
names.add(name[2:] if name.startswith("./") else name)
return names
# #endregion Tooling.DrEvidenceCheck.Containment.ArchiveNames
# #endregion Tooling.DrEvidenceCheck.Containment

View File

@@ -0,0 +1,164 @@
# #region Tooling.DrEvidenceCheck.TypedScope [C:4] [TYPE Module] [SEMANTICS dr,evidence,scope]
# @BRIEF Extract only schema-validated catalog, authority and active retained artifact references.
import json
import os
# #region Tooling.DrEvidenceCheck.TypedScope.Scopecontractrefused [C:3] [TYPE Class] [SEMANTICS dr,recovery]
class ScopeContractRefused(Exception):
"""Typed refusal raised when the reviewed scope contract cannot be read exactly."""
# #region Tooling.DrEvidenceCheck.TypedScope.Scopecontractrefused.Init [C:3] [TYPE Function] [SEMANTICS dr,recovery]
def __init__(self, code: str):
self.code = code
super().__init__(code)
# #endregion Tooling.DrEvidenceCheck.TypedScope.Scopecontractrefused.Init
# #endregion Tooling.DrEvidenceCheck.TypedScope.Scopecontractrefused
# #region Tooling.DrEvidenceCheck.TypedScope.EntryEvidenceRefs [C:3] [TYPE Function] [SEMANTICS dr,recovery]
def _entry_evidence_refs(entry) -> list[dict]:
"""Extract DraftRef evidence fields from one typed catalog entry revision."""
refs = []
native = getattr(entry.entry, "native_result", None)
if native is not None:
record = native.authority_record
refs.append({"ref": record.capture_content_ref, "sha256": record.source_response_hash,
"source": "catalog_capture_content_ref"})
descriptor = record.descriptor.native_request
refs.append({"ref": descriptor.content_ref, "sha256": descriptor.sha256,
"source": "catalog_descriptor_content_ref"})
expected_image = getattr(entry.entry, "expected_image_content_ref", None)
if expected_image:
refs.append({"ref": expected_image, "sha256": expected_image.rsplit(":", 1)[-1],
"source": "catalog_expected_image_content_ref"})
return refs
# #endregion Tooling.DrEvidenceCheck.TypedScope.EntryEvidenceRefs
# #region Tooling.DrEvidenceCheck.TypedScope.AuthorityEvidenceRefs [C:3] [TYPE Function] [SEMANTICS dr,recovery]
def _authority_evidence_refs(authority) -> list[dict]:
"""Extract protected evidence from the typed entry authority, including nested security evidence."""
refs = []
protected = getattr(authority, "protected_evidence_ref", None)
if protected is not None:
# The authoring envelope has no separate digest column: the DraftRef itself carries the digest.
refs.append({"ref": protected, "sha256": None,
"source": "entry_authority_protected_evidence"})
security = getattr(authority, "security_authority", None)
if security is not None:
refs.append({"ref": security.protected_evidence_ref,
"sha256": security.protected_evidence_sha256,
"source": "entry_authority_security_evidence"})
return refs
# #endregion Tooling.DrEvidenceCheck.TypedScope.AuthorityEvidenceRefs
# #region Tooling.DrEvidenceCheck.TypedScope.MergeScope [C:3] [TYPE Function] [SEMANTICS dr,recovery]
def _merge_scope(rows: list[dict]) -> list[dict]:
"""One row per ref; conflicting digests for one ref are a typed refusal, never a silent pick."""
merged: dict[str, dict] = {}
for row in rows:
ref, digest = row["ref"], row.get("sha256")
existing = merged.get(ref)
if existing is None:
merged[ref] = row
continue
existing_digest = existing.get("sha256")
if existing_digest is None:
existing["sha256"] = digest
elif digest is not None and existing_digest != digest:
raise ScopeContractRefused("EVIDENCE_SCOPE_CONFLICT")
return list(merged.values())
# #endregion Tooling.DrEvidenceCheck.TypedScope.MergeScope
# #region Tooling.DrEvidenceCheck.TypedScope.DocumentScopeRows [C:3] [TYPE Function] [SEMANTICS dr,recovery]
def _document_scope_rows(payload, CatalogRevisionDocument, authority_kinds) -> list[dict]:
"""Validate one stored document through the typed contract, then extract its evidence fields."""
try:
document = CatalogRevisionDocument.model_validate_json(
json.dumps(payload), context={"entry_authority_kinds": authority_kinds})
except Exception: # noqa: BLE001 — the typed contract must validate, no fallback
raise ScopeContractRefused("EVIDENCE_CATALOG_PAYLOAD_INVALID") from None
rows: list[dict] = []
for entry in document.entry_revisions + document.observatory_entries:
rows.extend(_entry_evidence_refs(entry))
return rows
# #endregion Tooling.DrEvidenceCheck.TypedScope.DocumentScopeRows
# #region Tooling.DrEvidenceCheck.TypedScope.AuthorityScopeRows [C:3] [TYPE Function] [SEMANTICS dr,recovery]
def _authority_scope_rows(payload, validate_authority) -> list[dict]:
"""Validate one stored authority envelope through the typed contract, then extract evidence."""
try:
authority = validate_authority(payload)
except Exception: # noqa: BLE001
raise ScopeContractRefused("EVIDENCE_ENTRY_AUTHORITY_INVALID") from None
return _authority_evidence_refs(authority)
# #endregion Tooling.DrEvidenceCheck.TypedScope.AuthorityScopeRows
# #region Tooling.DrEvidenceCheck.TypedScope.CatalogScopeRows [C:3] [TYPE Function] [SEMANTICS dr,recovery]
def _catalog_scope_rows(engine, CatalogRevisionDocument, validate_authority) -> list[dict]:
from sqlalchemy import text
rows: list[dict] = []
with engine.connect() as connection:
payloads = connection.execute(text(
"SELECT payload FROM baseline_catalog_revisions")).scalars().all()
authorities = connection.execute(text(
"SELECT catalog_revision_id, baseline_revision_id, authority_kind, authority "
"FROM baseline_catalog_entry_authorities")).mappings().all()
kinds_by_revision: dict[str, dict[str, str]] = {}
for item in authorities:
kinds_by_revision.setdefault(item["catalog_revision_id"], {})[
item["baseline_revision_id"]] = item["authority_kind"]
for payload in payloads:
revision_id = payload.get("catalog_revision_id") if isinstance(payload, dict) else None
rows.extend(_document_scope_rows(payload, CatalogRevisionDocument,
kinds_by_revision.get(revision_id, {})))
for item in authorities:
rows.extend(_authority_scope_rows(item["authority"], validate_authority))
return rows
# #endregion Tooling.DrEvidenceCheck.TypedScope.CatalogScopeRows
# #region Tooling.DrEvidenceCheck.TypedScope.ScopeFromDatabase [C:3] [TYPE Function] [SEMANTICS dr,recovery]
def _scope_from_database(CatalogRevisionDocument, validate_authority) -> tuple[list[dict], int]:
"""Return in-scope rows and the out-of-scope draft count; read-only queries only."""
from sqlalchemy import create_engine, text
database_url = os.environ.get("DATABASE_URL", "")
if not database_url:
raise ScopeContractRefused("DR_TARGET_UNRESOLVED")
schema = (os.environ.get("DB_SCHEMA") or "public").strip() or "public"
connect_args = {} if schema == "public" else {"options": f"-csearch_path={schema}"}
engine = create_engine(database_url, connect_args=connect_args)
try:
rows = _catalog_scope_rows(engine, CatalogRevisionDocument, validate_authority)
with engine.connect() as connection:
scenario_rows = connection.execute(text(
"SELECT a.content_ref AS ref, a.sha256 AS sha256 FROM scenario_artifacts a "
"LEFT JOIN scenario_retention_deletions d "
" ON d.target_type = 'artifact' AND d.target_id = a.id "
" AND d.state IN ('deleted', 'tombstoned') "
"WHERE a.is_active AND d.id IS NULL")).mappings().all()
known = {row["ref"] for row in rows}
for row in scenario_rows:
rows.append({"ref": row["ref"], "sha256": row["sha256"],
"source": "active_scenario_artifact"})
known.add(row["ref"])
out_of_scope = 0
for row in connection.execute(text(
"SELECT content_ref AS ref, sha256 AS sha256 FROM draft_artifacts")).mappings().all():
if row["ref"] in known:
rows.append({"ref": row["ref"], "sha256": row["sha256"],
"source": "referenced_draft_artifact"})
else:
out_of_scope += 1
finally:
engine.dispose()
return _merge_scope(rows), out_of_scope
# #endregion Tooling.DrEvidenceCheck.TypedScope.ScopeFromDatabase
# #endregion Tooling.DrEvidenceCheck.TypedScope

View File

@@ -32,6 +32,7 @@ from src.core.cot_logger import build_cot_event, seed_trace_id
RENDER_TOTAL_LIMIT = 128 * 1024 * 1024
# #region Tooling.DrRecovery.Event [C:3] [TYPE Function] [SEMANTICS dr,recovery]
def event(marker, code=None):
value = build_cot_event(
src="Tooling.DrRecovery",
@@ -44,19 +45,24 @@ def event(marker, code=None):
error_code=code,
)
print(json.dumps(value), file=sys.stderr)
# #endregion Tooling.DrRecovery.Event
# #region Tooling.DrRecovery.Typed [C:3] [TYPE Function] [SEMANTICS dr,recovery]
def typed(model, value):
try:
return model.model_validate_json(json.dumps(value), strict=True)
except (ValueError, TypeError, RecursionError):
raise Refused("DR_RECOVERY_CONTRACT_INVALID") from None
# #endregion Tooling.DrRecovery.Typed
# #region Tooling.DrRecovery.Unique [C:3] [TYPE Function] [SEMANTICS dr,recovery]
def unique(rows, key):
values = {getattr(row, key): row for row in rows}
require(len(values) == len(rows), "DR_RECOVERY_CONTRACT_INVALID")
return values
# #endregion Tooling.DrRecovery.Unique
# #region Tooling.DrRecovery.BindManifest [C:3] [TYPE Function]
@@ -176,6 +182,7 @@ def bind_sources(sidecar, manifest, operations):
# #endregion Tooling.DrRecovery.BindSources
# #region Tooling.DrRecovery.RenderInputs [C:3] [TYPE Function] [SEMANTICS dr,recovery]
def render_inputs(root_fd, sidecar, operations):
renders = unique(sidecar.renders, "operation_id")
require(set(renders) == set(operations), "DR_RECOVERY_CONTRACT_INVALID")
@@ -192,8 +199,10 @@ def render_inputs(root_fd, sidecar, operations):
root_fd, render.artifact.path, BLOB_LIMIT, render.artifact
)
return result
# #endregion Tooling.DrRecovery.RenderInputs
# #region Tooling.DrRecovery.CompareObserved [C:3] [TYPE Function] [SEMANTICS dr,recovery]
def compare_observed(sidecar, observed_path, mapping_path, manifest):
actual = typed(State, external_json(observed_path))
mapping = external_json(mapping_path) if mapping_path is not None else None
@@ -207,6 +216,7 @@ def compare_observed(sidecar, observed_path, mapping_path, manifest):
expected.pop("target")
observed.pop("target")
require(observed == expected, "DR_RECOVERY_STATE_MISMATCH")
# #endregion Tooling.DrRecovery.CompareObserved
# #region Tooling.DrRecovery.Check [C:4] [TYPE Function]
@@ -284,11 +294,16 @@ def check(
# #endregion Tooling.DrRecovery.Check
# #region Tooling.DrRecovery.Recoveryparser [C:3] [TYPE Class] [SEMANTICS dr,recovery]
class RecoveryParser(argparse.ArgumentParser):
# #region Tooling.DrRecovery.Recoveryparser.Error [C:3] [TYPE Function] [SEMANTICS dr,recovery]
def error(self, message):
raise Refused("DR_RECOVERY_CONTRACT_INVALID")
# #endregion Tooling.DrRecovery.Recoveryparser.Error
# #endregion Tooling.DrRecovery.Recoveryparser
# #region Tooling.DrRecovery.Main [C:3] [TYPE Function] [SEMANTICS dr,recovery]
def main(argv=None):
parser = RecoveryParser(
description="Required read-only recovery evidence gate; no DB/network/stand writes"
@@ -315,6 +330,7 @@ def main(argv=None):
codes = [error.code]
print(json.dumps({"status": "REFUSED" if codes else "OK", "codes": codes}))
return 1 if codes else 0
# #endregion Tooling.DrRecovery.Main
if __name__ == "__main__":

View File

@@ -1,5 +1,7 @@
# #region Tooling.DrRecovery.Contract [C:4] [TYPE Module] [SEMANTICS dr,recovery,git,holds]
# @BRIEF Closed recovery sidecar supplements the unchanged v1 manifest with exact source records.
# @RELATION DEPENDS_ON -> [Tooling.DrRecovery.Contract.Primitives]
# @RELATION DEPENDS_ON -> [Tooling.DrRecovery.Contract.Scalars]
# @PRE Inputs are reviewed captures; validation never discovers a configured source or queries a DB.
# @POST Every required component is explicit; malformed/missing authority refuses without a default.
# @RELATION DEPENDS_ON -> [Storage.NativeResultHold]
@@ -11,79 +13,45 @@ from pathlib import Path
import sys
from typing import Annotated, Literal
from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator
from pydantic import Field, field_validator, model_validator
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "backend"))
from src.schemas.dashboard_testing.result_descriptor import Sha256, UuidString # noqa: E402
from src.schemas.dashboard_testing.result_descriptor import Sha256 as Sha256, UuidString # noqa: E402
from src.services.dashboard_testing.execution.publication_config import (
PublicationDestination,
) # noqa: E402
from src.services.storage_holds import HoldIndex # noqa: E402
Text = Annotated[str, Field(min_length=1, max_length=4096, pattern=r"\S")]
Commit = Annotated[str, Field(pattern=r"^(?:[a-f0-9]{40}|[a-f0-9]{64})$")]
from dr_recovery_contract_types import Text as Text, Commit as Commit # noqa: E402
# #region Tooling.DrRecovery.Contract.Base [C:2] [TYPE Class]
class Closed(BaseModel):
model_config = ConfigDict(extra="forbid", frozen=True, strict=True)
@field_validator("schema_version", mode="before", check_fields=False)
@classmethod
def integer_version(cls, value):
if type(value) is not int:
raise ValueError("invalid version")
return value
# #endregion Tooling.DrRecovery.Contract.Base
class Stat(Closed):
bytes: int = Field(gt=0)
sha256: Sha256
class Artifact(Stat):
path: Text
@field_validator("path")
@classmethod
def confined_relative_path(cls, value):
if (
value.startswith("/")
or "\\" in value
or "\x00" in value
or any(part in ("", ".", "..") for part in value.split("/"))
or len(value) > 512
):
raise ValueError("invalid path")
return value
from dr_recovery_contract_base import Closed as Closed, Stat as Stat, Artifact as Artifact, aware # noqa: E402
# #region Tooling.DrRecovery.Contract.Catalog [C:1] [TYPE Class] [SEMANTICS dr,recovery]
class Catalog(Closed):
catalog_id: UuidString
catalog_revision_id: UuidString
catalog_digest: Sha256
integrity_sha256: Sha256
# #endregion Tooling.DrRecovery.Contract.Catalog
# #region Tooling.DrRecovery.Contract.Cataloghead [C:1] [TYPE Class] [SEMANTICS dr,recovery]
class CatalogHead(Closed):
catalog_id: UuidString
repository: Text
# #endregion Tooling.DrRecovery.Contract.Cataloghead
# #region Tooling.DrRecovery.Contract.Approval [C:1] [TYPE Class] [SEMANTICS dr,recovery]
class Approval(Closed):
receipt_id: UuidString
receipt_sha256: Sha256
# #endregion Tooling.DrRecovery.Contract.Approval
def aware(value):
if datetime.fromisoformat(value).utcoffset() is None:
raise ValueError("timezone required")
return value
# #region Tooling.DrRecovery.Contract.Receipt [C:1] [TYPE Class] [SEMANTICS dr,recovery]
class Receipt(Closed):
catalog_revision_id: UuidString
integrity_sha256: Sha256
@@ -93,6 +61,7 @@ class Receipt(Closed):
verified_at: Text
_aware = field_validator("verified_at")(aware)
# #endregion Tooling.DrRecovery.Contract.Receipt
# #region Tooling.DrRecovery.Contract.Publication [C:3] [TYPE Class]
@@ -111,6 +80,7 @@ class Publication(Closed):
commit_sha: Commit
published_receipt: Receipt
# #region Tooling.DrRecovery.Contract.Publication.ExactBinding [C:3] [TYPE Function] [SEMANTICS dr,recovery]
@model_validator(mode="after")
def exact_binding(self):
expected = dict(
@@ -128,11 +98,13 @@ class Publication(Closed):
):
raise ValueError("receipt binding")
return self
# #endregion Tooling.DrRecovery.Contract.Publication.ExactBinding
# #endregion Tooling.DrRecovery.Contract.Publication
# #region Tooling.DrRecovery.Contract.Holdreasons [C:3] [TYPE Class] [SEMANTICS dr,recovery]
class HoldReasons(Closed):
reasons: tuple[
Literal[
@@ -147,14 +119,18 @@ class HoldReasons(Closed):
at: Text
_aware = field_validator("at")(aware)
# #region Tooling.DrRecovery.Contract.Holdreasons.DistinctReasons [C:3] [TYPE Function] [SEMANTICS dr,recovery]
@field_validator("reasons")
@classmethod
def distinct_reasons(cls, value):
if len(set(value)) != len(value):
raise ValueError("duplicate reason")
return value
# #endregion Tooling.DrRecovery.Contract.Holdreasons.DistinctReasons
# #endregion Tooling.DrRecovery.Contract.Holdreasons
# #region Tooling.DrRecovery.Contract.Retention [C:3] [TYPE Class] [SEMANTICS dr,recovery]
class Retention(Closed):
id: UuidString
target_type: Literal["artifact", "run_metadata", "step_metrics", "notification"]
@@ -175,12 +151,16 @@ class Retention(Closed):
_created = field_validator("created_at")(aware)
_updated = field_validator("updated_at")(aware)
# #region Tooling.DrRecovery.Contract.Retention.OptionalTimestamp [C:3] [TYPE Function] [SEMANTICS dr,recovery]
@field_validator("verified_absent_at", "tombstoned_at")
@classmethod
def optional_timestamp(cls, value):
return aware(value) if value is not None else None
# #endregion Tooling.DrRecovery.Contract.Retention.OptionalTimestamp
# #endregion Tooling.DrRecovery.Contract.Retention
# #region Tooling.DrRecovery.Contract.State [C:3] [TYPE Class] [SEMANTICS dr,recovery]
class State(Closed):
target: dict[str, str]
alembic_version: Text
@@ -192,6 +172,7 @@ class State(Closed):
)
retention_deletions: tuple[Retention, ...] = Field(min_length=1, max_length=10000)
# #region Tooling.DrRecovery.Contract.State.ExactTarget [C:3] [TYPE Function] [SEMANTICS dr,recovery]
@field_validator("target")
@classmethod
def exact_target(cls, value):
@@ -200,13 +181,18 @@ class State(Closed):
if not _target_ok(value):
raise ValueError("invalid target")
return value
# #endregion Tooling.DrRecovery.Contract.State.ExactTarget
# #endregion Tooling.DrRecovery.Contract.State
# #region Tooling.DrRecovery.Contract.Ref [C:1] [TYPE Class] [SEMANTICS dr,recovery]
class Ref(Closed):
name: Annotated[str, Field(pattern=r"^refs/heads/[A-Za-z0-9][A-Za-z0-9._/-]*$")]
commit_sha: Commit
# #endregion Tooling.DrRecovery.Contract.Ref
# #region Tooling.DrRecovery.Contract.Source [C:1] [TYPE Class] [SEMANTICS dr,recovery]
class Source(Closed):
source_id: UuidString
base_url: Text
@@ -219,17 +205,22 @@ class Source(Closed):
prerequisites: tuple[Commit, ...] = Field(max_length=256)
operation_ids: tuple[UuidString, ...] = Field(min_length=1, max_length=10000)
_aware = field_validator("approved_at")(aware)
# #endregion Tooling.DrRecovery.Contract.Source
# #region Tooling.DrRecovery.Contract.Render [C:1] [TYPE Class] [SEMANTICS dr,recovery]
class Render(Closed):
operation_id: UuidString
artifact: Artifact
# #endregion Tooling.DrRecovery.Contract.Render
# #region Tooling.DrRecovery.Contract.Holds [C:1] [TYPE Class] [SEMANTICS dr,recovery]
class Holds(Closed):
activated: Stat
index: Stat
records: HoldIndex
# #endregion Tooling.DrRecovery.Contract.Holds
# #region Tooling.DrRecovery.Contract.Sidecar [C:3] [TYPE Class]
@@ -243,19 +234,23 @@ class Sidecar(Closed):
native_holds: Holds
_aware = field_validator("t_snap")(aware)
# #region Tooling.DrRecovery.Contract.Sidecar.UtcSnapshot [C:3] [TYPE Function] [SEMANTICS dr,recovery]
@field_validator("t_snap")
@classmethod
def utc_snapshot(cls, value):
if datetime.fromisoformat(value).utcoffset() != timedelta(0):
raise ValueError("UTC snapshot required")
return value
# #endregion Tooling.DrRecovery.Contract.Sidecar.UtcSnapshot
# #region Tooling.DrRecovery.Contract.Sidecar.NonemptyNativeHolds [C:3] [TYPE Function] [SEMANTICS dr,recovery]
@model_validator(mode="after")
def nonempty_native_holds(self):
holds = self.native_holds.records.holds
if not holds or len({hold.hold_id for hold in holds}) != len(holds):
raise ValueError("nonempty unique holds required")
return self
# #endregion Tooling.DrRecovery.Contract.Sidecar.NonemptyNativeHolds
# #endregion Tooling.DrRecovery.Contract.Sidecar

View File

@@ -0,0 +1,58 @@
# #region Tooling.DrRecovery.Contract.Primitives [C:3] [TYPE Module] [SEMANTICS dr,recovery]
# @BRIEF Strict sidecar base, artifact statistics, relative paths and timezone validation.
from datetime import datetime
from pydantic import BaseModel, ConfigDict, Field, field_validator
from dr_recovery_contract_types import Text, Sha256
# #region Tooling.DrRecovery.Contract.Base [C:2] [TYPE Class]
class Closed(BaseModel):
model_config = ConfigDict(extra="forbid", frozen=True, strict=True)
# #region Tooling.DrRecovery.Contract.Base.IntegerVersion [C:3] [TYPE Function] [SEMANTICS dr,recovery]
@field_validator("schema_version", mode="before", check_fields=False)
@classmethod
def integer_version(cls, value):
if type(value) is not int:
raise ValueError("invalid version")
return value
# #endregion Tooling.DrRecovery.Contract.Base.IntegerVersion
# #endregion Tooling.DrRecovery.Contract.Base
# #region Tooling.DrRecovery.Contract.Primitives.Stat [C:1] [TYPE Class] [SEMANTICS dr,recovery]
class Stat(Closed):
bytes: int = Field(gt=0)
sha256: Sha256
# #endregion Tooling.DrRecovery.Contract.Primitives.Stat
# #region Tooling.DrRecovery.Contract.Primitives.Artifact [C:3] [TYPE Class] [SEMANTICS dr,recovery]
class Artifact(Stat):
path: Text
# #region Tooling.DrRecovery.Contract.Primitives.Artifact.ConfinedRelativePath [C:3] [TYPE Function] [SEMANTICS dr,recovery]
@field_validator("path")
@classmethod
def confined_relative_path(cls, value):
if (
value.startswith("/")
or "\\" in value
or "\x00" in value
or any(part in ("", ".", "..") for part in value.split("/"))
or len(value) > 512
):
raise ValueError("invalid path")
return value
# #endregion Tooling.DrRecovery.Contract.Primitives.Artifact.ConfinedRelativePath
# #endregion Tooling.DrRecovery.Contract.Primitives.Artifact
# #region Tooling.DrRecovery.Contract.Primitives.Aware [C:3] [TYPE Function] [SEMANTICS dr,recovery]
def aware(value):
if datetime.fromisoformat(value).utcoffset() is None:
raise ValueError("timezone required")
return value
# #endregion Tooling.DrRecovery.Contract.Primitives.Aware
# #endregion Tooling.DrRecovery.Contract.Primitives

View File

@@ -0,0 +1,13 @@
# #region Tooling.DrRecovery.Contract.Scalars [C:3] [TYPE Module] [SEMANTICS dr,recovery]
# @BRIEF Shared explicit text, SHA256 digest and full SHA1/SHA256 object identifier types.
from pathlib import Path
import sys
from typing import Annotated
from pydantic import Field
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "backend"))
from src.schemas.dashboard_testing.result_descriptor import Sha256 as Sha256 # noqa: E402
Text = Annotated[str, Field(min_length=1, max_length=4096, pattern=r"\S")]
Commit = Annotated[str, Field(pattern=r"^(?:[a-f0-9]{40}|[a-f0-9]{64})$")]
# #endregion Tooling.DrRecovery.Contract.Scalars

View File

@@ -1,5 +1,6 @@
# #region Tooling.DrRecovery.Git [C:4] [TYPE Module] [SEMANTICS dr,recovery,git,closure]
# @BRIEF Verify actual bundle closure/commit/blob bytes in owned scratch, then independently inspect declared stand roots.
# @RELATION DEPENDS_ON -> [Tooling.DrRecovery.Git.Runner]
# @INVARIANT No transport, inherited Git config, authentication, replacement objects or another object source is used.
# @SIDE_EFFECT Writes only a caller-owned temporary bare repository; deletes only that temporary directory.
# @RATIONALE Importing the declared bundle into an empty ODB proves actual available objects, unlike ls-remote/header metadata.
@@ -8,83 +9,21 @@ import configparser
from hashlib import sha256
import os
from pathlib import Path
import resource
import signal
import subprocess
import subprocess as subprocess
import tempfile
from types import SimpleNamespace
from dr_recovery_io import Refused, require, read, pinned, BUNDLE_LIMIT, BLOB_LIMIT
def _limits():
resource.setrlimit(resource.RLIMIT_CPU, (30, 30))
resource.setrlimit(resource.RLIMIT_FSIZE, (128 * 1024 * 1024, 128 * 1024 * 1024))
resource.setrlimit(resource.RLIMIT_AS, (1024 * 1024 * 1024, 1024 * 1024 * 1024))
# #region Tooling.DrRecovery.Git.Command [C:3] [TYPE Function]
def git(root, args, code, output_limit=128 * 1024):
env = dict(
PATH="/usr/bin:/bin",
HOME="/nonexistent",
GIT_CONFIG_NOSYSTEM="1",
GIT_CONFIG_GLOBAL="/dev/null",
GIT_CONFIG_SYSTEM="/dev/null",
GIT_TERMINAL_PROMPT="0",
GIT_CONFIG_COUNT="0",
GIT_NO_REPLACE_OBJECTS="1",
GIT_OPTIONAL_LOCKS="0",
GIT_NO_LAZY_FETCH="1",
)
command = [
"/usr/bin/git",
"--git-dir=" + str(root),
"-c",
"protocol.allow=never",
"-c",
"core.hooksPath=/dev/null",
*args,
]
with tempfile.TemporaryFile() as stdout, tempfile.TemporaryFile() as stderr:
try:
process = subprocess.Popen(
command,
env=env,
stdin=subprocess.DEVNULL,
stdout=stdout,
stderr=stderr,
start_new_session=True,
preexec_fn=_limits,
)
except (OSError, subprocess.SubprocessError):
raise Refused("DR_RECOVERY_GIT_UNAVAILABLE") from None
try:
result = process.wait(timeout=30)
except subprocess.TimeoutExpired:
try:
os.killpg(process.pid, signal.SIGKILL)
except ProcessLookupError:
pass # The owned child/group can exit between the timeout and kill.
process.wait()
raise Refused("DR_RECOVERY_LIMIT") from None
require(result >= 0, "DR_RECOVERY_LIMIT")
require(result == 0, code)
require(
stdout.tell() <= output_limit and stderr.tell() <= 128 * 1024,
"DR_RECOVERY_LIMIT",
)
stdout.seek(0)
return stdout.read(output_limit + 1)
# #endregion Tooling.DrRecovery.Git.Command
from dr_recovery_git_command import git
# #region Tooling.DrRecovery.Git.Refs [C:3] [TYPE Function] [SEMANTICS dr,recovery]
def refs(source):
values = {item.name: item.commit_sha for item in source.refs}
require(len(values) == len(source.refs), "DR_RECOVERY_CONTRACT_INVALID")
return values
# #endregion Tooling.DrRecovery.Git.Refs
# #region Tooling.DrRecovery.Git.ExactCommit [C:3] [TYPE Function]
@@ -111,6 +50,7 @@ def exact_commit(root, identity):
# #endregion Tooling.DrRecovery.Git.ExactCommit
# #region Tooling.DrRecovery.Git.RequiredRoots [C:3] [TYPE Function] [SEMANTICS dr,recovery]
def required_roots(root, source, operations):
# Current publication contract requires one explicit nonnull reviewed parent; no parent is synthesized.
roots = {ref.commit_sha for ref in source.refs}
@@ -119,8 +59,10 @@ def required_roots(root, source, operations):
for identity in roots:
exact_commit(root, identity)
return sorted(roots)
# #endregion Tooling.DrRecovery.Git.RequiredRoots
# #region Tooling.DrRecovery.Git.Inspect [C:3] [TYPE Function] [SEMANTICS dr,recovery]
def inspect(root, source, operations, render_bytes):
for name, commit in refs(source).items():
actual = (
@@ -148,8 +90,10 @@ def inspect(root, source, operations, render_bytes):
and sha256(content).hexdigest() == operation.render_sha256,
"DR_RECOVERY_GIT_RENDER_MISMATCH",
)
# #endregion Tooling.DrRecovery.Git.Inspect
# #region Tooling.DrRecovery.Git.Provenance [C:3] [TYPE Function] [SEMANTICS dr,recovery]
def provenance(root, source, operation):
# Reuse the publication owner's exact parent+marker rule over actual local commit bytes.
try:
@@ -175,20 +119,36 @@ def provenance(root, source, operation):
"parents": parents,
"commit": {"message": message.decode("utf-8")},
}
reader = SimpleNamespace(
get=lambda *args, **kwargs: SimpleNamespace(
status_code=200, json=lambda: payload
)
)
# #region Tooling.DrRecovery.Git.Provenance.Localresponse [C:3] [TYPE Class] [SEMANTICS dr,recovery]
class LocalResponse:
status_code = 200
# #region Tooling.DrRecovery.Git.Provenance.Localresponse.Json [C:3] [TYPE Function] [SEMANTICS dr,recovery]
def json(self):
return payload
# #endregion Tooling.DrRecovery.Git.Provenance.Localresponse.Json
# #endregion Tooling.DrRecovery.Git.Provenance.Localresponse
# #region Tooling.DrRecovery.Git.Provenance.Localreader [C:3] [TYPE Class] [SEMANTICS dr,recovery]
class LocalReader:
# #region Tooling.DrRecovery.Git.Provenance.Localreader.Get [C:3] [TYPE Function] [SEMANTICS dr,recovery]
def get(self, *args, **kwargs):
return LocalResponse()
# #endregion Tooling.DrRecovery.Git.Provenance.Localreader.Get
# #endregion Tooling.DrRecovery.Git.Provenance.Localreader
reader = LocalReader()
require(
_observe_own_commit(
reader, source.repository, operation.commit_sha, operation
).matches,
"DR_RECOVERY_GIT_PROVENANCE_MISMATCH",
)
# #endregion Tooling.DrRecovery.Git.Provenance
# #region Tooling.DrRecovery.Git.Bundle [C:4] [TYPE Function]
# @INVARIANT Install every declared root in owned scratch before full closure validation.
def bundle(root_fd, source, operations, render_bytes):
data = read(root_fd, source.bundle.path, BUNDLE_LIMIT, source.bundle)
boundary = data.find(b"\n\n", 0, 128 * 1024)
@@ -234,8 +194,6 @@ def bundle(root_fd, source, operations, render_bytes):
git(odb, ["bundle", "unbundle", str(archive)], "DR_RECOVERY_GIT_BUNDLE_INVALID")
roots = required_roots(odb, source, operations)
# unbundle imports ODB objects but does not install refs; only this owned scratch is written.
# @INVARIANT Install every declared/advertised root before connectivity validation. An empty
# ref namespace lets fsck miss a reachable blob outside the publication path.
for name, commit in actual.items():
git(odb, ["update-ref", name, commit], "DR_RECOVERY_GIT_BUNDLE_INVALID")
git(

View File

@@ -0,0 +1,74 @@
# #region Tooling.DrRecovery.Git.Runner [C:3] [TYPE Module] [SEMANTICS dr,recovery]
# @BRIEF Run bounded local Git subprocesses with closed configuration and owned process-group cleanup.
import os
import resource
import signal
import subprocess
import tempfile
from dr_recovery_io import Refused, require
# #region Tooling.DrRecovery.Git.Runner.Limits [C:3] [TYPE Function] [SEMANTICS dr,recovery]
def _limits():
resource.setrlimit(resource.RLIMIT_CPU, (30, 30))
resource.setrlimit(resource.RLIMIT_FSIZE, (128 * 1024 * 1024, 128 * 1024 * 1024))
resource.setrlimit(resource.RLIMIT_AS, (1024 * 1024 * 1024, 1024 * 1024 * 1024))
# #endregion Tooling.DrRecovery.Git.Runner.Limits
# #region Tooling.DrRecovery.Git.Command [C:3] [TYPE Function]
def git(root, args, code, output_limit=128 * 1024):
env = dict(
PATH="/usr/bin:/bin",
HOME="/nonexistent",
GIT_CONFIG_NOSYSTEM="1",
GIT_CONFIG_GLOBAL="/dev/null",
GIT_CONFIG_SYSTEM="/dev/null",
GIT_TERMINAL_PROMPT="0",
GIT_CONFIG_COUNT="0",
GIT_NO_REPLACE_OBJECTS="1",
GIT_OPTIONAL_LOCKS="0",
GIT_NO_LAZY_FETCH="1",
)
command = [
"/usr/bin/git",
"--git-dir=" + str(root),
"-c",
"protocol.allow=never",
"-c",
"core.hooksPath=/dev/null",
*args,
]
with tempfile.TemporaryFile() as stdout, tempfile.TemporaryFile() as stderr:
try:
process = subprocess.Popen(
command,
env=env,
stdin=subprocess.DEVNULL,
stdout=stdout,
stderr=stderr,
start_new_session=True,
preexec_fn=_limits,
)
except (OSError, subprocess.SubprocessError):
raise Refused("DR_RECOVERY_GIT_UNAVAILABLE") from None
try:
result = process.wait(timeout=30)
except subprocess.TimeoutExpired:
try:
os.killpg(process.pid, signal.SIGKILL)
except ProcessLookupError:
pass # The owned child/group can exit between the timeout and kill.
process.wait()
raise Refused("DR_RECOVERY_LIMIT") from None
require(result >= 0, "DR_RECOVERY_LIMIT")
require(result == 0, code)
require(
stdout.tell() <= output_limit and stderr.tell() <= 128 * 1024,
"DR_RECOVERY_LIMIT",
)
stdout.seek(0)
return stdout.read(output_limit + 1)
# #endregion Tooling.DrRecovery.Git.Command
# #endregion Tooling.DrRecovery.Git.Runner

View File

@@ -22,6 +22,7 @@ from dr_recovery_io import (
)
# #region Tooling.DrRecovery.Holds.ExpectedPaths [C:3] [TYPE Function] [SEMANTICS dr,recovery]
def expected_paths(holds):
values = {}
for hold in holds.records.holds:
@@ -33,8 +34,10 @@ def expected_paths(holds):
)
values[path] = item.sha256
return values
# #endregion Tooling.DrRecovery.Holds.ExpectedPaths
# #region Tooling.DrRecovery.Holds.Metadata [C:3] [TYPE Function] [SEMANTICS dr,recovery]
def metadata(marker, raw_index, holds):
require(marker == _MARKER, "DR_RECOVERY_HOLDS_UNAVAILABLE")
require(
@@ -52,6 +55,7 @@ def metadata(marker, raw_index, holds):
except ValueError:
raise Refused("DR_RECOVERY_HOLDS_UNAVAILABLE") from None
require(actual == holds.records, "DR_RECOVERY_HOLDS_METADATA_MISMATCH")
# #endregion Tooling.DrRecovery.Holds.Metadata
# #region Tooling.DrRecovery.Holds.Archive [C:4] [TYPE Function]
@@ -115,6 +119,7 @@ def archived(root_fd, archive_stat, holds):
# #endregion Tooling.DrRecovery.Holds.Archive
# #region Tooling.DrRecovery.Holds.Observed [C:3] [TYPE Function] [SEMANTICS dr,recovery]
def observed(root, holds):
require(root is not None, "DR_RECOVERY_INPUT_MISSING")
try:
@@ -132,6 +137,7 @@ def observed(root, holds):
if error.code.startswith("DR_RECOVERY_INPUT_"):
raise Refused("DR_RECOVERY_HOLDS_UNAVAILABLE") from None
raise
# #endregion Tooling.DrRecovery.Holds.Observed
# #endregion Tooling.DrRecovery.Holds

View File

@@ -15,17 +15,24 @@ ARCHIVE_LIMIT = 256 * 1024 * 1024
BLOB_LIMIT = 16 * 1024 * 1024
# #region Tooling.DrRecovery.IO.Refused [C:3] [TYPE Class] [SEMANTICS dr,recovery]
class Refused(ValueError):
# #region Tooling.DrRecovery.IO.Refused.Init [C:3] [TYPE Function] [SEMANTICS dr,recovery]
def __init__(self, code):
self.code = code
super().__init__(code)
# #endregion Tooling.DrRecovery.IO.Refused.Init
# #endregion Tooling.DrRecovery.IO.Refused
# #region Tooling.DrRecovery.IO.Require [C:3] [TYPE Function] [SEMANTICS dr,recovery]
def require(condition, code):
if not condition:
raise Refused(code)
# #endregion Tooling.DrRecovery.IO.Require
# #region Tooling.DrRecovery.IO.Pinned [C:3] [TYPE Function] [SEMANTICS dr,recovery]
@contextmanager
def pinned(root):
root = Path(root)
@@ -38,6 +45,7 @@ def pinned(root):
yield descriptor
finally:
os.close(descriptor)
# #endregion Tooling.DrRecovery.IO.Pinned
# #region Tooling.DrRecovery.IO.Read [C:3] [TYPE Function]
@@ -72,29 +80,41 @@ def read(root_fd, relative, limit=JSON_LIMIT, expected=None):
# #endregion Tooling.DrRecovery.IO.Read
# #region Tooling.DrRecovery.IO.UniqueObject [C:3] [TYPE Function] [SEMANTICS dr,recovery]
def _unique_object(pairs):
value = dict(pairs)
require(len(value) == len(pairs), "DR_RECOVERY_CONTRACT_INVALID")
return value
# #endregion Tooling.DrRecovery.IO.UniqueObject
# #region Tooling.DrRecovery.IO.RejectConstant [C:3] [TYPE Function] [SEMANTICS dr,recovery]
def _reject_constant(value):
raise ValueError("constant")
# #endregion Tooling.DrRecovery.IO.RejectConstant
# #region Tooling.DrRecovery.IO.Decode [C:3] [TYPE Function] [SEMANTICS dr,recovery]
def decode(data):
try:
return json.loads(
data,
object_pairs_hook=_unique_object,
parse_constant=lambda _: (_ for _ in ()).throw(ValueError("constant")),
parse_constant=_reject_constant,
)
except (ValueError, UnicodeError, RecursionError):
raise Refused("DR_RECOVERY_CONTRACT_INVALID") from None
# #endregion Tooling.DrRecovery.IO.Decode
# #region Tooling.DrRecovery.IO.ExternalJson [C:3] [TYPE Function] [SEMANTICS dr,recovery]
def external_json(path):
require(path is not None, "DR_RECOVERY_INPUT_MISSING")
path = Path(path)
require(path.is_absolute(), "DR_RECOVERY_INPUT_UNSAFE")
with pinned(path.parent) as descriptor:
return decode(read(descriptor, path.name))
# #endregion Tooling.DrRecovery.IO.ExternalJson
# #endregion Tooling.DrRecovery.IO

View File

@@ -0,0 +1,330 @@
# #region Test.Tooling.DrRecovery.Fixtures [C:3] [TYPE Module] [SEMANTICS test,dr,recovery,git,holds]
# @BRIEF Literal records and real tmp-only Git bundles prove closure, bytes and required recovery inputs.
# @RELATION BINDS_TO -> [Tooling.DrRecovery]
import hashlib
import io
import json
from pathlib import Path
import subprocess
import sys
import pytest
import tarfile
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
import dr_recovery_check as recovery # noqa: E402
CAT, REV, OP, RECEIPT, SOURCE, RUN = [
f"00000000-0000-0000-0000-{n:012}" for n in range(1, 7)
]
STAMP = "2026-10-23T00:00:00+00:00"
DIGEST = "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
TARGET = dict(
host="synthetic", port="5432", database="fixture", user="fixture", schema="public"
)
RENDER_PATH = f"catalogs/{CAT}/{REV}.yaml"
# #region Test.Tooling.DrRecovery.Fixtures.WriteJson [C:3] [TYPE Function] [SEMANTICS dr,recovery]
def write_json(path, value):
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(json.dumps(value, sort_keys=True) + "\n")
# #endregion Test.Tooling.DrRecovery.Fixtures.WriteJson
# #region Test.Tooling.DrRecovery.Fixtures.Stat [C:3] [TYPE Function] [SEMANTICS dr,recovery]
def stat(path, name=None):
data = path.read_bytes()
result = dict(bytes=len(data), sha256=hashlib.sha256(data).hexdigest())
return {**result, "path": name} if name is not None else result
# #endregion Test.Tooling.DrRecovery.Fixtures.Stat
# #region Test.Tooling.DrRecovery.Fixtures.Git [C:3] [TYPE Function] [SEMANTICS dr,recovery]
def git(root, *args):
env = dict(
PATH="/usr/bin:/bin",
HOME=str(root.parent),
GIT_CONFIG_NOSYSTEM="1",
GIT_CONFIG_GLOBAL="/dev/null",
GIT_CONFIG_SYSTEM="/dev/null",
GIT_TERMINAL_PROMPT="0",
GIT_AUTHOR_DATE=STAMP,
GIT_COMMITTER_DATE=STAMP,
)
return (
subprocess.check_output(
[
"/usr/bin/git",
"-C",
str(root),
"-c",
"protocol.allow=never",
"-c",
"core.hooksPath=/dev/null",
"-c",
"user.name=Fixture",
"-c",
"user.email=fixture@example.invalid",
*args,
],
env=env,
stderr=subprocess.PIPE,
)
.decode()
.strip()
)
# #endregion Test.Tooling.DrRecovery.Fixtures.Git
# #region Test.Tooling.DrRecovery.Fixtures.Packet [C:3] [TYPE Function] [SEMANTICS dr,recovery]
@pytest.fixture
def packet(tmp_path, request):
object_format = getattr(request, "param", "sha1")
package = tmp_path / "package"
package.mkdir()
repo = tmp_path / "source"
repo.mkdir()
git(repo, "init", "-q", "-b", "main", "--object-format=" + object_format)
(repo / "README").write_text("base\n")
git(repo, "add", "README")
git(repo, "commit", "-qm", "base")
parent = git(repo, "rev-parse", "HEAD")
(repo / RENDER_PATH).parent.mkdir(parents=True)
(repo / RENDER_PATH).write_bytes(b"abc")
git(repo, "add", RENDER_PATH)
git(repo, "commit", "-qm", f"publication (publication {OP})")
commit = git(repo, "rev-parse", "HEAD")
(repo / "README").write_text("later\n")
git(repo, "add", "README")
git(repo, "commit", "-qm", "later")
head = git(repo, "rev-parse", "HEAD")
git(repo, "bundle", "create", str(package / "catalog.bundle"), "refs/heads/main")
(package / "render.yaml").write_bytes(b"abc")
index = {
"schema_version": 1,
"holds": [
{
"hold_id": "a" * 64,
"agent_run_id": RUN,
"capture_artifact_id": CAT,
"authority_record_sha256": "b" * 64,
"candidate_id": REV,
"gate_id": OP,
"refs": [
{
"content_ref": f"draft:{RUN}:{DIGEST}",
"sha256": DIGEST,
"purpose": "response",
}
],
}
],
}
marker = b"native-result-holds-v1\n"
index_bytes = json.dumps(index).encode()
members = {
".native-result-holds/activated": marker,
".native-result-holds/index.json": index_bytes,
f"drafts/{RUN}/{DIGEST}": b"abc",
}
with tarfile.open(package / "storage.tgz", "w:gz") as archive:
for name, data in members.items():
info = tarfile.TarInfo(name)
info.size = len(data)
archive.addfile(info, io.BytesIO(data))
(package / "storage.tgz.list").write_text("\n".join(members) + "\n")
(package / "ss_tools.dump").write_bytes(b"synthetic-not-a-database")
(package / "ss_tools.dump.list").write_text("1; 0 0 TABLE public fixture fixture\n")
dest = dict(
base_url="https://fixture.invalid",
repository="fixture/catalog",
branch="main",
path=RENDER_PATH,
)
receipt = dict(
catalog_revision_id=REV,
integrity_sha256="e" * 64,
render_sha256=DIGEST,
commit_sha=commit,
head_after=commit,
verified_at=STAMP,
)
operation = dict(
id=OP,
catalog_id=CAT,
catalog_revision_id=REV,
repository="logical-repository",
destination=dest,
catalog_digest="d" * 64,
integrity_sha256="e" * 64,
render_sha256=DIGEST,
expected_branch_head=parent,
state="published",
error_code=None,
commit_sha=commit,
published_receipt=receipt,
)
state = dict(
target=TARGET,
alembic_version="0050_git_source_bind",
catalog_heads=[dict(catalog_id=CAT, repository="logical-repository")],
catalog_revisions=[
dict(
catalog_id=CAT,
catalog_revision_id=REV,
catalog_digest="d" * 64,
integrity_sha256="e" * 64,
)
],
approval_receipts=[dict(receipt_id=RECEIPT, receipt_sha256="f" * 64)],
publication_operations=[operation],
retention_deletions=[
dict(
id=SOURCE,
target_type="artifact",
target_id="artifact",
content_ref=f"draft:{RUN}:{DIGEST}",
scenario_id=None,
run_id=RUN,
baseline_pin=dict(catalog_id=CAT, catalog_revision_id=REV),
retention_class="artifacts",
state="deletion_pending",
holds_snapshot=dict(reasons=["approved_baseline"], at=STAMP),
attempts=0,
error_code=None,
verified_absent_at=None,
tombstoned_at=None,
created_at=STAMP,
updated_at=STAMP,
)
],
)
tables = (
"baseline_catalog_heads",
"baseline_catalog_revisions",
"baseline_catalog_memberships",
"baseline_catalog_entry_authorities",
"baseline_catalog_dashboard_uuid_bindings",
"dashboard_reference_draft_approval_receipts",
"publication_operations",
)
manifest = dict(
schema_version=1,
mode="quiesced",
t_snap=STAMP,
t_dump_start=STAMP,
t_dump_end=STAMP,
t_storage_end=STAMP,
target=TARGET,
alembic_version=state["alembic_version"],
counts=dict.fromkeys(tables, 1),
reference_ids={
**{key: state[key] for key in ("catalog_revisions", "approval_receipts")},
"publication_operations": [
{
key: operation[key]
for key in (
"id",
"catalog_revision_id",
"commit_sha",
"render_sha256",
)
}
],
},
dump=stat(package / "ss_tools.dump"),
storage=stat(package / "storage.tgz"),
catalog_ref=dict(state="captured", ls_remote=[[head, "refs/heads/main"]]),
)
write_json(package / "manifest.json", manifest)
sidecar = dict(
schema_version=1,
manifest_sha256=stat(package / "manifest.json")["sha256"],
t_snap=STAMP,
source_state=state,
git_sources=[
dict(
source_id=SOURCE,
base_url=dest["base_url"],
repository=dest["repository"],
reviewed_by="literal reviewer",
approved_at=STAMP,
object_format=object_format,
bundle=stat(package / "catalog.bundle", "catalog.bundle"),
refs=[dict(name="refs/heads/main", commit_sha=head)],
prerequisites=[],
operation_ids=[OP],
)
],
renders=[
dict(operation_id=OP, artifact=stat(package / "render.yaml", "render.yaml"))
],
native_holds=dict(
activated=dict(
bytes=len(marker), sha256=hashlib.sha256(marker).hexdigest()
),
index=dict(
bytes=len(index_bytes), sha256=hashlib.sha256(index_bytes).hexdigest()
),
records=index,
),
)
write_json(package / "recovery.evidence.v1.json", sidecar)
storage = tmp_path / "observed-storage"
storage.mkdir()
for name, data in members.items():
path = storage / name
path.parent.mkdir(parents=True, exist_ok=True)
path.write_bytes(data)
recovered = tmp_path / "observed-git"
recovered.mkdir()
git(recovered, "init", "--bare", "-q", "--object-format=" + object_format)
git(recovered, "bundle", "unbundle", str(package / "catalog.bundle"))
git(recovered, "update-ref", "refs/heads/main", head)
write_json(tmp_path / "observed.json", state)
write_json(tmp_path / "git-roots.json", {SOURCE: str(recovered)})
return dict(
package=package,
sidecar=sidecar,
state=state,
storage=storage,
recovered=recovered,
repo=repo,
tmp=tmp_path,
head=head,
commit=commit,
)
# #endregion Test.Tooling.DrRecovery.Fixtures.Packet
# #region Test.Tooling.DrRecovery.Fixtures.Check [C:3] [TYPE Function] [SEMANTICS dr,recovery]
def check(packet, phase="backup", **kwargs):
return recovery.check(
packet["package"],
phase=phase,
storage_root=packet["storage"] if phase == "restored" else None,
observed_state=packet["tmp"] / "observed.json" if phase == "restored" else None,
git_roots=packet["tmp"] / "git-roots.json" if phase == "restored" else None,
**kwargs,
)
# #endregion Test.Tooling.DrRecovery.Fixtures.Check
# #region Test.Tooling.DrRecovery.Fixtures.Save [C:3] [TYPE Function] [SEMANTICS dr,recovery]
def save(packet):
write_json(packet["package"] / "recovery.evidence.v1.json", packet["sidecar"])
# #endregion Test.Tooling.DrRecovery.Fixtures.Save
# #region Test.Tooling.DrRecovery.Fixtures.RewriteManifest [C:3] [TYPE Function] [SEMANTICS dr,recovery]
def rewrite_manifest(packet, update):
path = packet["package"] / "manifest.json"
manifest = json.loads(path.read_text())
update(manifest)
write_json(path, manifest)
packet["sidecar"]["manifest_sha256"] = stat(path)["sha256"]
# #endregion Test.Tooling.DrRecovery.Fixtures.RewriteManifest
# #endregion Test.Tooling.DrRecovery.Fixtures

View File

@@ -0,0 +1,217 @@
# #region Test.Tooling.DrRecovery.Boundaries [C:3] [TYPE Module] [SEMANTICS dr,recovery]
# @BRIEF Owned Git process cleanup, pinned FIFO/symlink refusal, budgets and complete object closure.
import errno
import os
import stat as stat_module
import subprocess
import threading
import time
import pytest
from test_dr_recovery_check import (
packet as packet,
check,
save,
git,
stat,
)
import dr_recovery_check as recovery
import dr_recovery_git as git_check
import dr_recovery_io as recovery_io
import dr_evidence_check as evidence_owner
from dr_recovery_io import Refused
# #region Test.Tooling.DrRecovery.Boundaries.TestGitSubprocessHasClosedEnvironmentAndTimeout [C:3] [TYPE Function] [SEMANTICS dr,recovery]
def test_git_subprocess_has_closed_environment_and_timeout(monkeypatch, tmp_path):
calls = []
# #region Test.Tooling.DrRecovery.Boundaries.TestGitSubprocessHasClosedEnvironmentAndTimeout.Process [C:3] [TYPE Function] [SEMANTICS dr,recovery]
def process(command, **kwargs):
calls.append((command, kwargs))
# #region Test.Tooling.DrRecovery.Boundaries.TestGitSubprocessHasClosedEnvironmentAndTimeout.Process.Child [C:3] [TYPE Class] [SEMANTICS dr,recovery]
class Child:
# #region Test.Tooling.DrRecovery.Boundaries.TestGitSubprocessHasClosedEnvironmentAndTimeout.Process.Child.Wait [C:3] [TYPE Function] [SEMANTICS dr,recovery]
def wait(self, timeout):
return 0
# #endregion Test.Tooling.DrRecovery.Boundaries.TestGitSubprocessHasClosedEnvironmentAndTimeout.Process.Child.Wait
# #endregion Test.Tooling.DrRecovery.Boundaries.TestGitSubprocessHasClosedEnvironmentAndTimeout.Process.Child
return Child()
# #endregion Test.Tooling.DrRecovery.Boundaries.TestGitSubprocessHasClosedEnvironmentAndTimeout.Process
monkeypatch.setattr(git_check.subprocess, "Popen", process)
assert git_check.git(tmp_path, ["status"], "DR_RECOVERY_GIT_UNAVAILABLE") == b""
command, options = calls[0]
assert command[0] == "/usr/bin/git"
assert options["env"]["GIT_CONFIG_GLOBAL"] == "/dev/null"
assert options["env"]["GIT_NO_LAZY_FETCH"] == "1"
assert options["env"]["GIT_CONFIG_NOSYSTEM"] == "1"
assert (
not {
"DATABASE_URL",
"SSH_AUTH_SOCK",
"GIT_SSH_COMMAND",
"GIT_CONFIG_PARAMETERS",
}
& options["env"].keys()
)
assert options["start_new_session"] is True and callable(options["preexec_fn"])
# #endregion Test.Tooling.DrRecovery.Boundaries.TestGitSubprocessHasClosedEnvironmentAndTimeout
# #region Test.Tooling.DrRecovery.Boundaries.TestGitTimeoutKillsOnlyOwnedProcessGroup [C:3] [TYPE Function] [SEMANTICS dr,recovery]
def test_git_timeout_kills_only_owned_process_group(monkeypatch, tmp_path):
calls = []
# #region Test.Tooling.DrRecovery.Boundaries.TestGitTimeoutKillsOnlyOwnedProcessGroup.Child [C:3] [TYPE Class] [SEMANTICS dr,recovery]
class Child:
pid = 123456789
# #region Test.Tooling.DrRecovery.Boundaries.TestGitTimeoutKillsOnlyOwnedProcessGroup.Child.Wait [C:3] [TYPE Function] [SEMANTICS dr,recovery]
def wait(self, timeout=None):
if timeout is not None:
assert timeout == 30
raise subprocess.TimeoutExpired(["git"], timeout)
return -9
# #endregion Test.Tooling.DrRecovery.Boundaries.TestGitTimeoutKillsOnlyOwnedProcessGroup.Child.Wait
# #endregion Test.Tooling.DrRecovery.Boundaries.TestGitTimeoutKillsOnlyOwnedProcessGroup.Child
# #region Test.Tooling.DrRecovery.Boundaries.TestGitTimeoutKillsOnlyOwnedProcessGroup.SpawnChild [C:3] [TYPE Function] [SEMANTICS dr,recovery]
def spawn_child(*args, **kwargs):
return Child()
# #endregion Test.Tooling.DrRecovery.Boundaries.TestGitTimeoutKillsOnlyOwnedProcessGroup.SpawnChild
# #region Test.Tooling.DrRecovery.Boundaries.TestGitTimeoutKillsOnlyOwnedProcessGroup.KillGroup [C:3] [TYPE Function] [SEMANTICS dr,recovery]
def kill_group(pid, signal):
calls.append(pid)
# #endregion Test.Tooling.DrRecovery.Boundaries.TestGitTimeoutKillsOnlyOwnedProcessGroup.KillGroup
monkeypatch.setattr(git_check.subprocess, "Popen", spawn_child)
monkeypatch.setattr(git_check.os, "killpg", kill_group)
with pytest.raises(Refused, match="^DR_RECOVERY_LIMIT$"):
git_check.git(tmp_path, ["status"], "DR_RECOVERY_GIT_UNAVAILABLE")
assert calls == [123456789]
# #endregion Test.Tooling.DrRecovery.Boundaries.TestGitTimeoutKillsOnlyOwnedProcessGroup
# #region Test.Tooling.DrRecovery.Boundaries.TestTotalRenderBudgetPrecedesReadingMultipleArtifacts [C:3] [TYPE Function] [SEMANTICS dr,recovery]
def test_total_render_budget_precedes_reading_multiple_artifacts(packet, monkeypatch):
monkeypatch.setattr(recovery, "RENDER_TOTAL_LIMIT", 2)
assert check(packet) == ["DR_RECOVERY_LIMIT"]
# #endregion Test.Tooling.DrRecovery.Boundaries.TestTotalRenderBudgetPrecedesReadingMultipleArtifacts
# #region Test.Tooling.DrRecovery.Boundaries.TestRealFifoNeverBlocksBeforeRegularFileValidation [C:3] [TYPE Function] [SEMANTICS dr,recovery]
@pytest.mark.parametrize("replace_after_classify", [False, True])
def test_real_fifo_never_blocks_before_regular_file_validation(
tmp_path, monkeypatch, replace_after_classify
):
root = tmp_path / "input"
root.mkdir()
path = root / "artifact"
real_open = os.open
if replace_after_classify:
path.write_bytes(b"literal regular bytes")
else:
os.mkfifo(path, 0o600)
errors = []
# #region Test.Tooling.DrRecovery.Boundaries.TestRealFifoNeverBlocksBeforeRegularFileValidation.ReleaseOnlyABlockedOldReader [C:3] [TYPE Function] [SEMANTICS dr,recovery]
def release_only_a_blocked_old_reader():
try:
descriptor = real_open(path, os.O_WRONLY | os.O_NONBLOCK)
except OSError as error:
if error.errno != errno.ENXIO:
errors.append(error.errno)
else:
os.close(descriptor)
# #endregion Test.Tooling.DrRecovery.Boundaries.TestRealFifoNeverBlocksBeforeRegularFileValidation.ReleaseOnlyABlockedOldReader
with recovery_io.pinned(root) as root_fd:
if replace_after_classify:
# #region Test.Tooling.DrRecovery.Boundaries.TestRealFifoNeverBlocksBeforeRegularFileValidation.OpenWithReplacement [C:3] [TYPE Function] [SEMANTICS dr,recovery]
def open_with_replacement(name, flags, *args, **kwargs):
if name == "artifact" and kwargs.get("dir_fd") == root_fd:
path.unlink()
os.mkfifo(path, 0o600)
return real_open(name, flags, *args, **kwargs)
# #endregion Test.Tooling.DrRecovery.Boundaries.TestRealFifoNeverBlocksBeforeRegularFileValidation.OpenWithReplacement
# Mutate at the OS boundary after the real classification; the actual FIFO is still opened.
monkeypatch.setattr(evidence_owner.os, "open", open_with_replacement)
release = threading.Timer(0.5, release_only_a_blocked_old_reader)
release.start()
started = time.monotonic()
try:
with pytest.raises(Refused, match="^DR_RECOVERY_INPUT_MISSING$"):
recovery_io.read(root_fd, "artifact")
elapsed = time.monotonic() - started
finally:
release.join(timeout=2)
assert not release.is_alive() and not errors
assert stat_module.S_ISFIFO(path.stat().st_mode)
assert stat_module.S_IMODE(path.stat().st_mode) == 0o600
assert elapsed < 0.2, (
"FIFO opened in blocking mode before fstat regular-file refusal"
)
# #endregion Test.Tooling.DrRecovery.Boundaries.TestRealFifoNeverBlocksBeforeRegularFileValidation
# #region Test.Tooling.DrRecovery.Boundaries.TestRootAncestorSymlinkIsNotAnInputRoot [C:3] [TYPE Function] [SEMANTICS dr,recovery]
def test_root_ancestor_symlink_is_not_an_input_root(tmp_path):
actual = tmp_path / "actual"
(actual / "repo").mkdir(parents=True)
alias = tmp_path / "alias"
alias.symlink_to(actual, target_is_directory=True)
with pytest.raises(Refused, match="^DR_RECOVERY_INPUT_UNSAFE$"):
with recovery_io.pinned(alias / "repo"):
pass
# #endregion Test.Tooling.DrRecovery.Boundaries.TestRootAncestorSymlinkIsNotAnInputRoot
# #region Test.Tooling.DrRecovery.Boundaries.TestBundleMissingUnrelatedReachableBlobFailsWholeClosure [C:3] [TYPE Function] [SEMANTICS dr,recovery]
def test_bundle_missing_unrelated_reachable_blob_fails_whole_closure(packet):
operation = packet["sidecar"]["source_state"]["publication_operations"][0]
missing = git(
packet["repo"], "rev-parse", operation["expected_branch_head"] + ":README"
)
objects = git(
packet["repo"], "rev-list", "--objects", "--no-object-names", "refs/heads/main"
).splitlines()
assert missing in objects
# Produce a structurally valid, rehashed pack which deliberately omits the old README blob.
# Publication bytes/commit/parent and all advertised refs remain valid and unchanged.
env = dict(
PATH="/usr/bin:/bin",
HOME=str(packet["tmp"]),
GIT_CONFIG_NOSYSTEM="1",
GIT_CONFIG_GLOBAL="/dev/null",
GIT_CONFIG_SYSTEM="/dev/null",
GIT_TERMINAL_PROMPT="0",
)
pack = subprocess.run(
[
"/usr/bin/git",
"-C",
str(packet["repo"]),
"-c",
"protocol.allow=never",
"pack-objects",
"--stdout",
],
input=("\n".join(oid for oid in objects if oid != missing) + "\n").encode(),
capture_output=True,
check=True,
env=env,
).stdout
bundle_path = packet["package"] / "catalog.bundle"
header = b"# v2 git bundle\n" + packet["head"].encode() + b" refs/heads/main\n\n"
bundle_path.write_bytes(header + pack)
packet["sidecar"]["git_sources"][0]["bundle"] = stat(bundle_path, "catalog.bundle")
save(packet)
assert check(packet) == ["DR_RECOVERY_GIT_BUNDLE_INVALID"]
# #endregion Test.Tooling.DrRecovery.Boundaries.TestBundleMissingUnrelatedReachableBlobFailsWholeClosure
# #endregion Test.Tooling.DrRecovery.Boundaries

View File

@@ -1,317 +1,21 @@
# #region Test.Tooling.DrRecovery [C:3] [TYPE Module] [SEMANTICS test,dr,recovery,git,holds]
# @BRIEF Literal records and real tmp-only Git bundles prove closure, bytes and required recovery inputs.
# @RELATION BINDS_TO -> [Tooling.DrRecovery]
from copy import deepcopy
import hashlib
import io
import json
from pathlib import Path
import subprocess
import sys
# #region Test.Tooling.DrRecovery [C:3] [TYPE Module] [SEMANTICS dr,recovery]
# @BRIEF Real bundles retain closure and exact source/sidecar identity refusals.
import pytest
import tarfile
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
import dr_recovery_check as recovery # noqa: E402
CAT, REV, OP, RECEIPT, SOURCE, RUN = [
f"00000000-0000-0000-0000-{n:012}" for n in range(1, 7)
]
STAMP = "2026-10-23T00:00:00+00:00"
DIGEST = "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
TARGET = dict(
host="synthetic", port="5432", database="fixture", user="fixture", schema="public"
from dr_recovery_fixtures import (
packet as packet, write_json as write_json, stat as stat, git as git, check as check, save as save, rewrite_manifest as rewrite_manifest,
CAT as CAT, REV as REV, OP as OP, RECEIPT as RECEIPT, SOURCE as SOURCE, RUN as RUN, STAMP as STAMP, DIGEST as DIGEST, TARGET as TARGET, RENDER_PATH as RENDER_PATH,
)
RENDER_PATH = f"catalogs/{CAT}/{REV}.yaml"
def write_json(path, value):
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(json.dumps(value, sort_keys=True) + "\n")
def stat(path, name=None):
data = path.read_bytes()
result = dict(bytes=len(data), sha256=hashlib.sha256(data).hexdigest())
return {**result, "path": name} if name is not None else result
def git(root, *args):
env = dict(
PATH="/usr/bin:/bin",
HOME=str(root.parent),
GIT_CONFIG_NOSYSTEM="1",
GIT_CONFIG_GLOBAL="/dev/null",
GIT_CONFIG_SYSTEM="/dev/null",
GIT_TERMINAL_PROMPT="0",
GIT_AUTHOR_DATE=STAMP,
GIT_COMMITTER_DATE=STAMP,
)
return (
subprocess.check_output(
[
"/usr/bin/git",
"-C",
str(root),
"-c",
"protocol.allow=never",
"-c",
"core.hooksPath=/dev/null",
"-c",
"user.name=Fixture",
"-c",
"user.email=fixture@example.invalid",
*args,
],
env=env,
stderr=subprocess.PIPE,
)
.decode()
.strip()
)
@pytest.fixture
def packet(tmp_path, request):
object_format = getattr(request, "param", "sha1")
package = tmp_path / "package"
package.mkdir()
repo = tmp_path / "source"
repo.mkdir()
git(repo, "init", "-q", "-b", "main", "--object-format=" + object_format)
(repo / "README").write_text("base\n")
git(repo, "add", "README")
git(repo, "commit", "-qm", "base")
parent = git(repo, "rev-parse", "HEAD")
(repo / RENDER_PATH).parent.mkdir(parents=True)
(repo / RENDER_PATH).write_bytes(b"abc")
git(repo, "add", RENDER_PATH)
git(repo, "commit", "-qm", f"publication (publication {OP})")
commit = git(repo, "rev-parse", "HEAD")
(repo / "README").write_text("later\n")
git(repo, "add", "README")
git(repo, "commit", "-qm", "later")
head = git(repo, "rev-parse", "HEAD")
git(repo, "bundle", "create", str(package / "catalog.bundle"), "refs/heads/main")
(package / "render.yaml").write_bytes(b"abc")
index = {
"schema_version": 1,
"holds": [
{
"hold_id": "a" * 64,
"agent_run_id": RUN,
"capture_artifact_id": CAT,
"authority_record_sha256": "b" * 64,
"candidate_id": REV,
"gate_id": OP,
"refs": [
{
"content_ref": f"draft:{RUN}:{DIGEST}",
"sha256": DIGEST,
"purpose": "response",
}
],
}
],
}
marker = b"native-result-holds-v1\n"
index_bytes = json.dumps(index).encode()
members = {
".native-result-holds/activated": marker,
".native-result-holds/index.json": index_bytes,
f"drafts/{RUN}/{DIGEST}": b"abc",
}
with tarfile.open(package / "storage.tgz", "w:gz") as archive:
for name, data in members.items():
info = tarfile.TarInfo(name)
info.size = len(data)
archive.addfile(info, io.BytesIO(data))
(package / "storage.tgz.list").write_text("\n".join(members) + "\n")
(package / "ss_tools.dump").write_bytes(b"synthetic-not-a-database")
(package / "ss_tools.dump.list").write_text("1; 0 0 TABLE public fixture fixture\n")
dest = dict(
base_url="https://fixture.invalid",
repository="fixture/catalog",
branch="main",
path=RENDER_PATH,
)
receipt = dict(
catalog_revision_id=REV,
integrity_sha256="e" * 64,
render_sha256=DIGEST,
commit_sha=commit,
head_after=commit,
verified_at=STAMP,
)
operation = dict(
id=OP,
catalog_id=CAT,
catalog_revision_id=REV,
repository="logical-repository",
destination=dest,
catalog_digest="d" * 64,
integrity_sha256="e" * 64,
render_sha256=DIGEST,
expected_branch_head=parent,
state="published",
error_code=None,
commit_sha=commit,
published_receipt=receipt,
)
state = dict(
target=TARGET,
alembic_version="0050_git_source_bind",
catalog_heads=[dict(catalog_id=CAT, repository="logical-repository")],
catalog_revisions=[
dict(
catalog_id=CAT,
catalog_revision_id=REV,
catalog_digest="d" * 64,
integrity_sha256="e" * 64,
)
],
approval_receipts=[dict(receipt_id=RECEIPT, receipt_sha256="f" * 64)],
publication_operations=[operation],
retention_deletions=[
dict(
id=SOURCE,
target_type="artifact",
target_id="artifact",
content_ref=f"draft:{RUN}:{DIGEST}",
scenario_id=None,
run_id=RUN,
baseline_pin=dict(catalog_id=CAT, catalog_revision_id=REV),
retention_class="artifacts",
state="deletion_pending",
holds_snapshot=dict(reasons=["approved_baseline"], at=STAMP),
attempts=0,
error_code=None,
verified_absent_at=None,
tombstoned_at=None,
created_at=STAMP,
updated_at=STAMP,
)
],
)
tables = (
"baseline_catalog_heads",
"baseline_catalog_revisions",
"baseline_catalog_memberships",
"baseline_catalog_entry_authorities",
"baseline_catalog_dashboard_uuid_bindings",
"dashboard_reference_draft_approval_receipts",
"publication_operations",
)
manifest = dict(
schema_version=1,
mode="quiesced",
t_snap=STAMP,
t_dump_start=STAMP,
t_dump_end=STAMP,
t_storage_end=STAMP,
target=TARGET,
alembic_version=state["alembic_version"],
counts=dict.fromkeys(tables, 1),
reference_ids={
**{key: state[key] for key in ("catalog_revisions", "approval_receipts")},
"publication_operations": [
{
key: operation[key]
for key in (
"id",
"catalog_revision_id",
"commit_sha",
"render_sha256",
)
}
],
},
dump=stat(package / "ss_tools.dump"),
storage=stat(package / "storage.tgz"),
catalog_ref=dict(state="captured", ls_remote=[[head, "refs/heads/main"]]),
)
write_json(package / "manifest.json", manifest)
sidecar = dict(
schema_version=1,
manifest_sha256=stat(package / "manifest.json")["sha256"],
t_snap=STAMP,
source_state=state,
git_sources=[
dict(
source_id=SOURCE,
base_url=dest["base_url"],
repository=dest["repository"],
reviewed_by="literal reviewer",
approved_at=STAMP,
object_format=object_format,
bundle=stat(package / "catalog.bundle", "catalog.bundle"),
refs=[dict(name="refs/heads/main", commit_sha=head)],
prerequisites=[],
operation_ids=[OP],
)
],
renders=[
dict(operation_id=OP, artifact=stat(package / "render.yaml", "render.yaml"))
],
native_holds=dict(
activated=dict(
bytes=len(marker), sha256=hashlib.sha256(marker).hexdigest()
),
index=dict(
bytes=len(index_bytes), sha256=hashlib.sha256(index_bytes).hexdigest()
),
records=index,
),
)
write_json(package / "recovery.evidence.v1.json", sidecar)
storage = tmp_path / "observed-storage"
storage.mkdir()
for name, data in members.items():
path = storage / name
path.parent.mkdir(parents=True, exist_ok=True)
path.write_bytes(data)
recovered = tmp_path / "observed-git"
recovered.mkdir()
git(recovered, "init", "--bare", "-q", "--object-format=" + object_format)
git(recovered, "bundle", "unbundle", str(package / "catalog.bundle"))
git(recovered, "update-ref", "refs/heads/main", head)
write_json(tmp_path / "observed.json", state)
write_json(tmp_path / "git-roots.json", {SOURCE: str(recovered)})
return dict(
package=package,
sidecar=sidecar,
state=state,
storage=storage,
recovered=recovered,
repo=repo,
tmp=tmp_path,
head=head,
commit=commit,
)
def check(packet, phase="backup", **kwargs):
return recovery.check(
packet["package"],
phase=phase,
storage_root=packet["storage"] if phase == "restored" else None,
observed_state=packet["tmp"] / "observed.json" if phase == "restored" else None,
git_roots=packet["tmp"] / "git-roots.json" if phase == "restored" else None,
**kwargs,
)
def save(packet):
write_json(packet["package"] / "recovery.evidence.v1.json", packet["sidecar"])
# #region Test.Tooling.DrRecovery.TestRealBundleClosureHistoricalReceiptAndStand [C:3] [TYPE Function] [SEMANTICS dr,recovery]
def test_real_bundle_closure_historical_receipt_and_stand(packet):
assert packet["commit"] != packet["head"]
assert check(packet) == []
assert check(packet, "restored") == []
# #endregion Test.Tooling.DrRecovery.TestRealBundleClosureHistoricalReceiptAndStand
# #region Test.Tooling.DrRecovery.TestRequiredSidecarAndIdentity [C:3] [TYPE Function] [SEMANTICS dr,recovery]
@pytest.mark.parametrize(
"damage,code",
[
@@ -342,8 +46,10 @@ def test_required_sidecar_and_identity(packet, damage, code):
] = "0" * 40
save(packet)
assert code in check(packet)
# #endregion Test.Tooling.DrRecovery.TestRequiredSidecarAndIdentity
# #region Test.Tooling.DrRecovery.TestRealGitRefAndSourceNegatives [C:3] [TYPE Function] [SEMANTICS dr,recovery]
@pytest.mark.parametrize(
"damage,code",
[
@@ -362,8 +68,10 @@ def test_real_git_ref_and_source_negatives(packet, damage, code):
(packet["package"] / "catalog.bundle").write_bytes(b"broken")
save(packet)
assert code in check(packet)
# #endregion Test.Tooling.DrRecovery.TestRealGitRefAndSourceNegatives
# #region Test.Tooling.DrRecovery.TestIncrementalBundleIsNotSelfContained [C:3] [TYPE Function] [SEMANTICS dr,recovery]
def test_incremental_bundle_is_not_self_contained(packet):
source = packet["sidecar"]["git_sources"][0]
parent = packet["sidecar"]["source_state"]["publication_operations"][0][
@@ -383,200 +91,5 @@ def test_incremental_bundle_is_not_self_contained(packet):
source["prerequisites"] = [parent]
save(packet)
assert "DR_RECOVERY_GIT_NOT_SELF_CONTAINED" in check(packet)
@pytest.mark.parametrize(
"damage,code",
[
("marker", "DR_RECOVERY_HOLDS_UNAVAILABLE"),
("bytes", "DR_RECOVERY_HOLDS_BYTES_MISMATCH"),
("state", "DR_RECOVERY_STATE_MISMATCH"),
("ref", "DR_RECOVERY_GIT_REFS_MISMATCH"),
],
)
def test_stand_is_independent_of_valid_bundle(packet, damage, code):
if damage == "marker":
(packet["storage"] / ".native-result-holds/activated").unlink()
if damage == "bytes":
(packet["storage"] / f"drafts/{RUN}/{DIGEST}").write_bytes(b"changed")
if damage == "state":
value = deepcopy(packet["state"])
value["retention_deletions"][0]["attempts"] = 1
write_json(packet["tmp"] / "observed.json", value)
if damage == "ref":
git(packet["recovered"], "update-ref", "refs/heads/main", packet["commit"])
assert code in check(packet, "restored")
def test_symlink_inputs_refuse(packet):
render = packet["package"] / "render.yaml"
render.unlink()
(packet["tmp"] / "elsewhere").write_bytes(b"abc")
render.symlink_to(packet["tmp"] / "elsewhere")
assert "DR_RECOVERY_INPUT_UNSAFE" in check(packet)
def test_cli_sanitized_missing_restored_inputs(packet, capsys):
assert (
recovery.main(["--backup-dir", str(packet["package"]), "--phase", "restored"])
== 1
)
output = capsys.readouterr()
assert "DR_RECOVERY_INPUT_MISSING" in output.out
assert str(packet["tmp"]) not in output.out + output.err
assert "fixture.invalid" not in output.out + output.err
@pytest.mark.parametrize("packet", ["sha256"], indirect=True)
def test_sha256_bundle_and_stand(packet):
assert check(packet) == []
assert check(packet, "restored") == []
def test_git_reads_never_change_package_or_observed_root(packet):
def snapshot():
return {
(kind, str(path.relative_to(packet[kind]))): path.read_bytes()
for kind in ("package", "storage", "recovered")
for path in packet[kind].rglob("*")
if path.is_file()
}
before = snapshot()
assert check(packet, "restored") == []
assert snapshot() == before
@pytest.mark.parametrize("kind", ["include", "alternates", "symlink"])
def test_external_git_configuration_or_object_source_refuses(packet, kind):
root = packet["recovered"]
if kind == "include":
with (root / "config").open("a") as stream:
stream.write("[include]\npath=/private-must-not-read\n")
if kind == "alternates":
(root / "objects/info/alternates").write_text("/private-must-not-read\n")
if kind == "symlink":
(root / "objects/info").rmdir()
(root / "objects/info").symlink_to(packet["repo"] / ".git/objects/info")
assert "DR_RECOVERY_GIT_ROOT_UNSAFE" in check(packet, "restored")
def rewrite_manifest(packet, update):
path = packet["package"] / "manifest.json"
manifest = json.loads(path.read_text())
update(manifest)
write_json(path, manifest)
packet["sidecar"]["manifest_sha256"] = stat(path)["sha256"]
@pytest.mark.parametrize(
"damage,code",
[
("missing_commit", "DR_RECOVERY_GIT_OBJECT_UNAVAILABLE"),
("wrong_blob", "DR_RECOVERY_GIT_RENDER_MISMATCH"),
],
)
def test_expected_metadata_cannot_replace_git_objects_or_bytes(packet, damage, code):
operation = packet["sidecar"]["source_state"]["publication_operations"][0]
if damage == "missing_commit":
operation["commit_sha"] = operation["published_receipt"][
"commit_sha"
] = operation["published_receipt"]["head_after"] = "0" * 40
rewrite_manifest(
packet,
lambda value: value["reference_ids"]["publication_operations"][0].update(
commit_sha="0" * 40
),
)
else:
path = packet["package"] / "render.yaml"
path.write_bytes(b"wrong")
artifact = stat(path, "render.yaml")
packet["sidecar"]["renders"][0]["artifact"] = artifact
operation["render_sha256"] = operation["published_receipt"]["render_sha256"] = (
artifact["sha256"]
)
rewrite_manifest(
packet,
lambda value: value["reference_ids"]["publication_operations"][0].update(
render_sha256=artifact["sha256"]
),
)
save(packet)
assert code in check(packet)
@pytest.mark.parametrize("damage", ["marker", "index", "bytes"])
def test_archive_hold_completeness_even_when_archive_hash_matches(packet, damage):
path = packet["package"] / "storage.tgz"
with tarfile.open(path, "r:gz") as archive:
contents = {
member.name: archive.extractfile(member).read() for member in archive
}
if damage == "marker":
del contents[".native-result-holds/activated"]
if damage == "index":
contents[".native-result-holds/index.json"] = b"{}"
if damage == "bytes":
contents[f"drafts/{RUN}/{DIGEST}"] = b"wrong"
with tarfile.open(path, "w:gz") as archive:
for name, data in contents.items():
info = tarfile.TarInfo(name)
info.size = len(data)
archive.addfile(info, io.BytesIO(data))
rewrite_manifest(packet, lambda value: value.update(storage=stat(path)))
save(packet)
assert any(code.startswith("DR_RECOVERY_HOLDS_") for code in check(packet))
@pytest.mark.parametrize("allow_mapping", [False, True])
def test_explicit_foreign_destination_requires_exact_mapping(packet, allow_mapping):
observed = deepcopy(packet["state"])
observed["target"] = {**TARGET, "database": "clean"}
write_json(packet["tmp"] / "observed.json", observed)
mapping = packet["tmp"] / "mapping.json"
write_json(
mapping,
dict(
schema_version=1,
source=TARGET,
destination=observed["target"],
reviewed_by="fixture reviewer",
approved_at=STAMP,
),
)
codes = check(packet, "restored", mapping_path=mapping if allow_mapping else None)
assert codes == ([] if allow_mapping else ["DR_RECOVERY_MAPPING_INVALID"])
def test_exact_runbook_gate_stops_before_fake_writes(packet):
runbook = (
Path(__file__).resolve().parents[2] / "specs/DR-ROLLBACK-RUNBOOK.md"
).read_text()
fences = runbook.split("```bash\n")[1:]
block = next(
item.split("```", 1)[0]
for item in fences
if '"$RECOVERY_CHECK" --phase backup' in item
)
(packet["package"] / "recovery.evidence.v1.json").unlink()
marker = packet["tmp"] / "write-boundary"
env = dict(
PATH="/usr/bin:/bin",
REPO_ROOT=str(Path(__file__).resolve().parents[2]),
PYTHON=sys.executable,
BACKUP_DIR=str(packet["package"]),
PYTHONDONTWRITEBYTECODE="1",
)
script = "set -euo pipefail\n" + block + "\nprintf called > " + str(marker)
process = subprocess.run(
["/bin/bash", "--noprofile", "--norc", "-c", script],
env=env,
capture_output=True,
)
assert process.returncode == 1
assert not marker.exists()
assert b"DR_RECOVERY_INPUT_MISSING" in process.stdout
# #endregion Test.Tooling.DrRecovery.TestIncrementalBundleIsNotSelfContained
# #endregion Test.Tooling.DrRecovery

View File

@@ -15,6 +15,7 @@ from test_dr_recovery_check import (
)
# #region Test.Tooling.DrRecovery.Identity.Repack [C:3] [TYPE Function] [SEMANTICS dr,recovery]
def repack(packet, objects):
env = dict(
PATH="/usr/bin:/bin",
@@ -47,8 +48,10 @@ def repack(packet, objects):
+ process.stdout
)
packet["sidecar"]["git_sources"][0]["bundle"] = stat(path, "catalog.bundle")
# #endregion Test.Tooling.DrRecovery.Identity.Repack
# #region Test.Tooling.DrRecovery.Identity.AnnotatePublication [C:3] [TYPE Function] [SEMANTICS dr,recovery]
def annotate_publication(packet):
git(
packet["repo"],
@@ -65,8 +68,10 @@ def annotate_publication(packet):
packet["repo"], "rev-list", "--objects", "--no-object-names", "refs/heads/main"
).splitlines()
return identity, objects + [identity]
# #endregion Test.Tooling.DrRecovery.Identity.AnnotatePublication
# #region Test.Tooling.DrRecovery.Identity.TestAnnotatedTagIsNotTheExactPublicationCommit [C:3] [TYPE Function] [SEMANTICS dr,recovery]
def test_annotated_tag_is_not_the_exact_publication_commit(packet):
identity, objects = annotate_publication(packet)
operation = packet["sidecar"]["source_state"]["publication_operations"][0]
@@ -74,31 +79,41 @@ def test_annotated_tag_is_not_the_exact_publication_commit(packet):
"published_receipt"
]["head_after"] = identity
repack(packet, objects)
# #region Test.Tooling.DrRecovery.Identity.TestAnnotatedTagIsNotTheExactPublicationCommit.UpdateManifest79 [C:3] [TYPE Function] [SEMANTICS dr,recovery]
def update_manifest_79(value):
value['reference_ids']['publication_operations'][0].update(commit_sha=identity)
# #endregion Test.Tooling.DrRecovery.Identity.TestAnnotatedTagIsNotTheExactPublicationCommit.UpdateManifest79
rewrite_manifest(
packet,
lambda value: value["reference_ids"]["publication_operations"][0].update(
commit_sha=identity
),
update_manifest_79,
)
save(packet)
assert check(packet) == ["DR_RECOVERY_GIT_OBJECT_UNAVAILABLE"]
# #endregion Test.Tooling.DrRecovery.Identity.TestAnnotatedTagIsNotTheExactPublicationCommit
# #region Test.Tooling.DrRecovery.Identity.TestAnnotatedTagIsNotACapturedCommitHead [C:3] [TYPE Function] [SEMANTICS dr,recovery]
def test_annotated_tag_is_not_a_captured_commit_head(packet):
identity, objects = annotate_publication(packet)
packet["head"] = identity
packet["sidecar"]["git_sources"][0]["refs"][0]["commit_sha"] = identity
repack(packet, objects)
# #region Test.Tooling.DrRecovery.Identity.TestAnnotatedTagIsNotACapturedCommitHead.UpdateManifest95 [C:3] [TYPE Function] [SEMANTICS dr,recovery]
def update_manifest_95(value):
value['catalog_ref'].update(ls_remote=[[identity, 'refs/heads/main']])
# #endregion Test.Tooling.DrRecovery.Identity.TestAnnotatedTagIsNotACapturedCommitHead.UpdateManifest95
rewrite_manifest(
packet,
lambda value: value["catalog_ref"].update(
ls_remote=[[identity, "refs/heads/main"]]
),
update_manifest_95,
)
save(packet)
assert check(packet) == ["DR_RECOVERY_GIT_OBJECT_UNAVAILABLE"]
# #endregion Test.Tooling.DrRecovery.Identity.TestAnnotatedTagIsNotACapturedCommitHead
# #region Test.Tooling.DrRecovery.Identity.TestSha256ClaimCannotBeAbbreviatedToSha1Width [C:3] [TYPE Function] [SEMANTICS dr,recovery]
@pytest.mark.parametrize("packet", ["sha256"], indirect=True)
@pytest.mark.parametrize("field", ["commit_sha", "expected_branch_head"])
def test_sha256_claim_cannot_be_abbreviated_to_sha1_width(packet, field):
@@ -110,16 +125,21 @@ def test_sha256_claim_cannot_be_abbreviated_to_sha1_width(packet, field):
operation["published_receipt"]["commit_sha"] = operation["published_receipt"][
"head_after"
] = abbreviated
# #region Test.Tooling.DrRecovery.Identity.TestSha256ClaimCannotBeAbbreviatedToSha1Width.UpdateManifest117 [C:3] [TYPE Function] [SEMANTICS dr,recovery]
def update_manifest_117(value):
value['reference_ids']['publication_operations'][0].update(commit_sha=abbreviated)
# #endregion Test.Tooling.DrRecovery.Identity.TestSha256ClaimCannotBeAbbreviatedToSha1Width.UpdateManifest117
rewrite_manifest(
packet,
lambda value: value["reference_ids"]["publication_operations"][0].update(
commit_sha=abbreviated
),
update_manifest_117,
)
save(packet)
assert check(packet) == ["DR_RECOVERY_CONTRACT_INVALID"]
# #endregion Test.Tooling.DrRecovery.Identity.TestSha256ClaimCannotBeAbbreviatedToSha1Width
# #region Test.Tooling.DrRecovery.Identity.TestRequiredHistoricalGraphIsAClosureRootEvenAfterBranchRewrite [C:3] [TYPE Function] [SEMANTICS dr,recovery]
def test_required_historical_graph_is_a_closure_root_even_after_branch_rewrite(packet):
operation = packet["sidecar"]["source_state"]["publication_operations"][0]
missing = git(
@@ -140,14 +160,18 @@ def test_required_historical_graph_is_a_closure_root_even_after_branch_rewrite(p
packet["head"] = rewritten
packet["sidecar"]["git_sources"][0]["refs"][0]["commit_sha"] = rewritten
repack(packet, sorted((set(main_objects) | set(history)) - {missing}))
# #region Test.Tooling.DrRecovery.Identity.TestRequiredHistoricalGraphIsAClosureRootEvenAfterBranchRewrite.UpdateManifest147 [C:3] [TYPE Function] [SEMANTICS dr,recovery]
def update_manifest_147(value):
value['catalog_ref'].update(ls_remote=[[rewritten, 'refs/heads/main']])
# #endregion Test.Tooling.DrRecovery.Identity.TestRequiredHistoricalGraphIsAClosureRootEvenAfterBranchRewrite.UpdateManifest147
rewrite_manifest(
packet,
lambda value: value["catalog_ref"].update(
ls_remote=[[rewritten, "refs/heads/main"]]
),
update_manifest_147,
)
save(packet)
assert check(packet) == ["DR_RECOVERY_GIT_BUNDLE_INVALID"]
# #endregion Test.Tooling.DrRecovery.Identity.TestRequiredHistoricalGraphIsAClosureRootEvenAfterBranchRewrite
# #endregion Test.Tooling.DrRecovery.Identity

View File

@@ -2,14 +2,9 @@
# @BRIEF Required declarations, provenance and bounded input failures never select another source.
# @RELATION BINDS_TO -> [Tooling.DrRecovery]
import json
import errno
import os
from pathlib import Path
import stat as stat_module
import subprocess
import sys
import threading
import time
import pytest
@@ -28,12 +23,9 @@ from test_dr_recovery_check import (
)
import dr_recovery_check as recovery
import dr_recovery_holds as holds_check
import dr_recovery_git as git_check
import dr_recovery_io as recovery_io
import dr_evidence_check as evidence_owner
from dr_recovery_io import Refused
# #region Test.Tooling.DrRecovery.Refusals.TestMissingForeignOrConflictingAuthority [C:3] [TYPE Function] [SEMANTICS dr,recovery]
@pytest.mark.parametrize(
"damage,code",
[
@@ -64,41 +56,53 @@ def test_missing_foreign_or_conflicting_authority(packet, damage, code):
value["native_holds"]["records"]["holds"][0]["agent_run_id"] = SOURCE
save(packet)
assert code in check(packet)
# #endregion Test.Tooling.DrRecovery.Refusals.TestMissingForeignOrConflictingAuthority
# #region Test.Tooling.DrRecovery.Refusals.TestMissingObservedGitRootCannotUseBackupBundle [C:3] [TYPE Function] [SEMANTICS dr,recovery]
def test_missing_observed_git_root_cannot_use_backup_bundle(packet):
write_json(packet["tmp"] / "git-roots.json", {})
assert check(packet, "restored") == ["DR_RECOVERY_GIT_SOURCE_MISMATCH"]
# #endregion Test.Tooling.DrRecovery.Refusals.TestMissingObservedGitRootCannotUseBackupBundle
# #region Test.Tooling.DrRecovery.Refusals.TestJsonResourceLimitBeforeParseOrGit [C:3] [TYPE Function] [SEMANTICS dr,recovery]
def test_json_resource_limit_before_parse_or_git(packet):
(packet["package"] / "recovery.evidence.v1.json").write_bytes(
b" " * (16 * 1024 * 1024 + 1)
)
assert check(packet) == ["DR_RECOVERY_LIMIT"]
# #endregion Test.Tooling.DrRecovery.Refusals.TestJsonResourceLimitBeforeParseOrGit
# #region Test.Tooling.DrRecovery.Refusals.TestExpandedArchiveResourceLimit [C:3] [TYPE Function] [SEMANTICS dr,recovery]
def test_expanded_archive_resource_limit(packet, monkeypatch):
# Exercise the same fixed decompression guard at a small test budget, without a huge fixture.
monkeypatch.setattr(holds_check, "ARCHIVE_LIMIT", 2048)
assert check(packet) == ["DR_RECOVERY_LIMIT"]
# #endregion Test.Tooling.DrRecovery.Refusals.TestExpandedArchiveResourceLimit
# #region Test.Tooling.DrRecovery.Refusals.TestDuplicateOrNonJsonValuesRefuse [C:3] [TYPE Function] [SEMANTICS dr,recovery]
@pytest.mark.parametrize(
"raw", ['{"schema_version":1,"schema_version":1}', '{"bad":NaN}']
)
def test_duplicate_or_non_json_values_refuse(packet, raw):
(packet["package"] / "recovery.evidence.v1.json").write_text(raw)
assert check(packet) == ["DR_RECOVERY_CONTRACT_INVALID"]
# #endregion Test.Tooling.DrRecovery.Refusals.TestDuplicateOrNonJsonValuesRefuse
# #region Test.Tooling.DrRecovery.Refusals.TestCliNeverEchoesUnknownArguments [C:3] [TYPE Function] [SEMANTICS dr,recovery]
def test_cli_never_echoes_unknown_arguments(packet, capsys):
assert recovery.main(["--private-value-that-must-not-leak"]) == 1
captured = capsys.readouterr()
assert "DR_RECOVERY_CONTRACT_INVALID" in captured.out
assert "private-value-that-must-not-leak" not in captured.out + captured.err
# #endregion Test.Tooling.DrRecovery.Refusals.TestCliNeverEchoesUnknownArguments
# #region Test.Tooling.DrRecovery.Refusals.TestExactRestoredGateStopsBeforeFakeWriterStart [C:3] [TYPE Function] [SEMANTICS dr,recovery]
def test_exact_restored_gate_stops_before_fake_writer_start(packet):
root = Path(__file__).resolve().parents[2]
text = (root / "specs/DR-ROLLBACK-RUNBOOK.md").read_text()
@@ -128,8 +132,10 @@ def test_exact_restored_gate_stops_before_fake_writer_start(packet):
assert process.returncode == 1
assert b"DR_RECOVERY_INPUT_MISSING" in process.stdout
assert not marker.exists()
# #endregion Test.Tooling.DrRecovery.Refusals.TestExactRestoredGateStopsBeforeFakeWriterStart
# #region Test.Tooling.DrRecovery.Refusals.TestNoRecoveryInputsSelectedImplicitly [C:3] [TYPE Function] [SEMANTICS dr,recovery]
def test_no_recovery_inputs_selected_implicitly(packet):
# Both operation and phase are explicit: backup mode cannot silently ignore stand inputs.
assert recovery.check(
@@ -139,24 +145,30 @@ def test_no_recovery_inputs_selected_implicitly(packet):
) == ["DR_RECOVERY_CONTRACT_INVALID"]
value = json.loads((packet["package"] / "recovery.evidence.v1.json").read_text())
assert value["t_snap"] == STAMP
# #endregion Test.Tooling.DrRecovery.Refusals.TestNoRecoveryInputsSelectedImplicitly
# #region Test.Tooling.DrRecovery.Refusals.TestLogicalHeadRepositoryIsIndependentOfDestination [C:3] [TYPE Function] [SEMANTICS dr,recovery]
def test_logical_head_repository_is_independent_of_destination(packet):
packet["sidecar"]["source_state"]["catalog_heads"][0]["repository"] = (
"foreign-logical-repository"
)
save(packet)
assert check(packet) == ["DR_RECOVERY_CONTRACT_INVALID"]
# #endregion Test.Tooling.DrRecovery.Refusals.TestLogicalHeadRepositoryIsIndependentOfDestination
# #region Test.Tooling.DrRecovery.Refusals.TestActualPublicationParentMustMatchReviewedHead [C:3] [TYPE Function] [SEMANTICS dr,recovery]
def test_actual_publication_parent_must_match_reviewed_head(packet):
packet["sidecar"]["source_state"]["publication_operations"][0][
"expected_branch_head"
] = packet["head"]
save(packet)
assert check(packet) == ["DR_RECOVERY_GIT_PROVENANCE_MISMATCH"]
# #endregion Test.Tooling.DrRecovery.Refusals.TestActualPublicationParentMustMatchReviewedHead
# #region Test.Tooling.DrRecovery.Refusals.TestIdenticalBytesInForeignCommitDoNotReplacePublication [C:3] [TYPE Function] [SEMANTICS dr,recovery]
def test_identical_bytes_in_foreign_commit_do_not_replace_publication(packet):
operation = packet["sidecar"]["source_state"]["publication_operations"][0]
tree = git(packet["repo"], "rev-parse", packet["commit"] + "^{tree}")
@@ -184,16 +196,21 @@ def test_identical_bytes_in_foreign_commit_do_not_replace_publication(packet):
operation["commit_sha"] = operation["published_receipt"]["commit_sha"] = operation[
"published_receipt"
]["head_after"] = foreign
# #region Test.Tooling.DrRecovery.Refusals.TestIdenticalBytesInForeignCommitDoNotReplacePublication.UpdateManifest189 [C:3] [TYPE Function] [SEMANTICS dr,recovery]
def update_manifest_189(value):
value['reference_ids']['publication_operations'][0].update(commit_sha=foreign)
# #endregion Test.Tooling.DrRecovery.Refusals.TestIdenticalBytesInForeignCommitDoNotReplacePublication.UpdateManifest189
rewrite_manifest(
packet,
lambda value: value["reference_ids"]["publication_operations"][0].update(
commit_sha=foreign
),
update_manifest_189,
)
save(packet)
assert check(packet) == ["DR_RECOVERY_GIT_PROVENANCE_MISMATCH"]
# #endregion Test.Tooling.DrRecovery.Refusals.TestIdenticalBytesInForeignCommitDoNotReplacePublication
# #region Test.Tooling.DrRecovery.Refusals.TestCliSuccessWithNoDatabaseOrPrivateEnvironment [C:3] [TYPE Function] [SEMANTICS dr,recovery]
def test_cli_success_with_no_database_or_private_environment(packet):
root = Path(__file__).resolve().parents[2]
process = subprocess.run(
@@ -215,159 +232,7 @@ def test_cli_success_with_no_database_or_private_environment(packet):
events = [json.loads(line) for line in process.stderr.splitlines()]
assert [item["marker"] for item in events] == ["REASON", "REFLECT"]
assert CAT not in process.stderr and OP not in process.stderr
def test_git_subprocess_has_closed_environment_and_timeout(monkeypatch, tmp_path):
calls = []
def process(command, **kwargs):
calls.append((command, kwargs))
return type("Child", (), {"wait": lambda self, timeout: 0})()
monkeypatch.setattr(git_check.subprocess, "Popen", process)
assert git_check.git(tmp_path, ["status"], "DR_RECOVERY_GIT_UNAVAILABLE") == b""
command, options = calls[0]
assert command[0] == "/usr/bin/git"
assert options["env"]["GIT_CONFIG_GLOBAL"] == "/dev/null"
assert options["env"]["GIT_NO_LAZY_FETCH"] == "1"
assert options["env"]["GIT_CONFIG_NOSYSTEM"] == "1"
assert (
not {
"DATABASE_URL",
"SSH_AUTH_SOCK",
"GIT_SSH_COMMAND",
"GIT_CONFIG_PARAMETERS",
}
& options["env"].keys()
)
assert options["start_new_session"] is True and callable(options["preexec_fn"])
def test_git_timeout_kills_only_owned_process_group(monkeypatch, tmp_path):
calls = []
class Child:
pid = 123456789
def wait(self, timeout=None):
if timeout is not None:
assert timeout == 30
raise subprocess.TimeoutExpired(["git"], timeout)
return -9
monkeypatch.setattr(git_check.subprocess, "Popen", lambda *args, **kwargs: Child())
monkeypatch.setattr(git_check.os, "killpg", lambda pid, signal: calls.append(pid))
with pytest.raises(Refused, match="^DR_RECOVERY_LIMIT$"):
git_check.git(tmp_path, ["status"], "DR_RECOVERY_GIT_UNAVAILABLE")
assert calls == [123456789]
def test_total_render_budget_precedes_reading_multiple_artifacts(packet, monkeypatch):
monkeypatch.setattr(recovery, "RENDER_TOTAL_LIMIT", 2)
assert check(packet) == ["DR_RECOVERY_LIMIT"]
@pytest.mark.parametrize("replace_after_classify", [False, True])
def test_real_fifo_never_blocks_before_regular_file_validation(
tmp_path, monkeypatch, replace_after_classify
):
root = tmp_path / "input"
root.mkdir()
path = root / "artifact"
real_open = os.open
if replace_after_classify:
path.write_bytes(b"literal regular bytes")
else:
os.mkfifo(path, 0o600)
errors = []
def release_only_a_blocked_old_reader():
try:
descriptor = real_open(path, os.O_WRONLY | os.O_NONBLOCK)
except OSError as error:
if error.errno != errno.ENXIO:
errors.append(error.errno)
else:
os.close(descriptor)
with recovery_io.pinned(root) as root_fd:
if replace_after_classify:
def open_with_replacement(name, flags, *args, **kwargs):
if name == "artifact" and kwargs.get("dir_fd") == root_fd:
path.unlink()
os.mkfifo(path, 0o600)
return real_open(name, flags, *args, **kwargs)
# Mutate at the OS boundary after the real classification; the actual FIFO is still opened.
monkeypatch.setattr(evidence_owner.os, "open", open_with_replacement)
release = threading.Timer(0.5, release_only_a_blocked_old_reader)
release.start()
started = time.monotonic()
try:
with pytest.raises(Refused, match="^DR_RECOVERY_INPUT_MISSING$"):
recovery_io.read(root_fd, "artifact")
elapsed = time.monotonic() - started
finally:
release.join(timeout=2)
assert not release.is_alive() and not errors
assert stat_module.S_ISFIFO(path.stat().st_mode)
assert stat_module.S_IMODE(path.stat().st_mode) == 0o600
assert elapsed < 0.2, (
"FIFO opened in blocking mode before fstat regular-file refusal"
)
def test_root_ancestor_symlink_is_not_an_input_root(tmp_path):
actual = tmp_path / "actual"
(actual / "repo").mkdir(parents=True)
alias = tmp_path / "alias"
alias.symlink_to(actual, target_is_directory=True)
with pytest.raises(Refused, match="^DR_RECOVERY_INPUT_UNSAFE$"):
with recovery_io.pinned(alias / "repo"):
pass
def test_bundle_missing_unrelated_reachable_blob_fails_whole_closure(packet):
operation = packet["sidecar"]["source_state"]["publication_operations"][0]
missing = git(
packet["repo"], "rev-parse", operation["expected_branch_head"] + ":README"
)
objects = git(
packet["repo"], "rev-list", "--objects", "--no-object-names", "refs/heads/main"
).splitlines()
assert missing in objects
# Produce a structurally valid, rehashed pack which deliberately omits the old README blob.
# Publication bytes/commit/parent and all advertised refs remain valid and unchanged.
env = dict(
PATH="/usr/bin:/bin",
HOME=str(packet["tmp"]),
GIT_CONFIG_NOSYSTEM="1",
GIT_CONFIG_GLOBAL="/dev/null",
GIT_CONFIG_SYSTEM="/dev/null",
GIT_TERMINAL_PROMPT="0",
)
pack = subprocess.run(
[
"/usr/bin/git",
"-C",
str(packet["repo"]),
"-c",
"protocol.allow=never",
"pack-objects",
"--stdout",
],
input=("\n".join(oid for oid in objects if oid != missing) + "\n").encode(),
capture_output=True,
check=True,
env=env,
).stdout
bundle_path = packet["package"] / "catalog.bundle"
header = b"# v2 git bundle\n" + packet["head"].encode() + b" refs/heads/main\n\n"
bundle_path.write_bytes(header + pack)
packet["sidecar"]["git_sources"][0]["bundle"] = stat(bundle_path, "catalog.bundle")
save(packet)
assert check(packet) == ["DR_RECOVERY_GIT_BUNDLE_INVALID"]
# #endregion Test.Tooling.DrRecovery.Refusals.TestCliSuccessWithNoDatabaseOrPrivateEnvironment
# #endregion Test.Tooling.DrRecovery.Refusals

View File

@@ -0,0 +1,234 @@
# #region Test.Tooling.DrRecovery.Stand [C:3] [TYPE Module] [SEMANTICS dr,recovery]
# @BRIEF Restored stand independence, byte integrity, destination mapping and runbook stop gates.
from copy import deepcopy
import io
from pathlib import Path
import subprocess
import sys
import tarfile
import pytest
from dr_recovery_fixtures import (
packet as packet, write_json, stat, git, check, save, rewrite_manifest,
RUN, STAMP, DIGEST, TARGET,
)
import dr_recovery_check as recovery
# #region Test.Tooling.DrRecovery.Stand.TestStandIsIndependentOfValidBundle [C:3] [TYPE Function] [SEMANTICS dr,recovery]
@pytest.mark.parametrize(
"damage,code",
[
("marker", "DR_RECOVERY_HOLDS_UNAVAILABLE"),
("bytes", "DR_RECOVERY_HOLDS_BYTES_MISMATCH"),
("state", "DR_RECOVERY_STATE_MISMATCH"),
("ref", "DR_RECOVERY_GIT_REFS_MISMATCH"),
],
)
def test_stand_is_independent_of_valid_bundle(packet, damage, code):
if damage == "marker":
(packet["storage"] / ".native-result-holds/activated").unlink()
if damage == "bytes":
(packet["storage"] / f"drafts/{RUN}/{DIGEST}").write_bytes(b"changed")
if damage == "state":
value = deepcopy(packet["state"])
value["retention_deletions"][0]["attempts"] = 1
write_json(packet["tmp"] / "observed.json", value)
if damage == "ref":
git(packet["recovered"], "update-ref", "refs/heads/main", packet["commit"])
assert code in check(packet, "restored")
# #endregion Test.Tooling.DrRecovery.Stand.TestStandIsIndependentOfValidBundle
# #region Test.Tooling.DrRecovery.Stand.TestSymlinkInputsRefuse [C:3] [TYPE Function] [SEMANTICS dr,recovery]
def test_symlink_inputs_refuse(packet):
render = packet["package"] / "render.yaml"
render.unlink()
(packet["tmp"] / "elsewhere").write_bytes(b"abc")
render.symlink_to(packet["tmp"] / "elsewhere")
assert "DR_RECOVERY_INPUT_UNSAFE" in check(packet)
# #endregion Test.Tooling.DrRecovery.Stand.TestSymlinkInputsRefuse
# #region Test.Tooling.DrRecovery.Stand.TestCliSanitizedMissingRestoredInputs [C:3] [TYPE Function] [SEMANTICS dr,recovery]
def test_cli_sanitized_missing_restored_inputs(packet, capsys):
assert (
recovery.main(["--backup-dir", str(packet["package"]), "--phase", "restored"])
== 1
)
output = capsys.readouterr()
assert "DR_RECOVERY_INPUT_MISSING" in output.out
assert str(packet["tmp"]) not in output.out + output.err
assert "fixture.invalid" not in output.out + output.err
# #endregion Test.Tooling.DrRecovery.Stand.TestCliSanitizedMissingRestoredInputs
# #region Test.Tooling.DrRecovery.Stand.TestSha256BundleAndStand [C:3] [TYPE Function] [SEMANTICS dr,recovery]
@pytest.mark.parametrize("packet", ["sha256"], indirect=True)
def test_sha256_bundle_and_stand(packet):
assert check(packet) == []
assert check(packet, "restored") == []
# #endregion Test.Tooling.DrRecovery.Stand.TestSha256BundleAndStand
# #region Test.Tooling.DrRecovery.Stand.TestGitReadsNeverChangePackageOrObservedRoot [C:3] [TYPE Function] [SEMANTICS dr,recovery]
def test_git_reads_never_change_package_or_observed_root(packet):
# #region Test.Tooling.DrRecovery.Stand.TestGitReadsNeverChangePackageOrObservedRoot.Snapshot [C:3] [TYPE Function] [SEMANTICS dr,recovery]
def snapshot():
return {
(kind, str(path.relative_to(packet[kind]))): path.read_bytes()
for kind in ("package", "storage", "recovered")
for path in packet[kind].rglob("*")
if path.is_file()
}
# #endregion Test.Tooling.DrRecovery.Stand.TestGitReadsNeverChangePackageOrObservedRoot.Snapshot
before = snapshot()
assert check(packet, "restored") == []
assert snapshot() == before
# #endregion Test.Tooling.DrRecovery.Stand.TestGitReadsNeverChangePackageOrObservedRoot
# #region Test.Tooling.DrRecovery.Stand.TestExternalGitConfigurationOrObjectSourceRefuses [C:3] [TYPE Function] [SEMANTICS dr,recovery]
@pytest.mark.parametrize("kind", ["include", "alternates", "symlink"])
def test_external_git_configuration_or_object_source_refuses(packet, kind):
root = packet["recovered"]
if kind == "include":
with (root / "config").open("a") as stream:
stream.write("[include]\npath=/private-must-not-read\n")
if kind == "alternates":
(root / "objects/info/alternates").write_text("/private-must-not-read\n")
if kind == "symlink":
(root / "objects/info").rmdir()
(root / "objects/info").symlink_to(packet["repo"] / ".git/objects/info")
assert "DR_RECOVERY_GIT_ROOT_UNSAFE" in check(packet, "restored")
# #endregion Test.Tooling.DrRecovery.Stand.TestExternalGitConfigurationOrObjectSourceRefuses
# #region Test.Tooling.DrRecovery.Stand.TestExpectedMetadataCannotReplaceGitObjectsOrBytes [C:3] [TYPE Function] [SEMANTICS dr,recovery]
@pytest.mark.parametrize(
"damage,code",
[
("missing_commit", "DR_RECOVERY_GIT_OBJECT_UNAVAILABLE"),
("wrong_blob", "DR_RECOVERY_GIT_RENDER_MISMATCH"),
],
)
def test_expected_metadata_cannot_replace_git_objects_or_bytes(packet, damage, code):
operation = packet["sidecar"]["source_state"]["publication_operations"][0]
if damage == "missing_commit":
operation["commit_sha"] = operation["published_receipt"][
"commit_sha"
] = operation["published_receipt"]["head_after"] = "0" * 40
# #region Test.Tooling.DrRecovery.Stand.TestExpectedMetadataCannotReplaceGitObjectsOrBytes.UpdateManifest109 [C:3] [TYPE Function] [SEMANTICS dr,recovery]
def update_manifest_109(value):
value['reference_ids']['publication_operations'][0].update(commit_sha='0' * 40)
# #endregion Test.Tooling.DrRecovery.Stand.TestExpectedMetadataCannotReplaceGitObjectsOrBytes.UpdateManifest109
rewrite_manifest(
packet,
update_manifest_109,
)
else:
path = packet["package"] / "render.yaml"
path.write_bytes(b"wrong")
artifact = stat(path, "render.yaml")
packet["sidecar"]["renders"][0]["artifact"] = artifact
operation["render_sha256"] = operation["published_receipt"]["render_sha256"] = (
artifact["sha256"]
)
# #region Test.Tooling.DrRecovery.Stand.TestExpectedMetadataCannotReplaceGitObjectsOrBytes.UpdateManifest124 [C:3] [TYPE Function] [SEMANTICS dr,recovery]
def update_manifest_124(value):
value['reference_ids']['publication_operations'][0].update(render_sha256=artifact['sha256'])
# #endregion Test.Tooling.DrRecovery.Stand.TestExpectedMetadataCannotReplaceGitObjectsOrBytes.UpdateManifest124
rewrite_manifest(
packet,
update_manifest_124,
)
save(packet)
assert code in check(packet)
# #endregion Test.Tooling.DrRecovery.Stand.TestExpectedMetadataCannotReplaceGitObjectsOrBytes
# #region Test.Tooling.DrRecovery.Stand.TestArchiveHoldCompletenessEvenWhenArchiveHashMatches [C:3] [TYPE Function] [SEMANTICS dr,recovery]
@pytest.mark.parametrize("damage", ["marker", "index", "bytes"])
def test_archive_hold_completeness_even_when_archive_hash_matches(packet, damage):
path = packet["package"] / "storage.tgz"
with tarfile.open(path, "r:gz") as archive:
contents = {
member.name: archive.extractfile(member).read() for member in archive
}
if damage == "marker":
del contents[".native-result-holds/activated"]
if damage == "index":
contents[".native-result-holds/index.json"] = b"{}"
if damage == "bytes":
contents[f"drafts/{RUN}/{DIGEST}"] = b"wrong"
with tarfile.open(path, "w:gz") as archive:
for name, data in contents.items():
info = tarfile.TarInfo(name)
info.size = len(data)
archive.addfile(info, io.BytesIO(data))
# #region Test.Tooling.DrRecovery.Stand.TestArchiveHoldCompletenessEvenWhenArchiveHashMatches.UpdateManifest149 [C:3] [TYPE Function] [SEMANTICS dr,recovery]
def update_manifest_149(value):
value.update(storage=stat(path))
# #endregion Test.Tooling.DrRecovery.Stand.TestArchiveHoldCompletenessEvenWhenArchiveHashMatches.UpdateManifest149
rewrite_manifest(packet, update_manifest_149)
save(packet)
assert any(code.startswith("DR_RECOVERY_HOLDS_") for code in check(packet))
# #endregion Test.Tooling.DrRecovery.Stand.TestArchiveHoldCompletenessEvenWhenArchiveHashMatches
# #region Test.Tooling.DrRecovery.Stand.TestExplicitForeignDestinationRequiresExactMapping [C:3] [TYPE Function] [SEMANTICS dr,recovery]
@pytest.mark.parametrize("allow_mapping", [False, True])
def test_explicit_foreign_destination_requires_exact_mapping(packet, allow_mapping):
observed = deepcopy(packet["state"])
observed["target"] = {**TARGET, "database": "clean"}
write_json(packet["tmp"] / "observed.json", observed)
mapping = packet["tmp"] / "mapping.json"
write_json(
mapping,
dict(
schema_version=1,
source=TARGET,
destination=observed["target"],
reviewed_by="fixture reviewer",
approved_at=STAMP,
),
)
codes = check(packet, "restored", mapping_path=mapping if allow_mapping else None)
assert codes == ([] if allow_mapping else ["DR_RECOVERY_MAPPING_INVALID"])
# #endregion Test.Tooling.DrRecovery.Stand.TestExplicitForeignDestinationRequiresExactMapping
# #region Test.Tooling.DrRecovery.Stand.TestExactRunbookGateStopsBeforeFakeWrites [C:3] [TYPE Function] [SEMANTICS dr,recovery]
def test_exact_runbook_gate_stops_before_fake_writes(packet):
runbook = (
Path(__file__).resolve().parents[2] / "specs/DR-ROLLBACK-RUNBOOK.md"
).read_text()
fences = runbook.split("```bash\n")[1:]
block = next(
item.split("```", 1)[0]
for item in fences
if '"$RECOVERY_CHECK" --phase backup' in item
)
(packet["package"] / "recovery.evidence.v1.json").unlink()
marker = packet["tmp"] / "write-boundary"
env = dict(
PATH="/usr/bin:/bin",
REPO_ROOT=str(Path(__file__).resolve().parents[2]),
PYTHON=sys.executable,
BACKUP_DIR=str(packet["package"]),
PYTHONDONTWRITEBYTECODE="1",
)
script = "set -euo pipefail\n" + block + "\nprintf called > " + str(marker)
process = subprocess.run(
["/bin/bash", "--noprofile", "--norc", "-c", script],
env=env,
capture_output=True,
)
assert process.returncode == 1
assert not marker.exists()
assert b"DR_RECOVERY_INPUT_MISSING" in process.stdout
# #endregion Test.Tooling.DrRecovery.Stand.TestExactRunbookGateStopsBeforeFakeWrites
# #endregion Test.Tooling.DrRecovery.Stand

View File

@@ -0,0 +1,28 @@
<!-- #region Release.DrRecoveryIntegration20261024 [C:3] [TYPE ADR] [SEMANTICS dr,recovery,evidence,integration] -->
@BRIEF Record exact-source integration of the accepted bounded DR repair while retaining the historical red replay and open runtime gates.
# DR recovery integration — 2026-10-24
Integration base/HEAD: `05e664f245213722024fd009667f0da436090e3e`, worktree `.worktrees/integration-dr-ready-20261024`. This report describes an unstaged candidate; no new source commit is claimed. Before integration, all ten functional source paths from `e355dce56ccaa6031152c2f5090c66eca911b9bf` already matched that commit exactly. Its aggregate is `8f37e004e3bca3dad8cb6493bc6902474800fe3a519b2c37bcde0459d46ae07c`.
The accepted structural repair separates pinned evidence I/O, typed evidence scope, strict DTO primitives/scalars, the bounded Git runner and fixture/stand/boundary tests. Its 17 Python modules plus unchanged runbook match the independently accepted 18-path manifest exactly: aggregate `0eae0f196e03b4fb8dba66e27acb5a8fc4b78bab87385f86f061503e910c8498`; source patch SHA-256 `d9b070e0a409ef3366cd0138ad3f6c6d2acceedb30bc8777927ba15ebcec457e`. No functional source was replaced by an older version. Current wave3 `scripts/tests/test_dr_evidence_check.py` remains untouched, SHA-256 `66ab0e394addd2c627f31b4fac01c3591bb6656e3f7ca492c905673c56e7bbc8`.
Independent source review accepted bounded source integration and owned INV1–7: **17 module contracts, 23 classes, 125 functions**, maximum **338 physical lines** and actual McCabe **9**. No missing own contracts, lambdas, late metadata, mismatched anchors, duplicate IDs or removed baseline IDs remain. All 28 prior IDs, original relation multiplicities and 12 resolved targets survive; assertions from all 36 original test functions remain exact. These measurements are reused by exact byte identity, with no claim about global semantic health.
Executed from the integration worktree on Python **3.13.7**:
```bash
/home/busya/dev/ss-tools/backend/.venv/bin/python /tmp/dr_currentmaster_verify.py
git apply --check /home/busya/dev/ss-tools/.worktrees/dr-recovery-inv-20261024/artifacts/.orchestrator/dr-inv1-7-repair-20261024/CANDIDATE.patch
git diff --check
```
All returned **RC0**; patch admission ran before applying the patch. The verifier records exact nested argv, cwd, UTC timestamps and actual exits in `commands.json`. Targeted current-source replay: **129 passed**, comprising **128 source cases**, including old67, plus the unchanged supplementary refusal-order case; JUnit has zero failures/errors/skips. Regular Ruff on all 17 Python paths returned RC0. The harness pins and records actual candidate module origins. Database/socket attempts: **0**. Source and protected-file hashes remained exact across execution.
**Historical aggregate remains RED: 137 passed / 1 failed, actual RC1.** The immutable independent stale-root assertion expects `DR_RECOVERY_GIT_REFS_MISMATCH` while the required head object is absent; the mandatory earlier refusal is `DR_RECOVERY_GIT_OBJECT_UNAVAILABLE`. That assertion, error sets and production order were not changed. The supplementary case proves missing object → `OBJECT_UNAVAILABLE`; imported object with stale ref → `REFS_MISMATCH`; exact restored ref → success. The passing current subset does not replace the retained RC1/JUnit failure or establish aggregate green.
Raw overlap, hashes, commands, module origins, JUnit and the combined patch/manifest remain in ignored `artifacts/.orchestrator/dr-currentmaster-integration-20261024/`. Accepted source and independent review remain in `.worktrees/dr-recovery-inv-20261024/artifacts/.orchestrator/{dr-inv1-7-repair-20261024,dr-independent-inv-repair-20261024}/`; historical evidence was not rewritten. The evidence index remains a directory map.
No full suite, PostgreSQL, Docker, live API, backup/restore or deployment ran. Configured Git export, authoritative DB-state collection, actual restore/retention preservation and RTO/RPO remain runtime prerequisites. **G-DR-ROLLBACK and global semantic/product gates remain OPEN; product GO remains NO.**
<!-- #endregion Release.DrRecoveryIntegration20261024 -->