added
This commit is contained in:
commit
8313c5c6b5
84 files changed
+4337
No files matched your search
@@ -0,0 +1,131 @@
|
||||
import tempfile
|
||||
import unittest
|
||||
from datetime import UTC, datetime, timedelta
|
||||
from pathlib import Path
|
||||
|
||||
from scheduling_core.ledger import Ledger
|
||||
from scheduling_core.policy import PolicyConfig, PolicyViolation, evaluate_intent
|
||||
from scheduling_core.postmark import BoundMessage, PostmarkAdapter, ProviderDisabled
|
||||
from scheduling_core.mcp_stdio import Adapter
|
||||
from scheduling_core.workflow import SchedulingWorkflow
|
||||
|
||||
NOW = datetime(2030, 12, 31, 16, tzinfo=UTC)
|
||||
CONFIG = PolicyConfig(revision="offline-test", fixed_sender="[email protected]", max_exchange_messages=2)
|
||||
|
||||
|
||||
def raw_intent(**changes):
|
||||
value = {"transaction_id": "tx-1", "requester": "[email protected]", "sender": "[email protected]", "start_at": "2031-01-01T18:00:00Z", "end_at": "2031-01-01T19:00:00Z", "expires_at": "2031-01-02T00:00:00Z", "authentication_evidence_id": "auth-opaque", "availability_evidence_id": "freebusy-opaque"}
|
||||
value.update(changes)
|
||||
return value
|
||||
|
||||
|
||||
class LedgerTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.temp = tempfile.TemporaryDirectory()
|
||||
self.ledger = Ledger(Path(self.temp.name) / "ledger.sqlite3")
|
||||
intent = evaluate_intent(raw_intent(), CONFIG, NOW, [])
|
||||
self.ledger.create_transaction(intent, CONFIG.revision, CONFIG.max_exchange_messages)
|
||||
|
||||
def tearDown(self):
|
||||
self.temp.cleanup()
|
||||
|
||||
def lease(self):
|
||||
return self.ledger.claim("tx-1", 300).lease_token
|
||||
|
||||
def test_invalid_expired_and_buffered_inputs_rejected(self):
|
||||
with self.assertRaises(PolicyViolation):
|
||||
evaluate_intent(raw_intent(expires_at="2030-12-31T15:00:00Z"), CONFIG, NOW, [])
|
||||
with self.assertRaises(PolicyViolation):
|
||||
evaluate_intent(raw_intent(), CONFIG, NOW, [{"start_at": "2031-01-01T17:50:00Z", "end_at": "2031-01-01T18:10:00Z"}])
|
||||
with self.assertRaises(PolicyViolation):
|
||||
evaluate_intent(raw_intent(sender="[email protected]"), CONFIG, NOW, [])
|
||||
|
||||
def test_bound_sender_recipient_cap_and_duplicate_are_enforced(self):
|
||||
lease = self.lease()
|
||||
first = self.ledger.record_postmark_send("tx-1", lease, "send-1", "[email protected]", "[email protected]")
|
||||
same = self.ledger.record_postmark_send("tx-1", lease, "send-1", "[email protected]", "[email protected]")
|
||||
self.assertEqual(first["id"], same["id"])
|
||||
self.ledger.record_postmark_send("tx-1", lease, "send-2", "[email protected]", "[email protected]")
|
||||
with self.assertRaises(ValueError):
|
||||
self.ledger.record_postmark_send("tx-1", lease, "send-3", "[email protected]", "[email protected]")
|
||||
with self.assertRaises(ValueError):
|
||||
self.ledger.record_postmark_send("tx-1", lease, "send-x", "[email protected]", "[email protected]")
|
||||
|
||||
def test_crash_or_timeout_is_reconciliation_not_resend(self):
|
||||
class TimeoutClient:
|
||||
def send(self, **_):
|
||||
raise TimeoutError()
|
||||
adapter = PostmarkAdapter(self.ledger, TimeoutClient())
|
||||
lease = self.lease()
|
||||
self.assertIsNone(adapter.send_bound_message("tx-1", lease, "send-1", "[email protected]", "[email protected]", BoundMessage("Subject", "Body")))
|
||||
self.assertEqual(self.ledger.operations_needing_reconciliation()[0]["operation_key"], "send-1")
|
||||
self.assertIsNone(adapter.send_bound_message("tx-1", lease, "send-1", "[email protected]", "[email protected]", BoundMessage("Subject", "Body")))
|
||||
|
||||
def test_stranded_dispatch_is_never_retried(self):
|
||||
lease = self.lease()
|
||||
self.ledger.record_postmark_send("tx-1", lease, "send-crash", "[email protected]", "[email protected]")
|
||||
self.ledger.transition_operation("tx-1", lease, "send-crash", "dispatching")
|
||||
class Client:
|
||||
def send(self, **_): raise AssertionError("must reconcile, not resend")
|
||||
self.assertIsNone(PostmarkAdapter(self.ledger, Client()).send_bound_message("tx-1", lease, "send-crash", "[email protected]", "[email protected]", BoundMessage("Subject", "Body")))
|
||||
self.assertIn("send-crash", [row["operation_key"] for row in self.ledger.operations_needing_reconciliation()])
|
||||
|
||||
def test_disabled_adapter_never_sends(self):
|
||||
with self.assertRaises(ProviderDisabled):
|
||||
PostmarkAdapter(self.ledger).send_bound_message("tx-1", self.lease(), "send-disabled", "[email protected]", "[email protected]", BoundMessage("Subject", "Body"))
|
||||
self.assertEqual(self.ledger.operations_needing_reconciliation(), [])
|
||||
|
||||
def test_claim_is_exclusive(self):
|
||||
self.assertIsNotNone(self.ledger.claim("tx-1", 30))
|
||||
self.assertIsNone(self.ledger.claim("tx-1", 30))
|
||||
|
||||
def test_mcp_adapter_exposes_only_narrow_tools(self):
|
||||
response = Adapter(self.ledger, CONFIG).handle_request({"jsonrpc": "2.0", "id": 1, "method": "tools/list"})
|
||||
self.assertIn("confirm_booking_availability", {tool["name"] for tool in response["result"]["tools"]})
|
||||
self.assertIn("complete_booking", {tool["name"] for tool in response["result"]["tools"]})
|
||||
|
||||
def test_mcp_rejects_extra_or_untyped_arguments(self):
|
||||
adapter = Adapter(self.ledger, CONFIG)
|
||||
response = adapter.handle_request({"jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": {"name": "claim_transaction", "arguments": {"transaction_id": "tx-1", "lease_seconds": "60"}}})
|
||||
self.assertIn("error", response)
|
||||
response = adapter.handle_request({"jsonrpc": "2.0", "id": 2, "method": "tools/call", "params": {"name": "claim_transaction", "arguments": {"transaction_id": "tx-1", "unexpected": True}}})
|
||||
self.assertIn("error", response)
|
||||
|
||||
def test_mcp_reserves_calendar_and_zoom_without_calling_providers(self):
|
||||
adapter = Adapter(self.ledger, CONFIG)
|
||||
workflow = SchedulingWorkflow(self.ledger)
|
||||
offer = workflow.begin_round("tx-1", ("slot-a",), datetime.now(UTC) + timedelta(hours=1), "thread")
|
||||
workflow.bind_outbound("tx-1", offer["round_number"], "outbound")
|
||||
workflow.accept_selection("tx-1", slot_id="slot-a", transaction_token=offer["transaction_token"], thread_id="thread", in_reply_to="outbound", references=("outbound",))
|
||||
lease=adapter.call("claim_transaction", {"transaction_id":"tx-1"})["lease_token"]
|
||||
with self.assertRaises(ValueError):
|
||||
adapter.call("reserve_calendar_event", {"transaction_id": "tx-1", "lease_token":lease,"operation_key": "calendar-1"})
|
||||
|
||||
def test_mcp_postmark_execution_requires_injected_runtime_client(self):
|
||||
lease = self.lease()
|
||||
arguments = {"transaction_id": "tx-1", "lease_token":lease, "operation_key": "postmark-1", "sender": "[email protected]", "requester": "[email protected]", "purpose": "offer"}
|
||||
disabled = Adapter(self.ledger, CONFIG).call("prepare_postmark_send", arguments)
|
||||
self.assertEqual(disabled["status"], "disabled")
|
||||
self.assertIsNone(self.ledger.operation_for_key("postmark-1"))
|
||||
class Client:
|
||||
def send(self, **kwargs):
|
||||
self.kwargs = kwargs
|
||||
return "postmark-provider-id"
|
||||
workflow = SchedulingWorkflow(self.ledger)
|
||||
workflow.begin_round("tx-1", ({"slot_id":"slot-a", "start_at":"2031-01-01T18:00:00Z", "end_at":"2031-01-01T19:00:00Z"},), datetime.now(UTC) + timedelta(hours=1), "thread")
|
||||
client = Client()
|
||||
result = Adapter(self.ledger, CONFIG, client).call("prepare_postmark_send", arguments)
|
||||
self.assertEqual(result["status"], "accepted")
|
||||
self.assertEqual(result["provider_id"], "postmark-provider-id")
|
||||
self.assertRegex(result["outbound_rfc_message_id"], r"^<sched-[0-9a-f-]+@example\.test>$")
|
||||
self.assertEqual(client.kwargs["recipient"], "[email protected]")
|
||||
|
||||
def test_mcp_rejects_calendar_or_postmark_before_offer_acceptance(self):
|
||||
adapter = Adapter(self.ledger, CONFIG)
|
||||
with self.assertRaises(ValueError):
|
||||
adapter.call("reserve_calendar_event", {"transaction_id": "tx-1", "lease_token":"bad", "operation_key": "calendar-early"})
|
||||
class Client:
|
||||
def send(self, **_): return "unexpected"
|
||||
with self.assertRaises(ValueError):
|
||||
adapter = Adapter(self.ledger, CONFIG, Client())
|
||||
adapter.call("prepare_postmark_send", {"transaction_id":"tx-1","lease_token":self.lease(),"operation_key":"mail-early","sender":"[email protected]","requester":"[email protected]","purpose":"offer","subject":"s","text_body":"b"})
|
||||
@@ -0,0 +1,259 @@
|
||||
import json
|
||||
import tempfile
|
||||
import unittest
|
||||
from datetime import UTC, datetime, timedelta
|
||||
from pathlib import Path
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
from scheduling_core.ledger import Ledger
|
||||
from scheduling_core.mcp_stdio import Adapter
|
||||
from scheduling_core.policy import PolicyConfig
|
||||
|
||||
|
||||
class MockPostmark:
|
||||
def __init__(self):
|
||||
self.calls = []
|
||||
|
||||
def send(self, **kwargs):
|
||||
self.calls.append(kwargs)
|
||||
return f"postmark-{len(self.calls)}"
|
||||
|
||||
|
||||
class McpOnlyLifecycleTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.temp = tempfile.TemporaryDirectory()
|
||||
self.client = MockPostmark()
|
||||
# Four is the minimum viable budget here: offer, requester reply, requester
|
||||
# confirmation, and owner summary. It makes closing-cap exhaustion explicit.
|
||||
self.adapter = Adapter(Ledger(Path(self.temp.name) / "ledger.sqlite3"), PolicyConfig(revision="integration", fixed_sender="[email protected]", owner_email="[email protected]", delivery_alias="[email protected]", max_exchange_messages=4), self.client)
|
||||
local = datetime.now(ZoneInfo("UTC")) + timedelta(days=2)
|
||||
while local.weekday() > 4:
|
||||
local += timedelta(days=1)
|
||||
self.start = local.replace(hour=10, minute=0, second=0, microsecond=0).astimezone(UTC)
|
||||
self.expiry = datetime.now(UTC) + timedelta(hours=70)
|
||||
|
||||
def tearDown(self):
|
||||
self.temp.cleanup()
|
||||
|
||||
def invoke(self, name, arguments):
|
||||
# The public MCP contract has no caller-provided message content. Existing
|
||||
# lifecycle fixtures intentionally use only their transaction metadata.
|
||||
arguments = {key: value for key, value in arguments.items() if key not in {"subject", "text_body"}}
|
||||
if name == "prepare_postmark_send" and arguments.get("purpose") == "clarification":
|
||||
arguments.setdefault("reason", "missing_preference")
|
||||
response = self.adapter.handle_request({"jsonrpc": "2.0", "id": name, "method": "tools/call", "params": {"name": name, "arguments": arguments}})
|
||||
self.assertNotIn("error", response, response)
|
||||
return json.loads(response["result"]["content"][0]["text"])
|
||||
|
||||
def intent(self, number):
|
||||
start = self.start + timedelta(days=number)
|
||||
return {"transaction_id": "mcp-lifecycle", "requester": "[email protected]", "sender": "[email protected]", "start_at": start.isoformat(), "end_at": (start + timedelta(minutes=60)).isoformat(), "expires_at": self.expiry.isoformat(), "authentication_evidence_id": "auth-1", "availability_evidence_id": "availability-offer-1"}
|
||||
|
||||
def create_pending(self):
|
||||
return self.invoke("create_pending_negotiation", {"transaction_id":"mcp-lifecycle", "sender":"[email protected]", "expires_at":self.expiry.isoformat(), "intake_evidence":{"provenance_mode":"received_alias", "account_email":"[email protected]", "message_id":"intake-1", "thread_id":"thread", "label":"Scheduling/Intake", "headers":[{"name":"From", "value":"[email protected]"}, {"name":"To", "value":"[email protected]"}], "forwarded_requester":"[email protected]", "forwarded_recipient":"[email protected]", "authentication_evidence_id":"auth-1", "authenticated_mailbox":True, "intake_label_present":True}})
|
||||
|
||||
def owner_sent_forward_evidence(self):
|
||||
return {"provenance_mode":"owner_sent_forward", "account_email":"[email protected]", "message_id":"forward-gmail-id", "thread_id":"thread", "label":"Scheduling/Intake", "headers":[{"name":"From", "value":"[email protected]"}, {"name":"To", "value":"[email protected]"}, {"name":"Message-ID", "value":"<[email protected]>"}, {"name":"In-Reply-To", "value":"<[email protected]>"}, {"name":"References", "value":"<[email protected]>"}], "forwarded_requester":"[email protected]", "forwarded_recipient":"[email protected]", "authentication_evidence_id":"original-auth-id", "authenticated_mailbox":True, "intake_label_present":True, "original_message_id":"original-gmail-id", "original_thread_id":"thread", "original_rfc_message_id":"<[email protected]>", "original_headers":[{"name":"From", "value":"[email protected]"}, {"name":"To", "value":"[email protected]"}, {"name":"Message-ID", "value":"<[email protected]>"}, {"name":"Authentication-Results", "value":"mx.google.com; dkim=pass [email protected] header.s=20251104 header.b=example; arc=pass (i=1); spf=pass (google.com: domain of [email protected] designates mail.example.test as permitted sender) [email protected]; dmarc=pass (p=NONE sp=QUARANTINE dis=NONE) header.from=gmail.com; dara=pass [email protected]"}], "original_received":True, "original_authentication_evidence_id":"original-auth-id"}
|
||||
|
||||
def reply_evidence(self, rfc_message_id, *, message_id="reply-1", sender="[email protected]", route="[email protected]", references=None):
|
||||
return {"account_email":"[email protected]", "message_id":message_id, "thread_id":"different-reply-thread", "label":"Scheduling/Intake", "headers":[{"name":"From", "value":sender}, {"name":"Delivered-To", "value":route}, {"name":"In-Reply-To", "value":rfc_message_id}, {"name":"References", "value":references if references is not None else "<[email protected]> " + rfc_message_id}], "authenticated_mailbox":True, "intake_label_present":True}
|
||||
|
||||
def prepare_booking(self):
|
||||
self.create_pending()
|
||||
lease = self.invoke("claim_transaction", {"transaction_id": "mcp-lifecycle", "lease_seconds": 300})["lease_token"]
|
||||
slots = [{"slot_id": f"slot-{index}", "intent": self.intent(index)} for index in range(3)]
|
||||
offer = self.invoke("begin_offer_round", {"transaction_id":"mcp-lifecycle", "lease_token":lease, "slots":slots, "busy_intervals":[], "observed_at":datetime.now(UTC).isoformat(), "gmail_thread_id":"thread"})
|
||||
sent = self.invoke("prepare_postmark_send", {"transaction_id":"mcp-lifecycle", "lease_token":lease, "operation_key":"offer-1", "sender":"[email protected]", "requester":"[email protected]", "purpose":"offer", "subject":"Offer", "text_body":"Choose."})
|
||||
self.invoke("accept_offer_selection", {"transaction_id":"mcp-lifecycle", "lease_token":lease, "slot_id":"slot-1", "transaction_token":offer["transaction_token"], "reply_evidence":self.reply_evidence(sent["outbound_rfc_message_id"])})
|
||||
self.invoke("confirm_booking_availability", {"transaction_id":"mcp-lifecycle", "lease_token":lease, "availability_evidence_id":"fresh", "observed_at":datetime.now(UTC).isoformat(), "busy_intervals":[]})
|
||||
self.invoke("reserve_closing_capacity", {"transaction_id":"mcp-lifecycle", "lease_token":lease})
|
||||
return lease
|
||||
|
||||
def test_mcp_decline_replacement_and_clarification_roundtrip(self):
|
||||
self.adapter = Adapter(Ledger(Path(self.temp.name) / "rounds.sqlite3"), PolicyConfig(revision="rounds", fixed_sender="[email protected]", owner_email="[email protected]", delivery_alias="[email protected]", max_exchange_messages=8), self.client)
|
||||
self.create_pending()
|
||||
lease = self.invoke("claim_transaction", {"transaction_id":"mcp-lifecycle"})["lease_token"]
|
||||
clarification = self.invoke("begin_clarification_round", {"transaction_id":"mcp-lifecycle", "lease_token":lease, "gmail_thread_id":"thread"})
|
||||
sent = self.invoke("prepare_postmark_send", {"transaction_id":"mcp-lifecycle", "lease_token":lease, "operation_key":"clarify-1", "sender":"[email protected]", "requester":"[email protected]", "purpose":"clarification", "subject":"Clarify", "text_body":"Please clarify."})
|
||||
self.invoke("record_bound_reply", {"transaction_id":"mcp-lifecycle", "lease_token":lease, "reply_kind":"clarification", "transaction_token":clarification["transaction_token"], "reply_evidence":self.reply_evidence(sent["outbound_rfc_message_id"], message_id="clarify-reply")})
|
||||
replacement = self.invoke("begin_offer_round", {"transaction_id":"mcp-lifecycle", "lease_token":lease, "slots":[{"slot_id":f"replacement-{i}", "intent":self.intent(i)} for i in range(3)], "busy_intervals":[], "observed_at":datetime.now(UTC).isoformat(), "gmail_thread_id":"thread"})
|
||||
replacement_send = self.invoke("prepare_postmark_send", {"transaction_id":"mcp-lifecycle", "lease_token":lease, "operation_key":"offer-replacement", "sender":"[email protected]", "requester":"[email protected]", "purpose":"offer", "subject":"Options", "text_body":"Choose."})
|
||||
self.invoke("record_bound_reply", {"transaction_id":"mcp-lifecycle", "lease_token":lease, "reply_kind":"alternative", "transaction_token":replacement["transaction_token"], "reply_evidence":self.reply_evidence(replacement_send["outbound_rfc_message_id"], message_id="decline-1")})
|
||||
next_round = self.invoke("begin_offer_round", {"transaction_id":"mcp-lifecycle", "lease_token":lease, "slots":[{"slot_id":f"next-{i}", "intent":self.intent(i)} for i in range(3)], "busy_intervals":[], "observed_at":datetime.now(UTC).isoformat(), "gmail_thread_id":"thread"})
|
||||
self.assertEqual(next_round["round_number"], 3)
|
||||
|
||||
def test_owner_sent_forward_requires_exact_authenticated_cross_message_binding(self):
|
||||
evidence = self.owner_sent_forward_evidence()
|
||||
result = self.invoke("create_pending_negotiation", {"transaction_id":"mcp-lifecycle", "sender":"[email protected]", "expires_at":self.expiry.isoformat(), "intake_evidence":evidence})
|
||||
self.assertEqual(result["transaction_id"], "mcp-lifecycle")
|
||||
with self.adapter.ledger._session() as connection:
|
||||
stored = connection.execute("SELECT policy_evidence_json FROM transactions WHERE id='mcp-lifecycle'").fetchone()["policy_evidence_json"]
|
||||
bindings = connection.execute("SELECT COUNT(*) AS count FROM intake_message_bindings WHERE transaction_id='mcp-lifecycle'").fetchone()["count"]
|
||||
self.assertEqual(bindings, 2)
|
||||
self.assertNotIn("forward-gmail-id", stored)
|
||||
self.assertNotIn("original-gmail-id", stored)
|
||||
self.assertNotIn("[email protected]", stored)
|
||||
replay = self.adapter.handle_request({"jsonrpc":"2.0", "id":"replay", "method":"tools/call", "params":{"name":"create_pending_negotiation", "arguments":{"transaction_id":"replayed-intake", "sender":"[email protected]", "expires_at":self.expiry.isoformat(), "intake_evidence":evidence}}})
|
||||
self.assertIn("error", replay)
|
||||
for key, value in (("original_received", False), ("original_thread_id", "different"), ("original_authentication_evidence_id", "different")):
|
||||
bad = {**evidence, key:value}
|
||||
response = self.adapter.handle_request({"jsonrpc":"2.0", "id":key, "method":"tools/call", "params":{"name":"create_pending_negotiation", "arguments":{"transaction_id":"bad-" + key, "sender":"[email protected]", "expires_at":self.expiry.isoformat(), "intake_evidence":bad}}})
|
||||
self.assertIn("error", response)
|
||||
for header_name, replacement in (("In-Reply-To", "<[email protected]>"), ("Authentication-Results", "mx.example.test; dkim=pass; spf=fail; dmarc=pass")):
|
||||
bad = {**evidence, "headers":[{**item, "value":replacement} if item["name"] == header_name else item for item in evidence["headers"]], "original_headers":[{**item, "value":replacement} if item["name"] == header_name else item for item in evidence["original_headers"]]}
|
||||
response = self.adapter.handle_request({"jsonrpc":"2.0", "id":header_name, "method":"tools/call", "params":{"name":"create_pending_negotiation", "arguments":{"transaction_id":"bad-" + header_name, "sender":"[email protected]", "expires_at":self.expiry.isoformat(), "intake_evidence":bad}}})
|
||||
self.assertIn("error", response)
|
||||
for suffix, original_headers in (("duplicate-auth", evidence["original_headers"] + [{"name":"Authentication-Results", "value":"mx.example.test; dkim=pass; spf=pass; dmarc=pass"}]), ("wrong-requester", [{**item, "value":"[email protected]"} if item["name"] == "From" else item for item in evidence["original_headers"]])):
|
||||
bad = {**evidence, "original_headers":original_headers}
|
||||
response = self.adapter.handle_request({"jsonrpc":"2.0", "id":suffix, "method":"tools/call", "params":{"name":"create_pending_negotiation", "arguments":{"transaction_id":"bad-" + suffix, "sender":"[email protected]", "expires_at":self.expiry.isoformat(), "intake_evidence":bad}}})
|
||||
self.assertIn("error", response)
|
||||
auth_variants = {
|
||||
"untrusted-issuer": "mail.example.test; dkim=pass [email protected]; spf=pass [email protected]; dmarc=pass header.from=gmail.com",
|
||||
"pass-substring": "mx.google.com; dkim=passive [email protected]; spf=pass [email protected]; dmarc=pass header.from=gmail.com",
|
||||
"conflicting-result": "mx.google.com; dkim=pass [email protected]; dkim=fail [email protected]; spf=pass [email protected]; dmarc=pass header.from=gmail.com",
|
||||
"wrong-alignment": "mx.google.com; dkim=pass [email protected]; spf=pass [email protected]; dmarc=pass header.from=gmail.com",
|
||||
"dara-only-dkim-identity": "mx.google.com; dkim=pass header.s=20251104; spf=pass [email protected]; dmarc=pass header.from=gmail.com; dara=pass [email protected]",
|
||||
"comment-pass-token": "mx.google.com; dkim=fail (dkim=pass [email protected]); spf=pass [email protected]; dmarc=pass header.from=gmail.com",
|
||||
"comment-only-dkim-pass": "mx.google.com; (dkim=pass [email protected]); spf=pass [email protected]; dmarc=pass header.from=gmail.com",
|
||||
"duplicate-method": "mx.google.com; dkim=pass [email protected]; dkim=pass [email protected]; spf=pass [email protected]; dmarc=pass header.from=gmail.com",
|
||||
}
|
||||
for suffix, value in auth_variants.items():
|
||||
bad = {**evidence, "original_headers":[{**item, "value":value} if item["name"] == "Authentication-Results" else item for item in evidence["original_headers"]]}
|
||||
response = self.adapter.handle_request({"jsonrpc":"2.0", "id":suffix, "method":"tools/call", "params":{"name":"create_pending_negotiation", "arguments":{"transaction_id":"bad-" + suffix, "sender":"[email protected]", "expires_at":self.expiry.isoformat(), "intake_evidence":bad}}})
|
||||
self.assertIn("error", response)
|
||||
|
||||
def test_uncertain_calendar_and_zoom_operations_cannot_be_re_reserved(self):
|
||||
lease = self.prepare_booking()
|
||||
for provider, reserve, key in (("calendar", "reserve_calendar_event", "calendar-crash"), ("zoom", "reserve_zoom_meeting", "zoom-crash")):
|
||||
self.invoke(reserve, {"transaction_id":"mcp-lifecycle", "lease_token":lease, "operation_key":key})
|
||||
self.invoke("record_provider_outcome", {"transaction_id":"mcp-lifecycle", "lease_token":lease, "operation_key":key, "state":"uncertain"})
|
||||
self.assertEqual(self.invoke(reserve, {"transaction_id":"mcp-lifecycle", "lease_token":lease, "operation_key":key})["operation_key"], key)
|
||||
with self.assertRaises(AssertionError):
|
||||
self.invoke(reserve, {"transaction_id":"mcp-lifecycle", "lease_token":lease, "operation_key":key + "-retry"})
|
||||
|
||||
def test_complete_lifecycle_uses_mcp_and_requires_fresh_recheck(self):
|
||||
self.create_pending()
|
||||
lease = self.invoke("claim_transaction", {"transaction_id": "mcp-lifecycle", "lease_seconds": 300})["lease_token"]
|
||||
slots = [{"slot_id": f"slot-{index}", "intent": self.intent(index)} for index in range(3)]
|
||||
offer = self.invoke("begin_offer_round", {"transaction_id": "mcp-lifecycle", "lease_token": lease, "slots": slots, "busy_intervals": [], "observed_at": datetime.now(UTC).isoformat(), "gmail_thread_id": "gmail-thread-1"})
|
||||
sent = self.invoke("prepare_postmark_send", {"transaction_id": "mcp-lifecycle", "lease_token": lease, "operation_key": "offer-1", "sender": "[email protected]", "requester": "[email protected]", "purpose": "offer", "subject": "Choose a time", "text_body": "Choose one slot."})
|
||||
self.invoke("accept_offer_selection", {"transaction_id": "mcp-lifecycle", "lease_token": lease, "slot_id": "slot-1", "transaction_token": offer["transaction_token"], "reply_evidence":self.reply_evidence(sent["outbound_rfc_message_id"], message_id="requester-reply-1")})
|
||||
stale = {"transaction_id": "mcp-lifecycle", "lease_token": lease, "availability_evidence_id": "availability-book-1", "observed_at": (datetime.now(UTC) - timedelta(minutes=6)).isoformat(), "busy_intervals": []}
|
||||
self.assertIn("error", self.adapter.handle_request({"jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": {"name": "confirm_booking_availability", "arguments": stale}}))
|
||||
newly_busy = {**stale, "observed_at": datetime.now(UTC).isoformat(), "busy_intervals": [{"start_at": self.intent(1)["start_at"], "end_at": self.intent(1)["end_at"]}]}
|
||||
self.assertIn("error", self.adapter.handle_request({"jsonrpc": "2.0", "id": 2, "method": "tools/call", "params": {"name": "confirm_booking_availability", "arguments": newly_busy}}))
|
||||
self.invoke("confirm_booking_availability", {**stale, "observed_at": datetime.now(UTC).isoformat()})
|
||||
self.invoke("reserve_closing_capacity", {"transaction_id": "mcp-lifecycle", "lease_token": lease})
|
||||
self.invoke("reserve_calendar_event", {"transaction_id": "mcp-lifecycle", "lease_token": lease, "operation_key": "calendar-1"})
|
||||
self.invoke("reserve_zoom_meeting", {"transaction_id": "mcp-lifecycle", "lease_token": lease, "operation_key": "zoom-1"})
|
||||
# Zoom completion precedes Calendar completion because Calendar must
|
||||
# contain the exact verified join URL.
|
||||
for operation, provider_id in (("zoom-1", "zoom-meeting-1"), ("calendar-1", "calendar-event-1")):
|
||||
self.invoke("record_provider_outcome", {"transaction_id": "mcp-lifecycle", "lease_token": lease, "operation_key": operation, "state": "accepted", "provider_id": provider_id})
|
||||
readback = ({"event_id":"calendar-event-1", "start_time":self.intent(1)["start_at"], "end_time":self.intent(1)["end_at"], "attendees":["[email protected]", "[email protected]"], "status":"confirmed", "visibility":"private", "location":"https://zoom.test/j/zoom-meeting-1", "description":"https://zoom.test/j/zoom-meeting-1", "guests_can_modify":None} if operation == "calendar-1" else {"meeting_id":"zoom-meeting-1", "join_url":"https://zoom.test/j/zoom-meeting-1", "start_time":self.intent(1)["start_at"], "duration_minutes":60, "timezone":"UTC", "host":"[email protected]"})
|
||||
self.invoke("record_provider_outcome", {"transaction_id": "mcp-lifecycle", "lease_token": lease, "operation_key": operation, "state": "completed", "provider_id": provider_id, "provider_readback": readback})
|
||||
self.assertEqual(self.invoke("complete_booking", {"transaction_id": "mcp-lifecycle", "lease_token": lease})["status"], "completed")
|
||||
self.invoke("prepare_postmark_send", {"transaction_id": "mcp-lifecycle", "lease_token": lease, "operation_key": "confirmation-1", "sender": "[email protected]", "requester": "[email protected]", "purpose": "confirmation", "subject": "Confirmed", "text_body": "Your meeting is confirmed."})
|
||||
self.invoke("prepare_postmark_send", {"transaction_id": "mcp-lifecycle", "lease_token": lease, "operation_key": "owner-summary-1", "sender": "[email protected]", "requester": "[email protected]", "purpose": "owner_summary", "subject": "Booked", "text_body": "A meeting was booked."})
|
||||
status = self.invoke("get_transaction_status", {"transaction_id": "mcp-lifecycle"})
|
||||
self.assertEqual((status["state"], status["exchange_count"], len(self.client.calls)), ("completed", 4, 3))
|
||||
self.assertEqual(status["exchange_count"], status["max_exchanges"])
|
||||
self.assertEqual(self.client.calls[-1]["recipient"], "[email protected]")
|
||||
|
||||
def test_closing_messages_are_role_specific_idempotent_and_fenced(self):
|
||||
self.test_complete_lifecycle_uses_mcp_and_requires_fresh_recheck()
|
||||
lease = self.invoke("claim_transaction", {"transaction_id": "mcp-lifecycle", "lease_seconds": 300})
|
||||
self.assertEqual(lease, {})
|
||||
# The first lease remains valid; a second caller cannot use a fabricated token.
|
||||
with self.assertRaises(AssertionError):
|
||||
self.invoke("prepare_postmark_send", {"transaction_id":"mcp-lifecycle","lease_token":"takeover","operation_key":"confirmation-2","sender":"[email protected]","requester":"[email protected]","purpose":"confirmation","subject":"x","text_body":"x"})
|
||||
# Replaying the durable operation key is a restart-safe read, but another closing purpose cannot be duplicated.
|
||||
row = self.invoke("get_transaction_status", {"transaction_id": "mcp-lifecycle"})
|
||||
with self.adapter.ledger._session() as connection:
|
||||
active = connection.execute("SELECT lease_token FROM transactions WHERE id='mcp-lifecycle'").fetchone()["lease_token"]
|
||||
replay = self.invoke("prepare_postmark_send", {"transaction_id":"mcp-lifecycle","lease_token":active,"operation_key":"confirmation-1","sender":"[email protected]","requester":"[email protected]","purpose":"confirmation","subject":"Confirmed","text_body":"Your meeting is confirmed."})
|
||||
self.assertEqual(replay["provider_id"], "postmark-2")
|
||||
with self.assertRaises(AssertionError):
|
||||
self.invoke("prepare_postmark_send", {"transaction_id":"mcp-lifecycle","lease_token":active,"operation_key":"owner-summary-2","sender":"[email protected]","requester":"[email protected]","purpose":"owner_summary","subject":"Again","text_body":"Again"})
|
||||
with self.assertRaises(AssertionError):
|
||||
self.invoke("prepare_postmark_send", {"transaction_id":"mcp-lifecycle","lease_token":active,"operation_key":"wrong-owner","sender":"[email protected]","requester":"[email protected]","purpose":"owner_summary","subject":"Wrong","text_body":"Wrong"})
|
||||
self.assertEqual(row["exchange_count"], 4)
|
||||
|
||||
def test_postmark_rejects_arbitrary_content_and_renders_durable_offer(self):
|
||||
self.create_pending()
|
||||
lease = self.invoke("claim_transaction", {"transaction_id": "mcp-lifecycle"})["lease_token"]
|
||||
offer = self.invoke("begin_offer_round", {"transaction_id":"mcp-lifecycle", "lease_token":lease, "slots":[{"slot_id":f"slot-{i}", "intent":self.intent(i)} for i in range(3)], "busy_intervals":[], "observed_at":datetime.now(UTC).isoformat(), "gmail_thread_id":"thread"})
|
||||
bad = self.adapter.handle_request({"jsonrpc":"2.0", "id":1, "method":"tools/call", "params":{"name":"prepare_postmark_send", "arguments":{"transaction_id":"mcp-lifecycle", "lease_token":lease, "operation_key":"mail", "sender":"[email protected]", "requester":"[email protected]", "purpose":"offer", "subject":"injected", "text_body":"injected"}}})
|
||||
self.assertIn("error", bad)
|
||||
self.invoke("prepare_postmark_send", {"transaction_id":"mcp-lifecycle", "lease_token":lease, "operation_key":"mail", "sender":"[email protected]", "requester":"[email protected]", "purpose":"offer"})
|
||||
self.assertEqual(self.client.calls[-1]["subject"], "Scheduling options")
|
||||
self.assertIn("slot-0", self.client.calls[-1]["text_body"])
|
||||
self.assertEqual(offer["round_number"], 1)
|
||||
|
||||
def test_outbound_rfc_lineage_is_server_generated_restart_safe_and_reply_bound(self):
|
||||
self.create_pending()
|
||||
lease = self.invoke("claim_transaction", {"transaction_id":"mcp-lifecycle", "lease_seconds":300})["lease_token"]
|
||||
self.invoke("begin_offer_round", {"transaction_id":"mcp-lifecycle", "lease_token":lease, "slots":[{"slot_id":f"slot-{i}", "intent":self.intent(i)} for i in range(3)], "busy_intervals":[], "observed_at":datetime.now(UTC).isoformat(), "gmail_thread_id":"intake-thread"})
|
||||
legacy = self.adapter.handle_request({"jsonrpc":"2.0", "id":"legacy", "method":"tools/call", "params":{"name":"get_active_round_binding", "arguments":{"transaction_id":"mcp-lifecycle", "lease_token":lease}}})
|
||||
self.assertIn("error", legacy)
|
||||
sent = self.invoke("prepare_postmark_send", {"transaction_id":"mcp-lifecycle", "lease_token":lease, "operation_key":"offer-rfc", "sender":"[email protected]", "requester":"[email protected]", "purpose":"offer"})
|
||||
binding = self.invoke("get_active_round_binding", {"transaction_id":"mcp-lifecycle", "lease_token":lease})
|
||||
self.assertEqual(binding["outbound_rfc_message_id"], sent["outbound_rfc_message_id"])
|
||||
self.assertNotEqual(binding["outbound_rfc_message_id"], sent["provider_id"])
|
||||
self.assertEqual(self.client.calls[-1]["rfc_message_id"], binding["outbound_rfc_message_id"])
|
||||
self.assertIn("Petra Scheduling", self.client.calls[-1]["text_body"])
|
||||
restarted = Adapter(Ledger(Path(self.temp.name) / "ledger.sqlite3"), self.adapter.policy, self.client)
|
||||
recovered = json.loads(restarted.handle_request({"jsonrpc":"2.0", "id":1, "method":"tools/call", "params":{"name":"get_active_round_binding", "arguments":{"transaction_id":"mcp-lifecycle", "lease_token":lease}}})["result"]["content"][0]["text"])
|
||||
self.assertEqual(recovered, binding)
|
||||
|
||||
def rejected(name, evidence):
|
||||
response = self.adapter.handle_request({"jsonrpc":"2.0", "id":name, "method":"tools/call", "params":{"name":"accept_offer_selection", "arguments":{"transaction_id":"mcp-lifecycle", "lease_token":lease, "slot_id":"slot-1", "transaction_token":binding["transaction_token"], "reply_evidence":evidence}}})
|
||||
self.assertIn("error", response, response)
|
||||
|
||||
rejected("wrong-sender", self.reply_evidence(binding["outbound_rfc_message_id"], sender="[email protected]"))
|
||||
rejected("wrong-route", self.reply_evidence(binding["outbound_rfc_message_id"], route="[email protected]"))
|
||||
rejected("missing-reference", self.reply_evidence(binding["outbound_rfc_message_id"], references="<[email protected]>"))
|
||||
rejected("wrong-rfc", self.reply_evidence("<[email protected]>"))
|
||||
rejected("api-id-as-rfc", self.reply_evidence(sent["provider_id"]))
|
||||
|
||||
accepted = self.invoke("accept_offer_selection", {"transaction_id":"mcp-lifecycle", "lease_token":lease, "slot_id":"slot-1", "transaction_token":binding["transaction_token"], "reply_evidence":self.reply_evidence(binding["outbound_rfc_message_id"], message_id="unique-reply")})
|
||||
self.assertEqual(accepted["slot_id"], "slot-1")
|
||||
with self.adapter.ledger._session() as connection:
|
||||
stored = connection.execute("SELECT message_digest, thread_digest FROM reply_message_bindings").fetchone()
|
||||
self.assertNotIn("unique-reply", stored["message_digest"])
|
||||
self.assertNotIn("different-reply-thread", stored["thread_digest"])
|
||||
|
||||
def test_active_rfc_reply_binding_fails_closed_when_round_expires(self):
|
||||
self.create_pending()
|
||||
lease = self.invoke("claim_transaction", {"transaction_id":"mcp-lifecycle", "lease_seconds":300})["lease_token"]
|
||||
self.invoke("begin_offer_round", {"transaction_id":"mcp-lifecycle", "lease_token":lease, "slots":[{"slot_id":f"slot-{i}", "intent":self.intent(i)} for i in range(3)], "busy_intervals":[], "observed_at":datetime.now(UTC).isoformat(), "gmail_thread_id":"intake-thread"})
|
||||
self.invoke("prepare_postmark_send", {"transaction_id":"mcp-lifecycle", "lease_token":lease, "operation_key":"offer-expired", "sender":"[email protected]", "requester":"[email protected]", "purpose":"offer"})
|
||||
with self.adapter.ledger._session() as connection:
|
||||
connection.execute("UPDATE workflow_rounds SET expires_at=? WHERE transaction_id=?", ((datetime.now(UTC) - timedelta(seconds=1)).isoformat(), "mcp-lifecycle"))
|
||||
response = self.adapter.handle_request({"jsonrpc":"2.0", "id":"expired", "method":"tools/call", "params":{"name":"get_active_round_binding", "arguments":{"transaction_id":"mcp-lifecycle", "lease_token":lease}}})
|
||||
self.assertIn("error", response)
|
||||
|
||||
def test_provider_completion_rejects_mismatches_and_persists_no_pii(self):
|
||||
lease = self.prepare_booking()
|
||||
self.invoke("reserve_zoom_meeting", {"transaction_id":"mcp-lifecycle", "lease_token":lease, "operation_key":"zoom"})
|
||||
self.invoke("reserve_calendar_event", {"transaction_id":"mcp-lifecycle", "lease_token":lease, "operation_key":"calendar"})
|
||||
self.invoke("record_provider_outcome", {"transaction_id":"mcp-lifecycle", "lease_token":lease, "operation_key":"zoom", "state":"accepted", "provider_id":"zoom-1"})
|
||||
zoom = {"meeting_id":"zoom-1", "join_url":"https://zoom.test/j/zoom-1", "start_time":self.intent(1)["start_at"], "duration_minutes":60, "timezone":"UTC", "host":"[email protected]"}
|
||||
def rejected(operation, readback):
|
||||
response = self.adapter.handle_request({"jsonrpc":"2.0", "id":operation, "method":"tools/call", "params":{"name":"record_provider_outcome", "arguments":{"transaction_id":"mcp-lifecycle", "lease_token":lease, "operation_key":operation, "state":"completed", "provider_id":"zoom-1" if operation == "zoom" else "calendar-1", "provider_readback":readback}}})
|
||||
self.assertIn("error", response, response)
|
||||
rejected("zoom", {**zoom, "start_time":self.intent(0)["start_at"]})
|
||||
rejected("zoom", {key:value for key,value in zoom.items() if key != "host"})
|
||||
self.invoke("record_provider_outcome", {"transaction_id":"mcp-lifecycle", "lease_token":lease, "operation_key":"zoom", "state":"completed", "provider_id":"zoom-1", "provider_readback":zoom})
|
||||
self.invoke("record_provider_outcome", {"transaction_id":"mcp-lifecycle", "lease_token":lease, "operation_key":"calendar", "state":"accepted", "provider_id":"calendar-1"})
|
||||
calendar = {"event_id":"calendar-1", "start_time":self.intent(1)["start_at"], "end_time":self.intent(1)["end_at"], "attendees":["[email protected]", "[email protected]"], "status":"confirmed", "visibility":"private", "location":"https://zoom.test/j/zoom-1", "description":"", "guests_can_modify":None}
|
||||
rejected("calendar", {**calendar, "attendees":["[email protected]", "[email protected]"]})
|
||||
rejected("calendar", {**calendar, "visibility":"default"})
|
||||
rejected("calendar", {**calendar, "end_time":self.intent(0)["end_at"]})
|
||||
rejected("calendar", {**calendar, "location":"https://zoom.test/j/a-different-meeting"})
|
||||
rejected("calendar", {key:value for key,value in calendar.items() if key != "location"})
|
||||
self.invoke("record_provider_outcome", {"transaction_id":"mcp-lifecycle", "lease_token":lease, "operation_key":"calendar", "state":"completed", "provider_id":"calendar-1", "provider_readback":calendar})
|
||||
with self.adapter.ledger._session() as connection:
|
||||
stored = connection.execute("SELECT provider_evidence_json FROM provider_operations WHERE operation_key='calendar'").fetchone()["provider_evidence_json"]
|
||||
self.assertNotIn("[email protected]", stored)
|
||||
self.assertNotIn("https://zoom.test", stored)
|
||||
@@ -0,0 +1,65 @@
|
||||
import json
|
||||
import unittest
|
||||
from datetime import UTC, datetime, timedelta
|
||||
from pathlib import Path
|
||||
|
||||
from scheduling_core.gmail_validation import SanitizedGmailMetadata
|
||||
from scheduling_core.orchestration import CalendarEvidence, EvidenceError, ProviderConfirmation, require_confirmations, validate_authenticated_intake, validate_bound_reply, validate_calendar_availability_response
|
||||
from scheduling_core.policy import PolicyConfig, PolicyViolation, evaluate_intent
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
class OrchestrationSimulationTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.happy = json.loads((ROOT / "fixtures" / "orchestration" / "happy-path.json").read_text())
|
||||
self.failures = json.loads((ROOT / "fixtures" / "orchestration" / "failure-cases.json").read_text())
|
||||
self.now = datetime.fromisoformat(self.happy["now"].replace("Z", "+00:00"))
|
||||
self.config = PolicyConfig(revision="simulation", fixed_sender="[email protected]")
|
||||
|
||||
def test_happy_path_is_authenticated_fresh_and_confirmed(self):
|
||||
gmail = self.happy["gmail"]
|
||||
metadata = SanitizedGmailMetadata(gmail["message_id"], gmail["thread_id"], gmail["sender"], gmail["delivered_to"], gmail["label"], authenticated=True, forwarded_requester="[email protected]")
|
||||
validate_authenticated_intake(metadata, authenticated=gmail["authenticated"], expected_sender="[email protected]", route="[email protected]", intake_label="intake")
|
||||
calendar_payload = dict(self.happy["calendar"])
|
||||
calendar_payload["busy_intervals"] = tuple(calendar_payload["busy_intervals"])
|
||||
calendar = CalendarEvidence(**calendar_payload)
|
||||
calendar.require_fresh_after(self.now)
|
||||
checked = evaluate_intent(self.happy["intent"], self.config, self.now, calendar.busy_intervals)
|
||||
confirmations = [ProviderConfirmation(**item) for item in self.happy["confirmations"]]
|
||||
self.assertEqual(require_confirmations(confirmations, checked.transaction_id)["zoom"].provider_id, "zoom-meeting-1")
|
||||
|
||||
def test_fail_closed_on_auth_stale_calendar_or_missing_zoom(self):
|
||||
gmail = self.happy["gmail"]
|
||||
metadata = SanitizedGmailMetadata(gmail["message_id"], gmail["thread_id"], gmail["sender"], gmail["delivered_to"], gmail["label"], authenticated=True, forwarded_requester="[email protected]")
|
||||
with self.assertRaises(EvidenceError):
|
||||
validate_authenticated_intake(metadata, authenticated=self.failures["unauthenticated_gmail"]["authenticated"], expected_sender="[email protected]", route="[email protected]", intake_label="intake")
|
||||
calendar = CalendarEvidence("calendar-1", self.failures["stale_calendar"]["observed_at"], "2031-01-01T18:00:00Z", "2031-01-01T19:00:00Z", ())
|
||||
with self.assertRaises(EvidenceError):
|
||||
calendar.require_fresh_after(self.now)
|
||||
with self.assertRaises(EvidenceError):
|
||||
require_confirmations([ProviderConfirmation(**item) for item in self.failures["missing_zoom_confirmation"]], "simulation-tx")
|
||||
|
||||
def test_reply_requires_authenticated_thread_lineage(self):
|
||||
reply = SanitizedGmailMetadata("reply-1", "thread-1", "[email protected]", "[email protected]", "intake", "outbound-message-1", ("outbound-message-1",), "token", True)
|
||||
self.assertEqual(validate_bound_reply(reply, authenticated=True, bound_requester="[email protected]", route="[email protected]", intake_label="intake", outbound_rfc_message_id="outbound-message-1", transaction_token="token").message_id, "reply-1")
|
||||
with self.assertRaises(EvidenceError):
|
||||
validate_bound_reply(reply, authenticated=False, bound_requester="[email protected]", route="[email protected]", intake_label="intake", outbound_rfc_message_id="outbound-message-1", transaction_token="token")
|
||||
|
||||
def test_canonical_policy_rejections_remain_local_and_deterministic(self):
|
||||
raw = dict(self.happy["intent"])
|
||||
raw["start_at"] = (self.now + timedelta(hours=2)).isoformat()
|
||||
raw["end_at"] = (self.now + timedelta(hours=3)).isoformat()
|
||||
with self.assertRaises(PolicyViolation):
|
||||
evaluate_intent(raw, self.config, self.now, [])
|
||||
|
||||
def test_calendar_response_requires_complete_error_free_coverage(self):
|
||||
busy = validate_calendar_availability_response(requested_calendar_ids=("primary",), requested_start="2031-01-01T18:00:00Z", requested_end="2031-01-01T19:00:00Z", request_started_at=self.now, response_received_at=self.now, calendars=({"calendar_id":"primary", "busy":[], "errors":[]},))
|
||||
self.assertEqual(busy, ())
|
||||
with self.assertRaises(EvidenceError):
|
||||
validate_calendar_availability_response(requested_calendar_ids=("primary",), requested_start="2031-01-01T18:00:00Z", requested_end="2031-01-01T19:00:00Z", request_started_at=self.now, response_received_at=self.now, calendars=({"calendar_id":"primary", "busy":[], "errors":["denied"]},))
|
||||
raw = dict(self.happy["intent"])
|
||||
raw["sender"] = "[email protected]"
|
||||
with self.assertRaises(PolicyViolation):
|
||||
evaluate_intent(raw, self.config, self.now, [])
|
||||
@@ -0,0 +1,90 @@
|
||||
import tempfile
|
||||
import unittest
|
||||
from datetime import UTC, datetime, timedelta
|
||||
from pathlib import Path
|
||||
|
||||
from scheduling_core.gmail_validation import GmailValidationError, SanitizedGmailMetadata, validate_intake, validate_reply_lineage, validate_owner_forward_boundary
|
||||
from scheduling_core.ledger import Ledger, OperationState
|
||||
from scheduling_core.policy import PolicyConfig, PolicyViolation, evaluate_intent, load_policy_config, validate_offer_slots
|
||||
from scheduling_core.postmark import PostmarkHttpsClient, ProviderDisabled
|
||||
|
||||
|
||||
NOW = datetime(2030, 12, 31, 16, tzinfo=UTC)
|
||||
CONFIG = PolicyConfig(revision="test", fixed_sender="[email protected]")
|
||||
|
||||
|
||||
def intent(number="1", **overrides):
|
||||
data = {"transaction_id": f"tx-{number}", "requester": "[email protected]", "sender": "[email protected]", "start_at": f"2031-01-0{number}T18:00:00Z", "end_at": f"2031-01-0{number}T19:00:00Z", "expires_at": "2031-01-02T00:00:00Z", "authentication_evidence_id": "auth-id", "availability_evidence_id": "busy-id"}
|
||||
data.update(overrides)
|
||||
return data
|
||||
|
||||
|
||||
class PolicyAndRecoveryTests(unittest.TestCase):
|
||||
def test_duration_horizon_workweek_and_offer_count(self):
|
||||
with self.assertRaises(PolicyViolation):
|
||||
evaluate_intent(intent(end_at="2031-01-01T19:20:00Z"), CONFIG, NOW, [])
|
||||
with self.assertRaises(PolicyViolation):
|
||||
evaluate_intent(intent(start_at="2031-01-23T18:00:00Z", end_at="2031-01-23T19:00:00Z"), CONFIG, NOW, [])
|
||||
with self.assertRaises(PolicyViolation):
|
||||
validate_offer_slots([intent()], CONFIG, NOW, [])
|
||||
slots = [intent("1"), intent("2"), intent("3")]
|
||||
self.assertEqual(len(validate_offer_slots(slots, CONFIG, NOW, [])), 3)
|
||||
|
||||
def test_dst_offsets_are_evaluated_in_denver_local_work_hours(self):
|
||||
before_spring_forward = datetime(2031, 3, 7, 16, tzinfo=UTC)
|
||||
spring = intent("1", start_at="2031-03-10T15:00:00Z", end_at="2031-03-10T16:00:00Z", expires_at="2031-03-10T15:30:00Z")
|
||||
self.assertEqual(evaluate_intent(spring, CONFIG, before_spring_forward, []).start_at, "2031-03-10T15:00:00Z")
|
||||
before_fall_back = datetime(2031, 10, 31, 16, 30, tzinfo=UTC)
|
||||
fall = intent("2", start_at="2031-11-03T16:00:00Z", end_at="2031-11-03T17:00:00Z", expires_at="2031-11-03T16:20:00Z")
|
||||
self.assertEqual(evaluate_intent(fall, CONFIG, before_fall_back, []).start_at, "2031-11-03T16:00:00Z")
|
||||
|
||||
def test_gmail_metadata_is_bound_without_retaining_headers(self):
|
||||
intake = SanitizedGmailMetadata("m1", "t1", "[email protected]", "[email protected]", "intake", authenticated=True, forwarded_requester="[email protected]")
|
||||
self.assertEqual(validate_intake(intake, "[email protected]", "[email protected]", "intake").message_id, "m1")
|
||||
reply = SanitizedGmailMetadata("m2", "t1", "[email protected]", "[email protected]", "intake", "outbound-1", ("outbound-1",), "token", True)
|
||||
self.assertEqual(validate_reply_lineage(reply, "[email protected]", "[email protected]", "intake", "outbound-1", "token").message_id, "m2")
|
||||
with self.assertRaises(GmailValidationError):
|
||||
validate_reply_lineage(reply, "[email protected]", "[email protected]", "intake", "other", "token")
|
||||
|
||||
def test_owner_forward_boundary_uses_canonical_route_and_provider_context(self):
|
||||
headers = (("From", "[email protected]"), ("To", "[email protected]"))
|
||||
validate_owner_forward_boundary(headers, "[email protected]", "[email protected]", authenticated_mailbox=True, intake_label_present=True)
|
||||
with self.assertRaises(GmailValidationError):
|
||||
validate_owner_forward_boundary(headers, "[email protected]", "[email protected]", authenticated_mailbox=False, intake_label_present=True)
|
||||
|
||||
def test_restart_recovers_expired_lease_and_uncertain_operation(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
path = Path(directory) / "ledger.sqlite3"
|
||||
ledger = Ledger(path)
|
||||
checked = evaluate_intent(intent(), CONFIG, NOW, [])
|
||||
ledger.create_transaction(checked, CONFIG.revision, CONFIG.max_exchange_messages)
|
||||
self.assertIsNotNone(ledger.claim("tx-1", 1, NOW))
|
||||
# Simulate a new process after the lease has elapsed.
|
||||
restarted = Ledger(path)
|
||||
self.assertIsNotNone(restarted.claim("tx-1", 1, NOW + timedelta(seconds=2)))
|
||||
lease = restarted.claim("tx-1", 60, NOW + timedelta(seconds=4)).lease_token
|
||||
restarted.record_postmark_send("tx-1", lease, "op-1", "[email protected]", "[email protected]", NOW + timedelta(seconds=4))
|
||||
restarted.transition_operation("tx-1", lease, "op-1", OperationState.UNCERTAIN)
|
||||
self.assertEqual(restarted.operations_needing_reconciliation()[0]["operation_key"], "op-1")
|
||||
|
||||
def test_existing_postmark_operation_remains_idempotent_after_expiry(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
ledger = Ledger(Path(directory) / "ledger.sqlite3")
|
||||
checked = evaluate_intent(intent(), CONFIG, NOW, [])
|
||||
ledger.create_transaction(checked, CONFIG.revision, CONFIG.max_exchange_messages)
|
||||
lease = ledger.claim("tx-1", 60, NOW).lease_token
|
||||
first = ledger.record_postmark_send("tx-1", lease, "send-1", "[email protected]", "[email protected]", NOW)
|
||||
expired_lease = ledger.claim("tx-1", 60, datetime(2031, 1, 3, tzinfo=UTC)).lease_token
|
||||
same = ledger.record_postmark_send("tx-1", expired_lease, "send-1", "[email protected]", "[email protected]", datetime(2031, 1, 3, tzinfo=UTC))
|
||||
self.assertEqual(first["id"], same["id"])
|
||||
|
||||
def test_https_client_cannot_call_without_explicit_enablement(self):
|
||||
client = PostmarkHttpsClient(lambda: "not-used")
|
||||
with self.assertRaises(ProviderDisabled):
|
||||
client.status("message-id")
|
||||
|
||||
def test_reviewed_policy_file_loads_approved_defaults(self):
|
||||
config = load_policy_config(Path("config/scheduling-policy.json"), "[email protected]")
|
||||
self.assertEqual(config.minimum_notice_minutes, 24 * 60)
|
||||
self.assertEqual(config.offer_count, 3)
|
||||
self.assertTrue(config.guests_can_invite_others)
|
||||
@@ -0,0 +1,68 @@
|
||||
import tempfile
|
||||
import unittest
|
||||
from datetime import UTC, datetime
|
||||
from pathlib import Path
|
||||
|
||||
from scheduling_core.ledger import Ledger
|
||||
from scheduling_core.policy import PolicyConfig, evaluate_intent
|
||||
from scheduling_core.postmark import BoundMessage, PostmarkAdapter
|
||||
from scripts.verify_postmark_readonly import build_readonly_request
|
||||
|
||||
|
||||
class CapturingClient:
|
||||
def __init__(self): self.calls = []
|
||||
def send(self, **kwargs): self.calls.append(kwargs); return "postmark-id"
|
||||
|
||||
|
||||
class PostmarkExecutionTests(unittest.TestCase):
|
||||
def test_owner_delivery_test_is_bound_to_one_sender_recipient_and_exchange(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
ledger = Ledger(Path(directory) / "ledger.sqlite3")
|
||||
transaction_id = ledger.create_authorized_owner_delivery_test(
|
||||
transaction_id="authorized-owner-delivery-test-unit-v1",
|
||||
sender="Petra - Scheduling <[email protected]>",
|
||||
recipient="[email protected]",
|
||||
expires_at=datetime(2031, 1, 1, tzinfo=UTC),
|
||||
)
|
||||
lease = ledger.claim(transaction_id, 60, datetime(2030, 12, 31, tzinfo=UTC)).lease_token
|
||||
first = ledger.record_postmark_send(transaction_id, lease, "test-send", "Petra - Scheduling <[email protected]>", "[email protected]", now=datetime(2030, 12, 31, tzinfo=UTC))
|
||||
self.assertEqual(first["state"], "pending")
|
||||
with self.assertRaises(ValueError):
|
||||
ledger.record_postmark_send(transaction_id, lease, "second-send", "Petra - Scheduling <[email protected]>", "[email protected]", now=datetime(2030, 12, 31, tzinfo=UTC))
|
||||
|
||||
def test_owner_reply_evidence_is_digest_only_and_not_a_transaction(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
ledger = Ledger(Path(directory) / "ledger.sqlite3")
|
||||
ledger.record_owner_transport_evidence(
|
||||
"authorized-owner-delivery-test-gmail-reply-v1",
|
||||
{"message_id": "m", "thread_id": "t", "sender": "[email protected]", "recipient": "[email protected]", "observed_at": "2030-01-01T00:00:00Z"},
|
||||
)
|
||||
with ledger._session() as connection:
|
||||
evidence = connection.execute("SELECT evidence_digest FROM test_evidence").fetchone()
|
||||
transactions = connection.execute("SELECT COUNT(*) AS count FROM transactions").fetchone()
|
||||
self.assertIsNotNone(evidence["evidence_digest"])
|
||||
self.assertEqual(transactions["count"], 0)
|
||||
|
||||
def test_readonly_request_uses_the_documented_server_token_contract(self):
|
||||
request = build_readonly_request("/server", "dummy-token")
|
||||
self.assertEqual(request.full_url, "https://api.postmarkapp.com/server")
|
||||
self.assertEqual(request.get_header("Accept"), "application/json")
|
||||
self.assertEqual(request.get_header("X-postmark-server-token"), "dummy-token")
|
||||
|
||||
def test_bound_execution_forces_message_stream_contract(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
ledger = Ledger(Path(directory) / "ledger.sqlite3")
|
||||
config = PolicyConfig(revision="test", fixed_sender="[email protected]")
|
||||
now = datetime(2030, 12, 31, 16, tzinfo=UTC)
|
||||
intent = evaluate_intent({"transaction_id":"tx","requester":"[email protected]","sender":"[email protected]","start_at":"2031-01-01T18:00:00Z","end_at":"2031-01-01T19:00:00Z","expires_at":"2031-01-02T00:00:00Z","authentication_evidence_id":"a","availability_evidence_id":"b"}, config, now, [])
|
||||
ledger.create_transaction(intent, config.revision, config.max_exchange_messages)
|
||||
client = CapturingClient()
|
||||
lease = ledger.claim("tx", 60).lease_token
|
||||
result = PostmarkAdapter(ledger, client).send_bound_message("tx", lease, "send", "[email protected]", "[email protected]", BoundMessage("Offer", "Select a slot."))
|
||||
self.assertEqual(result, "postmark-id")
|
||||
self.assertEqual(client.calls[0]["reply_to"], "[email protected]")
|
||||
self.assertEqual(client.calls[0]["recipient"], "[email protected]")
|
||||
self.assertRegex(client.calls[0]["rfc_message_id"], r"^<sched-[0-9a-f-]+@example\.test>$")
|
||||
operation = ledger.operation_for_key("send")
|
||||
self.assertEqual(operation["provider_id"], "postmark-id")
|
||||
self.assertEqual(operation["rfc_message_id"], client.calls[0]["rfc_message_id"])
|
||||
@@ -0,0 +1,11 @@
|
||||
import unittest
|
||||
from datetime import UTC,datetime
|
||||
from scheduling_core.policy import PolicyConfig,PolicyViolation
|
||||
from scheduling_core.slotting import compliant_slots
|
||||
class SlotTests(unittest.TestCase):
|
||||
def test_offers_three_default_duration_slots_and_rejects_no_availability(self):
|
||||
c=PolicyConfig(revision='x',fixed_sender='[email protected]'); now=datetime(2030,12,31,16,tzinfo=UTC)
|
||||
slots=compliant_slots(transaction_id='x',requester='[email protected]',sender='[email protected]',authentication_evidence_id='a',availability_evidence_id='b',now=now,busy_intervals=[],config=c)
|
||||
self.assertEqual(len(slots),3)
|
||||
blocked=[{'start_at':'2031-01-01T00:00:00Z','end_at':'2031-01-22T00:00:00Z'}]
|
||||
with self.assertRaises(PolicyViolation): compliant_slots(transaction_id='y',requester='[email protected]',sender='[email protected]',authentication_evidence_id='a',availability_evidence_id='b',now=now,busy_intervals=blocked,config=c)
|
||||
@@ -0,0 +1,28 @@
|
||||
import unittest
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import patch
|
||||
from scheduling_core.mcp_stdio import Adapter
|
||||
|
||||
class SupervisedSendScopeTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.scope = {'transaction_id':'approved-test', 'requester':'[email protected]', 'owner':'[email protected]'}
|
||||
self.policy = SimpleNamespace(owner_email='[email protected]')
|
||||
self.adapter = Adapter(object(), self.policy, object(), supervised_send_scope=self.scope)
|
||||
self.args = {'transaction_id':'approved-test', 'lease_token':'lease', 'operation_key':'operation', 'sender':'[email protected]', 'requester':'[email protected]', 'purpose':'offer'}
|
||||
|
||||
def test_other_transaction_and_recipient_rejected_before_ledger_or_transport(self):
|
||||
for change in ({'transaction_id':'other'}, {'requester':'[email protected]'}, {'purpose':'owner_summary'}):
|
||||
with self.subTest(change=change), patch('scheduling_core.mcp_stdio.SchedulingWorkflow', side_effect=AssertionError('Ledger must not be accessed')):
|
||||
with self.assertRaisesRegex(ValueError, 'outside the approved'):
|
||||
self.adapter.call('prepare_postmark_send', {**self.args, **change})
|
||||
|
||||
def test_approved_requester_and_owner_continue_to_existing_safeguards(self):
|
||||
for change in ({}, {'purpose':'confirmation'}, {'purpose':'owner_summary','requester':'[email protected]'}):
|
||||
with self.subTest(change=change), patch('scheduling_core.mcp_stdio.SchedulingWorkflow', side_effect=RuntimeError('Existing safeguards reached')):
|
||||
with self.assertRaisesRegex(RuntimeError, 'Existing safeguards reached'):
|
||||
self.adapter.call('prepare_postmark_send', {**self.args, **change})
|
||||
|
||||
def test_incomplete_scope_and_different_owner_fail_closed(self):
|
||||
for scope in ({'transaction_id':'approved-test'}, {**self.scope,'owner':'[email protected]'}):
|
||||
with self.subTest(scope=scope), self.assertRaises(ValueError):
|
||||
Adapter(object(), self.policy, object(), supervised_send_scope=scope)
|
||||
@@ -0,0 +1,67 @@
|
||||
import tempfile
|
||||
import unittest
|
||||
from datetime import UTC, datetime, timedelta
|
||||
from pathlib import Path
|
||||
|
||||
from scheduling_core.ledger import Ledger, OperationState
|
||||
from scheduling_core.policy import PolicyConfig, evaluate_intent
|
||||
from scheduling_core.workflow import SchedulingWorkflow, WorkflowError
|
||||
|
||||
|
||||
NOW = datetime(2030, 12, 31, 16, tzinfo=UTC)
|
||||
CONFIG = PolicyConfig(revision="test", fixed_sender="[email protected]", max_exchange_messages=8)
|
||||
|
||||
|
||||
def intent():
|
||||
return evaluate_intent({"transaction_id":"workflow-tx","requester":"[email protected]","sender":"[email protected]","start_at":"2031-01-01T18:00:00Z","end_at":"2031-01-01T19:00:00Z","expires_at":"2031-01-02T00:00:00Z","authentication_evidence_id":"auth","availability_evidence_id":"calendar"}, CONFIG, NOW, [])
|
||||
|
||||
|
||||
class WorkflowTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.temp = tempfile.TemporaryDirectory()
|
||||
self.ledger = Ledger(Path(self.temp.name) / "ledger.sqlite3")
|
||||
self.ledger.create_transaction(intent(), CONFIG.revision, CONFIG.max_exchange_messages, owner="[email protected]")
|
||||
self.workflow = SchedulingWorkflow(self.ledger)
|
||||
|
||||
def tearDown(self): self.temp.cleanup()
|
||||
|
||||
def test_offer_selection_booking_and_confirmation(self):
|
||||
slots = tuple({"slot_id": name, "start_at":"2031-01-01T18:00:00Z", "end_at":"2031-01-01T19:00:00Z", "expires_at":"2031-01-02T00:00:00Z", "availability_evidence_id":"calendar", "authentication_evidence_id":"auth"} for name in ("slot-a", "slot-b", "slot-c"))
|
||||
round_data = self.workflow.begin_round("workflow-tx", slots, NOW + timedelta(hours=2), "gmail-thread", NOW)
|
||||
self.workflow.bind_outbound("workflow-tx", round_data["round_number"], "postmark-outbound")
|
||||
self.assertEqual(self.workflow.accept_selection("workflow-tx", slot_id="slot-b", transaction_token=round_data["transaction_token"], thread_id="gmail-thread", in_reply_to="postmark-outbound", references=("postmark-outbound",), now=NOW), "slot-b")
|
||||
lease = self.ledger.claim("workflow-tx", 60, NOW).lease_token
|
||||
self.ledger.record_booking_evidence("workflow-tx", lease, {"availability_evidence_id":"fresh", "observed_at":NOW.isoformat(), "slot_id":"slot-b", "start_at":"2031-01-01T18:00:00Z", "end_at":"2031-01-01T19:00:00Z"}, NOW)
|
||||
self.ledger.reserve_closing_capacity("workflow-tx", lease, NOW)
|
||||
self.ledger.reserve_booking_operation("workflow-tx", lease, "calendar-op", "calendar")
|
||||
self.ledger.reserve_booking_operation("workflow-tx", lease, "zoom-op", "zoom")
|
||||
self.ledger.transition_operation("workflow-tx", lease, "zoom-op", OperationState.ACCEPTED, "zoom-id")
|
||||
import hashlib
|
||||
digest = lambda value: hashlib.sha256(value.strip().casefold().encode()).hexdigest()
|
||||
self.ledger.transition_operation("workflow-tx", lease, "zoom-op", OperationState.COMPLETED, "zoom-id", {"meeting_id":"zoom-id", "join_url_digest":digest("https://zoom.test/j/zoom-id"), "start_time":"2031-01-01T18:00:00+00:00", "duration_minutes":60, "timezone":"UTC", "host_fingerprint":digest("[email protected]")})
|
||||
self.ledger.transition_operation("workflow-tx", lease, "calendar-op", OperationState.ACCEPTED, "calendar-id")
|
||||
self.ledger.transition_operation("workflow-tx", lease, "calendar-op", OperationState.COMPLETED, "calendar-id", {"event_id":"calendar-id", "start_time":"2031-01-01T18:00:00Z", "end_time":"2031-01-01T19:00:00Z", "attendee_fingerprints":sorted([digest("[email protected]"), digest("[email protected]")]), "status":"confirmed", "visibility":"private", "join_url_candidates":[digest("https://zoom.test/j/zoom-id")], "guests_can_modify":None})
|
||||
self.workflow.require_booking_confirmed("workflow-tx")
|
||||
self.assertEqual(self.ledger.transaction_status("workflow-tx")["state"], "completed")
|
||||
|
||||
def test_pending_negotiation_uses_default_duration_then_offers_before_selection(self):
|
||||
ledger = Ledger(Path(self.temp.name) / "negotiation.sqlite3")
|
||||
ledger.create_pending_negotiation(transaction_id="negotiation", requester="[email protected]", sender="[email protected]", owner="[email protected]", authentication_evidence_id="auth", gmail_thread_id="thread", policy_revision="test", default_duration_minutes=60, max_exchanges=8, expires_at=NOW + timedelta(hours=72))
|
||||
workflow = SchedulingWorkflow(ledger)
|
||||
offer = workflow.begin_round("negotiation", ("slot-1", "slot-2", "slot-3"), NOW + timedelta(hours=72), "thread", NOW)
|
||||
self.assertEqual(offer["slot_ids"], ("slot-1", "slot-2", "slot-3"))
|
||||
self.assertEqual(ledger.transaction_status("negotiation")["state"], "awaiting_requester")
|
||||
|
||||
def test_rejects_unbound_duplicate_or_expired_selection(self):
|
||||
round_data = self.workflow.begin_round("workflow-tx", ("slot-a",), NOW + timedelta(hours=1), "thread", NOW)
|
||||
self.workflow.bind_outbound("workflow-tx", 1, "outbound")
|
||||
with self.assertRaises(WorkflowError):
|
||||
self.workflow.accept_selection("workflow-tx", slot_id="other", transaction_token=round_data["transaction_token"], thread_id="thread", in_reply_to="outbound", references=("outbound",), now=NOW)
|
||||
self.workflow.accept_selection("workflow-tx", slot_id="slot-a", transaction_token=round_data["transaction_token"], thread_id="thread", in_reply_to="outbound", references=("outbound",), now=NOW)
|
||||
with self.assertRaises(WorkflowError):
|
||||
self.workflow.accept_selection("workflow-tx", slot_id="slot-a", transaction_token=round_data["transaction_token"], thread_id="thread", in_reply_to="outbound", references=("outbound",), now=NOW)
|
||||
self.ledger.create_transaction(evaluate_intent({"transaction_id":"expired-tx","requester":"[email protected]","sender":"[email protected]","start_at":"2031-01-01T18:00:00Z","end_at":"2031-01-01T19:00:00Z","expires_at":"2031-01-02T00:00:00Z","authentication_evidence_id":"auth","availability_evidence_id":"calendar"}, CONFIG, NOW, []), CONFIG.revision, CONFIG.max_exchange_messages)
|
||||
expired = self.workflow.begin_round("expired-tx", ("slot-a",), NOW + timedelta(minutes=1), "thread", NOW)
|
||||
self.workflow.bind_outbound("expired-tx", 1, "outbound")
|
||||
with self.assertRaises(WorkflowError):
|
||||
self.workflow.accept_selection("expired-tx", slot_id="slot-a", transaction_token=expired["transaction_token"], thread_id="thread", in_reply_to="outbound", references=("outbound",), now=NOW + timedelta(minutes=2))
|
||||
Reference in new issue
Block a user