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 capability contracts with recipient-scaled impact
Beenu Arora8204271191b2
diff --git a/services/actions/app/clients/factories.py b/services/actions/app/clients/factories.pyindex 094a0f205..0c67dbda1 100644--- a/services/actions/app/clients/factories.py+++ b/services/actions/app/clients/factories.py@@ -29,7 +29,9 @@ from app.clients.cortex_xdr_client import CortexXdrClientfrom app.clients.crowdstrike_rtr import CrowdStrikeRTRClientfrom app.clients.defender_client import DefenderClientfrom app.clients.fortigate_client import FortiGateClient+from app.clients.gmail_client import GmailClientfrom app.clients.google_workspace_client import GoogleWorkspaceClient+from app.clients.m365_mail_client import M365MailClientfrom app.clients.okta_client import OktaClientfrom app.clients.panos_client import PanOsClientfrom app.clients.sentinelone_client import SentinelOneClient@@ -190,6 +192,43 @@ def _s1_client(params: dict) -> SentinelOneClient | None:return SentinelOneClient(console_url=console_url, api_token=api_token)+def _m365_mail_client(params: dict) -> M365MailClient | None:+ """Mailbox client from the same three fields the Entra client reads.++ Deliberately the same credential names: one Azure app registration with+ both the directory and the mail permissions covers identity response and+ mailbox remediation, and asking an operator to register a second app to+ purge a phishing message is friction with no security benefit.+ """+ tenant_id = params.get("azure_tenant_id")+ client_id = params.get("azure_client_id")+ client_secret = params.get("azure_client_secret")+ if not (tenant_id and client_id and client_secret):+ return None+ return M365MailClient(tenant_id=tenant_id, client_id=client_id, client_secret=client_secret)+++def _gmail_client(params: dict) -> GmailClient | None:+ """Gmail client from the Workspace service-account key.++ ``gws_subject_email`` is optional here and required on the Workspace+ client, because Gmail impersonates the mailbox being acted on rather than+ a fixed admin — the subject is per call. It is still read so a deployment+ that configures only a report mailbox has a default.+ """+ key = params.get("gws_service_account_key")+ if not key:+ return None+ try:+ return GmailClient(service_account_key=key, subject_email=str(params.get("gws_subject_email") or ""))+ except ValueError:+ # A malformed key is a configuration error, and the caller's+ # "credentials not configured" branch is the right place for it to+ # surface: both mean "we did not reach the vendor", and raising here+ # would turn it into an executor crash instead.+ return None++__all__ = ["_aws_client","_cloudflare_client",@@ -198,7 +237,9 @@ __all__ = ["_cs_client","_entra_client","_fortigate_client",+ "_gmail_client","_gws_client",+ "_m365_mail_client","_mde_client","_okta_client","_panos_client",diff --git a/services/actions/app/clients/gmail_client.py b/services/actions/app/clients/gmail_client.pynew file mode 100644index 000000000..eeb700457--- /dev/null+++ b/services/actions/app/clients/gmail_client.py@@ -0,0 +1,302 @@+"""Gmail client — reported-phish remediation across Workspace mailboxes.++Beside :mod:`app.clients.google_workspace_client` rather than inside it, and+the reason is structural rather than tidiness. That client holds **one**+delegated subject for its whole lifetime, because the Admin SDK acts on the+directory and one admin subject covers every user in it. Gmail does not work+that way: under domain-wide delegation the mailbox you may touch is the one+named in the JWT's ``sub`` claim, so acting on twenty-five recipients means+twenty-five tokens. Reusing the existing client would have meant constructing+twenty-five of it, or silently acting on the wrong mailbox.++Verbs, all documented by the Gmail API+--------------------------------------+* search — ``GET users/{mailbox}/messages?q=rfc822msgid:<id>``+* read — ``GET users/{mailbox}/messages/{id}?format=metadata``+* trash — ``POST users/{mailbox}/messages/{id}/trash``+* untrash — ``POST users/{mailbox}/messages/{id}/untrash``+* filters — ``POST`` / ``DELETE users/{mailbox}/settings/filters``++Trash is the Workspace half of ``purge_email`` and untrash is its reverse,+exactly as the plan specifies. A trashed message is recoverable for 30 days;+``users.messages.delete`` is permanent, has no reverse, and is deliberately+absent.++As on Microsoft, the sender block is a **per-mailbox** filter. Workspace's+domain-level blocked-sender list lives in Admin console email settings, which+the Admin SDK does not expose, so the organisation-wide verb is not declared.++Scopes the service account needs, granted domain-wide:++* ``https://www.googleapis.com/auth/gmail.modify`` — trash, untrash+* ``https://www.googleapis.com/auth/gmail.settings.basic`` — filters+* ``https://www.googleapis.com/auth/gmail.readonly`` — search, read++Credentials expected in ``LiveActionRequest.params``:++* ``gws_service_account_key`` — the JSON key, as a string or an object+* ``gws_subject_email`` — fallback mailbox when the caller names none,+ normally the report mailbox the poller reads+"""++from __future__ import annotations++import base64+import json+import time+from typing import Any+from urllib.parse import quote++import httpx+import structlog++logger = structlog.get_logger()++_TOKEN_URI = "https://oauth2.googleapis.com/token"+_GMAIL = "https://gmail.googleapis.com/gmail/v1"++_SCOPES = " ".join(+ [+ "https://www.googleapis.com/auth/gmail.readonly",+ "https://www.googleapis.com/auth/gmail.modify",+ "https://www.googleapis.com/auth/gmail.settings.basic",+ ]+)++#: Headers the intake path needs. Gmail returns only what you ask for in+#: ``metadataHeaders``, so a header omitted here is a header the analysis+#: cannot recover later — the field is not merely unparsed, it was never+#: fetched.+METADATA_HEADERS = (+ "Message-ID",+ "From",+ "Sender",+ "Reply-To",+ "Return-Path",+ "To",+ "Cc",+ "Subject",+ "Date",+ "Received",+ "Received-SPF",+ "Authentication-Results",+ "ARC-Authentication-Results",+ "DKIM-Signature",+)+++def quote_gmail_query_value(value: str) -> str:+ """Make an attacker-supplied value safe inside a Gmail ``q=`` expression.++ Gmail's search grammar is whitespace-separated operators, so a raw value+ containing a space, a quote or a colon can close one term and open+ another: ``rfc822msgid:x in:anywhere from:ceo@`` searches for something+ nobody asked for. Every value here comes off a message a stranger sent.++ The refusal is deliberate and follows the osquery lesson: a denylist of+ dangerous characters is the wrong control, and an escaped value that+ reaches the API and matches nothing reports a clean result from a query+ that never ran. So the dangerous shape is made unrepresentable — the value+ is restricted to the characters a message id or an address can contain,+ and anything else raises.+ """+ cleaned = str(value).strip().strip("<>")+ if not cleaned:+ raise ValueError("empty Gmail query value")+ allowed = set("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.@_-+=/")+ bad = sorted({ch for ch in cleaned if ch not in allowed})+ if bad:+ raise ValueError(f"value is not a message id or an address; refusing rather than escaping (disallowed: {bad!r})")+ return cleaned+++class GmailClient:+ """Async Gmail wrapper that mints one delegated token per mailbox.++ Tokens are cached per mailbox for their lifetime less a safety margin, so+ a 25-recipient purge mints 25 tokens once rather than 50 times.+ """++ def __init__(self, service_account_key: str | dict, subject_email: str = "", *, timeout: float = 30.0) -> None:+ if isinstance(service_account_key, str):+ try:+ service_account_key = json.loads(service_account_key)+ except json.JSONDecodeError as exc:+ raise ValueError(f"gws_service_account_key is not valid JSON: {exc}") from exc+ if not isinstance(service_account_key, dict):+ raise ValueError(f"gws_service_account_key must be a JSON object, got {type(service_account_key).__name__}")+ self._key: dict[str, Any] = service_account_key+ self._default_subject = subject_email+ self._timeout = timeout+ #: mailbox -> (access token, expiry epoch seconds)+ self._tokens: dict[str, tuple[str, float]] = {}++ def _subject_for(self, mailbox: str) -> str:+ subject = (mailbox or self._default_subject or "").strip()+ if not subject:+ raise ValueError("Gmail calls need a mailbox: domain-wide delegation impersonates exactly one user per token")+ return subject++ async def _mint_token(self, client: httpx.AsyncClient, subject: str) -> str:+ """Sign a delegated JWT for ``subject`` and exchange it for a token.++ Signed inline for the same reason the Workspace client does it: the+ claim set is fixed and pulling in ``google-auth`` for one RSA-SHA256+ signature is not worth the dependency.+ """+ from cryptography.hazmat.primitives import hashes, serialization+ from cryptography.hazmat.primitives.asymmetric import padding++ now = int(time.time())+ header = {"alg": "RS256", "typ": "JWT"}+ claims = {+ "iss": self._key["client_email"],+ "sub": subject,+ "scope": _SCOPES,+ "aud": _TOKEN_URI,+ "iat": now,+ "exp": now + 3600,+ }++ def _b64(blob: dict) -> str:+ return base64.urlsafe_b64encode(json.dumps(blob, separators=(",", ":")).encode()).rstrip(b"=").decode()++ signing_input = f"{_b64(header)}.{_b64(claims)}".encode()+ private_key = serialization.load_pem_private_key(self._key["private_key"].encode(), password=None)+ signature = private_key.sign(signing_input, padding.PKCS1v15(), hashes.SHA256())+ jwt_str = f"{signing_input.decode()}.{base64.urlsafe_b64encode(signature).rstrip(b'=').decode()}"++ resp = await client.post(+ _TOKEN_URI,+ data={"grant_type": "urn:ietf:params:oauth:grant-type:jwt-bearer", "assertion": jwt_str},+ )+ resp.raise_for_status()+ body = resp.json()+ token = str(body["access_token"])+ self._tokens[subject] = (token, time.time() + int(body.get("expires_in", 3600)) - 60)+ return token++ async def _headers_for(self, client: httpx.AsyncClient, mailbox: str) -> dict[str, str]:+ subject = self._subject_for(mailbox)+ cached = self._tokens.get(subject)+ token = cached[0] if cached and time.time() < cached[1] else await self._mint_token(client, subject)+ return {"Authorization": f"Bearer {token}", "Content-Type": "application/json"}++ @staticmethod+ def _path(mailbox: str, suffix: str) -> str:+ return f"{_GMAIL}/users/{quote(mailbox, safe='')}/{suffix}"++ # ── Reads ────────────────────────────────────────────────────────────++ async def search_messages(+ self,+ mailbox: str,+ *,+ internet_message_id: str = "",+ sender: str = "",+ after_epoch_seconds: int = 0,+ limit: int = 25,+ ) -> list[dict[str, Any]]:+ """Return ``{id, threadId}`` for each match. Terms combine with AND.++ At least one of the message id or the sender is required. An unfiltered+ mailbox listing is a different operation from finding one reported+ message and is not what this is for.+ """+ terms: list[str] = []+ if internet_message_id:+ terms.append(f"rfc822msgid:{quote_gmail_query_value(internet_message_id)}")+ if sender:+ terms.append(f"from:{quote_gmail_query_value(sender)}")+ if not terms:+ raise ValueError("search_messages needs an internet_message_id or a sender")+ if after_epoch_seconds > 0:+ # `after:` takes a bare epoch; it is generated here and never+ # caller-supplied, so there is no value to sanitise.+ terms.append(f"after:{int(after_epoch_seconds)}")++ async with httpx.AsyncClient(timeout=self._timeout) as client:+ headers = await self._headers_for(client, mailbox)+ resp = await client.get(+ self._path(self._subject_for(mailbox), "messages"),+ headers=headers,+ params={+ "q": " ".join(terms),+ "maxResults": str(max(1, min(int(limit), 100))),+ "includeSpamTrash": "true",+ },+ )+ resp.raise_for_status()+ return list(resp.json().get("messages") or [])++ async def get_message(self, mailbox: str, message_id: str) -> dict[str, Any]:+ """Metadata and headers only. The body is never fetched.++ ``format=metadata`` is a deliberate ceiling: the intake path runs+ unattended against every reported message, and pulling message bodies+ out of a customer's tenant into AiSOC's database is a disclosure+ nobody asked for. Headers are what the analysis needs.+ """+ async with httpx.AsyncClient(timeout=self._timeout) as client:+ headers = await self._headers_for(client, mailbox)+ resp = await client.get(+ self._path(self._subject_for(mailbox), f"messages/{quote(message_id, safe='')}"),+ headers=headers,+ params=[("format", "metadata"), *[("metadataHeaders", h) for h in METADATA_HEADERS]],+ )+ resp.raise_for_status()+ return dict(resp.json())++ async def list_messages_with_label(self, mailbox: str, label: str, *, limit: int = 50) -> list[dict[str, Any]]:+ """List message ids carrying ``label``. Used by the report-mailbox poller."""+ async with httpx.AsyncClient(timeout=self._timeout) as client:+ headers = await self._headers_for(client, mailbox)+ resp = await client.get(+ self._path(self._subject_for(mailbox), "messages"),+ headers=headers,+ params={"labelIds": label, "maxResults": str(max(1, min(int(limit), 100)))},+ )+ resp.raise_for_status()+ return list(resp.json().get("messages") or [])++ # ── State changes ────────────────────────────────────────────────────++ async def trash_message(self, mailbox: str, message_id: str) -> dict[str, Any]:+ """Move a message to Trash. Recoverable for 30 days; undone by untrash."""+ return await self._post(mailbox, f"messages/{quote(message_id, safe='')}/trash")++ async def untrash_message(self, mailbox: str, message_id: str) -> dict[str, Any]:+ """Take a message back out of Trash. The declared reverse of trash."""+ return await self._post(mailbox, f"messages/{quote(message_id, safe='')}/untrash")++ async def _post(self, mailbox: str, suffix: str, payload: dict[str, Any] | None = None) -> dict[str, Any]:+ async with httpx.AsyncClient(timeout=self._timeout) as client:+ headers = await self._headers_for(client, mailbox)+ resp = await client.post(self._path(self._subject_for(mailbox), suffix), headers=headers, json=payload or {})+ resp.raise_for_status()+ return dict(resp.json()) if resp.content else {}++ async def create_filter(self, mailbox: str, sender: str) -> dict[str, Any]:+ """Add a filter trashing future mail from ``sender``. Per-mailbox only."""+ return await self._post(+ mailbox,+ "settings/filters",+ {"criteria": {"from": sender}, "action": {"addLabelIds": ["TRASH"], "removeLabelIds": ["INBOX"]}},+ )++ async def list_filters(self, mailbox: str) -> list[dict[str, Any]]:+ async with httpx.AsyncClient(timeout=self._timeout) as client:+ headers = await self._headers_for(client, mailbox)+ resp = await client.get(self._path(self._subject_for(mailbox), "settings/filters"), headers=headers)+ resp.raise_for_status()+ return list(resp.json().get("filter") or [])++ async def delete_filter(self, mailbox: str, filter_id: str) -> dict[str, Any]:+ async with httpx.AsyncClient(timeout=self._timeout) as client:+ headers = await self._headers_for(client, mailbox)+ resp = await client.delete(+ self._path(self._subject_for(mailbox), f"settings/filters/{quote(filter_id, safe='')}"),+ headers=headers,+ )+ resp.raise_for_status()+ return {"deleted": True, "filter_id": filter_id}diff --git a/services/actions/app/live_actions/capability_contracts.py b/services/actions/app/live_actions/capability_contracts.pyindex 97ced04a6..1ed1a5b26 100644--- a/services/actions/app/live_actions/capability_contracts.py+++ b/services/actions/app/live_actions/capability_contracts.py@@ -705,9 +705,184 @@ CAPABILITY_CONTRACTS: dict[str, CapabilityContract] = {),note=("A message cannot be unsent, but paging the wrong channel is embarrassment rather than impact."),),+ # ── Mailbox remediation ───────────────────────────────────────────────+ #+ # These are the only verbs in the vocabulary whose impact genuinely is+ # not a constant: purging one copy of a message out of one mailbox and+ # purging it out of a thousand are different acts. The constant below is+ # the floor, and `scaled_impact` raises it from the recipient count —+ # see that function for why the scaling lives outside the table.+ "search_mailboxes": CapabilityContract(+ impact=ActionImpact.READ_ONLY,+ approval=ApprovalRequirement.AUTOMATIC,+ reversal=Reversal.NOT_APPLICABLE,+ required_permission=_INVESTIGATE,+ has_verification_probe=False,+ verification_gap=("A read leaves nothing behind to read back, the same gap search_siem and lookup_cloud_audit record."),+ note=(+ "Find the copies of one reported message across mailboxes, by "+ "internet message id, sender, subject or receipt window. Every "+ "other verb here depends on it: a purge needs a per-mailbox "+ "message id and only this maps one message onto the mailboxes "+ "holding it."+ ),+ ),+ "purge_email": CapabilityContract(+ impact=ActionImpact.MODERATE,+ approval=ApprovalRequirement.ANALYST,+ reversal=Reversal.PLATFORM,+ reverse_capability="restore_email",+ required_permission=_CONTAIN,+ has_verification_probe=True,+ note=(+ "Soft-delete one copy of a message from one mailbox: a move to "+ "recoverableitemsdeletions on Microsoft, a move to Trash on "+ "Gmail. Never a hard delete, which has no reverse. MODERATE is "+ "the single-recipient floor and scaled_impact raises it with the "+ "campaign's size; ANALYST rather than AUTOMATIC because a wrong "+ "purge removes a message the recipient may have needed and the "+ "restore, while real, is not instantaneous."+ ),+ ),+ "restore_email": CapabilityContract(+ impact=ActionImpact.LOW,+ approval=ApprovalRequirement.AUTOMATIC,+ reversal=Reversal.PLATFORM,+ reverse_capability="purge_email",+ required_permission=_CONTAIN,+ has_verification_probe=True,+ note=(+ "Put a soft-deleted message back. The declared rollback for "+ "purge_email, and the reason that verb may be dispatched at all: "+ "a reverse that resolves to nothing is the defect "+ "KNOWN_ORPHANS exists to catch, and it would be at its worst on "+ "the most disruptive verb in the product. LOW and automatic "+ "because undoing a containment must never be harder than "+ "applying it."+ ),+ ),+ "block_sender": CapabilityContract(+ impact=ActionImpact.LOW,+ approval=ApprovalRequirement.ANALYST,+ reversal=Reversal.PLATFORM,+ reverse_capability="unblock_sender",+ required_permission=_CONTAIN,+ has_verification_probe=True,+ note=(+ "Stop future mail from one sender reaching one mailbox: an inbox "+ "message rule on Microsoft, a filter on Gmail. Per-mailbox, not "+ "tenant-wide — neither vendor exposes its organisation-level "+ "block list through the API this platform speaks, and declaring "+ "the broader verb would have an analyst believe the organisation "+ "is covered when one mailbox is."+ ),+ ),+ "unblock_sender": CapabilityContract(+ impact=ActionImpact.LOW,+ approval=ApprovalRequirement.AUTOMATIC,+ reversal=Reversal.PLATFORM,+ reverse_capability="block_sender",+ required_permission=_CONTAIN,+ has_verification_probe=True,+ note="Remove the rule or filter block_sender created. Its declared reverse.",+ ),}+#: Recipient counts at which ``purge_email`` stops being the verb its base+#: contract describes. Ascending, and read as "at least this many".+#:+#: The numbers are a judgement and are stated rather than hidden in an `if`+#: so a deployment reviewing its own posture can read them:+#:+#: * **1–4** stays MODERATE. One analyst clearing a message from a handful of+#: mailboxes is routine phishing work.+#: * **5+** is HIGH. It is no longer one person's mail; a mistake now+#: disrupts a team and several people notice at once.+#: * **25+** is SEVERE, which ``NEVER_AUTONOMOUS`` makes mandatory-human at+#: any confidence and any autonomy tier. A purge at that scale is an+#: organisation-visible event, and the gap-closure plan names exactly this+#: case: a 25-recipient campaign must yield one proposal that requires+#: approval.+RECIPIENT_IMPACT_LADDER: tuple[tuple[int, ActionImpact], ...] = (+ (25, ActionImpact.SEVERE),+ (5, ActionImpact.HIGH),+)++#: Capabilities whose impact scales with how many mailboxes they touch.+#: ``restore_email`` is deliberately absent: putting a thousand messages back+#: is not disruptive in the way taking them away is, and making the rollback+#: harder to authorise than the action is how a containment becomes permanent.+_RECIPIENT_SCALED: frozenset[str] = frozenset({"purge_email", "block_sender"})++#: Parameter keys a caller may use to declare the blast radius. Several+#: because the count arrives from three places — a campaign proposal knows it+#: up front, a fan-out executor counts its own targets, and a single-mailbox+#: dispatch has one.+_RECIPIENT_COUNT_KEYS: tuple[str, ...] = ("recipient_count", "mailbox_count", "affected_recipients")+++def recipient_count_from(params: dict | None) -> int:+ """How many mailboxes an action says it will touch. Unknown reads as one.++ Unknown is **not** treated as zero and not treated as large. Zero would+ let a caller omit the field to dodge the ladder, which is the same shape+ as "missing confidence is not high confidence". Large would route every+ single-mailbox purge to a mandatory human and train people to approve+ without reading. One is the honest floor: a dispatch with no count is a+ dispatch against the one mailbox in ``target``.+ """+ if not params:+ return 1+ for key in _RECIPIENT_COUNT_KEYS:+ raw = params.get(key)+ if raw is None:+ continue+ try:+ value = int(raw)+ except (TypeError, ValueError):+ continue+ return max(1, value)+ recipients = params.get("recipients")+ if isinstance(recipients, (list, tuple, set)):+ return max(1, len(recipients))+ return 1+++def scaled_impact(capability: str, params: dict | None) -> ActionImpact:+ """The impact this dispatch actually carries, given its blast radius.++ Why this is a function and not more rows in the table: the contract+ belongs to the *verb*, and ``purge_email`` is one verb. Splitting it into+ ``purge_email_small`` and ``purge_email_large`` would hand a caller the+ choice of which contract to be graded under, which is the opposite of+ what a contract is for. The verb stays one entry and the dispatch+ declares its size.++ **It only ever raises.** A ladder entry below the contract's own floor is+ ignored, so no parameter a caller supplies can make an action cheaper+ than its contract says it is — the same one-way property the approval+ matrix has.+ """+ contract = CAPABILITY_CONTRACTS.get(capability)+ base = contract.impact if contract else ActionImpact.IRREVERSIBLE+ if capability not in _RECIPIENT_SCALED:+ return base+ count = recipient_count_from(params)+ order = (+ ActionImpact.READ_ONLY,+ ActionImpact.LOW,+ ActionImpact.MODERATE,+ ActionImpact.HIGH,+ ActionImpact.SEVERE,+ ActionImpact.IRREVERSIBLE,+ )+ for threshold, impact in RECIPIENT_IMPACT_LADDER:+ if count >= threshold:+ return impact if order.index(impact) > order.index(base) else base+ return base++#: Legacy ``ActionType`` value -> capability name, for the cases where the#: two vocabularies chose different words for the same verb.#: