File size: 19,662 Bytes
7f8e190 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 | """Structured text-only mail rendering and safe business outbox."""
from __future__ import annotations
import hashlib
import html
import json
import re
import secrets
import sqlite3
import time
from string import Template
from typing import Any, Mapping
from .database import SiteDatabaseLifecycle, utc_now
from .errors import MailError
from .runtime import RuntimeConfig
EMAIL_RE = re.compile(r"^[^@\s]{1,128}@[^@\s]{1,190}$")
IDEMPOTENCY_RE = re.compile(r"^[A-Za-z0-9._:-]{8,200}$")
ERROR_CATEGORIES = frozenset(
{
"configuration",
"provider-auth",
"provider-rate-limit",
"provider-rejected",
"network",
"unknown",
}
)
MAX_DELIVERY_ATTEMPTS = 3
CLAIM_TOKEN_RE = re.compile(r"^[A-Za-z0-9_-]{20,200}$")
def _recipient_digest(recipient: str) -> tuple[str, str]:
if (
not isinstance(recipient, str)
or recipient != recipient.strip()
or len(recipient) > 320
or not EMAIL_RE.fullmatch(recipient)
):
raise MailError("recipient must be a valid bounded email address")
normalized = recipient.casefold()
return normalized, hashlib.sha256(normalized.encode("utf-8")).hexdigest()
def _variables(
template: Mapping[str, Any], variables: Mapping[str, Any]
) -> dict[str, str]:
if not isinstance(variables, Mapping):
raise MailError("mail variables must be an object")
required = list(template["required_variables"])
if set(variables) != set(required):
raise MailError("mail variables do not match the frozen template contract")
normalized: dict[str, str] = {}
for key in required:
value = variables[key]
if not isinstance(value, (str, int)) or isinstance(value, bool):
raise MailError(f"mail variable {key!r} must be text or integer")
text = str(value)
if not text or len(text) > 1000 or "\x00" in text or "\r" in text:
raise MailError(f"mail variable {key!r} is invalid")
normalized[key] = text
return normalized
def _render_field(value: str, variables: Mapping[str, str]) -> str:
try:
return Template(value).substitute(variables)
except (KeyError, ValueError) as exc:
raise MailError("mail template placeholders are invalid") from exc
class SiteMail:
"""Render branded mail and persist only non-secret template snapshots."""
def __init__(self, runtime: RuntimeConfig, lifecycle: SiteDatabaseLifecycle) -> None:
self.runtime = runtime
self.lifecycle = lifecycle
def _caller_connection(
self, connection: sqlite3.Connection
) -> sqlite3.Connection:
if (
not isinstance(connection, sqlite3.Connection)
or not connection.in_transaction
):
raise MailError(
"caller-supplied mail connection must have an active transaction"
)
self.lifecycle._assert_binding(connection)
return connection
def issue(
self,
purpose: str,
recipient: str,
variables: Mapping[str, Any],
) -> dict[str, Any]:
templates = self.runtime.mail["purposes"]
if purpose not in templates:
raise MailError("mail purpose is not enabled for this site")
template = templates[purpose]
normalized_recipient, _ = _recipient_digest(recipient)
normalized_variables = _variables(template, variables)
rendered = {
field: _render_field(template[field], normalized_variables)
for field in ("subject", "lead", "body", "expiry", "footer")
}
text = "\n\n".join(
rendered[field] for field in ("lead", "body", "expiry", "footer")
)
html_body = "".join(
f"<p>{html.escape(rendered[field])}</p>"
for field in ("lead", "body", "expiry", "footer")
)
return {
"site_id": self.runtime.site_id,
"purpose": purpose,
"template_id": template["template_id"],
"sender_display_name": self.runtime.mail["sender"]["display_name"],
"sender_address_env": self.runtime.mail["sender"]["address_env"],
"recipient": normalized_recipient,
"subject": rendered["subject"],
"text": text,
"html": html_body,
"contains_secret_variables": bool(template["secret_variables"]),
}
def enqueue(
self,
purpose: str,
recipient: str,
variables: Mapping[str, Any],
*,
idempotency_key: str,
simulation: bool,
connection: sqlite3.Connection | None = None,
) -> dict[str, Any]:
templates = self.runtime.mail["purposes"]
if purpose not in templates:
raise MailError("mail purpose is not enabled for this site")
template = templates[purpose]
normalized_variables = _variables(template, variables)
if template["secret_variables"]:
raise MailError(
"secret-bearing verification mail cannot be persisted; issue a new code after a failed delivery"
)
_, recipient_digest = _recipient_digest(recipient)
if not isinstance(idempotency_key, str) or not IDEMPOTENCY_RE.fullmatch(
idempotency_key
):
raise MailError("mail idempotency_key is invalid")
now = utc_now()
status = "LOCAL_SIMULATION" if simulation else "PENDING"
mail_id = f"mail_{secrets.token_urlsafe(18)}"
def execute(active: sqlite3.Connection) -> dict[str, Any]:
self.lifecycle._assert_binding(active)
existing = active.execute(
"SELECT * FROM websitebench_mail_jobs "
"WHERE site_id=? AND purpose=? AND idempotency_key=?",
(self.runtime.site_id, purpose, idempotency_key),
).fetchone()
snapshot = json.dumps(
normalized_variables,
ensure_ascii=False,
sort_keys=True,
separators=(",", ":"),
)
if existing is not None:
if (
existing["template_id"] != template["template_id"]
or existing["recipient_digest"] != recipient_digest
or existing["variables_json"] != snapshot
or bool(existing["is_simulation"]) is not simulation
):
raise MailError("mail idempotency key conflicts with immutable facts")
return self._public_job(existing)
active.execute(
"INSERT INTO websitebench_mail_jobs("
"mail_id,site_id,purpose,template_id,recipient,recipient_digest,"
"variables_json,"
"status,is_simulation,idempotency_key,created_at,updated_at"
") VALUES (?,?,?,?,?,?,?,?,?,?,?,?)",
(
mail_id,
self.runtime.site_id,
purpose,
template["template_id"],
recipient.casefold(),
recipient_digest,
snapshot,
status,
int(simulation),
idempotency_key,
now,
now,
),
)
row = active.execute(
"SELECT * FROM websitebench_mail_jobs WHERE mail_id=?", (mail_id,)
).fetchone()
return self._public_job(row)
if connection is not None:
return execute(self._caller_connection(connection))
with self.lifecycle.connection(transaction=True) as active:
return execute(active)
def claim_pending(
self,
*,
mail_id: str | None = None,
now: int | None = None,
connection: sqlite3.Connection | None = None,
) -> dict[str, Any] | None:
"""Atomically claim one replayable, non-secret mail job."""
current_time = int(time.time()) if now is None else now
if (
isinstance(current_time, bool)
or not isinstance(current_time, int)
or current_time < 0
):
raise MailError("mail claim time is invalid")
if mail_id is not None and (
not isinstance(mail_id, str) or not mail_id.startswith("mail_")
):
raise MailError("mail id is invalid")
claim_token = secrets.token_urlsafe(24)
def execute(active: sqlite3.Connection) -> dict[str, Any] | None:
self.lifecycle._assert_binding(active)
parameters: list[Any] = [
self.runtime.site_id,
current_time,
MAX_DELIVERY_ATTEMPTS,
]
mail_clause = ""
if mail_id is not None:
mail_clause = " AND mail_id=?"
parameters.append(mail_id)
row = active.execute(
"SELECT * FROM websitebench_mail_jobs "
"WHERE site_id=? AND status='PENDING' AND claim_token IS NULL "
"AND next_attempt_at<=? AND delivery_attempts<? "
"AND recipient<>''"
f"{mail_clause} ORDER BY created_at,mail_id LIMIT 1",
parameters,
).fetchone()
if row is None:
return None
try:
variables = json.loads(str(row["variables_json"]))
except (TypeError, json.JSONDecodeError) as exc:
raise MailError("mail job variables are invalid") from exc
if not isinstance(variables, Mapping):
raise MailError("mail job variables are invalid")
delivery = self._delivery_envelope(row, variables)
message = self.issue(
str(row["purpose"]),
str(row["recipient"]),
variables,
)
changed = active.execute(
"UPDATE websitebench_mail_jobs SET claim_token=?,claimed_at=?,"
"delivery_attempts=delivery_attempts+1,updated_at=? "
"WHERE site_id=? AND mail_id=? AND status='PENDING' "
"AND claim_token IS NULL AND delivery_attempts=?",
(
claim_token,
current_time,
utc_now(),
self.runtime.site_id,
row["mail_id"],
row["delivery_attempts"],
),
).rowcount
if changed != 1:
return None
claimed = active.execute(
"SELECT * FROM websitebench_mail_jobs WHERE site_id=? AND mail_id=?",
(self.runtime.site_id, row["mail_id"]),
).fetchone()
return {
**self._public_job(claimed),
"claim_token": claim_token,
# ``message`` is retained for existing local inbox consumers.
# Effects transports must use the structured ``delivery`` envelope
# below, never caller-rendered HTML/text.
"message": message,
"delivery": delivery,
}
if connection is not None:
return execute(self._caller_connection(connection))
with self.lifecycle.connection(transaction=True) as active:
return execute(active)
def _delivery_envelope(
self,
row: sqlite3.Row,
variables: Mapping[str, Any],
) -> dict[str, Any]:
"""Return the only payload an effects transport may receive.
The outbox is intentionally allowed to retain a non-secret business
template snapshot, but an effects gateway must independently render
that snapshot from its frozen runtime. This envelope therefore never
includes rendered subject, text, HTML, sender credentials, or a
verification-code purpose.
"""
purpose = str(row["purpose"])
template = self.runtime.mail["purposes"].get(purpose)
if template is None or str(row["template_id"]) != template["template_id"]:
raise MailError("mail job template does not match the frozen runtime")
if template["secret_variables"]:
raise MailError("secret-bearing mail job cannot use the business outbox")
recipient, _ = _recipient_digest(str(row["recipient"]))
return {
"purpose": purpose,
"template_id": template["template_id"],
"recipient": recipient,
"variables": _variables(template, variables),
}
def mark_sent(
self,
mail_id: str,
*,
claim_token: str,
connection: sqlite3.Connection | None = None,
) -> dict[str, Any]:
if not isinstance(claim_token, str) or not CLAIM_TOKEN_RE.fullmatch(
claim_token
):
raise MailError("mail claim token is invalid")
def execute(active: sqlite3.Connection) -> dict[str, Any]:
self.lifecycle._assert_binding(active)
changed = active.execute(
"UPDATE websitebench_mail_jobs SET status='SENT',claim_token=NULL,"
"claimed_at=NULL,error_category=NULL,sent_at=?,updated_at=? "
"WHERE site_id=? AND mail_id=? AND status='PENDING' "
"AND claim_token=?",
(
utc_now(),
utc_now(),
self.runtime.site_id,
mail_id,
claim_token,
),
).rowcount
if changed != 1:
raise MailError("mail job claim is missing or stale")
row = active.execute(
"SELECT * FROM websitebench_mail_jobs WHERE mail_id=?", (mail_id,)
).fetchone()
return self._public_job(row)
if connection is not None:
return execute(self._caller_connection(connection))
with self.lifecycle.connection(transaction=True) as active:
return execute(active)
def mark_failed(
self,
mail_id: str,
*,
category: str,
claim_token: str | None = None,
retry_delay_seconds: int = 0,
now: int | None = None,
connection: sqlite3.Connection | None = None,
) -> dict[str, Any]:
if category not in ERROR_CATEGORIES:
raise MailError("mail failure category is not sanitized")
if claim_token is not None and not CLAIM_TOKEN_RE.fullmatch(claim_token):
raise MailError("mail claim token is invalid")
if (
isinstance(retry_delay_seconds, bool)
or not isinstance(retry_delay_seconds, int)
or not 0 <= retry_delay_seconds <= 3600
):
raise MailError("mail retry delay is invalid")
current_time = int(time.time()) if now is None else now
if (
isinstance(current_time, bool)
or not isinstance(current_time, int)
or current_time < 0
):
raise MailError("mail failure time is invalid")
def execute(active: sqlite3.Connection) -> dict[str, Any]:
self.lifecycle._assert_binding(active)
row = active.execute(
"SELECT * FROM websitebench_mail_jobs "
"WHERE site_id=? AND mail_id=? AND status='PENDING'",
(self.runtime.site_id, mail_id),
).fetchone()
if row is None:
raise MailError("mail job is missing or not pending")
if claim_token is None:
if row["claim_token"] is not None:
raise MailError("mail job is claimed")
attempts = int(row["delivery_attempts"]) + 1
claim_clause = "AND claim_token IS NULL"
parameters: tuple[Any, ...] = ()
else:
if row["claim_token"] != claim_token:
raise MailError("mail job claim is missing or stale")
attempts = int(row["delivery_attempts"])
claim_clause = "AND claim_token=?"
parameters = (claim_token,)
status = "FAILED" if attempts >= MAX_DELIVERY_ATTEMPTS else "PENDING"
changed = active.execute(
"UPDATE websitebench_mail_jobs SET status=?,error_category=?,"
"delivery_attempts=?,claim_token=NULL,claimed_at=NULL,"
"next_attempt_at=?,updated_at=? "
"WHERE site_id=? AND mail_id=? AND status='PENDING' "
f"{claim_clause}",
(
status,
category,
attempts,
current_time + retry_delay_seconds,
utc_now(),
self.runtime.site_id,
mail_id,
*parameters,
),
).rowcount
if changed != 1:
raise MailError("mail job is missing or not pending")
row = active.execute(
"SELECT * FROM websitebench_mail_jobs WHERE mail_id=?", (mail_id,)
).fetchone()
return self._public_job(row)
if connection is not None:
return execute(self._caller_connection(connection))
with self.lifecycle.connection(transaction=True) as active:
return execute(active)
def release_stale_claims(
self,
*,
older_than: int,
now: int | None = None,
connection: sqlite3.Connection | None = None,
) -> int:
current_time = int(time.time()) if now is None else now
if (
isinstance(older_than, bool)
or not isinstance(older_than, int)
or older_than < 0
or isinstance(current_time, bool)
or not isinstance(current_time, int)
or current_time < older_than
):
raise MailError("stale claim window is invalid")
def execute(active: sqlite3.Connection) -> int:
self.lifecycle._assert_binding(active)
return active.execute(
"UPDATE websitebench_mail_jobs SET "
"status=CASE WHEN delivery_attempts>=? THEN 'FAILED' ELSE status END,"
"claim_token=NULL,claimed_at=NULL,error_category='unknown',"
"next_attempt_at=?,updated_at=? "
"WHERE site_id=? AND status='PENDING' AND claim_token IS NOT NULL "
"AND claimed_at<=?",
(
MAX_DELIVERY_ATTEMPTS,
current_time,
utc_now(),
self.runtime.site_id,
older_than,
),
).rowcount
if connection is not None:
return execute(self._caller_connection(connection))
with self.lifecycle.connection(transaction=True) as active:
return execute(active)
@staticmethod
def _public_job(row: sqlite3.Row) -> dict[str, Any]:
return {
"mail_id": row["mail_id"],
"site_id": row["site_id"],
"purpose": row["purpose"],
"template_id": row["template_id"],
"status": row["status"],
"is_simulation": bool(row["is_simulation"]),
"delivery_attempts": int(row["delivery_attempts"]),
"error_category": row["error_category"],
"claimed": row["claim_token"] is not None,
"next_attempt_at": int(row["next_attempt_at"]),
}
|