Implement P05 checked services and safe selected delivery recovery

Assistant: codex
Assistant-Model: gpt-6-astra
Assistant-Session: 01a092fe-13b1-7f12-ac74-7d258af4d79c
This commit is contained in:
tegwick 2026-09-13 22:11:49 +02:00
parent 21eebffc56
commit 0fcfddc342
5 changed files with 459 additions and 67 deletions

View file

@ -51,7 +51,9 @@ def invoke(app, payload, token="opaque", key=None, path="/v1/send"):
"HTTP_AUTHORIZATION": f"Bearer {token}",
}
if path == "/v1/send":
env["HTTP_IDEMPOTENCY_KEY"] = key if key is not None else payload.get("id", "evt-1")
env["HTTP_IDEMPOTENCY_KEY"] = (
key if key is not None else payload.get("id", "evt-1")
)
body = b"".join(app(env, lambda s, h: result.update(status=s)))
return result["status"], json.loads(body)
@ -59,7 +61,10 @@ def invoke(app, payload, token="opaque", key=None, path="/v1/send"):
def test_sends_fixed_template_once(tmp_path):
provider = Provider()
app = TransactionalApplication(
SQLiteDeliveryStore(str(tmp_path / "mail.db")), provider, "opaque", "https://users.example"
SQLiteDeliveryStore(str(tmp_path / "mail.db")),
provider,
"opaque",
"https://users.example",
)
status, body = invoke(app, event())
assert status.startswith("202")
@ -71,7 +76,10 @@ def test_sends_fixed_template_once(tmp_path):
def test_rejects_auth_recipient_template_and_key(tmp_path):
app = TransactionalApplication(
SQLiteDeliveryStore(str(tmp_path / "mail.db")), Provider(), "opaque", "https://users.example"
SQLiteDeliveryStore(str(tmp_path / "mail.db")),
Provider(),
"opaque",
"https://users.example",
)
assert invoke(app, event(), token="bad")[0].startswith("401")
bad = event()
@ -86,7 +94,10 @@ def test_rejects_auth_recipient_template_and_key(tmp_path):
def test_resend_is_separate_event_and_sends_again(tmp_path):
provider = Provider()
app = TransactionalApplication(
SQLiteDeliveryStore(str(tmp_path / "mail.db")), provider, "opaque", "https://users.example"
SQLiteDeliveryStore(str(tmp_path / "mail.db")),
provider,
"opaque",
"https://users.example",
)
assert invoke(app, event("evt-1", "family_member.invited"))[0].startswith("202")
status, body = invoke(app, event("evt-2", "family_invitation.resent"))
@ -141,7 +152,7 @@ def test_smtp_provider_maps_recipient_refused_to_permanent():
def __exit__(self, *a):
return False
def starttls(self):
def starttls(self, *, context=None):
return None
def login(self, *a):
@ -251,7 +262,9 @@ def test_registration_cancellation_is_single_use_and_prevents_verification(tmp_p
"wsgi.input": io.BytesIO(payload),
"HTTP_AUTHORIZATION": "Bearer opaque",
}
canceled = json.loads(b"".join(app(cancel_env, lambda s, h: result.update(status=s))))
canceled = json.loads(
b"".join(app(cancel_env, lambda s, h: result.update(status=s)))
)
assert canceled["purpose"] == "public-registration-cancel"
assert canceled["authorization"] is False
consume_env = {
@ -261,7 +274,9 @@ def test_registration_cancellation_is_single_use_and_prevents_verification(tmp_p
"wsgi.input": io.BytesIO(payload),
"HTTP_AUTHORIZATION": "Bearer opaque",
}
rejected = json.loads(b"".join(app(consume_env, lambda s, h: result.update(status=s))))
rejected = json.loads(
b"".join(app(consume_env, lambda s, h: result.update(status=s)))
)
assert rejected["error"] == "verification_invalid"
cancel_env["wsgi.input"] = io.BytesIO(payload)
replay = json.loads(b"".join(app(cancel_env, lambda s, h: result.update(status=s))))
@ -272,10 +287,15 @@ def test_mailbox_evidence_is_not_authorization(tmp_path):
"""Provider acceptance and mailbox challenge never grant user-engine authority."""
provider = Provider()
app = TransactionalApplication(
SQLiteDeliveryStore(str(tmp_path / "mail.db")), provider, "opaque", "https://users.example"
SQLiteDeliveryStore(str(tmp_path / "mail.db")),
provider,
"opaque",
"https://users.example",
)
_, accepted = invoke(app, event())
assert accepted.get("authorization") is None or accepted.get("authorization") is False
assert (
accepted.get("authorization") is None or accepted.get("authorization") is False
)
assert accepted["evidence_ceiling"] == "provider_accepted"
# Ceiling is explicit; user-engine must not elevate this to authz.
assert "authorized" not in accepted
@ -299,7 +319,8 @@ class RecordingSMTP:
def __exit__(self, *exc):
return False
def starttls(self):
def starttls(self, *, context=None):
assert context.check_hostname
self.starttls_calls += 1
def login(self, username, password):
@ -312,7 +333,9 @@ class RecordingSMTP:
def test_smtp_provider_defaults_to_starttls(monkeypatch):
monkeypatch.setattr(smtplib, "SMTP", RecordingSMTP)
RecordingSMTP.instances = []
provider = SMTPProvider("smtp.example.com", 587, "user", "pass", "noreply@example.com")
provider = SMTPProvider(
"smtp.example.com", 587, "user", "pass", "noreply@example.com"
)
assert provider.security == "starttls"
provider.send("person@example.test", "Subject", "body")
@ -322,7 +345,9 @@ def test_smtp_provider_defaults_to_starttls(monkeypatch):
def test_plaintext_security_skips_starttls_on_loopback(monkeypatch):
monkeypatch.setattr(smtplib, "SMTP", RecordingSMTP)
RecordingSMTP.instances = []
provider = SMTPProvider("127.0.0.1", 3025, "user", "pass", "noreply@example.com", security="plaintext")
provider = SMTPProvider(
"127.0.0.1", 3025, "user", "pass", "noreply@example.com", security="plaintext"
)
provider.send("person@example.test", "Subject", "body")
smtp = RecordingSMTP.instances[0]
@ -331,17 +356,142 @@ def test_plaintext_security_skips_starttls_on_loopback(monkeypatch):
assert len(smtp.sent) == 1
@pytest.mark.parametrize("host", ["127.0.0.1", "127.0.1.1", "::1", "[::1]", "localhost", "LOCALHOST"])
@pytest.mark.parametrize(
"host", ["127.0.0.1", "127.0.1.1", "::1", "[::1]", "localhost", "LOCALHOST"]
)
def test_plaintext_security_is_allowed_for_loopback_hosts(host):
assert SMTPProvider(host, 3025, "user", "pass", "noreply@example.com", security="plaintext")
assert SMTPProvider(
host, 3025, "user", "pass", "noreply@example.com", security="plaintext"
)
@pytest.mark.parametrize("host", ["smtp.example.com", "10.0.0.5", "::ffff:10.0.0.5", "", "localhost.example.com"])
@pytest.mark.parametrize(
"host",
["smtp.example.com", "10.0.0.5", "::ffff:10.0.0.5", "", "localhost.example.com"],
)
def test_plaintext_security_is_refused_for_non_loopback_hosts(host):
with pytest.raises(ValueError, match="loopback"):
SMTPProvider(host, 3025, "user", "pass", "noreply@example.com", security="plaintext")
SMTPProvider(
host, 3025, "user", "pass", "noreply@example.com", security="plaintext"
)
def test_unsupported_security_mode_is_refused():
with pytest.raises(ValueError, match="security mode"):
SMTPProvider("127.0.0.1", 3025, "user", "pass", "noreply@example.com", security="none")
SMTPProvider(
"127.0.0.1", 3025, "user", "pass", "noreply@example.com", security="none"
)
def test_status_authenticates_without_sending_and_redacts_errors(tmp_path):
class Diagnostic(Provider):
def check(self):
pass
provider = Diagnostic()
app = TransactionalApplication(
SQLiteDeliveryStore(str(tmp_path / "status.db")),
provider,
"opaque",
"https://users.example",
)
assert invoke(app, {}, path="/v1/status", token="bad")[0].startswith("401")
status, body = invoke(app, {}, path="/v1/status")
assert body["checks"] == {"database": "ok", "smtp_authentication": "ok"}
assert body["message_sent"] is False and provider.calls == []
def unavailable():
raise RuntimeError("private-smtp-password")
provider.check = unavailable
app._status_cache = None
body = invoke(app, {}, path="/v1/status")[1]
assert body["checks"][
"smtp_authentication"
] == "failed" and "private-smtp" not in json.dumps(body)
def test_lost_post_send_record_never_resends_after_restart(tmp_path):
path = str(tmp_path / "lost.db")
store = SQLiteDeliveryStore(path)
provider = Provider()
app = TransactionalApplication(store, provider, "opaque", "https://users.example")
def failed_write(*args):
raise RuntimeError("private-db-error")
store.record = failed_write
assert invoke(app, event())[1]["error"] == "delivery_outcome_unknown"
app = TransactionalApplication(
SQLiteDeliveryStore(path), provider, "opaque", "https://users.example"
)
assert invoke(app, event())[1]["error"] == "delivery_outcome_unknown"
assert len(provider.calls) == 1
assert (
invoke(app, {"event_id": "evt-1"}, path="/v1/delivery-status")[1]["state"]
== "unknown"
)
def test_definitive_failure_retries_but_changed_payload_is_rejected(tmp_path):
provider = FailingProvider(ProviderError("temporary_deferral", retryable=True))
app = TransactionalApplication(
SQLiteDeliveryStore(str(tmp_path / "retry.db")),
provider,
"opaque",
"https://users.example",
)
assert invoke(app, event())[0].startswith("503")
app.provider = Provider()
assert invoke(app, event())[0].startswith("202")
assert (
invoke(app, event(email="different@example.test"))[1]["error"]
== "idempotency_payload_mismatch"
)
assert len(app.provider.calls) == 1
def test_disconnect_after_smtp_acceptance_never_releases_reservation(
tmp_path, monkeypatch
):
import smtplib
class SMTP:
sends = 0
def __init__(self, *args, **kwargs):
pass
def __enter__(self):
return self
def __exit__(self, *args):
raise smtplib.SMTPResponseException(550, b"private quit failure")
def login(self, *args):
pass
def send_message(self, message):
self.__class__.sends += 1
monkeypatch.setattr("email_connect.transactional.smtplib.SMTP", SMTP)
from email_connect.transactional import SMTPProvider
app = TransactionalApplication(
SQLiteDeliveryStore(str(tmp_path / "quit.db")),
SMTPProvider(
"127.0.0.1",
3025,
"fixture",
"fixture",
"from@example.test",
security="plaintext",
),
"opaque",
"https://users.example",
)
for _ in range(2):
status, body = invoke(app, event())
assert body["error"] == "delivery_outcome_unknown"
assert "private" not in str(body)
assert SMTP.sends == 1