diff --git a/changelog.d/6832.fixed.md b/changelog.d/6832.fixed.md new file mode 100644 index 0000000000..e1cdc61baf --- /dev/null +++ b/changelog.d/6832.fixed.md @@ -0,0 +1,8 @@ +- **A cut close of the security notifier records the notices it left unsent.** When the shutdown + cut `SecurityEventNotifier.aclose` while a send waited on a slow relay, the notices still queued + got no audit row, and on a full queue the drain ran on past the close. The close now stops + waiting for its drain at part of the shutdown step's bound, cancels it, and records the cut send + with `reason: interrupted` and each queued notice with `reason: abandoned`, and logs how many were + queued. A send still waiting for a worker thread at the cut is skipped, never mailed, and + recorded `abandoned`. The writes are not bounded, so under a full queue many can still be lost to the store's + close; [SECURITY.md](../docs/SECURITY.md) keeps that as an open residual. (`BACKLOG #6832`) diff --git a/docs/SECURITY.md b/docs/SECURITY.md index 683b84c934..c69cce5c3b 100644 --- a/docs/SECURITY.md +++ b/docs/SECURITY.md @@ -7960,18 +7960,21 @@ same drops give totals one apart by lane. when the notice is handed to the relay. It reads `mailed: true` only when the relay queued the notice: one its full queue dropped, or one it refused because it had begun to close, reads `mailed: false`, so the next lock of the kind mails again (vault BACKLOG #3120). When the relay's queue is full, the relay refuses the notice because it has -begun to close, or the send fails, the engine writes one more row, with the notice's recipient as -the actor. A lock +begun to close, a cut close leaves the notice queued or cuts its send, or the send fails, the +engine tries to write one more row, with the notice's recipient as the actor; when that write +can fail is under *Still open* below. A lock notice writes `auth.lock_notice_undelivered`, hidden as above. Every other notice kind writes `auth.security_notice_undelivered`, which every `audit:read` reader sees. The detail names the -notice kind and the `reason`, `queue_full`, `closing` or `send_failed`. An issuer's reminder also names the +notice kind and the `reason`, at least `queue_full`, `closing`, `abandoned`, `interrupted` or +`send_failed`. An issuer's reminder also names the holder. The row never carries the address, the rest of the notice's detail, or the error. The source of record is `SecurityEventNotifier._record_undelivered` in `messagefoundry/pipeline/security_notify.py`. At least the offline commands `provision-admin` and `admin-reset-totp` record it the same way (BACKLOG #5634). `provision-admin` writes it into the store it holds open, so a takeover notice whose `auth.first_administrator_provisioned` row reads `holder_notice: dispatched` and whose send failed gets its own undelivered row too, except in at -least these cases: that write fails, or the run is interrupted mid-send. The command's own result +least these cases: that write fails, or an interrupt ends the run before it lands. An interrupt +mid-send can instead leave a `reason: interrupted` row (BACKLOG #6832). The command's own result says so as well: `holder_notice_send_failed` in `--json`, and a WARNING line in text. Both say the notifier requested to record the notice as undelivered, that is, its send raised, so delivery is unconfirmed; a send can raise after the relay has queued the mail. That row can @@ -7980,9 +7983,19 @@ come before the provision row in the chain, because the notice is sent while the again for the row, and only when a send failed. **Still open, at least:** - At shutdown the notifier closes while the store is still open (BACKLOG #3191), so a send that - fails in its final drain is recorded. That close is one bounded step of the shutdown. When the - step is cut, a notice still queued is neither sent nor recorded, and a send already under way - may still go out or fail unrecorded. A lock notice among them keeps its `auth.lock_notice` row + fails in its final drain is recorded. That close is one bounded step of the shutdown. The close + stops waiting for its drain at part of that step's bound, or when the step is cut, then cancels + the drain and records the send it cut with `reason: interrupted` and each notice still queued + with `reason: abandoned` (BACKLOG #6832). A send still waiting for a worker thread at the cut + is skipped, so it never mails, and is recorded `abandoned` too; one that ended just before the + cut is recorded as it ended. A cut send whose thread began runs on to its own timeout, so that + notice may still go out. Those writes run one at a time and are not bounded. The shutdown + stops waiting for them at the step's bound plus its cut grace; the rest go on beside + `engine.stop()`, competing with its writes, until the store closes, and those still to run then + fail. Under a full queue that can be most of them. A WARNING line counting the queued notices + comes before their writes, and one counting the writes that failed comes after; it does not + count the writes a cancel stopped before they ran. Neither line counts a lock notice. A lock + notice among them keeps its `auth.lock_notice` row reading `mailed: true`, so the throttle holds back that account's next lock notice of the kind for the rest of its 24 hours. - A notice that reaches the notifier once it has begun to close is refused and recorded with diff --git a/messagefoundry/__main__.py b/messagefoundry/__main__.py index 8cc7d70e4e..2c5d8f31d1 100644 --- a/messagefoundry/__main__.py +++ b/messagefoundry/__main__.py @@ -9651,11 +9651,13 @@ def run() -> None: class _CountingNoticeAudit: """A :class:`NoticeAuditSink` that forwards to ``inner`` and counts the undelivered records the notifier asked for, so ``provision-admin`` can say that delivery of a notice it reported as - dispatched is unconfirmed (BACKLOG #5634). For a dispatched notice the notifier records only a - send that raised, so a count above zero is one, whether or not the forwarded write then - succeeded. A send can raise after the relay queued the mail, so it is not proof the notice - never left. A count of zero is not a delivery receipt: at least a drain ended by an interrupt - asks for no record.""" + dispatched is unconfirmed (BACKLOG #5634). For a dispatched notice the notifier records a send + that raised, and, when its close is cut, the send it cut or the notice it left queued (BACKLOG + #6832); at least an interrupt cuts this command's close, and it ends the run before the count + is read. So a count above zero says delivery is unconfirmed, whether or not the forwarded write + then succeeded. A send can raise after the relay queued the mail, so it is not proof the notice + never left. A count of zero is not a delivery receipt: a send that returned says only that the + relay took the mail.""" def __init__(self, inner: NoticeAuditSink) -> None: self._inner = inner @@ -11543,7 +11545,7 @@ async def alert() -> bool: # BACKLOG #5634: the notifier drained before run() returned, so its count is final here. None # unless a notice was dispatched. False is not a delivery receipt: it says only that the - # notifier recorded no undelivered notice, and at least a drain ended by an interrupt records none. + # notifier recorded no undelivered notice, and a send that returned says only the relay took it. holder_send_failed: bool | None = ( bool(notice_audit) and notice_audit[0].undelivered > 0 if outcome.holder_notice == HOLDER_NOTICE_DISPATCHED diff --git a/messagefoundry/api/app.py b/messagefoundry/api/app.py index b4bff70fae..6e3ad0c226 100644 --- a/messagefoundry/api/app.py +++ b/messagefoundry/api/app.py @@ -1781,7 +1781,11 @@ def _managed_teardown_steps( # #3191). steps.append( _TeardownStep( - "the security notifier's close", 0.25, lambda _b: security_notifier.aclose() + "the security notifier's close", + 0.25, + # Part of the bound, so the close cuts its own drain and starts recording the + # notices it left before the step is cut (BACKLOG #6832). + lambda b: security_notifier.aclose(b * _INNER_SHARE), ) ) # This takes the observers off. An unpinned cluster node's posture inverse is not raised here, diff --git a/messagefoundry/pipeline/alert_sinks.py b/messagefoundry/pipeline/alert_sinks.py index ad32ff6750..87d3ba98d5 100644 --- a/messagefoundry/pipeline/alert_sinks.py +++ b/messagefoundry/pipeline/alert_sinks.py @@ -2610,8 +2610,10 @@ async def aclose(self) -> None: was never started. A close cancelled while its sentinel waits on a full queue cancels the delivery task too and waits for it (BACKLOG #5907), so the startup unwind's cut does not leave the drain running after the store closed; a send that outlives the drain's grace is - still left running (:meth:`_cut_sends`). Only this sink does that: an undelivered alert is - counted by :attr:`undelivered`, while a security notice's loss must reach its audit row.""" + still left running (:meth:`_cut_sends`). The security notifier's close cancels its drain + too, and then starts recording, where it has an audit sink, each notice the cut left + unsent (BACKLOG #6832); a write that meets the closed store is lost, + while an undelivered alert is counted by :attr:`undelivered`.""" drain = self._task try: await super().aclose() diff --git a/messagefoundry/pipeline/security_notify.py b/messagefoundry/pipeline/security_notify.py index 1b0ea76bf4..7226e834a5 100644 --- a/messagefoundry/pipeline/security_notify.py +++ b/messagefoundry/pipeline/security_notify.py @@ -18,8 +18,9 @@ import asyncio import json import logging +import threading from collections.abc import Callable -from typing import Final, Protocol +from typing import Any, Final, Protocol from messagefoundry.auth.audit_visibility import LOCK_NOTICE_UNDELIVERED_ACTION from messagefoundry.auth.notifications import ( @@ -75,7 +76,9 @@ #: states the row. Defined here, not in ``auth/notifications.py``, where every upper-case string is a #: notice kind. SECURITY_NOTICE_UNDELIVERED_ACTION: Final = "auth.security_notice_undelivered" -#: How many queue-full records may be in flight at once. Past it a drop goes unrecorded, so the +#: How many records may be in flight at once when a queue-full drop starts one. Other records +#: held in the same set take slots too, at least a failed send's and a cut close's. Past it a +#: drop goes unrecorded, so the #: overload that filled the queue cannot also grow tasks and store writers without bound. _MAX_RECORDING: Final = 64 @@ -642,6 +645,40 @@ def _build_body(event: SecurityEvent) -> str: return "\n".join(lines) +def _consume_outcome(send: asyncio.Future[bool]) -> None: + """Read a send's outcome, so asyncio never reports it unread: after a cut close nobody else + reads it (BACKLOG #6832).""" + if not send.cancelled(): + send.exception() + + +class _SendGate: + """Whether a send's thread has begun, so a cut close can stop one still waiting for a worker + thread from mailing after the close (BACKLOG #6832). Thread-safe: the send's thread calls + :meth:`begin`, the loop calls :meth:`skip`, and exactly one of them wins.""" + + def __init__(self) -> None: + self._lock = threading.Lock() + self._started = False + self._skipped = False + + def begin(self) -> bool: + """In the send's thread: whether to send. False once :meth:`skip` won.""" + with self._lock: + if self._skipped: + return False + self._started = True + return True + + def skip(self) -> bool: + """On the loop: whether the send never began, and now never will.""" + with self._lock: + if self._started: + return False + self._skipped = True + return True + + class SecurityEventNotifier(_BackgroundDispatcher[SecurityEvent]): """Emails the affected user about a security event, on a bounded background queue. @@ -702,9 +739,17 @@ def __init__( # lifespan passes the store. Of the offline commands, provision-admin passes its store and # admin-reset-totp a sink that reopens the store for the write (BACKLOG #5634). self._audit = audit - # The queue-full records still being written, held so the loop keeps them alive and so - # aclose() can wait for them. - self._recording: set[asyncio.Task[None]] = set() + # The records still being written, at least the queue-full ones and a failed send's, held so + # the loop keeps them alive and so aclose() can wait for them. + self._recording: set[asyncio.Future[Any]] = set() + # The send the drain is waiting on, with what it needs to record or count it, so a cut + # close can record it (BACKLOG #6832). None between sends. + self._sending: ( + tuple[SecurityEvent, asyncio.Future[bool], _SendGate, Callable[[], None]] | None + ) = None + # Set when the first aclose() has finished or been cut, so a second one waits for it rather + # than racing it (BACKLOG #6832). + self._closed = asyncio.Event() # Set when aclose() begins, and never cleared: start() refuses (vault BACKLOG #3120). An event # queued after that sits behind the stop sentinel, or on a queue nothing reads, and is never # sent, so notify() refuses it; the contract on ``SecurityNotifier`` says why. @@ -797,44 +842,183 @@ def _record_dropped(self, event: SecurityEvent, reason: str) -> None: task.add_done_callback(self._recording.discard) def start(self) -> None: - # Never again once closed (vault BACKLOG #3120). A close the teardown cut short can leave its - # stop sentinel on the queue, so a drain loop started again would read it and stop, and - # notify() would answer True for events nothing sends. The engine builds a new notifier for - # each lifespan rather than restart one. + # Never again once closed (vault BACKLOG #3120). The close has stopped the drain, emptied the + # queue and refuses new events (BACKLOG #6832), so a drain started again would sit on a queue + # nothing fills while notify() answers False. The engine builds a new notifier for each + # lifespan rather than restart one. if self._closing: raise RuntimeError(f"{type(self).__name__} has been closed and cannot be started again") super().start() - async def aclose(self) -> None: + async def aclose(self, timeout: float | None = None) -> None: + """Drain the queue and stop. A close cut short cancels the drain and starts recording, with a + sink, the send it cut and each notice still queued (BACKLOG #6832). It waits for those + writes unless it is cancelled again, which stops only the wait. ``timeout`` cuts the + wait for the drain from inside, so the shutdown hands this close part of its step's bound + and the records start before the step itself is cut; a cancel of the caller cuts it the same + way. The writes are not bounded: past the step's bound the shutdown stops waiting for them, + and they go on, beside engine.stop(), until the store closes, which fails the rest. The + count of queued notices is logged before any of them is written. A second call waits for + the first to finish or be cut, and closes nothing itself.""" + if self._closing: + await self._closed.wait() + return self._closing = True # before the sentinel goes in, so nothing is queued behind it try: - await super().aclose() + await self._close(timeout) finally: - # Each one swallows its own failure, so this only waits. - await asyncio.gather(*self._recording, return_exceptions=True) + self._closed.set() - async def _handle(self, event: SecurityEvent, delivered: Callable[[], None]) -> None: + async def _close(self, timeout: float | None) -> None: + drain = self._task + deadline = asyncio.timeout(timeout) + cut = timed_out = False try: - if await asyncio.to_thread(self._send, event): + async with deadline: + await super().aclose() + except TimeoutError: + if not deadline.expired(): + raise + cut = timed_out = True + except asyncio.CancelledError: + cut = True + raise + finally: + # Taken and logged before any await, so a second cancel cannot leave them untold. + left = self._take_queued(timeout if timed_out else None) + try: + if drain is not None: + # Cut while the sentinel waited on a full queue, the drain still runs; cut while + # the close waited on the drain, it is already cancelled. + drain.cancel() + self._task = None + await asyncio.gather(drain, return_exceptions=True) + # Uncut, the base close has already raised the drain's failure to the caller. + if cut and not drain.cancelled() and (error := drain.exception()) is not None: + log.error("%s drain loop failed", type(self).__name__, exc_info=error) + finally: + # Held and shielded like a failed send's record, so a cut of this close stops only + # its wait: the writes go on until the store closes. + records = asyncio.ensure_future(self._record_cut(left)) + self._recording.add(records) + records.add_done_callback(self._recording.discard) + # Each one swallows its own failure, so this only waits. + await asyncio.shield(asyncio.gather(*self._recording, return_exceptions=True)) + + def _take_queued(self, timed_out: float | None) -> list[SecurityEvent]: + """Empty the queue, stop sentinel included, and log how many notices it held. At least a + cut close, and the close of a notifier never started, leave some. ``timed_out`` is the + timeout that cut the close, if one did.""" + left: list[SecurityEvent] = [] + while not self._queue.empty(): + if (event := self._queue.get_nowait()) is not None: + left.append(event) + # A count, never one that includes a lock notice (BACKLOG #1131). + shown = sum(event.event_type not in LOG_SILENT_EVENT_TYPES for event in left) + if timed_out is not None: + # On every timeout cut, whatever kinds were in flight, so neither its presence nor its + # absence says a lock landed. It stands in for the teardown's own cut line, which a + # close cut inside its bound no longer reaches, and at that line's level. + log.error( + "%s did not drain within %.2fs; cut it with %d security notice(s) still queued, " + "never sent", + type(self).__name__, + timed_out, + shown, + ) + elif shown: + log.warning( + "%s closed with %d security notice(s) still queued, never sent", + type(self).__name__, + shown, + ) + return left + + async def _record_cut(self, left: list[SecurityEvent]) -> None: + """Record the send a cut close stopped waiting for, and each notice it left queued.""" + records: list[tuple[SecurityEvent, str]] = [] + pending, self._sending = self._sending, None + if pending is not None: + event, send, gate, delivered = pending + if not send.done() or send.cancelled(): + # A send still waiting for a worker thread is skipped, so it never mails after the + # close: "abandoned", like a queued one. One whose thread began runs on to its own + # timeout, so the notice may still go out: "interrupted" says its delivery is + # unknown. No line for it: a cut that leaves notices queued nearly always has a send + # in flight, so a line skipped for a lock notice would say a lock landed (BACKLOG + # #1131). + records.append((event, "abandoned" if gate.skip() else "interrupted")) + elif (exc := send.exception()) is not None: + # It ended before the cut reached the drain, so its outcome is known. + self._log_send_failed(event, exc) + records.append((event, "send_failed")) + elif send.result(): delivered() - except Exception: - # Best-effort: a failed send must never propagate. The event is usually also in the audit - # log; a refused directory-reconciler audit write leaves no row (BACKLOG #3018). - # A lock notice fails silently here (BACKLOG #1131, LOG_SILENT_EVENT_TYPES): a line per - # failed lock mail would show a logs:view reader when a lock landed. A relay that is down - # still shows, on every other kind of notice. - if event.event_type not in LOG_SILENT_EVENT_TYPES: + # "abandoned", apart from "closing": a lock notice refused at notify() reads mailed: false + # on its auth.lock_notice row, while one queued before the close reads mailed: true. + records += [(event, "abandoned") for event in left] + if self._audit is None: + return # nowhere to record them; the counts are already in the log + failed = 0 + try: + for event, reason in records: + recorded = await self._record_undelivered( + event, {"reason": reason}, log_failure=False + ) + failed += not recorded and event.event_type not in LOG_SILENT_EVENT_TYPES + finally: + if failed: + # One line, not one per row: a store closing under a full queue refuses them all. log.warning( - "security-event email failed for %s (%s)", - event.username, - event.event_type, - exc_info=True, + "%d undelivered security notice(s) could not be recorded in the audit log at " + "close", + failed, ) + + async def _handle(self, event: SecurityEvent, delivered: Callable[[], None]) -> None: + # Shielded, so a cut close can read how the send ended (BACKLOG #6832). Its outcome is + # consumed here, since a cut leaves nobody else to read it. + gate = _SendGate() + send = asyncio.ensure_future(asyncio.to_thread(self._send_gated, event, gate)) + send.add_done_callback(_consume_outcome) + self._sending = (event, send, gate, delivered) + try: + sent = await asyncio.shield(send) + except Exception as exc: + self._sending = None + # Best-effort: a failed send must never propagate. + self._log_send_failed(event, exc) # The reason only. The exception's text can quote the relay's reply or the address, and # even its class would tell the recipient, in their own feed, that the relay is broken. - await self._record_undelivered(event, {"reason": "send_failed"}) + # Shielded and held, so a cut close waits for this write rather than cancelling it. + record = asyncio.ensure_future( + self._record_undelivered(event, {"reason": "send_failed"}) + ) + self._recording.add(record) + record.add_done_callback(self._recording.discard) + await asyncio.shield(record) + return + # A cancel leaves self._sending set, for the cut close to record. + self._sending = None + if sent: + delivered() - async def _record_undelivered(self, event: SecurityEvent, why: dict[str, str]) -> None: + def _log_send_failed(self, event: SecurityEvent, exc: BaseException) -> None: + # The event is usually also in the audit log; a refused directory-reconciler audit write + # leaves no row (BACKLOG #3018). A lock notice fails silently here (BACKLOG #1131, + # LOG_SILENT_EVENT_TYPES): a line per failed lock mail would show a logs:view reader when a + # lock landed. A relay that is down still shows, on every other kind of notice. + if event.event_type not in LOG_SILENT_EVENT_TYPES: + log.warning( + "security-event email failed for %s (%s)", + scrub_log_argument(event.username), + notice_kind_log_label(event.event_type), + exc_info=exc, + ) + + async def _record_undelivered( + self, event: SecurityEvent, why: dict[str, str], *, log_failure: bool = True + ) -> bool: """Write the audit row that says this notice never left the engine (BACKLOG #2383). Before this, a full queue or a failed send left only a WARNING line, so the trail could not @@ -843,11 +1027,11 @@ async def _record_undelivered(self, event: SecurityEvent, why: dict[str, str]) - ``why``, plus the holder's username on an issuer's reminder, which says whose credential it was. Never the rest of ``event.detail`` or the address: an EMAIL_CHANGED carries an address in its detail. A lock notice writes the hidden ``auth.lock_notice_undelivered`` action (BACKLOG - #1131). A failed write is swallowed, like the send it reports on. It is logged by class, and - not at all for a lock notice: that kind writes no other line, so a lone line would say a - lock landed.""" + #1131). A failed write is swallowed, like the send it reports on. It is logged by class, + unless ``log_failure`` is False, and never for a lock notice: that kind writes no other + line, so a lone line would say a lock landed. Returns whether the row was written.""" if self._audit is None: - return + return False silent = event.event_type in LOG_SILENT_EVENT_TYPES action = LOCK_NOTICE_UNDELIVERED_ACTION if silent else SECURITY_NOTICE_UNDELIVERED_ACTION detail = {"notice": notice_kind_log_label(event.event_type), **why} @@ -859,11 +1043,19 @@ async def _record_undelivered(self, event: SecurityEvent, why: dict[str, str]) - action, actor=event.username, detail=json.dumps(detail, sort_keys=True) ) except Exception as exc: # noqa: BLE001 - best-effort, like the notice itself - if not silent: + if log_failure and not silent: log.warning( "an undelivered security notice could not be recorded in the audit log (%s)", type(exc).__name__, ) + return False + return True + + def _send_gated(self, event: SecurityEvent, gate: _SendGate) -> bool: + """Mail the notice unless a cut close skipped it before its thread began.""" + if not gate.begin(): + return False + return self._send(event) def _send(self, event: SecurityEvent) -> bool: """Mail the notice, returning whether it was sent.""" diff --git a/tests/test_lock_notice_off_request_path.py b/tests/test_lock_notice_off_request_path.py index 721dbc7269..1431b44983 100644 --- a/tests/test_lock_notice_off_request_path.py +++ b/tests/test_lock_notice_off_request_path.py @@ -856,9 +856,10 @@ async def test_after_a_cut_close_a_notice_reported_queued_is_sent( monkeypatch: pytest.MonkeyPatch, ) -> None: """Vault BACKLOG #3120, review round two. The teardown bounds the notifier's close, and a close - cut while a send is under way leaves its stop sentinel on the queue. A drain loop started again - then read that sentinel and stopped, and ``notify`` answered ``True`` for an event nothing ever - sent. Whatever ``start`` does after a cut close, a notice reported queued must be sent. + cut while a send is under way left its stop sentinel on the queue, until BACKLOG #6832 had the + cut close empty it. A drain loop started again then read that sentinel and stopped, and + ``notify`` answered ``True`` for an event nothing ever sent. Whatever ``start`` does after a cut + close, a notice reported queued must be sent. The control is the event taken before the close: its send was under way when the close was cut, and once released it goes out and shows in ``sent``.""" @@ -882,7 +883,9 @@ def held_send(**kw: Any) -> None: assert await asyncio.to_thread(started.wait, _STALL_SECONDS), "the send never started" with pytest.raises(TimeoutError): # the teardown's bound, cutting the close await asyncio.wait_for(relay.aclose(), 0.05) - assert relay._queue.qsize() == 1, "the cut close left no stop sentinel to test against" + # BACKLOG #6832: the cut close now empties the queue, its stop sentinel too, recording each + # notice it took. The property below still binds a start after it. + assert relay._queue.qsize() == 0, "the cut close left its sentinel or a notice queued" with suppress(RuntimeError): # refusing is one way to keep the property below relay.start() late = SecurityEvent(PASSWORD_CHANGED, username="b", email="b@x.test") diff --git a/tests/test_security_notice_undelivered.py b/tests/test_security_notice_undelivered.py index 780ebf2697..5566690cb1 100644 --- a/tests/test_security_notice_undelivered.py +++ b/tests/test_security_notice_undelivered.py @@ -11,6 +11,7 @@ import asyncio import json +import threading from collections.abc import AsyncIterator from pathlib import Path from typing import Any, cast @@ -31,6 +32,7 @@ from messagefoundry.pipeline.security_notify import ( SECURITY_NOTICE_UNDELIVERED_ACTION, SecurityEventNotifier, + _SendGate, ) from messagefoundry.store.base import AuditStore from messagefoundry.store.store import MessageStore @@ -601,3 +603,383 @@ async def opener() -> Any: "an undelivered security notice could not be recorded in the audit log (OSError)" ] assert _STILL_RUNNING not in [r.getMessage() for r in caplog.records] + + +def _blocking_send(monkeypatch: pytest.MonkeyPatch) -> tuple[threading.Event, threading.Event]: + """A send that blocks its worker thread until released, as a slow relay would.""" + started = threading.Event() + release = threading.Event() + + def slow(**_: Any) -> None: + started.set() + release.wait(5.0) + + monkeypatch.setattr(_SEND, slow) + return started, release + + +async def test_a_cut_close_records_every_notice_it_left_unsent( + store: MessageStore, monkeypatch: pytest.MonkeyPatch +) -> None: + """BACKLOG #6832. The shutdown cuts the notifier's close while a send waits on a slow relay. The + send under way and each notice still queued gets its own row while the store is open, and the + drain does not outlive the close.""" + started, release = _blocking_send(monkeypatch) + notifier = _notifier(store) + notifier.start() + drain = notifier._task + assert drain is not None + for name in ("amy", "ben"): + await notifier.notify( + SecurityEvent(PASSWORD_CHANGED, username=name, email=f"{name}@x.test") + ) + await notifier.notify(SecurityEvent(ACCOUNT_LOCKED, username="lock-c", email="c@x.test")) + try: + assert await asyncio.to_thread(started.wait, 5.0) + closing = asyncio.create_task(notifier.aclose()) + await asyncio.sleep(0.05) + closing.cancel() + with pytest.raises(asyncio.CancelledError): + await closing + assert drain.done() + assert sorted(await _undelivered(store)) == [ + ( + LOCK_NOTICE_UNDELIVERED_ACTION, + "lock-c", + {"notice": "account_locked", "reason": "abandoned"}, + ), + ( + SECURITY_NOTICE_UNDELIVERED_ACTION, + "amy", + {"notice": "password_changed", "reason": "interrupted"}, + ), + ( + SECURITY_NOTICE_UNDELIVERED_ACTION, + "ben", + {"notice": "password_changed", "reason": "abandoned"}, + ), + ] + assert notifier.undelivered == 3 + finally: + release.set() + + +async def test_a_close_cut_on_a_full_queue_cancels_the_drain( + store: MessageStore, monkeypatch: pytest.MonkeyPatch +) -> None: + """BACKLOG #6832. On a full queue the close waits to put its stop sentinel, so a cut there used + to leave the drain running past the close, into the closed store.""" + started, release = _blocking_send(monkeypatch) + notifier = _notifier(store) + notifier._queue = asyncio.Queue(maxsize=1) + notifier.start() + drain = notifier._task + assert drain is not None + await notifier.notify(SecurityEvent(PASSWORD_CHANGED, username="amy", email="amy@x.test")) + try: + assert await asyncio.to_thread(started.wait, 5.0) + await notifier.notify(SecurityEvent(PASSWORD_CHANGED, username="ben", email="ben@x.test")) + closing = asyncio.create_task(notifier.aclose()) + await asyncio.sleep(0.05) + assert not closing.done() # waiting on the full queue + closing.cancel() + with pytest.raises(asyncio.CancelledError): + await closing + assert drain.done() + assert sorted(await _undelivered(store)) == [ + ( + SECURITY_NOTICE_UNDELIVERED_ACTION, + "amy", + {"notice": "password_changed", "reason": "interrupted"}, + ), + ( + SECURITY_NOTICE_UNDELIVERED_ACTION, + "ben", + {"notice": "password_changed", "reason": "abandoned"}, + ), + ] + finally: + release.set() + + +async def test_a_cut_during_a_failed_send_s_record_keeps_that_record( + store: MessageStore, monkeypatch: pytest.MonkeyPatch +) -> None: + """BACKLOG #6832, review round one. A cut landing while the drain writes a failed send's row + must not cancel that write, or the notice leaves no row at all.""" + + def boom(**_: Any) -> None: + raise OSError("relay down") + + monkeypatch.setattr(_SEND, boom) + gate = asyncio.Event() + entered = asyncio.Event() + + class _GatedAudit: + async def record_view( + self, message_id: str, *, actor: str | None = None, now: float | None = None + ) -> None: + raise AssertionError("the notifier never records a view") + + async def record_audit( + self, + action: str, + *, + actor: str | None = None, + channel_id: str | None = None, + detail: str | None = None, + client: str | None = None, + now: float | None = None, + ) -> None: + entered.set() + await gate.wait() + await store.record_audit(action, actor=actor, detail=detail) + + notifier = SecurityEventNotifier( + host="smtp.example.org", + port=25, + sender="mf@example.org", + audit=cast(AuditStore, _GatedAudit()), + ) + notifier.start() + await notifier.notify(SecurityEvent(PASSWORD_CHANGED, username="amy", email="amy@x.test")) + try: + await asyncio.wait_for(entered.wait(), 5.0) + closing = asyncio.create_task(notifier.aclose()) + await asyncio.sleep(0.05) + closing.cancel() + await asyncio.sleep(0.05) + finally: + gate.set() + with pytest.raises(asyncio.CancelledError): + await closing + assert await _undelivered(store) == [ + ( + SECURITY_NOTICE_UNDELIVERED_ACTION, + "amy", + {"notice": "password_changed", "reason": "send_failed"}, + ) + ] + + +async def test_a_cut_close_with_no_audit_sink_still_logs_the_queued_count( + monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture +) -> None: + """BACKLOG #6832, review round one. With no sink the queued notices still show in the log, and + the line claims no record.""" + started, release = _blocking_send(monkeypatch) + notifier = SecurityEventNotifier(host="smtp.example.org", port=25, sender="mf@example.org") + notifier.start() + await notifier.notify(SecurityEvent(PASSWORD_CHANGED, username="amy", email="amy@x.test")) + await notifier.notify(SecurityEvent(PASSWORD_CHANGED, username="ben", email="ben@x.test")) + try: + assert await asyncio.to_thread(started.wait, 5.0) + closing = asyncio.create_task(notifier.aclose()) + await asyncio.sleep(0.05) + closing.cancel() + with pytest.raises(asyncio.CancelledError): + await closing + finally: + release.set() + assert [r.getMessage() for r in caplog.records if "still queued" in r.getMessage()] == [ + "SecurityEventNotifier closed with 1 security notice(s) still queued, never sent" + ] + assert not [r for r in caplog.records if "could not be recorded" in r.getMessage()] + + +async def test_a_close_timeout_cuts_the_drain_and_records_before_returning( + store: MessageStore, monkeypatch: pytest.MonkeyPatch +) -> None: + """BACKLOG #6832, review round two. The shutdown hands the close part of its bound, so the + close cuts its own drain and records, then returns without raising.""" + started, release = _blocking_send(monkeypatch) + notifier = _notifier(store) + notifier.start() + drain = notifier._task + assert drain is not None + await notifier.notify(SecurityEvent(PASSWORD_CHANGED, username="amy", email="amy@x.test")) + await notifier.notify(SecurityEvent(PASSWORD_CHANGED, username="ben", email="ben@x.test")) + try: + assert await asyncio.to_thread(started.wait, 5.0) + await asyncio.wait_for(notifier.aclose(0.05), 5.0) + assert drain.done() + assert sorted((actor, d["reason"]) for _, actor, d in await _undelivered(store)) == [ + ("amy", "interrupted"), + ("ben", "abandoned"), + ] + finally: + release.set() + + +async def test_a_cut_of_the_close_while_it_records_stops_only_its_wait( + store: MessageStore, monkeypatch: pytest.MonkeyPatch +) -> None: + """BACKLOG #6832, final review round. The teardown cuts the step while the close is still + writing its rows; the cut stops the wait, and every row is still written.""" + started, release = _blocking_send(monkeypatch) + gate = asyncio.Event() + entered = asyncio.Event() + + class _GatedAudit: + async def record_view( + self, message_id: str, *, actor: str | None = None, now: float | None = None + ) -> None: + raise AssertionError("the notifier never records a view") + + async def record_audit( + self, + action: str, + *, + actor: str | None = None, + channel_id: str | None = None, + detail: str | None = None, + client: str | None = None, + now: float | None = None, + ) -> None: + entered.set() + await gate.wait() + await store.record_audit(action, actor=actor, detail=detail) + + notifier = SecurityEventNotifier( + host="smtp.example.org", + port=25, + sender="mf@example.org", + audit=cast(AuditStore, _GatedAudit()), + ) + notifier.start() + for name in ("amy", "ben", "cat"): + await notifier.notify( + SecurityEvent(PASSWORD_CHANGED, username=name, email=f"{name}@x.test") + ) + try: + assert await asyncio.to_thread(started.wait, 5.0) + closing = asyncio.create_task(notifier.aclose(0.05)) + await asyncio.wait_for(entered.wait(), 5.0) + closing.cancel() # the step's own cut, mid-record + with pytest.raises(asyncio.CancelledError): + await closing + finally: + gate.set() + release.set() + await asyncio.wait_for(asyncio.gather(*notifier._recording), 5.0) + assert sorted((actor, d["reason"]) for _, actor, d in await _undelivered(store)) == [ + ("amy", "interrupted"), + ("ben", "abandoned"), + ("cat", "abandoned"), + ] + + +@pytest.mark.parametrize( + ("outcome", "rows"), + [("sent", []), ("raised", ["send_failed"]), ("cancelled", ["interrupted"])], +) +async def test_a_send_settled_before_the_cut_reached_the_drain_is_read_as_it_ended( + store: MessageStore, outcome: str, rows: list[str] +) -> None: + """BACKLOG #6832, review rounds one and two. A send can end between the cut and the drain's + resumption: a sent one is no undelivered row, a raised one is send_failed, and a cancelled one + (the loop tearing down) still lets the queued notices be recorded.""" + notifier = _notifier(store) + loop = asyncio.get_running_loop() + send: asyncio.Future[bool] = loop.create_future() + if outcome == "sent": + send.set_result(True) + elif outcome == "raised": + send.set_exception(OSError("relay down")) + else: + send.cancel() + calls: list[int] = [] + amy = SecurityEvent(PASSWORD_CHANGED, username="amy", email="amy@x.test") + gate = _SendGate() + assert gate.begin() # its thread began, so a cut cannot skip it + notifier._sending = (amy, send, gate, lambda: calls.append(1)) + ben = SecurityEvent(PASSWORD_CHANGED, username="ben", email="ben@x.test") + await notifier._record_cut([ben]) + assert calls == ([1] if outcome == "sent" else []) + assert sorted((actor, d["reason"]) for _, actor, d in await _undelivered(store)) == sorted( + [("amy", reason) for reason in rows] + [("ben", "abandoned")] + ) + + +async def test_a_second_close_beside_a_cut_one_returns_cleanly( + store: MessageStore, monkeypatch: pytest.MonkeyPatch +) -> None: + """BACKLOG #6832, Manager repair (a). Two closes overlap on a full queue and the first is cut. + The second waits for it and returns, rather than awaiting the drain the first set to None.""" + started, release = _blocking_send(monkeypatch) + notifier = _notifier(store) + notifier._queue = asyncio.Queue(maxsize=1) + notifier.start() + await notifier.notify(SecurityEvent(PASSWORD_CHANGED, username="amy", email="amy@x.test")) + try: + assert await asyncio.to_thread(started.wait, 5.0) + await notifier.notify(SecurityEvent(PASSWORD_CHANGED, username="ben", email="ben@x.test")) + first = asyncio.create_task(notifier.aclose(0.05)) + second = asyncio.create_task(notifier.aclose()) + await asyncio.wait_for(asyncio.gather(first, second), 5.0) + finally: + release.set() + assert notifier._queue.qsize() == 0 + + +async def test_a_send_still_waiting_for_a_thread_at_the_cut_never_mails( + store: MessageStore, monkeypatch: pytest.MonkeyPatch +) -> None: + """BACKLOG #6832, Manager repair (b). The executor is busy, so the send waits for a thread when + the close is cut. It must not mail once a thread frees up, and it is recorded as abandoned.""" + import concurrent.futures + + sent: list[list[str]] = [] + monkeypatch.setattr(_SEND, lambda **kw: sent.append(kw["recipients"])) + loop = asyncio.get_running_loop() + executor = concurrent.futures.ThreadPoolExecutor(max_workers=1) + real = loop.run_in_executor + + def on_busy_executor(_executor: Any, func: Any, *args: Any) -> Any: + return real(executor, func, *args) + + # Only this loop, only this test: the default executor stays the loop's own. + monkeypatch.setattr(loop, "run_in_executor", on_busy_executor) + busy = threading.Event() + occupied = real(executor, busy.wait, 5.0) + notifier = _notifier(store) + notifier.start() + try: + await notifier.notify(SecurityEvent(PASSWORD_CHANGED, username="amy", email="amy@x.test")) + await asyncio.sleep(0.05) # the drain is now waiting on the queued send + await asyncio.wait_for(notifier.aclose(0.05), 5.0) + finally: + busy.set() + await occupied + executor.shutdown(wait=True) # the queued work item has had its thread by now + assert sent == [] + assert [(actor, d["reason"]) for _, actor, d in await _undelivered(store)] == [ + ("amy", "abandoned") + ] + + +async def test_a_timeout_cut_logs_a_warning_naming_the_queued_count( + store: MessageStore, monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture +) -> None: + """BACKLOG #6832, Manager repair (c). A close cut by its own timeout ends inside the step's + bound, so the teardown's cut line no longer fires; the close logs one of its own, on every + timeout cut, with a count that leaves lock notices out (BACKLOG #1131).""" + started, release = _blocking_send(monkeypatch) + notifier = _notifier(store) + notifier.start() + await notifier.notify(SecurityEvent(ACCOUNT_LOCKED, username="lock-a", email="a@x.test")) + await notifier.notify(SecurityEvent(PASSWORD_CHANGED, username="ben", email="ben@x.test")) + await notifier.notify(SecurityEvent(ACCOUNT_LOCKED, username="lock-c", email="c@x.test")) + try: + assert await asyncio.to_thread(started.wait, 5.0) + await asyncio.wait_for(notifier.aclose(0.05), 5.0) + finally: + release.set() + lines = [r for r in caplog.records if "did not drain" in r.getMessage()] + assert [(r.levelname, r.getMessage()) for r in lines] == [ + ( + "ERROR", + "SecurityEventNotifier did not drain within 0.05s; cut it with 1 security notice(s) " + "still queued, never sent", + ) + ]