ops-warden/tests/test_case_original_context_consistency.py
tegwick 117fec9241
All checks were successful
CI Smoke / host-smoke (push) Successful in 0s
CI Smoke / container-smoke (push) Successful in 1s
fix(case): validate original intent and bind its running receipt
Assistant: codex
Assistant-Model: gpt-6.1-sol
Assistant-Session: 01a1468b-63fa-7710-85dc-8f2e16b3ebfa
2026-10-17 10:33:43 +02:00

198 lines
6.3 KiB
Python

"""Original-intent consistency checks with generated metadata only.
Reuse the existing synthetic owner rig. These checks do not provide a native
holder or independently authenticate original creation from local SQL/JSON.
"""
from dataclasses import asdict, replace
import json
from pathlib import Path
import sqlite3
import subprocess
import sys
import pytest
from tests.test_case_run import rig as rig
from warden.case_receipt_state import Outcome, Refused
from warden.case_run import OriginalIntent
def interrupted(rig):
executor, args, calls, sources, kwargs = rig
old = executor.adapters[args[0].adapter]
seen = []
def lost(inv):
calls.append(inv)
raise TimeoutError("generated lost response")
def original(ctx):
seen.append(ctx)
return old.reconcile(ctx.attempt)
executor.adapters[old.reference] = replace(
old, invoke=lost, reconcile=None, reconcile_original=original
)
assert executor.run(*args).last.outcome is Outcome.UNCERTAIN
return executor, args, calls, old, seen
def alter_payload(executor, **changes):
row = executor.journal.db.execute(
"SELECT seq,payload FROM intents ORDER BY seq DESC LIMIT 1"
).fetchone()
obj = json.loads(row[1])
obj.update(changes)
executor.journal.db.execute(
"UPDATE intents SET payload=? WHERE seq=?", (json.dumps(obj), row[0])
)
def test_original_actor_mismatch_is_refused(rig):
executor, args, calls, old, _ = interrupted(rig)
alter_payload(executor, actor="agent")
with pytest.raises(Refused):
executor.journal.original_intent(
"mint-secret:fixture-client", args[1], old.source
)
def test_payload_attempt_id_must_match_sql_column_and_original_receipt(rig):
executor, args, calls, old, _ = interrupted(rig)
actual = calls[0].attempt_id
alter_payload(executor, attempt_id="attempt-unrelated")
with pytest.raises(Refused):
executor.journal.original_intent(
"mint-secret:fixture-client", args[1], old.source
)
assert (
executor.journal.db.execute("SELECT attempt_id FROM intents").fetchone()[0]
== actual
)
def test_orphan_intent_without_original_running_receipt_is_refused(rig):
executor, args, calls, old, _ = interrupted(rig)
executor.journal.db.execute(
"DELETE FROM receipts WHERE seq=(SELECT MIN(seq) FROM receipts)"
)
assert (
executor.journal.load("mint-secret:fixture-client", args[2]).last.outcome
is Outcome.UNCERTAIN
)
with pytest.raises(Refused):
executor.journal.original_intent(
"mint-secret:fixture-client", args[1], old.source
)
def test_serializer_refuses_arbitrary_values_outside_normal_admit(rig):
_, args, _, _, _ = rig
inv = replace(
args[1],
target={"unexpected": "synthetic-owner-payload"},
operation="run",
attempt_id="attempt-fixture",
)
record = OriginalIntent("mint-secret:fixture-client", inv, "sha256:" + "1" * 64)
with pytest.raises(Refused):
OriginalIntent.decode(record.payload())
# This is a direct serialization API gap, not an observed normal-admit leak.
# Owner trust is the existing synthetic fixture; this proves call shape only.
@pytest.mark.parametrize(
"field,value",
[
("principal", "another-person"),
("tenant", "another-tenant"),
("realm", "another-realm"),
],
)
def test_existing_lookup_does_refuse_stored_principal_tenant_realm_mismatch(
rig, field, value
):
executor, args, _, old, _ = interrupted(rig)
alter_payload(executor, **{field: value})
with pytest.raises(Refused):
executor.journal.original_intent(
"mint-secret:fixture-client", args[1], old.source
)
def test_existing_atomic_insert_failure_prevents_dispatch_and_both_records(rig):
executor, args, calls, _, _ = rig
executor.journal.db.execute(
"CREATE TRIGGER fail_receipt BEFORE INSERT ON receipts BEGIN SELECT RAISE(ABORT,'fixture'); END"
)
with pytest.raises(sqlite3.IntegrityError):
executor.run(*args)
assert not calls
assert executor.journal.db.execute("SELECT COUNT(*) FROM intents").fetchone() == (
0,
)
assert executor.journal.db.execute("SELECT COUNT(*) FROM receipts").fetchone() == (
0,
)
def test_existing_missing_original_refuses_before_callback(rig):
executor, args, _, _, seen = interrupted(rig)
executor.journal.db.execute("DELETE FROM intents")
with pytest.raises(Refused):
executor.reconcile(*args)
assert not seen
assert (
executor.journal.load("mint-secret:fixture-client", args[2]).last.outcome
is Outcome.UNCERTAIN
)
def test_existing_current_parent_revocation_remains_mandatory(rig):
executor, args, _, _, _ = interrupted(rig)
old = executor.evidence_verifier
def refuse_session(purpose, source, evidence):
return (
False
if purpose.startswith("session-revocation:")
else old(purpose, source, evidence)
)
executor.evidence_verifier = refuse_session
with pytest.raises(Refused):
executor.reconcile(*args)
assert (
executor.journal.load("mint-secret:fixture-client", args[2]).last.outcome
is Outcome.UNCERTAIN
)
def test_existing_intent_survives_actual_distinct_interpreter(rig):
executor, args, calls, old, _ = interrupted(rig)
code = """import json,sys
from pathlib import Path
from warden.case_run import Journal,Invocation
from warden.case_receipt_state import Pins
obj=json.load(sys.stdin);obj['pins']=Pins(**obj['pins']);j=Journal(Path(sys.argv[1]))
with j.locked():
i=j.original_intent('mint-secret:fixture-client',Invocation(**obj),sys.argv[2])
print(json.dumps({'attempt':i.invocation.attempt_id,'operation':i.invocation.operation}))
"""
result = subprocess.run(
[sys.executable, "-B", "-c", code, str(executor.journal.directory), old.source],
input=json.dumps(asdict(args[1])),
text=True,
capture_output=True,
timeout=15,
env={
"PATH": "/usr/bin:/bin",
"PYTHONPATH": str(Path(__file__).parents[1] / "src"),
"PYTHONDONTWRITEBYTECODE": "1",
},
check=True,
)
assert json.loads(result.stdout) == {
"attempt": calls[0].attempt_id,
"operation": "run",
}