Open-source AI Security Operations Center: alert fusion, LLM-agent triage, MITRE ATT&CK investigation, and a replayable decision ledger for every agent step. Self-hostable, runs with no API keys, MIT licensed. Ships an MCP server for Claude, Cursor and Continue.
Python agentic-aiai-securityalert-triageblue-teamcybersecuritydetection-engineeringincident-responselanggraphllm-agentsmcpmitre-attackmodel-context-protocolpurple-teamsecurity-operationsself-hostedsiemsoarsocthreat-detectionthreat-intelligence
feat(actions): mailbox remediation arms, probes and recipient-scaled approval
Beenu Arora062e0994f81d
diff --git a/services/actions/app/clients/m365_mail_client.py b/services/actions/app/clients/m365_mail_client.pyindex f5fd34790..a2278e94f 100644--- a/services/actions/app/clients/m365_mail_client.py+++ b/services/actions/app/clients/m365_mail_client.py@@ -79,10 +79,7 @@ DEFAULT_RESTORE_FOLDER = "inbox"#: omits ``internetMessageHeaders`` from the default projection, and a header#: analysis cannot recover a field the read never asked for — the same defect#: that left hostname and username null on four of five closed-finding readers.-MESSAGE_SELECT = (- "id,internetMessageId,subject,from,sender,toRecipients,ccRecipients,"- "receivedDateTime,parentFolderId,hasAttachments,webLink"-)+MESSAGE_SELECT = "id,internetMessageId,subject,from,sender,toRecipients,ccRecipients,receivedDateTime,parentFolderId,hasAttachments,webLink"#: ``internetMessageHeaders`` is only populated on a single-message GET, never#: on a collection, so the poller fetches the list and then reads headers perdiff --git a/services/actions/app/core/config.py b/services/actions/app/core/config.pyindex bb0536218..07a218b78 100644--- a/services/actions/app/core/config.py+++ b/services/actions/app/core/config.py@@ -60,6 +60,26 @@ class ActionsSettings(BaseSettings):description="Master toggle for the Slack/Teams interactive user-verification action.",)+ # Depth 7.1 — mailbox remediation (search / purge / restore / sender+ # block) across the recipients of a reported phishing message.+ #+ # **Off by default, unlike every flag above it.** A capability that+ # reaches out of the platform and removes somebody's mail is not one an+ # upgrade should silently acquire: an operator who upgrades AiSOC has+ # consented to a new version, not to the platform being able to delete+ # from every mailbox in their tenant. Turning it on is a deliberate act,+ # and the arms say exactly that when it is off rather than simulating a+ # purge — a dry run reporting a send or a purge that never happened is+ # the defect that shipped in NotifySlackExecutor.+ AISOC_FEATURE_MAILBOX_REMEDIATION: bool = Field(+ default=False,+ description=(+ "Master toggle for mailbox remediation (search_mailboxes, purge_email, "+ "restore_email, block_sender, unblock_sender). Off by default: enabling it "+ "grants AiSOC the ability to remove mail from the tenant's mailboxes."+ ),+ )+AISOC_CHATOPS_RESPONSE_SECRET: str = Field(default="",description=("HMAC secret used to sign ChatOps response tokens so we can verify a callback genuinely came from a message we sent."),diff --git a/services/actions/app/executors/mailbox.py b/services/actions/app/executors/mailbox.pynew file mode 100644index 000000000..7ae5161cb--- /dev/null+++ b/services/actions/app/executors/mailbox.py@@ -0,0 +1,442 @@+"""Mailbox remediation: find a reported message, take it out, put it back.++Five verbs across Microsoft 365 and Google Workspace. Before this module the+registry held 79 builtin arms and not one could touch a mailbox, so governed+dispatch answered ``executor_not_found`` for ``purge_email`` — a phishing+response that could block the sender's domain at the firewall and could not+remove the message it arrived in.++Three properties are load-bearing, and each exists because its opposite has+already shipped in this repository.++**Off by default.** ``AISOC_FEATURE_MAILBOX_REMEDIATION`` gates every verb,+including the read. An operator upgrading AiSOC has consented to a new version+of the product, not to it acquiring the ability to delete from every mailbox+in their tenant.++**Disabled is not simulated, and absent credentials are not a clean result.**+Both return ``FAILED`` naming the cause, never ``COMPLETED``. ``executed`` is+the single field meaning a vendor was touched, and every result here sets it+explicitly. ``NotifySlackExecutor`` reporting ``message_sent: true`` for a+message it never sent is the precedent; on this surface the equivalent is+reporting a purge that never happened, across twenty-five mailboxes.++**Nothing found is not a purge.** A fan-out that reports every mailbox purged+when the message was in three of them teaches an analyst to trust a number+that means nothing, so a mailbox with no copy answers FAILED with the reason.++Why the vendor logic sits in one executor per verb+--------------------------------------------------+``ActionType`` is vendor-agnostic and the post-action verifier is keyed by it,+so each verb needs exactly one legacy executor. The per-vendor arms in+``live_actions/builtins.py`` are adapters onto these, pinning ``alert_vendor``+so ``m365/purge_email`` means Microsoft — and the pin is honoured **only when+that vendor's credentials are present**, because honouring a pin blindly is+the defect that had a "dry run" call a customer's Splunk.++Restore needs what the purge returned+--------------------------------------+Microsoft's move gives the message a **new id** in the destination folder, and+the folder it came from is only knowable before the move. Both travel back in+``rollback_data`` as ``restore_message_id`` and ``restore_folder_id``. Gmail+keeps the id across a trash and untrash restores the original labels, so its+restore needs only the id. The asymmetry is the vendors', not ours, and+collapsing it would make the Microsoft rollback guess — which on the most+disruptive verb in the product is the same as not having one.+"""++from __future__ import annotations++from datetime import datetime+from typing import Any++import structlog++from app.clients.factories import _gmail_client, _m365_mail_client+from app.clients.m365_mail_client import DEFAULT_RESTORE_FOLDER, RECOVERABLE_ITEMS, normalise_internet_message_id+from app.core.config import get_settings+from app.executors.base import BaseExecutor+from app.models.action import (+ ACTION_BLAST_RADIUS,+ ActionRequest,+ ActionResult,+ ActionStatus,+ ActionType,+ BlastRadius,+)++logger = structlog.get_logger()++M365 = "m365"+GOOGLE_WORKSPACE = "google_workspace"++#: Credential keys each vendor's factory reads, declared here so the adapters+#: in ``builtins.py`` strip exactly these on a dry run and the two cannot+#: drift. A hand-copied list on the adapter is the shape that let a "dry run"+#: reach production Splunk.+M365_CLIENT_PARAM_KEYS: tuple[str, ...] = ("azure_tenant_id", "azure_client_id", "azure_client_secret")+GMAIL_CLIENT_PARAM_KEYS: tuple[str, ...] = ("gws_service_account_key", "gws_subject_email")++_M365_PINS = frozenset({"m365", "microsoft", "microsoft365", "office365", "exchange", "outlook"})+_GMAIL_PINS = frozenset({"google_workspace", "gmail", "google", "workspace"})++#: Said verbatim whenever the feature is off, so an operator reading a failed+#: action knows it is a setting rather than a vendor outage or a bad+#: credential. Three different causes, three different next steps.+DISABLED_REASON = (+ "Mailbox remediation is disabled on this deployment. No mailbox was read or changed. "+ "Set AISOC_FEATURE_MAILBOX_REMEDIATION=true to enable it; it ships off because enabling "+ "it grants AiSOC the ability to remove mail from the tenant's mailboxes."+)++NO_CREDENTIALS_REASON = (+ "No mailbox credentials are configured. Provide the Microsoft 365 app registration "+ "(azure_tenant_id / azure_client_id / azure_client_secret) or the Google Workspace "+ "service-account key (gws_service_account_key). Nothing was read or changed."+)+++def choose_vendor(params: dict[str, Any]) -> str:+ """``"m365"``, ``"google_workspace"``, or ``""`` when neither is configured.++ An explicit pin wins only when that vendor's credentials exist. A pin+ honoured without that check acts on whichever tenant's mail the ambient+ credentials happen to address.+ """+ has_m365 = _m365_mail_client(params) is not None+ has_gmail = _gmail_client(params) is not None+ pin = str(params.get("alert_vendor") or params.get("vendor") or "").strip().lower()+ if pin in _M365_PINS and has_m365:+ return M365+ if pin in _GMAIL_PINS and has_gmail:+ return GOOGLE_WORKSPACE+ if has_m365:+ return M365+ if has_gmail:+ return GOOGLE_WORKSPACE+ return ""+++class _MailboxExecutor(BaseExecutor):+ """Shared preamble: feature flag, vendor choice, error shape."""++ action_type: ActionType++ def _blast(self) -> BlastRadius:+ return ACTION_BLAST_RADIUS.get(self.action_type, BlastRadius.HIGH)++ def _refused(self, request: ActionRequest, reason: str, **output: Any) -> ActionResult:+ return ActionResult(+ action_id=request.id,+ status=ActionStatus.FAILED,+ blast_radius=self._blast(),+ output={"action": self.action_type.value, "executed": False, **output},+ error=reason,+ completed_at=datetime.utcnow(),+ )++ def _failed(self, request: ActionRequest, vendor: str, exc: Exception) -> ActionResult:+ logger.warning(+ "mailbox_action.failed",+ capability=self.action_type.value,+ vendor=vendor,+ error=str(exc)[:500].replace("\r", "").replace("\n", " "),+ )+ return self._refused(request, f"{vendor} {self.action_type.value} failed: {exc}", vendor=vendor)++ def _ok(self, request: ActionRequest, vendor: str, output: dict[str, Any], rollback: dict[str, Any] | None = None) -> ActionResult:+ return ActionResult(+ action_id=request.id,+ status=ActionStatus.COMPLETED,+ blast_radius=self._blast(),+ output={"action": self.action_type.value, "executed": True, "vendor": vendor, **output},+ rollback_data={"vendor": vendor, "mailbox": request.target, **(rollback or {})},+ completed_at=datetime.utcnow(),+ )++ def _preamble(self, request: ActionRequest) -> tuple[str, Any, ActionResult | None]:+ """``(vendor, client, early_result)``. A non-None result ends the call."""+ if not get_settings().AISOC_FEATURE_MAILBOX_REMEDIATION:+ return "", None, self._refused(request, DISABLED_REASON)+ params = dict(request.parameters or {})+ vendor = choose_vendor(params)+ if not vendor:+ return "", None, self._refused(request, NO_CREDENTIALS_REASON)+ client = _m365_mail_client(params) if vendor == M365 else _gmail_client(params)+ if client is None: # pragma: no cover - choose_vendor already proved it builds+ return vendor, None, self._refused(request, NO_CREDENTIALS_REASON, vendor=vendor)+ return vendor, client, None+++class SearchMailboxesExecutor(_MailboxExecutor):+ """Find the copies of one reported message. The read the others depend on."""++ action_type = ActionType.SEARCH_MAILBOXES++ async def execute(self, request: ActionRequest) -> ActionResult:+ vendor, client, early = self._preamble(request)+ if early is not None:+ return early+ params = dict(request.parameters or {})+ try:+ if vendor == M365:+ matches = await client.search_messages(+ request.target,+ internet_message_id=str(params.get("internet_message_id") or ""),+ sender=str(params.get("sender") or ""),+ subject=str(params.get("subject") or ""),+ received_after=str(params.get("received_after") or ""),+ limit=int(params.get("limit") or 25),+ )+ else:+ matches = await client.search_messages(+ request.target,+ internet_message_id=str(params.get("internet_message_id") or ""),+ sender=str(params.get("sender") or ""),+ limit=int(params.get("limit") or 25),+ )+ except ValueError as exc:+ # The Gmail sanitiser refuses rather than escapes, and a refusal+ # is a failure rather than an empty result: an escaped value that+ # reaches the API and matches nothing reports a clean mailbox+ # from a search that never ran.+ return self._refused(request, f"{vendor} search refused the query: {exc}", vendor=vendor)+ except Exception as exc: # noqa: BLE001 - a vendor error is FAILED, never silent+ return self._failed(request, vendor, exc)+ return self._ok(+ request,+ vendor,+ {"mailbox": request.target, "matches": matches, "match_count": len(matches)},+ )+++class PurgeEmailExecutor(_MailboxExecutor):+ """Soft-delete one copy of a message. Reversible by ``RestoreEmailExecutor``."""++ action_type = ActionType.PURGE_EMAIL++ async def execute(self, request: ActionRequest) -> ActionResult:+ vendor, client, early = self._preamble(request)+ if early is not None:+ return early+ params = dict(request.parameters or {})+ message_id = str(params.get("message_id") or "")+ internet_id = str(params.get("internet_message_id") or "")+ source_folder = str(params.get("source_folder_id") or "")++ try:+ if not message_id:+ # A reported message carries an internet message id; the move+ # needs a per-mailbox one. Resolve it here rather than make+ # every caller run the search first.+ if not internet_id:+ return self._refused(request, "purge_email needs either message_id or internet_message_id", vendor=vendor)+ found = await client.search_messages(request.target, internet_message_id=internet_id, limit=5)+ if not found:+ return self._refused(+ request,+ "The message was not found in this mailbox, so nothing was purged.",+ vendor=vendor,+ mailbox=request.target,+ match_count=0,+ )+ message_id = str(found[0].get("id") or "")+ if vendor == M365:+ source_folder = source_folder or str(found[0].get("parentFolderId") or "")++ if vendor == M365:+ moved = await client.soft_delete_message(request.target, message_id)+ restore_id = str(moved.get("id") or "")+ restore_folder = source_folder or DEFAULT_RESTORE_FOLDER+ summary = f"message soft-deleted from {request.target} (recoverable items)"+ else:+ await client.trash_message(request.target, message_id)+ # Gmail keeps the id across a trash and untrash restores the+ # labels the message had, which is strictly better than a+ # single destination folder.+ restore_id = message_id+ restore_folder = ""+ summary = f"message moved to Trash in {request.target}"+ except ValueError as exc:+ return self._refused(request, f"{vendor} search refused the query: {exc}", vendor=vendor)+ except Exception as exc: # noqa: BLE001+ return self._failed(request, vendor, exc)++ return self._ok(+ request,+ vendor,+ {+ "mailbox": request.target,+ "summary": summary,+ "purged_message_id": message_id,+ "internet_message_id": normalise_internet_message_id(internet_id) if internet_id else "",+ },+ rollback={+ "restore_message_id": restore_id,+ "restore_folder_id": restore_folder,+ "internet_message_id": internet_id,+ },+ )++ async def rollback(self, result: ActionResult) -> bool:+ """Put the message back, for real. ``BaseExecutor`` defaults to ``False``.++ ``purge_email`` is the most disruptive verb this service offers and+ the one whose rollback most needs to exist rather than return a+ hopeful ``True``: ``unisolate_host`` resolving to nothing is the+ precedent, and this is the same shape with a wider blast radius.+ """+ data = dict(result.rollback_data or {})+ mailbox = str(data.get("mailbox") or "")+ if not mailbox or not data.get("restore_message_id"):+ logger.warning("purge_email.rollback_incomplete", has_mailbox=bool(mailbox))+ return False+ restored = await RestoreEmailExecutor().execute(+ ActionRequest(+ incident_id=result.action_id,+ tenant_id=result.action_id,+ action_type=ActionType.RESTORE_EMAIL,+ target=mailbox,+ parameters={**data, **(result.output.get("credentials") or {})},+ )+ )+ return restored.status == ActionStatus.COMPLETED+++class RestoreEmailExecutor(_MailboxExecutor):+ """The declared reverse of ``purge_email``."""++ action_type = ActionType.RESTORE_EMAIL++ async def execute(self, request: ActionRequest) -> ActionResult:+ vendor, client, early = self._preamble(request)+ if early is not None:+ return early+ params = dict(request.parameters or {})+ message_id = str(params.get("restore_message_id") or params.get("message_id") or "")+ if not message_id:+ return self._refused(request, "restore_email needs the restore_message_id the purge returned", vendor=vendor)+ folder = str(params.get("restore_folder_id") or DEFAULT_RESTORE_FOLDER)+ try:+ if vendor == M365:+ restored = await client.restore_message(request.target, message_id, folder)+ new_id = str(restored.get("id") or message_id)+ else:+ await client.untrash_message(request.target, message_id)+ new_id = message_id+ folder = "original labels"+ except Exception as exc: # noqa: BLE001+ return self._failed(request, vendor, exc)+ return self._ok(+ request,+ vendor,+ {+ "mailbox": request.target,+ "restored_message_id": new_id,+ "folder": folder,+ "summary": f"message restored to {folder} in {request.target}",+ },+ rollback={"message_id": new_id},+ )+++class BlockSenderExecutor(_MailboxExecutor):+ """Stop future mail from one sender reaching **one** mailbox."""++ action_type = ActionType.BLOCK_SENDER++ async def execute(self, request: ActionRequest) -> ActionResult:+ vendor, client, early = self._preamble(request)+ if early is not None:+ return early+ params = dict(request.parameters or {})+ sender = str(params.get("sender") or "")+ if not sender:+ return self._refused(request, "block_sender needs a sender address", vendor=vendor)+ try:+ created = await (+ client.create_inbox_rule(request.target, sender) if vendor == M365 else client.create_filter(request.target, sender)+ )+ except Exception as exc: # noqa: BLE001+ return self._failed(request, vendor, exc)+ mechanism = "inbox rule" if vendor == M365 else "filter"+ rule_id = str(created.get("id") or "")+ return self._ok(+ request,+ vendor,+ {+ "mailbox": request.target,+ "sender": sender,+ "rule_id": rule_id,+ "scope": "mailbox",+ # The scope is in the summary, not only in a docstring: this+ # string lands on the case timeline, and "sender blocked"+ # read without it means something the action did not do.+ "summary": (+ f"{sender} blocked in the mailbox {request.target} only "+ f"(per-mailbox {mechanism}; neither vendor exposes its "+ f"organisation-wide block list through this API)"+ ),+ },+ rollback={"rule_id": rule_id, "sender": sender},+ )++ async def rollback(self, result: ActionResult) -> bool:+ data = dict(result.rollback_data or {})+ mailbox = str(data.get("mailbox") or "")+ if not mailbox or not data.get("rule_id"):+ return False+ removed = await UnblockSenderExecutor().execute(+ ActionRequest(+ incident_id=result.action_id,+ tenant_id=result.action_id,+ action_type=ActionType.UNBLOCK_SENDER,+ target=mailbox,+ parameters=data,+ )+ )+ return removed.status == ActionStatus.COMPLETED+++class UnblockSenderExecutor(_MailboxExecutor):+ """The declared reverse of ``block_sender``."""++ action_type = ActionType.UNBLOCK_SENDER++ async def execute(self, request: ActionRequest) -> ActionResult:+ vendor, client, early = self._preamble(request)+ if early is not None:+ return early+ params = dict(request.parameters or {})+ rule_id = str(params.get("rule_id") or params.get("filter_id") or "")+ if not rule_id:+ return self._refused(request, "unblock_sender needs the rule_id block_sender returned", vendor=vendor)+ try:+ if vendor == M365:+ await client.delete_inbox_rule(request.target, rule_id)+ else:+ await client.delete_filter(request.target, rule_id)+ except Exception as exc: # noqa: BLE001+ return self._failed(request, vendor, exc)+ return self._ok(+ request,+ vendor,+ {"mailbox": request.target, "rule_id": rule_id, "summary": f"sender block removed from {request.target}"},+ )+++__all__ = [+ "BlockSenderExecutor",+ "DISABLED_REASON",+ "GMAIL_CLIENT_PARAM_KEYS",+ "GOOGLE_WORKSPACE",+ "M365",+ "M365_CLIENT_PARAM_KEYS",+ "NO_CREDENTIALS_REASON",+ "PurgeEmailExecutor",+ "RECOVERABLE_ITEMS",+ "RestoreEmailExecutor",+ "SearchMailboxesExecutor",+ "UnblockSenderExecutor",+ "choose_vendor",+]diff --git a/services/actions/app/live_actions/builtins.py b/services/actions/app/live_actions/builtins.pyindex 1f4e77c8f..5469e3cbb 100644--- a/services/actions/app/live_actions/builtins.py+++ b/services/actions/app/live_actions/builtins.py@@ -56,6 +56,17 @@ from app.executors.identity import (ResetPasswordExecutor,SuspendSessionExecutor,)+from app.executors.mailbox import (+ GMAIL_CLIENT_PARAM_KEYS,+ GOOGLE_WORKSPACE,+ M365,+ M365_CLIENT_PARAM_KEYS,+ BlockSenderExecutor,+ PurgeEmailExecutor,+ RestoreEmailExecutor,+ SearchMailboxesExecutor,+ UnblockSenderExecutor,+)from app.executors.network import (AllowIPExecutor,BlockDomainExecutor,@@ -968,6 +979,180 @@ class TeamsChatOpsVerify(_ChatOpsVerify):_transport = "teams"+# ---------------------------------------------------------------------------+# Mailbox remediation (depth 7.1)+# ---------------------------------------------------------------------------+#+# Ten adapters over the five verbs in `app.executors.mailbox`. The legacy+# executors are vendor-agnostic — `ActionType` is, and the post-action+# verifier is keyed by it — so each adapter pins its vendor into the request+# and the executor honours the pin **only when that vendor's credentials are+# present**. Honouring a pin blindly is the defect that had a dry run call a+# customer's Splunk; here it would act on the wrong tenant's mail.+#+# `_credential_keys` is imported from the executor module rather than+# retyped, so the dry-run strip and the client factory read one list.+++class _MailboxAdapter(_LegacyExecutorAdapter):+ """Pin the vendor, refuse a preview before any client is built.++ The dry-run override is not redundant with `_LegacyExecutorAdapter`'s+ credential strip. That strip works by making the legacy executor fall+ through to a simulation branch, and these executors deliberately have no+ simulation branch: a purge that did not happen must never be reported as+ one that did. Returning SIMULATED here, before a client exists, says what+ is true — nothing was read and nothing was changed — and the step grader+ counts `simulated` as a failure to execute, which is correct.+ """++ _vendor_pin: str = ""++ async def execute(self, request: LiveActionRequest) -> LiveActionResult:+ if request.dry_run:+ return LiveActionResult(+ request_id=request.request_id,+ status=LiveActionStatus.SIMULATED,+ capability=self.capability,+ vendor_id=self.vendor_id,+ summary=f"would {self.capability.replace('_', ' ')} for {request.target or 'the named mailbox'}",+ details={+ "would_run": self.capability,+ "mailbox": request.target,+ "internet_message_id": (request.params or {}).get("internet_message_id", ""),+ "executed": False,+ },+ )+ pinned = {**(request.params or {}), "alert_vendor": self._vendor_pin}+ return await super().execute(request.model_copy(update={"params": pinned}))++ def _summarise(self, output: dict[str, Any], status: LiveActionStatus) -> str:+ # The executors write a summary that states the scope of what they+ # did — "per-mailbox rule, not a tenant-wide block" — and the base+ # class's generic "<verb> <target>" would drop exactly that.+ return str(output.get("summary") or super()._summarise(output, status))+++@apply_contract+class M365SearchMailboxes(_MailboxAdapter):+ vendor_id = M365+ capability = "search_mailboxes"+ description = "Find copies of a reported message in a Microsoft 365 mailbox."+ requires_credentials = True+ _legacy_executor = SearchMailboxesExecutor()+ _legacy_action_type = ActionType.SEARCH_MAILBOXES+ _credential_keys = M365_CLIENT_PARAM_KEYS+ _vendor_pin = M365+++@apply_contract+class M365PurgeEmail(_MailboxAdapter):+ vendor_id = M365+ capability = "purge_email"+ description = "Soft-delete a message from one Microsoft 365 mailbox (recoverable items)."+ requires_credentials = True+ _legacy_executor = PurgeEmailExecutor()+ _legacy_action_type = ActionType.PURGE_EMAIL+ _credential_keys = M365_CLIENT_PARAM_KEYS+ _vendor_pin = M365+++@apply_contract+class M365RestoreEmail(_MailboxAdapter):+ vendor_id = M365+ capability = "restore_email"+ description = "Move a soft-deleted message back into a Microsoft 365 mailbox folder."+ requires_credentials = True+ _legacy_executor = RestoreEmailExecutor()+ _legacy_action_type = ActionType.RESTORE_EMAIL+ _credential_keys = M365_CLIENT_PARAM_KEYS+ _vendor_pin = M365+++@apply_contract+class M365BlockSender(_MailboxAdapter):+ vendor_id = M365+ capability = "block_sender"+ description = "Add an inbox rule deleting future mail from a sender, in one mailbox."+ requires_credentials = True+ _legacy_executor = BlockSenderExecutor()+ _legacy_action_type = ActionType.BLOCK_SENDER+ _credential_keys = M365_CLIENT_PARAM_KEYS+ _vendor_pin = M365+++@apply_contract+class M365UnblockSender(_MailboxAdapter):+ vendor_id = M365+ capability = "unblock_sender"+ description = "Remove the inbox rule block_sender created."+ requires_credentials = True+ _legacy_executor = UnblockSenderExecutor()+ _legacy_action_type = ActionType.UNBLOCK_SENDER+ _credential_keys = M365_CLIENT_PARAM_KEYS+ _vendor_pin = M365+++@apply_contract+class GmailSearchMailboxes(_MailboxAdapter):+ vendor_id = GOOGLE_WORKSPACE+ capability = "search_mailboxes"+ description = "Find copies of a reported message in a Gmail mailbox."+ requires_credentials = True+ _legacy_executor = SearchMailboxesExecutor()+ _legacy_action_type = ActionType.SEARCH_MAILBOXES+ _credential_keys = GMAIL_CLIENT_PARAM_KEYS+ _vendor_pin = GOOGLE_WORKSPACE+++@apply_contract+class GmailPurgeEmail(_MailboxAdapter):+ vendor_id = GOOGLE_WORKSPACE+ capability = "purge_email"+ description = "Move a message to Trash in one Gmail mailbox."+ requires_credentials = True+ _legacy_executor = PurgeEmailExecutor()+ _legacy_action_type = ActionType.PURGE_EMAIL+ _credential_keys = GMAIL_CLIENT_PARAM_KEYS+ _vendor_pin = GOOGLE_WORKSPACE+++@apply_contract+class GmailRestoreEmail(_MailboxAdapter):+ vendor_id = GOOGLE_WORKSPACE+ capability = "restore_email"+ description = "Take a message back out of Gmail Trash."+ requires_credentials = True+ _legacy_executor = RestoreEmailExecutor()+ _legacy_action_type = ActionType.RESTORE_EMAIL+ _credential_keys = GMAIL_CLIENT_PARAM_KEYS+ _vendor_pin = GOOGLE_WORKSPACE+++@apply_contract+class GmailBlockSender(_MailboxAdapter):+ vendor_id = GOOGLE_WORKSPACE+ capability = "block_sender"+ description = "Add a Gmail filter trashing future mail from a sender, in one mailbox."+ requires_credentials = True+ _legacy_executor = BlockSenderExecutor()+ _legacy_action_type = ActionType.BLOCK_SENDER+ _credential_keys = GMAIL_CLIENT_PARAM_KEYS+ _vendor_pin = GOOGLE_WORKSPACE+++@apply_contract+class GmailUnblockSender(_MailboxAdapter):+ vendor_id = GOOGLE_WORKSPACE+ capability = "unblock_sender"+ description = "Remove the Gmail filter block_sender created."+ requires_credentials = True+ _legacy_executor = UnblockSenderExecutor()+ _legacy_action_type = ActionType.UNBLOCK_SENDER+ _credential_keys = GMAIL_CLIENT_PARAM_KEYS+ _vendor_pin = GOOGLE_WORKSPACE++# ---------------------------------------------------------------------------# Registration entry point# ---------------------------------------------------------------------------@@ -1061,6 +1246,23 @@ _BUILTIN_ADAPTERS: tuple[type[LiveActionExecutor], ...] = (# so it raised in every agents image. Same verb, run where its clients and# its credentials are.*OSQUERY_ARMS,+ # Depth 7.1. A phishing response that could block the sender's domain at+ # the firewall and could not remove the message it arrived in.+ # Registered like every other arm, so discovery lists them and the+ # console can say the verb exists, and refused at execute() unless+ # AISOC_FEATURE_MAILBOX_REMEDIATION is set. Gating registration instead+ # would make a disabled deployment answer executor_not_found, which+ # reads as a missing integration rather than as a deliberate setting.+ M365SearchMailboxes,+ M365PurgeEmail,+ M365RestoreEmail,+ M365BlockSender,+ M365UnblockSender,+ GmailSearchMailboxes,+ GmailPurgeEmail,+ GmailRestoreEmail,+ GmailBlockSender,+ GmailUnblockSender,)diff --git a/services/actions/app/models/action.py b/services/actions/app/models/action.pyindex 5c7720b6f..ff1a326a3 100644--- a/services/actions/app/models/action.py+++ b/services/actions/app/models/action.py@@ -84,6 +84,19 @@ class ActionType(str, Enum):# raised the alert. Distinct from ack/suppress because the disposition —# not the caller — decides whether the finding is closed or escalated.UPDATE_ALERT_DISPOSITION = "update_alert_disposition"+ # Depth 7.1 — mailbox remediation for reported phish. Present here, and+ # not only in the capability vocabulary, because the post-action verifier+ # is keyed by ActionType: a verb absent from this enum can declare a+ # probe and never have it reached, which the contract gate now refuses.+ # `purge_email` is the one verb in the product whose blast radius is a+ # property of the dispatch rather than of the verb, so the entry in+ # ACTION_BLAST_RADIUS below is its single-mailbox floor and+ # `capability_contracts.scaled_impact` raises it per campaign.+ SEARCH_MAILBOXES = "search_mailboxes"+ PURGE_EMAIL = "purge_email"+ RESTORE_EMAIL = "restore_email"+ BLOCK_SENDER = "block_sender"+ UNBLOCK_SENDER = "unblock_sender"class ActionStatus(str, Enum):@@ -144,6 +157,17 @@ ACTION_BLAST_RADIUS: dict[ActionType, BlastRadius] = {# for: "classified the same as create_notable_event ... it changes a# queue item, not an estate", and create_notable_event is LOW.ActionType.UPDATE_ALERT_DISPOSITION: BlastRadius.LOW,+ # Depth 7.1 — mailbox remediation. The purge entry is the floor for one+ # mailbox; `BlastRadiusGate` reads this table and cannot see a recipient+ # count, so the campaign-scaled grading happens in the capability+ # contract where the parameters are in scope. MEDIUM is already above+ # `_AUTO_EXECUTE_LIMIT`'s sibling tiers for the legacy door's purposes+ # and `APPROVAL_REQUIRED_ACTIONS` below makes the point unconditional.+ ActionType.SEARCH_MAILBOXES: BlastRadius.MINIMAL,+ ActionType.PURGE_EMAIL: BlastRadius.MEDIUM,+ ActionType.RESTORE_EMAIL: BlastRadius.LOW,+ ActionType.BLOCK_SENDER: BlastRadius.LOW,+ ActionType.UNBLOCK_SENDER: BlastRadius.LOW,}# Actions that require explicit human approval@@ -156,6 +180,13 @@ APPROVAL_REQUIRED_ACTIONS = {ActionType.SUSPEND_SESSION,ActionType.BLOCK_IOC,ActionType.SYNC_DETECTION_RULE,+ # Removing somebody's mail is never automatic, whatever the autonomy+ # tier. The capability contract says the same thing through the matrix;+ # this is the legacy door saying it too, because the two doors+ # disagreeing about one verb is the defect `test_approval_doors_agree`+ # exists to catch.+ ActionType.PURGE_EMAIL,+ ActionType.BLOCK_SENDER,}diff --git a/services/actions/app/services/executor_registry.py b/services/actions/app/services/executor_registry.pyindex 6d3fe4e74..655c60493 100644--- a/services/actions/app/services/executor_registry.py+++ b/services/actions/app/services/executor_registry.py@@ -21,6 +21,13 @@ from app.executors.identity import (ResetPasswordExecutor,SuspendSessionExecutor,)+from app.executors.mailbox import (+ BlockSenderExecutor,+ PurgeEmailExecutor,+ RestoreEmailExecutor,+ SearchMailboxesExecutor,+ UnblockSenderExecutor,+)from app.executors.network import AllowIPExecutor, BlockDomainExecutor, BlockIPExecutorfrom app.executors.notification import CreateTicketExecutor, NotifySlackExecutorfrom app.executors.siem import (@@ -65,6 +72,16 @@ EXECUTOR_REGISTRY = {ActionType.SUPPRESS_ALERT: SuppressAlertExecutor(),# Two-way loop: AiSOC's verdict back onto the source finding.ActionType.UPDATE_ALERT_DISPOSITION: UpdateAlertDispositionExecutor(),+ # Depth 7.1 — mailbox remediation. These delegate to the live-action+ # arms rather than reimplementing them, so there is one "purge a+ # message" and both doors reach it. They are here because the post-action+ # verifier is keyed by ActionType: a capability that declares a probe and+ # has no ActionType declares a probe nothing can call.+ ActionType.SEARCH_MAILBOXES: SearchMailboxesExecutor(),+ ActionType.PURGE_EMAIL: PurgeEmailExecutor(),+ ActionType.RESTORE_EMAIL: RestoreEmailExecutor(),+ ActionType.BLOCK_SENDER: BlockSenderExecutor(),+ ActionType.UNBLOCK_SENDER: UnblockSenderExecutor(),# Notifications & orchestrationActionType.NOTIFY_SLACK: NotifySlackExecutor(),ActionType.CREATE_TICKET: CreateTicketExecutor(),diff --git a/services/actions/app/services/verification.py b/services/actions/app/services/verification.pyindex 5649620b5..7588700b5 100644--- a/services/actions/app/services/verification.py+++ b/services/actions/app/services/verification.py@@ -30,7 +30,10 @@ from typing import Anyimport structlog-from app.clients.factories import _entra_client, _mde_client, _okta_client+from app.clients.factories import _entra_client, _gmail_client, _m365_mail_client, _mde_client, _okta_client+from app.clients.gmail_client import GmailClient+from app.clients.m365_mail_client import RECOVERABLE_ITEMS+from app.core.config import get_settingsfrom app.executors.endpoint import AV_SCAN_ACTION, INVESTIGATION_PACKAGE_ACTION, _cs_clientfrom app.executors.siem import _ack_vendor, _qradar_client, _splunk_clientfrom app.models.action import ActionType@@ -448,6 +451,118 @@ async def _probe_suppress_alert(target: str, params: dict[str, Any]) -> bool | Nreturn await _read_back_finding_state(target, params, expect_closed=True)+async def _mailbox_client(params: dict[str, Any]) -> Any | None:+ """Whichever mail client the credentials in ``params`` describe.++ The two vendors are tried in a fixed order and an explicit+ ``alert_vendor`` pin wins — but a pin is honoured **only** when that+ vendor's credentials are actually present. Honouring a pin without+ checking is how a dry run called a customer's Splunk, and the same shape+ here would probe the wrong tenant's mail.+ """+ pin = str(params.get("alert_vendor") or params.get("vendor") or "").strip().lower()+ m365 = _m365_mail_client(params)+ gmail = _gmail_client(params)+ if pin in {"m365", "microsoft", "microsoft365", "office365"} and m365 is not None:+ return m365+ if pin in {"google_workspace", "gmail", "google"} and gmail is not None:+ return gmail+ return m365 or gmail+++async def _probe_purge_email(target: str, params: dict[str, Any]) -> bool | None:+ """Re-query the mailbox and confirm the message is no longer in it.++ This is the read-back the plan's contract clause names: "verification+ re-queries the mailboxes". It is also the one probe in this module whose+ confirming answer is an **absence**, which is worth stating because the+ polarity is easy to invert: ``True`` here means "the effect is present",+ and for a purge the effect is the message being gone.++ Both vendors' searches are scoped to the user-visible store on Microsoft+ and include Trash on Gmail, so the Gmail arm checks the label rather than+ the existence. A trashed Gmail message is still findable; a trashed+ message that still carries ``INBOX`` was not purged.++ Returns ``None`` — indeterminate, never a confirmation — when the feature+ is off, credentials are absent, or no message id was recorded.+ """+ if not get_settings().AISOC_FEATURE_MAILBOX_REMEDIATION:+ return None+ client = await _mailbox_client(params)+ if client is None:+ return None+ internet_id = str(params.get("internet_message_id") or "")+ message_id = str(params.get("purged_message_id") or params.get("message_id") or "")+ if not (internet_id or message_id):+ return None+ try:+ if isinstance(client, GmailClient):+ if not message_id:+ return None+ message = await client.get_message(target, message_id)+ labels = {str(label).upper() for label in (message.get("labelIds") or [])}+ # TRASH is the purge's effect; the absence of INBOX alone is not,+ # because a message the user had already archived never had it.+ return "TRASH" in labels+ if not internet_id:+ return None+ remaining = await client.search_messages(target, internet_message_id=internet_id, limit=5)+ return len(remaining) == 0+ except Exception as exc: # noqa: BLE001 - an unreadable mailbox is indeterminate+ logger.warning("verification.mailbox_probe_error", target=target, error=str(exc)[:300])+ return None+++async def _probe_restore_email(target: str, params: dict[str, Any]) -> bool | None:+ """Confirm the message is back where a user can see it."""+ if not get_settings().AISOC_FEATURE_MAILBOX_REMEDIATION:+ return None+ client = await _mailbox_client(params)+ if client is None:+ return None+ message_id = str(params.get("restored_message_id") or params.get("restore_message_id") or params.get("message_id") or "")+ if not message_id:+ return None+ try:+ if isinstance(client, GmailClient):+ message = await client.get_message(target, message_id)+ return "TRASH" not in {str(label).upper() for label in (message.get("labelIds") or [])}+ message = await client.get_message(target, message_id, with_headers=False)+ folder = str(message.get("parentFolderId") or "")+ # Graph answers with the folder the message now sits in. A restore+ # that landed back in recoverable items did not happen, whatever the+ # move returned.+ return bool(folder) and RECOVERABLE_ITEMS not in folder.lower()+ except Exception as exc: # noqa: BLE001+ logger.warning("verification.mailbox_probe_error", target=target, error=str(exc)[:300])+ return None+++async def _probe_block_sender(target: str, params: dict[str, Any]) -> bool | None:+ """Confirm the rule or filter exists in the mailbox it was created in."""+ if not get_settings().AISOC_FEATURE_MAILBOX_REMEDIATION:+ return None+ client = await _mailbox_client(params)+ if client is None:+ return None+ rule_id = str(params.get("rule_id") or params.get("filter_id") or "")+ if not rule_id:+ return None+ try:+ existing = await (client.list_filters(target) if isinstance(client, GmailClient) else client.list_inbox_rules(target))+ except Exception as exc: # noqa: BLE001+ logger.warning("verification.mailbox_probe_error", target=target, error=str(exc)[:300])+ return None+ return any(str(entry.get("id") or "") == rule_id for entry in existing)+++async def _probe_unblock_sender(target: str, params: dict[str, Any]) -> bool | None:+ """The inverse read: the rule must be gone."""+ present = await _probe_block_sender(target, params)+ return None if present is None else not present++_DEFAULT_PROBES: dict[ActionType, Probe] = {ActionType.ISOLATE_HOST: _probe_isolate,ActionType.BLOCK_IP: _probe_block_ip,@@ -463,6 +578,14 @@ _DEFAULT_PROBES: dict[ActionType, Probe] = {ActionType.KILL_PROCESS: _probe_kill_process,ActionType.QUARANTINE_FILE: _probe_quarantine_file,ActionType.RUN_AV_SCAN: _probe_run_av_scan,+ # Depth 7.1. "Verification re-queries the mailboxes" is a clause in the+ # contract the plan specifies, not a nice-to-have: a purge reported from+ # an accepted move, across twenty-five mailboxes, is twenty-five+ # unverified claims that the message is gone.+ ActionType.PURGE_EMAIL: _probe_purge_email,+ ActionType.RESTORE_EMAIL: _probe_restore_email,+ ActionType.BLOCK_SENDER: _probe_block_sender,+ ActionType.UNBLOCK_SENDER: _probe_unblock_sender,}diff --git a/services/actions/tests/test_live_action_builtins.py b/services/actions/tests/test_live_action_builtins.pyindex 4d43d806c..837844c48 100644--- a/services/actions/tests/test_live_action_builtins.py+++ b/services/actions/tests/test_live_action_builtins.py@@ -66,7 +66,7 @@ def test_register_builtin_executors_returns_full_count() -> None:# sign-ins, Google Workspace login audit) and two verbs whose subject is# neither a host nor a principal (AWS CloudTrail lookup, Defender# endpoint-telemetry search).- assert count == 79+ assert count == 89def test_builtin_executors_cover_canonical_vendor_capability_pairs() -> None:@@ -169,6 +169,20 @@ def test_builtin_executors_cover_canonical_vendor_capability_pairs() -> None:("splunk", "sync_detection_rule"),("splunk", "update_alert_disposition"),("teams", "chatops_verify"),+ # Depth 7.1 — mailbox remediation. Ten pairs: five verbs against+ # Microsoft 365 and Google Workspace. Before these the registry had+ # no way to touch a mailbox at all, so the phishing response could+ # block the sender's domain and not remove the message.+ ("m365", "search_mailboxes"),+ ("m365", "purge_email"),+ ("m365", "restore_email"),+ ("m365", "block_sender"),+ ("m365", "unblock_sender"),+ ("google_workspace", "search_mailboxes"),+ ("google_workspace", "purge_email"),+ ("google_workspace", "restore_email"),+ ("google_workspace", "block_sender"),+ ("google_workspace", "unblock_sender"),}assert pairs == expected@@ -199,7 +213,7 @@ def test_register_builtin_executors_is_idempotent_with_overwrite() -> None:register_builtin_executors()# Second call without overwrite would raise — confirm overwrite works.count = register_builtin_executors(overwrite=True)- assert count == 79+ assert count == 89def test_register_builtin_twice_without_overwrite_raises() -> None:diff --git a/services/actions/tests/test_mailbox_remediation.py b/services/actions/tests/test_mailbox_remediation.pynew file mode 100644index 000000000..17a536671--- /dev/null+++ b/services/actions/tests/test_mailbox_remediation.py@@ -0,0 +1,594 @@+"""Mailbox remediation: the reproduction, the behaviour, and the negative controls.++The reproduction this file pins first is the one the gate found: before depth+7.1 the live-action registry held 79 builtin arms and not one of them could+touch a mailbox, so ``dispatcher.dispatch`` answered ``executor_not_found``+for ``purge_email``. That is recorded in+:func:`test_every_mailbox_verb_resolves_through_governed_dispatch`, which+fails on the pre-fix tree for exactly that reason.++Everything else here exists because its opposite has shipped in this+repository at least once:++* a dry run reporting a vendor call that never happened;+* a "purge" over mailboxes that never held the message, counted as a success;+* a rollback that returns ``True`` without contacting anything;+* a pinned vendor honoured without checking that vendor's credentials exist;+* a verification probe whose confirming answer has the polarity inverted.++The vendor payloads are the documented shapes — a Microsoft Graph ``message``+resource and a Gmail ``Message`` — and the HTTP layer is a real ``respx``+mock, so the request path, the URL and the body are exercised rather than+described. That is the point of+:class:`TestTheRequestShapeIsWhatTheVendorDocuments`: a mock that answers+whatever the reader asks for cannot notice a query that never requested the+field, which is how hostname and username came to be null on four of five+closed-finding readers.+"""++from __future__ import annotations++import json+import uuid++import httpx+import pytest+import respx+from app.clients import factories+from app.clients.m365_mail_client import RECOVERABLE_ITEMS, normalise_internet_message_id, quote_odata_string+from app.core.config import get_settings+from app.executors import mailbox+from app.executors.mailbox import (+ BlockSenderExecutor,+ PurgeEmailExecutor,+ SearchMailboxesExecutor,+ choose_vendor,+)+from app.live_actions import builtins, dispatcher, registry+from app.live_actions.capability_contracts import (+ CAPABILITY_CONTRACTS,+ recipient_count_from,+ scaled_impact,+)+from app.live_actions.contract import ActionImpact, ApprovalRequirement, Reversal+from app.live_actions.models import LiveActionRequest, LiveActionStatus+from app.models.action import ActionRequest, ActionStatus, ActionType+from app.services.verification import PostActionVerifier, VerificationOutcome++MAILBOX_VERBS = ("search_mailboxes", "purge_email", "restore_email", "block_sender", "unblock_sender")+VENDORS = ("m365", "google_workspace")++#: RFC 5737 documentation addresses and RFC 2606 names throughout. Nothing+#: here resolves, and that is asserted by the repo's own fixture conventions+#: rather than left to reviewer discipline.+MAILBOX = "[email protected]"+SENDER = "[email protected]"+INTERNET_ID = "<[email protected]>"++M365_CREDENTIALS = {+ "azure_tenant_id": "00000000-0000-4000-8000-000000000001",+ "azure_client_id": "00000000-0000-4000-8000-000000000002",+ "azure_client_secret": "unit-test-placeholder",+}+GMAIL_CREDENTIALS = {+ # A structurally valid service-account document. The private key is only+ # ever used by a test that does not mint a token.+ "gws_service_account_key": json.dumps({"client_email": "[email protected]", "private_key": "-----BEGIN-----"}),+ "gws_subject_email": "[email protected]",+}++#: A trimmed Microsoft Graph `message` resource, in the documented shape.+GRAPH_MESSAGE = {+ "id": "AAMkAGI2THVSAAA=",+ "internetMessageId": INTERNET_ID,+ "subject": "Action required: your invoice is overdue",+ "from": {"emailAddress": {"name": "Billing", "address": SENDER}},+ "toRecipients": [{"emailAddress": {"address": MAILBOX}}],+ "receivedDateTime": "2026-10-11T06:04:00Z",+ "parentFolderId": "AQMkADAwATM0MDAAMS0wAGZmYy1",+ "hasAttachments": True,+}++#: Gmail's `users.messages.list` answers id + threadId and nothing else.+GMAIL_LIST = {"messages": [{"id": "19a2f4c1d0e5b7a3", "threadId": "19a2f4c1d0e5b7a3"}], "resultSizeEstimate": 1}++[email protected](autouse=True)+def _registered() -> None:+ registry.reset_for_tests()+ builtins.register_builtin_executors(overwrite=True)+++def _enabled(monkeypatch: pytest.MonkeyPatch):+ """Turn the feature on for the duration of one test.++ ``get_settings`` is ``lru_cache``d, so the object is shared and the+ attribute is patched on the instance rather than the environment.+ """+ monkeypatch.setattr(get_settings(), "AISOC_FEATURE_MAILBOX_REMEDIATION", True, raising=False)+ return None+++def _request(action_type: ActionType, target: str = MAILBOX, **params) -> ActionRequest:+ return ActionRequest(+ incident_id=uuid.uuid4(),+ tenant_id=uuid.uuid4(),+ action_type=action_type,+ target=target,+ parameters=params,+ )+++def _graph_token_route() -> None:+ respx.post(url__regex=r"https://login\.microsoftonline\.com/.*/oauth2/v2\.0/token").mock(+ return_value=httpx.Response(200, json={"access_token": "unit-test-token", "expires_in": 3600})+ )+++# ───────────────────────── reproduction ──────────────────────────────────++[email protected]("vendor", VENDORS)[email protected]("capability", MAILBOX_VERBS)+def test_every_mailbox_verb_resolves_through_governed_dispatch(vendor: str, capability: str) -> None:+ """The regression. All ten of these returned ``None`` before depth 7.1.++ Recorded against the pre-fix tree by driving the dispatcher directly: it+ logged ``live_action.unknown`` and answered ``executor_not_found`` for a+ phishing response that could block the sender's domain at the firewall+ and could not remove the message it arrived in.+ """+ assert registry.get_executor(vendor, capability) is not None, (+ f"{vendor}/{capability} does not resolve, so dispatcher.dispatch answers executor_not_found."+ )+++async def test_dispatch_no_longer_answers_executor_not_found() -> None:+ result = await dispatcher.dispatch(+ LiveActionRequest(capability="purge_email", vendor_id="m365", target=MAILBOX, dry_run=True, confidence=0.5)+ )+ assert result.error != "executor_not_found"+++# ───────────────────────── off by default ────────────────────────────────+++class TestOffByDefault:+ """A reach-out capability an upgrade must not silently acquire."""++ def test_the_flag_defaults_off(self) -> None:+ from app.core.config import ActionsSettings++ assert ActionsSettings.model_fields["AISOC_FEATURE_MAILBOX_REMEDIATION"].default is False++ @pytest.mark.asyncio+ @pytest.mark.parametrize("action_type", [ActionType.SEARCH_MAILBOXES, ActionType.PURGE_EMAIL, ActionType.BLOCK_SENDER])+ async def test_disabled_fails_and_says_why_rather_than_simulating(self, action_type: ActionType) -> None:+ executor = {+ ActionType.SEARCH_MAILBOXES: SearchMailboxesExecutor(),+ ActionType.PURGE_EMAIL: PurgeEmailExecutor(),+ ActionType.BLOCK_SENDER: BlockSenderExecutor(),+ }[action_type]+ result = await executor.execute(_request(action_type, sender=SENDER, **M365_CREDENTIALS))+ assert result.status is ActionStatus.FAILED+ assert result.output["executed"] is False+ assert "AISOC_FEATURE_MAILBOX_REMEDIATION" in (result.error or "")++ @pytest.mark.asyncio+ async def test_disabled_reads_differently_from_a_missing_credential(self, monkeypatch: pytest.MonkeyPatch) -> None:+ """Three causes, three next steps. A shared message sends an operator to the wrong one."""+ disabled = await PurgeEmailExecutor().execute(_request(ActionType.PURGE_EMAIL, **M365_CREDENTIALS))+ monkeypatch.setattr(get_settings(), "AISOC_FEATURE_MAILBOX_REMEDIATION", True, raising=False)+ uncredentialed = await PurgeEmailExecutor().execute(_request(ActionType.PURGE_EMAIL))+ assert disabled.error != uncredentialed.error+ assert "credentials" in (uncredentialed.error or "")+++# ───────────────────────── a dry run is not a success ────────────────────+++class TestADryRunNeverReportsAVendorCall:+ """``NotifySlackExecutor`` reported ``message_sent: true`` for a message it never sent."""++ @pytest.mark.asyncio+ @pytest.mark.parametrize("vendor", VENDORS)+ async def test_dry_run_is_simulated_and_executed_is_false(self, vendor: str, _enabled) -> None:+ executor = registry.get_executor(vendor, "purge_email")+ result = await executor.execute(+ LiveActionRequest(+ capability="purge_email",+ vendor_id=vendor,+ target=MAILBOX,+ params={**M365_CREDENTIALS, **GMAIL_CREDENTIALS, "internet_message_id": INTERNET_ID},+ dry_run=True,+ )+ )+ assert result.status is LiveActionStatus.SIMULATED+ assert result.details["executed"] is False++ @pytest.mark.asyncio+ @respx.mock+ async def test_a_dry_run_makes_no_http_call_at_all(self, _enabled) -> None:+ """Stronger than checking the status: nothing may reach the network.++ Every route is mocked to raise, so a request of any kind fails the+ test with the URL rather than by relying on CI refusing egress.+ """+ tripwire = respx.route().mock(side_effect=AssertionError("a dry run made an HTTP call"))+ executor = registry.get_executor("m365", "purge_email")+ result = await executor.execute(+ LiveActionRequest(+ capability="purge_email",+ vendor_id="m365",+ target=MAILBOX,+ params={**M365_CREDENTIALS, "internet_message_id": INTERNET_ID},+ dry_run=True,+ )+ )+ assert result.status is LiveActionStatus.SIMULATED+ assert not tripwire.called+++# ───────────────────────── the vendor request shape ──────────────────────+++class TestTheRequestShapeIsWhatTheVendorDocuments:+ """A mock that answers whatever is asked cannot notice an unasked field."""++ @pytest.mark.asyncio+ @respx.mock+ async def test_m365_search_filters_on_the_bracketed_internet_message_id(self, _enabled) -> None:+ _graph_token_route()+ route = respx.get(url__regex=r"https://graph\.microsoft\.com/v1\.0/users/.*/messages").mock(+ return_value=httpx.Response(200, json={"value": [GRAPH_MESSAGE]})+ )+ result = await SearchMailboxesExecutor().execute(+ _request(ActionType.SEARCH_MAILBOXES, internet_message_id=INTERNET_ID.strip("<>"), **M365_CREDENTIALS)+ )+ assert result.status is ActionStatus.COMPLETED+ assert result.output["match_count"] == 1+ # Read the decoded parameters, not the raw URL: percent-encoding+ # would hide both of these assertions behind `%27%3C`.+ params = route.calls.last.request.url.params+ assert f"internetMessageId eq '{INTERNET_ID}'" == params["$filter"], (+ "Graph stores a Message-ID bracketed; an unbracketed filter matches nothing and reads as 'the message is not in that mailbox'."+ )+ assert "parentFolderId" in params["$select"], "restore needs the original folder, and only the search can read it"++ @pytest.mark.asyncio+ @respx.mock+ async def test_gmail_search_uses_the_documented_rfc822msgid_operator(self, _enabled) -> None:+ respx.post("https://oauth2.googleapis.com/token").mock(+ return_value=httpx.Response(200, json={"access_token": "unit-test-token", "expires_in": 3600})+ )+ route = respx.get(url__regex=r"https://gmail\.googleapis\.com/gmail/v1/users/.*/messages").mock(+ return_value=httpx.Response(200, json=GMAIL_LIST)+ )+ client = factories._gmail_client(GMAIL_CREDENTIALS)+ # Minting a token needs a real RSA key; the search itself is what is+ # under test, so the token cache is primed directly.+ client._tokens[MAILBOX] = ("unit-test-token", 2**31)+ found = await client.search_messages(MAILBOX, internet_message_id=INTERNET_ID)+ assert found == GMAIL_LIST["messages"]+ assert "rfc822msgid" in str(route.calls.last.request.url)++ @pytest.mark.asyncio+ @respx.mock+ async def test_m365_purge_moves_to_recoverable_items_not_a_hard_delete(self, _enabled) -> None:+ _graph_token_route()+ respx.get(url__regex=r"https://graph\.microsoft\.com/v1\.0/users/.*/messages\?.*").mock(+ return_value=httpx.Response(200, json={"value": [GRAPH_MESSAGE]})+ )+ move = respx.post(url__regex=r"https://graph\.microsoft\.com/v1\.0/users/.*/messages/.*/move").mock(+ return_value=httpx.Response(201, json={**GRAPH_MESSAGE, "id": "AAMkNEWID=", "parentFolderId": "recoverableitems"})+ )+ deleted = respx.delete(url__regex=r"https://graph\.microsoft\.com/v1\.0/users/.*/messages/.*").mock(+ side_effect=AssertionError("purge must never issue a hard DELETE: it has no reverse")+ )++ result = await PurgeEmailExecutor().execute(_request(ActionType.PURGE_EMAIL, internet_message_id=INTERNET_ID, **M365_CREDENTIALS))++ assert result.status is ActionStatus.COMPLETED+ assert result.output["executed"] is True+ assert json.loads(move.calls.last.request.content)["destinationId"] == RECOVERABLE_ITEMS+ assert not deleted.called+ # What the rollback needs, carried out of the action that created it.+ assert result.rollback_data["restore_message_id"] == "AAMkNEWID="+ assert result.rollback_data["restore_folder_id"] == GRAPH_MESSAGE["parentFolderId"]+++# ───────────────────────── nothing found is not a purge ──────────────────+++class TestNothingFoundIsNotASuccess:+ @pytest.mark.asyncio+ @respx.mock+ async def test_a_mailbox_without_the_message_fails_rather_than_reporting_a_purge(self, _enabled) -> None:+ """A fan-out that counts empty mailboxes as purged publishes a meaningless number."""+ _graph_token_route()+ respx.get(url__regex=r"https://graph\.microsoft\.com/v1\.0/users/.*/messages\?.*").mock(+ return_value=httpx.Response(200, json={"value": []})+ )+ move = respx.post(url__regex=r".*/move").mock(side_effect=AssertionError("nothing to move"))+ result = await PurgeEmailExecutor().execute(_request(ActionType.PURGE_EMAIL, internet_message_id=INTERNET_ID, **M365_CREDENTIALS))+ assert result.status is ActionStatus.FAILED+ assert result.output["executed"] is False+ assert result.output["match_count"] == 0+ assert not move.called+++# ───────────────────────── the rollback is real ──────────────────────────+++class TestTheRollbackContactsTheVendor:+ """``unisolate_host`` resolved to nothing. This is the same shape, wider."""++ @pytest.mark.asyncio+ @respx.mock+ async def test_purge_rollback_issues_a_move_back_to_the_original_folder(self, _enabled) -> None:+ _graph_token_route()+ move = respx.post(url__regex=r"https://graph\.microsoft\.com/v1\.0/users/.*/messages/.*/move").mock(+ return_value=httpx.Response(201, json={**GRAPH_MESSAGE, "id": "AAMkRESTORED="})+ )+ purged = await PurgeEmailExecutor().execute(+ _request(+ ActionType.PURGE_EMAIL,+ message_id=GRAPH_MESSAGE["id"],+ source_folder_id=GRAPH_MESSAGE["parentFolderId"],+ **M365_CREDENTIALS,+ )+ )+ assert purged.status is ActionStatus.COMPLETED+ # The credentials have to travel with the rollback; without them the+ # reverse resolves to "no credentials" and returns False, which is+ # the honest answer and a useless one.+ purged.output["credentials"] = M365_CREDENTIALS+ ok = await PurgeEmailExecutor().rollback(purged)+ assert ok is True+ assert move.call_count == 2+ assert json.loads(move.calls.last.request.content)["destinationId"] == GRAPH_MESSAGE["parentFolderId"]++ @pytest.mark.asyncio+ async def test_a_rollback_with_nothing_to_restore_returns_false_rather_than_true(self, _enabled) -> None:+ """``BaseExecutor.rollback`` defaults to ``False``; an optimistic ``True`` is worse than no rollback."""+ from app.models.action import ActionResult, BlastRadius++ incomplete = ActionResult(+ action_id=uuid.uuid4(),+ status=ActionStatus.COMPLETED,+ blast_radius=BlastRadius.MEDIUM,+ rollback_data={"vendor": "m365", "mailbox": MAILBOX},+ )+ assert await PurgeEmailExecutor().rollback(incomplete) is False++ def test_the_contract_names_a_reverse_that_exists(self) -> None:+ contract = CAPABILITY_CONTRACTS["purge_email"]+ assert contract.reversal is Reversal.PLATFORM+ assert contract.reverse_capability == "restore_email"+ assert registry.get_executor("m365", contract.reverse_capability) is not None+ assert registry.get_executor("google_workspace", contract.reverse_capability) is not None+++# ───────────────────────── blast radius scales ───────────────────────────+++class TestBlastRadiusScalesWithRecipients:+ """Gap-closure 10.2: "blast radius scales with the number of recipients"."""++ @pytest.mark.parametrize(+ ("count", "expected"),+ [+ (1, ActionImpact.MODERATE),+ (4, ActionImpact.MODERATE),+ (5, ActionImpact.HIGH),+ (24, ActionImpact.HIGH),+ (25, ActionImpact.SEVERE),+ ],+ )+ def test_the_ladder(self, count: int, expected: ActionImpact) -> None:+ assert scaled_impact("purge_email", {"recipient_count": count}) is expected++ def test_an_unknown_count_reads_as_one_not_as_zero(self) -> None:+ """Zero would let a caller omit the field to dodge the ladder."""+ assert recipient_count_from(None) == 1+ assert recipient_count_from({}) == 1+ assert recipient_count_from({"recipient_count": "not a number"}) == 1+ assert recipient_count_from({"recipient_count": 0}) == 1++ def test_a_recipient_list_counts_itself(self) -> None:+ assert recipient_count_from({"recipients": [MAILBOX, "[email protected]"]}) == 2++ def test_scaling_never_lowers_an_impact(self) -> None:+ """The same one-way property the approval matrix has."""+ base = CAPABILITY_CONTRACTS["purge_email"].impact+ for count in (1, 2, 5, 25, 1000):+ assert scaled_impact("purge_email", {"recipient_count": count}).value in {+ base.value,+ ActionImpact.HIGH.value,+ ActionImpact.SEVERE.value,+ }++ def test_restore_is_deliberately_not_scaled(self) -> None:+ """Making the rollback harder to authorise than the action is how a containment becomes permanent."""+ assert scaled_impact("restore_email", {"recipient_count": 500}) is CAPABILITY_CONTRACTS["restore_email"].impact++ def test_a_twenty_five_recipient_campaign_requires_a_human_at_any_confidence(self) -> None:+ """The gap-closure plan's own 'Done when' clause, as an assertion."""+ from app.live_actions.approval_rules import evaluate++ for tier in ("L0", "L1", "L2", "L3", "L4"):+ decision = evaluate(+ impact=scaled_impact("purge_email", {"recipient_count": 25}),+ declared_approval=CAPABILITY_CONTRACTS["purge_email"].approval,+ confidence=1.0,+ tier=tier,+ )+ assert decision.requirement is ApprovalRequirement.MANDATORY_HUMAN+ assert decision.can_auto_execute is False++ def test_a_single_recipient_purge_still_needs_an_analyst(self) -> None:+ from app.live_actions.approval_rules import evaluate++ decision = evaluate(+ impact=scaled_impact("purge_email", {"recipient_count": 1}),+ declared_approval=CAPABILITY_CONTRACTS["purge_email"].approval,+ confidence=1.0,+ tier="L4",+ )+ assert decision.requirement is ApprovalRequirement.ANALYST+++# ───────────────────────── verification re-queries ───────────────────────+++class TestVerificationRequeriesTheMailbox:+ """10.2: "verification re-queries the mailboxes". The probe's confirming answer is an absence."""++ @pytest.mark.asyncio+ @respx.mock+ async def test_a_purged_message_that_is_gone_verifies(self, _enabled) -> None:+ _graph_token_route()+ respx.get(url__regex=r"https://graph\.microsoft\.com/v1\.0/users/.*/messages\?.*").mock(+ return_value=httpx.Response(200, json={"value": []})+ )+ result = await PostActionVerifier().verify(+ ActionType.PURGE_EMAIL, MAILBOX, {"internet_message_id": INTERNET_ID, **M365_CREDENTIALS}+ )+ assert result.outcome is VerificationOutcome.VERIFIED++ @pytest.mark.asyncio+ @respx.mock+ async def test_a_message_still_present_fails_verification(self, _enabled) -> None:+ """The negative control for the polarity. Inverting the probe makes this pass as VERIFIED."""+ _graph_token_route()+ respx.get(url__regex=r"https://graph\.microsoft\.com/v1\.0/users/.*/messages\?.*").mock(+ return_value=httpx.Response(200, json={"value": [GRAPH_MESSAGE]})+ )+ result = await PostActionVerifier().verify(+ ActionType.PURGE_EMAIL, MAILBOX, {"internet_message_id": INTERNET_ID, **M365_CREDENTIALS}+ )+ assert result.outcome is VerificationOutcome.FAILED++ @pytest.mark.asyncio+ async def test_no_credentials_is_unverified_never_verified(self) -> None:+ result = await PostActionVerifier().verify(ActionType.PURGE_EMAIL, MAILBOX, {"internet_message_id": INTERNET_ID})+ assert result.outcome is VerificationOutcome.UNVERIFIED++ @pytest.mark.asyncio+ async def test_the_feature_being_off_is_unverified_never_verified(self) -> None:+ """Off must not certify: a probe that cannot run has not confirmed anything."""+ result = await PostActionVerifier().verify(+ ActionType.PURGE_EMAIL, MAILBOX, {"internet_message_id": INTERNET_ID, **M365_CREDENTIALS}+ )+ assert result.outcome is VerificationOutcome.UNVERIFIED++ @pytest.mark.parametrize("action_type", [ActionType.PURGE_EMAIL, ActionType.RESTORE_EMAIL, ActionType.BLOCK_SENDER])+ def test_every_verb_declaring_a_probe_has_one_registered(self, action_type: ActionType) -> None:+ """A contract declaring a probe nothing can call is worse than declaring none."""+ assert CAPABILITY_CONTRACTS[action_type.value].has_verification_probe is True+ assert action_type in PostActionVerifier().probes+++# ───────────────────────── vendor selection ──────────────────────────────+++class TestVendorSelection:+ def test_a_pin_is_ignored_when_that_vendors_credentials_are_absent(self) -> None:+ """Honouring a pin blindly is how a dry run called a customer's Splunk."""+ assert choose_vendor({"alert_vendor": "m365", **GMAIL_CREDENTIALS}) == mailbox.GOOGLE_WORKSPACE++ def test_a_pin_wins_when_both_are_configured(self) -> None:+ both = {**M365_CREDENTIALS, **GMAIL_CREDENTIALS}+ assert choose_vendor({"alert_vendor": "gmail", **both}) == mailbox.GOOGLE_WORKSPACE+ assert choose_vendor({"alert_vendor": "m365", **both}) == mailbox.M365++ def test_no_credentials_selects_nothing(self) -> None:+ assert choose_vendor({}) == ""++ def test_the_adapter_pins_its_own_vendor(self) -> None:+ for vendor in VENDORS:+ for capability in MAILBOX_VERBS:+ executor = registry.get_executor(vendor, capability)+ assert executor._vendor_pin == vendor # noqa: SLF001++ def test_each_adapters_strip_list_is_its_factorys_key_set(self) -> None:+ """The hand-copied list is the shape that let a 'dry run' reach production Splunk."""+ expected = {+ "m365": set(mailbox.M365_CLIENT_PARAM_KEYS),+ "google_workspace": set(mailbox.GMAIL_CLIENT_PARAM_KEYS),+ }+ for vendor in VENDORS:+ for capability in MAILBOX_VERBS:+ executor = registry.get_executor(vendor, capability)+ assert set(executor._credential_keys) == expected[vendor] # noqa: SLF001++ @pytest.mark.parametrize(+ ("vendor", "factory", "credentials"),+ [+ ("m365", factories._m365_mail_client, M365_CREDENTIALS),+ ("google_workspace", factories._gmail_client, GMAIL_CREDENTIALS),+ ],+ )+ def test_stripping_the_declared_keys_disables_the_factory(self, vendor: str, factory, credentials: dict) -> None:+ """The behavioural claim behind the strip list."""+ full = {**M365_CREDENTIALS, **GMAIL_CREDENTIALS}+ assert factory(full) is not None+ declared = mailbox.M365_CLIENT_PARAM_KEYS if vendor == "m365" else mailbox.GMAIL_CLIENT_PARAM_KEYS+ assert factory({k: v for k, v in full.items() if k not in set(declared)}) is None+++# ───────────────────────── scope honesty ─────────────────────────────────+++class TestTheSenderBlockSaysItIsPerMailbox:+ @pytest.mark.asyncio+ @respx.mock+ async def test_the_summary_an_analyst_reads_states_the_scope(self, _enabled) -> None:+ """ "Sender blocked" without the scope means something the action did not do."""+ _graph_token_route()+ respx.post(url__regex=r".*/mailFolders/inbox/messageRules").mock(return_value=httpx.Response(201, json={"id": "rule-1"}))+ result = await BlockSenderExecutor().execute(_request(ActionType.BLOCK_SENDER, sender=SENDER, **M365_CREDENTIALS))+ assert result.status is ActionStatus.COMPLETED+ assert result.output["scope"] == "mailbox"+ assert "only" in result.output["summary"]+ assert "organisation-wide" in result.output["summary"] or "tenant-wide" in result.output["summary"]+++# ───────────────────────── injection surfaces ────────────────────────────+++class TestAttackerSuppliedValuesCannotCloseAQuery:+ """Every value here comes off a message a stranger sent to the customer."""++ def test_odata_single_quotes_are_doubled(self) -> None:+ assert quote_odata_string("o'[email protected]") == "o''[email protected]"++ def test_control_characters_are_dropped_rather_than_escaped(self) -> None:+ assert "\n" not in quote_odata_string("a\[email protected]")++ def test_an_unbracketed_message_id_is_bracketed(self) -> None:+ assert normalise_internet_message_id("[email protected]") == "<[email protected]>"+ assert normalise_internet_message_id("<[email protected]>") == "<[email protected]>"++ @pytest.mark.parametrize(+ "payload",+ [+ "x in:anywhere from:[email protected]",+ 'x" OR label:inbox',+ "x\nfrom:[email protected]",+ "subject:(secret)",+ ],+ )+ def test_gmail_refuses_a_query_value_rather_than_escaping_it(self, payload: str) -> None:+ """Refuse, do not escape: an escaped value that matches nothing reports a clean mailbox."""+ from app.clients.gmail_client import quote_gmail_query_value++ with pytest.raises(ValueError):+ quote_gmail_query_value(payload)++ def test_an_ordinary_message_id_is_accepted(self) -> None:+ from app.clients.gmail_client import quote_gmail_query_value++ assert quote_gmail_query_value(INTERNET_ID) == INTERNET_ID.strip("<>")