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
test(connectors): harden 6 wave-2 connectors to wave-1 test + fixture parity (#328)
Aadit Singalf3a67e2d9120
diff --git a/README.md b/README.mdindex c71821b3f..6f23765e7 100644--- a/README.md+++ b/README.md@@ -1042,7 +1042,7 @@ Next (planned — checkpointed with `[~]` in `AISOC_V8_PROGRESS.md`):- Attack-chain ranking + timeline UI hardening (T3.3) and business-context YAML rule engine (T3.5)- Effective-permissions resolvers for Azure / GCP / Okta / GWS (T3.2)- ChatOps full coverage: Slack Block Kit approvals, Teams Adaptive Card mirror, signed email approval URLs (T3.6)-- Remaining wave-2 connectors hardened to wave-1 quality (sublime_security, abnormal_security, box, dropbox, oci, datadog)+- ~~Remaining wave-2 connectors hardened to wave-1 quality (sublime_security, abnormal_security, box, dropbox, oci, datadog)~~ → **wave-1 test + fixture parity landed** for all six- Mobile responder console (React Native), plugin marketplace v3, AI-generated threat intel briefings, embedded red-team scoring widget, SLA breach predictor, SOC-in-a-box one-click cloud deploy---diff --git a/services/connectors/tests/connectors/test_abnormal_security.py b/services/connectors/tests/connectors/test_abnormal_security.pynew file mode 100644index 000000000..4b096a266--- /dev/null+++ b/services/connectors/tests/connectors/test_abnormal_security.py@@ -0,0 +1,128 @@+"""Tests for the Abnormal Security email-security connector (T4.5).++Brings the wave-2 ``abnormal_security`` connector to wave-1 test parity:+schema + registry wiring, the threatType->severity collapse (high attack+families, low graymail/spam, medium default), the case-severity override,+the two-endpoint (threats + cases) paginated fetch, and the+``test_connection`` paths. Network is mocked with :mod:`respx`.+"""++from __future__ import annotations++import json+from pathlib import Path++import httpx+import pytest+import respx+from app.connectors import CONNECTOR_REGISTRY+from app.connectors.abnormal_security import AbnormalSecurityConnector+from app.connectors.base import Capability++_FIXTURE = Path(__file__).resolve().parent.parent / "fixtures" / "abnormal_security" / "sample_event.json"+_BASE = "https://api.abnormalplatform.com"++[email protected](scope="module")+def fixture() -> dict:+ return json.loads(_FIXTURE.read_text())+++def test_schema_valid():+ schema = AbnormalSecurityConnector.schema()+ assert schema.connector_id == "abnormal_security"+ assert schema.category == "saas"+ names = {f.name for f in schema.fields}+ assert {"base_url", "api_token"} <= names+ assert Capability.PULL_ALERTS in AbnormalSecurityConnector.capabilities()+++def test_registry_contains_abnormal_security():+ assert "abnormal_security" in CONNECTOR_REGISTRY+ assert CONNECTOR_REGISTRY["abnormal_security"] is AbnormalSecurityConnector+++def test_normalize_bec_to_high(fixture):+ c = AbnormalSecurityConnector(api_token="t")+ out = c.normalize(fixture["threats"][0])+ assert out["severity"] == "high"+ assert out["stream"] == "threat"+ assert out["external_id"] == "t-bec"+ assert out["actor_email"] == "[email protected]"+++def test_normalize_credential_phishing_via_attacktype_to_high(fixture):+ """``attackType`` is an accepted alias for ``threatType``; sender can+ arrive nested under ``sender.email``."""+ c = AbnormalSecurityConnector(api_token="t")+ out = c.normalize(fixture["threats"][1])+ assert out["severity"] == "high"+ assert out["actor_email"] == "[email protected]"+++def test_normalize_spam_to_low(fixture):+ c = AbnormalSecurityConnector(api_token="t")+ assert c.normalize(fixture["threats"][2])["severity"] == "low"+++def test_normalize_unknown_type_to_medium(fixture):+ """Abnormal only reports things it considers abnormal — unknown types+ floor at medium, never info."""+ c = AbnormalSecurityConnector(api_token="t")+ assert c.normalize(fixture["threats"][3])["severity"] == "medium"+++def test_normalize_case_high_severity(fixture):+ c = AbnormalSecurityConnector(api_token="t")+ out = c.normalize(fixture["cases"][0])+ assert out["severity"] == "high"+ assert out["stream"] == "case"+ assert out["external_id"] == "c-ato"+++def test_normalize_case_severity_overrides_low_type(fixture):+ """A low threatType (spam) still reports high when the case severity is+ high — the case rollup is the max of its constituents."""+ c = AbnormalSecurityConnector(api_token="t")+ assert c.normalize(fixture["cases"][1])["severity"] == "high"+++async def test_fetch_alerts_merges_threats_and_cases(fixture, monkeypatch):+ monkeypatch.setattr("app.connectors.abnormal_security._PER_PAGE", 2)+ c = AbnormalSecurityConnector(api_token="t")++ threats_p1 = {"threats": fixture["threats"][:2], "nextPageNumber": 2}+ threats_p2 = {"threats": fixture["threats"][2:3]} # short → stop+ respx.get(f"{_BASE}/v1/threats").side_effect = [+ httpx.Response(200, json=threats_p1),+ httpx.Response(200, json=threats_p2),+ ]+ respx.get(f"{_BASE}/v1/cases").respond(200, json={"cases": fixture["cases"][:1]})++ out = await c.fetch_alerts(since_seconds=300)++ assert len(out) == 4 # 3 threats (2 + 1) + 1 case+ streams = {e["stream"] for e in out}+ assert streams == {"threat", "case"}+ assert all(e["source"] == "abnormal_security" for e in out)+++async def test_test_connection_success():+ c = AbnormalSecurityConnector(api_token="t")+ respx.get(f"{_BASE}/v1/threats").respond(200, json={"threats": []})+ res = await c.test_connection()+ assert res["success"] is True+++async def test_test_connection_failure():+ c = AbnormalSecurityConnector(api_token="t")+ respx.get(f"{_BASE}/v1/threats").respond(500, json={"error": "boom"})+ res = await c.test_connection()+ assert res["success"] is False+ assert "500" in res["error"]diff --git a/services/connectors/tests/connectors/test_box.py b/services/connectors/tests/connectors/test_box.pynew file mode 100644index 000000000..453c4e736--- /dev/null+++ b/services/connectors/tests/connectors/test_box.py@@ -0,0 +1,117 @@+"""Tests for the Box content-cloud audit-events connector (T4.12).++Brings the wave-2 ``box`` connector to wave-1 test parity: schema ++registry wiring, the event_type->severity collapse (Shield + admin/role+events high, collaboration + failed-login medium, info floor), the+external-collaborator download escalation, the ``next_stream_position``+cursor pagination, and ``test_connection``. Network mocked with respx.+"""++from __future__ import annotations++import json+from pathlib import Path++import httpx+import pytest+import respx+from app.connectors import CONNECTOR_REGISTRY+from app.connectors.base import Capability+from app.connectors.box import BoxConnector++_FIXTURE = Path(__file__).resolve().parent.parent / "fixtures" / "box" / "sample_event.json"+_BASE = "https://api.box.com"++[email protected](scope="module")+def fixture() -> list[dict]:+ return json.loads(_FIXTURE.read_text())+++def test_schema_valid():+ schema = BoxConnector.schema()+ assert schema.connector_id == "box"+ assert schema.category == "saas"+ names = {f.name for f in schema.fields}+ assert {"access_token"} <= names+ assert Capability.PULL_AUDIT in BoxConnector.capabilities()+++def test_registry_contains_box():+ assert "box" in CONNECTOR_REGISTRY+ assert CONNECTOR_REGISTRY["box"] is BoxConnector+++def test_normalize_shield_alert_to_high(fixture):+ out = BoxConnector(access_token="t").normalize(fixture[0])+ assert out["severity"] == "high"+ assert out["external_id"] == "box-shield"+ assert out["actor_email"] == "[email protected]"+ assert out["src_ip"] == "203.0.113.9"+ assert out["target"] == "confidential.docx"+++def test_normalize_collaboration_invite_to_medium(fixture):+ assert BoxConnector(access_token="t").normalize(fixture[1])["severity"] == "medium"+++def test_normalize_failed_login_to_medium(fixture):+ assert BoxConnector(access_token="t").normalize(fixture[2])["severity"] == "medium"+++def test_normalize_preview_to_info(fixture):+ assert BoxConnector(access_token="t").normalize(fixture[3])["severity"] == "info"+++def test_normalize_external_download_escalates_to_high(fixture):+ """An ITEM_DOWNLOAD whose action_by is a consumer (external) mailbox is+ promoted to high even though the bare event type is otherwise info."""+ out = BoxConnector(access_token="t").normalize(fixture[4])+ assert out["severity"] == "high"+++async def test_fetch_alerts_uses_stream_position(fixture, monkeypatch):+ monkeypatch.setattr("app.connectors.box._PER_PAGE", 2)+ c = BoxConnector(access_token="t")+ page1 = {"entries": fixture[:2], "next_stream_position": "pos2"}+ page2 = {"entries": fixture[2:3]} # short → stop+ route = respx.get(f"{_BASE}/2.0/events")+ route.side_effect = [+ httpx.Response(200, json=page1),+ httpx.Response(200, json=page2),+ ]+ out = await c.fetch_alerts(since_seconds=300)+ assert len(out) == 3+ assert all(e["source"] == "box" for e in out)+++async def test_fetch_alerts_stops_on_non_200():+ c = BoxConnector(access_token="t")+ respx.get(f"{_BASE}/2.0/events").respond(401, json={"code": "unauthorized"})+ out = await c.fetch_alerts(since_seconds=300)+ assert out == []+++async def test_test_connection_success():+ c = BoxConnector(access_token="t")+ respx.get(f"{_BASE}/2.0/users/me").respond(200, json={"login": "[email protected]", "name": "Admin", "enterprise": {"name": "Acme"}})+ res = await c.test_connection()+ assert res["success"] is True+ assert res["user"] == "[email protected]"+ assert res["enterprise"] == "Acme"+++async def test_test_connection_failure():+ c = BoxConnector(access_token="t")+ respx.get(f"{_BASE}/2.0/users/me").respond(401, json={"code": "unauthorized"})+ res = await c.test_connection()+ assert res["success"] is False+ assert "401" in res["error"]diff --git a/services/connectors/tests/connectors/test_datadog.py b/services/connectors/tests/connectors/test_datadog.pynew file mode 100644index 000000000..f37760783--- /dev/null+++ b/services/connectors/tests/connectors/test_datadog.py@@ -0,0 +1,146 @@+"""Tests for the Datadog (Logs + APM) connector (T4.13).++Brings the wave-2 ``datadog`` connector to wave-1 test parity: schema ++registry wiring, site/mode validation, both normalizer branches (log+status->severity and event alert_type/priority->severity), the logs+cursor pagination and the single-shot events fetch, and+``test_connection``. Network mocked with respx.+"""++from __future__ import annotations++import json+from pathlib import Path++import httpx+import pytest+import respx+from app.connectors import CONNECTOR_REGISTRY+from app.connectors.base import Capability+from app.connectors.datadog import DatadogConnector++_FIXTURE = Path(__file__).resolve().parent.parent / "fixtures" / "datadog" / "sample_event.json"+_BASE = "https://api.datadoghq.com"++[email protected](scope="module")+def fixture() -> dict:+ return json.loads(_FIXTURE.read_text())+++def _logs_connector() -> DatadogConnector:+ return DatadogConnector(site="us1", mode="logs", api_key="k", application_key="a")+++def test_schema_valid():+ schema = DatadogConnector.schema()+ assert schema.connector_id == "datadog"+ assert schema.category == "siem"+ names = {f.name for f in schema.fields}+ assert {"site", "mode", "query", "api_key", "application_key"} <= names+ assert Capability.PULL_LOGS in DatadogConnector.capabilities()+++def test_registry_contains_datadog():+ assert "datadog" in CONNECTOR_REGISTRY+ assert CONNECTOR_REGISTRY["datadog"] is DatadogConnector+++def test_invalid_site_rejected():+ with pytest.raises(ValueError):+ DatadogConnector(site="mars1", mode="logs", api_key="k", application_key="a")+++def test_invalid_mode_rejected():+ with pytest.raises(ValueError):+ DatadogConnector(site="us1", mode="bogus", api_key="k", application_key="a")+++def test_normalize_log_critical_to_high(fixture):+ out = _logs_connector().normalize(fixture["logs"][0])+ assert out["severity"] == "high"+ assert out["stream"] == "logs"+ assert out["host"] == "web-1"+ assert out["service"] == "api"+++def test_normalize_log_error_to_medium(fixture):+ assert _logs_connector().normalize(fixture["logs"][1])["severity"] == "medium"+++def test_normalize_log_warn_via_level_alias_to_low(fixture):+ assert _logs_connector().normalize(fixture["logs"][2])["severity"] == "low"+++def test_normalize_log_info_to_info(fixture):+ assert _logs_connector().normalize(fixture["logs"][3])["severity"] == "info"+++def test_normalize_event_error_to_high(fixture):+ out = _logs_connector().normalize({"_kind": "event", **fixture["events"][0]})+ assert out["severity"] == "high"+ assert out["stream"] == "events"+ assert out["external_id"] == "111"+++def test_normalize_event_warning_to_medium(fixture):+ out = _logs_connector().normalize({"_kind": "event", **fixture["events"][1]})+ assert out["severity"] == "medium"+++def test_normalize_event_info_priority_low_to_low(fixture):+ out = _logs_connector().normalize({"_kind": "event", **fixture["events"][2]})+ assert out["severity"] == "low"+++def test_normalize_event_info_to_info(fixture):+ out = _logs_connector().normalize({"_kind": "event", **fixture["events"][3]})+ assert out["severity"] == "info"+++async def test_fetch_logs_uses_cursor_pagination(fixture, monkeypatch):+ monkeypatch.setattr("app.connectors.datadog._LOGS_PER_PAGE", 2)+ c = _logs_connector()+ page1 = {"data": fixture["logs"][:2], "meta": {"page": {"after": "cur1"}}}+ page2 = {"data": fixture["logs"][2:3]} # short → stop+ route = respx.post(f"{_BASE}/api/v2/logs/events/search")+ route.side_effect = [+ httpx.Response(200, json=page1),+ httpx.Response(200, json=page2),+ ]+ out = await c.fetch_alerts(since_seconds=300)+ assert len(out) == 3+ assert all(e["stream"] == "logs" for e in out)+++async def test_fetch_events_single_shot(fixture):+ c = DatadogConnector(site="us1", mode="events", api_key="k", application_key="a")+ respx.get(f"{_BASE}/api/v1/events").respond(200, json={"events": fixture["events"][:2]})+ out = await c.fetch_alerts(since_seconds=300)+ assert len(out) == 2+ assert all(e["stream"] == "events" for e in out)+++async def test_test_connection_success():+ c = _logs_connector()+ respx.get(f"{_BASE}/api/v1/validate").respond(200, json={"valid": True})+ res = await c.test_connection()+ assert res["success"] is True+ assert res["site"] == "us1"+ assert res["mode"] == "logs"+++async def test_test_connection_failure():+ c = _logs_connector()+ respx.get(f"{_BASE}/api/v1/validate").respond(403, json={"errors": ["forbidden"]})+ res = await c.test_connection()+ assert res["success"] is False+ assert "403" in res["error"]diff --git a/services/connectors/tests/connectors/test_dropbox.py b/services/connectors/tests/connectors/test_dropbox.pynew file mode 100644index 000000000..3cb8eea5c--- /dev/null+++ b/services/connectors/tests/connectors/test_dropbox.py@@ -0,0 +1,117 @@+"""Tests for the Dropbox Business audit-log connector (T4.12).++Brings the wave-2 ``dropbox`` connector to wave-1 test parity: schema ++registry wiring, the tagged-union ``event_type`` -> severity collapse+(high-risk admin/app/sharing events, medium sharing + login_fail, info+floor), actor/src_ip extraction, the ``get_events`` -> ``continue``+cursor pagination, and ``test_connection``. Network mocked with respx.+"""++from __future__ import annotations++import json+from pathlib import Path++import pytest+import respx+from app.connectors import CONNECTOR_REGISTRY+from app.connectors.base import Capability+from app.connectors.dropbox import DropboxConnector++_FIXTURE = Path(__file__).resolve().parent.parent / "fixtures" / "dropbox" / "sample_event.json"+_BASE = "https://api.dropboxapi.com"++[email protected](scope="module")+def fixture() -> list[dict]:+ return json.loads(_FIXTURE.read_text())+++def test_schema_valid():+ schema = DropboxConnector.schema()+ assert schema.connector_id == "dropbox"+ assert schema.category == "saas"+ names = {f.name for f in schema.fields}+ assert {"team_admin_token"} <= names+ assert Capability.PULL_AUDIT in DropboxConnector.capabilities()+++def test_registry_contains_dropbox():+ assert "dropbox" in CONNECTOR_REGISTRY+ assert CONNECTOR_REGISTRY["dropbox"] is DropboxConnector+++def test_normalize_app_link_to_high(fixture):+ c = DropboxConnector(team_admin_token="t")+ out = c.normalize(fixture[0])+ assert out["severity"] == "high"+ assert out["external_id"] == "d-app-link"+ assert out["actor_email"] == "[email protected]"+ assert out["event_type"] == "dropbox.app_link_team"+++def test_normalize_admin_role_change_to_high(fixture):+ c = DropboxConnector(team_admin_token="t")+ assert c.normalize(fixture[1])["severity"] == "high"+++def test_normalize_shared_link_to_medium(fixture):+ c = DropboxConnector(team_admin_token="t")+ assert c.normalize(fixture[2])["severity"] == "medium"+++def test_normalize_login_fail_to_medium_with_src_ip(fixture):+ c = DropboxConnector(team_admin_token="t")+ out = c.normalize(fixture[3])+ assert out["severity"] == "medium"+ assert out["src_ip"] == "203.0.113.5"+++def test_normalize_benign_event_to_info(fixture):+ c = DropboxConnector(team_admin_token="t")+ assert c.normalize(fixture[4])["severity"] == "info"+++async def test_fetch_alerts_uses_cursor_continue(fixture):+ c = DropboxConnector(team_admin_token="t")+ page1 = {"events": fixture[:2], "has_more": True, "cursor": "cur1"}+ page2 = {"events": fixture[2:3], "has_more": False}+ respx.post(f"{_BASE}/2/team_log/get_events").respond(200, json=page1)+ respx.post(f"{_BASE}/2/team_log/get_events/continue").respond(200, json=page2)++ out = await c.fetch_alerts(since_seconds=300)++ assert len(out) == 3 # 2 from first page + 1 from continue+ assert all(e["source"] == "dropbox" for e in out)+++async def test_fetch_alerts_stops_on_non_200():+ c = DropboxConnector(team_admin_token="t")+ respx.post(f"{_BASE}/2/team_log/get_events").respond(401, json={"error": "expired_access_token"})+ out = await c.fetch_alerts(since_seconds=300)+ assert out == []+++async def test_test_connection_success():+ c = DropboxConnector(team_admin_token="t")+ respx.post(f"{_BASE}/2/team/get_info").respond(200, json={"name": "Acme Team", "num_provisioned_users": 42})+ res = await c.test_connection()+ assert res["success"] is True+ assert res["team"] == "Acme Team"+ assert res["members"] == 42+++async def test_test_connection_failure():+ c = DropboxConnector(team_admin_token="t")+ respx.post(f"{_BASE}/2/team/get_info").respond(401, json={"error": "invalid"})+ res = await c.test_connection()+ assert res["success"] is False+ assert "401" in res["error"]diff --git a/services/connectors/tests/connectors/test_oci.py b/services/connectors/tests/connectors/test_oci.pynew file mode 100644index 000000000..184346fbf--- /dev/null+++ b/services/connectors/tests/connectors/test_oci.py@@ -0,0 +1,111 @@+"""Tests for the Oracle Cloud Infrastructure (OCI) audit connector (T4.15).++Brings the wave-2 ``oci`` connector to wave-1 test parity: schema ++registry wiring, the eventName->severity collapse (high-risk Delete*,+medium Create/Update/ChangeCompartment, failed-call floor to low), the+cloudevents-style ``data`` unwrapping, the ``opc-next-page`` header+pagination, and ``test_connection``. The OCI request signer is absent in+tests (the SDK isn't installed); respx intercepts before signing matters.+"""++from __future__ import annotations++import json+from pathlib import Path++import httpx+import pytest+import respx+from app.connectors import CONNECTOR_REGISTRY+from app.connectors.base import Capability+from app.connectors.oci import OCIConnector++_FIXTURE = Path(__file__).resolve().parent.parent / "fixtures" / "oci" / "sample_event.json"+_BASE = "https://audit.us-ashburn-1.oraclecloud.com"+_PATH = "/20190901/auditEvents"++[email protected](scope="module")+def fixture() -> list[dict]:+ return json.loads(_FIXTURE.read_text())+++def _connector() -> OCIConnector:+ return OCIConnector(+ tenancy_ocid="ocid1.tenancy.oc1..aaa",+ user_ocid="ocid1.user.oc1..bbb",+ compartment_ocid="ocid1.compartment.oc1..ccc",+ fingerprint="aa:bb:cc:dd",+ private_key_pem="-----BEGIN PRIVATE KEY-----\nstub\n-----END PRIVATE KEY-----\n",+ region="us-ashburn-1",+ )+++def test_schema_valid():+ schema = OCIConnector.schema()+ assert schema.connector_id == "oci"+ assert schema.category == "cloud"+ names = {f.name for f in schema.fields}+ assert {"tenancy_ocid", "user_ocid", "compartment_ocid", "fingerprint", "private_key_pem", "region"} <= names+ assert Capability.PULL_AUDIT in OCIConnector.capabilities()+++def test_registry_contains_oci():+ assert "oci" in CONNECTOR_REGISTRY+ assert CONNECTOR_REGISTRY["oci"] is OCIConnector+++def test_normalize_delete_user_to_high(fixture):+ out = _connector().normalize(fixture[0])+ assert out["severity"] == "high"+ assert out["external_id"] == "oci-delete-user"+ assert out["actor"] == "admin"+ assert out["src_ip"] == "203.0.113.7"+++def test_normalize_create_user_to_medium(fixture):+ assert _connector().normalize(fixture[1])["severity"] == "medium"+++def test_normalize_list_buckets_to_info(fixture):+ assert _connector().normalize(fixture[2])["severity"] == "info"+++def test_normalize_failed_call_floors_to_low(fixture):+ """A non-risky read that returned >=400 surfaces as low, not info."""+ assert _connector().normalize(fixture[3])["severity"] == "low"+++async def test_fetch_alerts_uses_opc_next_page(fixture, monkeypatch):+ monkeypatch.setattr("app.connectors.oci._PER_PAGE", 2)+ c = _connector()+ route = respx.get(f"{_BASE}{_PATH}")+ route.side_effect = [+ httpx.Response(200, json=fixture[:2], headers={"opc-next-page": "cur1"}),+ httpx.Response(200, json=fixture[2:3]), # short, no header → stop+ ]+ out = await c.fetch_alerts(since_seconds=300)+ assert len(out) == 3+ assert all(e["source"] == "oci" for e in out)+++async def test_test_connection_success():+ c = _connector()+ respx.get(f"{_BASE}{_PATH}").respond(200, json=[])+ res = await c.test_connection()+ assert res["success"] is True+ assert res["region"] == "us-ashburn-1"+++async def test_test_connection_failure():+ c = _connector()+ respx.get(f"{_BASE}{_PATH}").respond(401, json={"message": "NotAuthenticated"})+ res = await c.test_connection()+ assert res["success"] is False+ assert "401" in res["error"]diff --git a/services/connectors/tests/connectors/test_sublime_security.py b/services/connectors/tests/connectors/test_sublime_security.pynew file mode 100644index 000000000..5f215f4ae--- /dev/null+++ b/services/connectors/tests/connectors/test_sublime_security.py@@ -0,0 +1,148 @@+"""Tests for the Sublime Security email-security connector (T4.4).++Brings the wave-2 ``sublime_security`` connector up to wave-1 test parity:+schema + registry wiring, the full verdict→severity collapse (including the+attack-rule escalation and the nested ``review.classification`` fallback),+cursor pagination, and the ``test_connection`` happy/sad paths. Network is+mocked with :mod:`respx` so the suite stays offline-safe.+"""++from __future__ import annotations++import json+from pathlib import Path++import httpx+import pytest+import respx+from app.connectors import CONNECTOR_REGISTRY+from app.connectors.base import Capability+from app.connectors.sublime_security import SublimeSecurityConnector++_FIXTURE = Path(__file__).resolve().parent.parent / "fixtures" / "sublime_security" / "sample_event.json"+_BASE = "https://api.platform.sublimesecurity.com"++[email protected](scope="module")+def fixture() -> list[dict]:+ return json.loads(_FIXTURE.read_text())+++def test_schema_valid():+ schema = SublimeSecurityConnector.schema()+ assert schema.connector_id == "sublime_security"+ assert schema.category == "saas"+ names = {f.name for f in schema.fields}+ assert {"base_url", "api_key"} <= names+ assert Capability.PULL_ALERTS in SublimeSecurityConnector.capabilities()+++def test_registry_contains_sublime_security():+ assert "sublime_security" in CONNECTOR_REGISTRY+ assert CONNECTOR_REGISTRY["sublime_security"] is SublimeSecurityConnector+++def test_normalize_malicious_to_high(fixture):+ c = SublimeSecurityConnector(api_key="t")+ out = c.normalize(fixture[0])+ assert out["severity"] == "high"+ assert out["source"] == "sublime_security"+ assert out["external_id"] == "msg-malicious"+ assert out["actor"] == "[email protected]"+ assert out["actor_email"] == "[email protected]"+ assert out["target"] == "[email protected]"+ assert out["event_type"] == "sublime_security.malicious"+++def test_normalize_suspicious_to_medium(fixture):+ c = SublimeSecurityConnector(api_key="t")+ assert c.normalize(fixture[1])["severity"] == "medium"+++def test_normalize_graymail_to_low(fixture):+ c = SublimeSecurityConnector(api_key="t")+ assert c.normalize(fixture[2])["severity"] == "low"+++def test_normalize_benign_to_info(fixture):+ c = SublimeSecurityConnector(api_key="t")+ assert c.normalize(fixture[3])["severity"] == "info"+++def test_normalize_bec_rule_escalates_spam_to_high(fixture):+ """A low-ish verdict still escalates to high when an attack-shaped rule+ (BEC / credential / phishing / impersonation) fires."""+ c = SublimeSecurityConnector(api_key="t")+ out = c.normalize(fixture[4])+ assert out["severity"] == "high"+++def test_normalize_reads_nested_review_classification(fixture):+ """Verdict can arrive as ``review.classification``; sender can arrive as+ a flat ``from_email`` rather than a ``from`` object."""+ c = SublimeSecurityConnector(api_key="t")+ out = c.normalize(fixture[5])+ assert out["severity"] == "medium"+ assert out["external_id"] == "msg-nested-review"+ assert out["actor_email"] == "[email protected]"+ assert out["target"] == "[email protected]"+++def test_normalize_unknown_verdict_defaults_to_info():+ c = SublimeSecurityConnector(api_key="t")+ out = c.normalize({"id": "x", "classification": "totally-unknown"})+ assert out["severity"] == "info"+++async def test_fetch_alerts_uses_cursor_pagination(fixture, monkeypatch):+ # Shrink the page size so two small fixture pages exercise the cursor+ # advance (the loop only continues on a full page + a next cursor).+ monkeypatch.setattr("app.connectors.sublime_security._PER_PAGE", 2)+ c = SublimeSecurityConnector(api_key="t")++ page1 = {"messages": [fixture[0], fixture[1]], "next_cursor": "cur1"}+ page2 = {"messages": [fixture[2]]}+ route = respx.get(f"{_BASE}/v1/messages")+ route.side_effect = [+ httpx.Response(200, json=page1),+ httpx.Response(200, json=page2),+ ]++ out = await c.fetch_alerts(since_seconds=300)++ # 2 from page 1 (full page + cursor → continue), 1 from page 2 (short → stop).+ assert len(out) == 3+ assert all(e["source"] == "sublime_security" for e in out)+ # The second request must carry the cursor returned by page 1.+ assert "cur1" in str(route.calls[1].request.url)+++async def test_fetch_alerts_stops_on_non_200():+ c = SublimeSecurityConnector(api_key="t")+ respx.get(f"{_BASE}/v1/messages").respond(401, json={"error": "unauthorized"})+ out = await c.fetch_alerts(since_seconds=300)+ assert out == []+++async def test_test_connection_success():+ c = SublimeSecurityConnector(api_key="t")+ respx.get(f"{_BASE}/v1/me").respond(200, json={"organization": {"name": "Acme Corp"}})+ res = await c.test_connection()+ assert res["success"] is True+ assert res["tenant"] == "Acme Corp"+++async def test_test_connection_failure():+ c = SublimeSecurityConnector(api_key="t")+ respx.get(f"{_BASE}/v1/me").respond(403, json={"error": "forbidden"})+ res = await c.test_connection()+ assert res["success"] is False+ assert "403" in res["error"]diff --git a/services/connectors/tests/fixtures/abnormal_security/sample_event.json b/services/connectors/tests/fixtures/abnormal_security/sample_event.jsonnew file mode 100644index 000000000..50f9d9cbc--- /dev/null+++ b/services/connectors/tests/fixtures/abnormal_security/sample_event.json@@ -0,0 +1,56 @@+{+ "threats": [+ {+ "threatId": "t-bec",+ "threatType": "businessEmailCompromise",+ "subject": "Urgent wire request",+ "fromAddress": "[email protected]",+ "toAddresses": ["[email protected]"],+ "receivedTime": "2026-06-01T10:00:00Z"+ },+ {+ "id": "t-credphish",+ "attackType": "Credential Phishing",+ "subject": "Verify your account",+ "sender": { "email": "[email protected]" },+ "recipients": [{ "email": "[email protected]" }],+ "receivedTime": "2026-06-01T10:01:00Z"+ },+ {+ "threatId": "t-spam",+ "threatType": "spam",+ "subject": "Limited time deal",+ "fromAddress": "[email protected]",+ "toAddresses": ["[email protected]"],+ "receivedTime": "2026-06-01T10:02:00Z"+ },+ {+ "threatId": "t-recon",+ "threatType": "reconnaissance",+ "subject": "Are you available?",+ "fromAddress": "[email protected]",+ "toAddresses": ["[email protected]"],+ "receivedTime": "2026-06-01T10:03:00Z"+ }+ ],+ "cases": [+ {+ "_kind": "case",+ "caseId": "c-ato",+ "threatType": "accountTakeover",+ "severity": "critical",+ "subject": "Account takeover case",+ "fromAddress": "[email protected]",+ "createdTime": "2026-06-01T10:04:00Z"+ },+ {+ "_kind": "case",+ "caseId": "c-override",+ "threatType": "spam",+ "severity": "high",+ "subject": "Escalated low-type case",+ "fromAddress": "[email protected]",+ "createdTime": "2026-06-01T10:05:00Z"+ }+ ]+}diff --git a/services/connectors/tests/fixtures/box/sample_event.json b/services/connectors/tests/fixtures/box/sample_event.jsonnew file mode 100644index 000000000..df49b4d26--- /dev/null+++ b/services/connectors/tests/fixtures/box/sample_event.json@@ -0,0 +1,41 @@+[+ {+ "event_id": "box-shield",+ "event_type": "SHIELD_ALERT",+ "created_by": { "login": "[email protected]", "name": "Security Bot" },+ "source": { "item_name": "confidential.docx" },+ "ip_address": "203.0.113.9",+ "created_at": "2026-06-01T10:00:00Z"+ },+ {+ "event_id": "box-collab",+ "event_type": "COLLABORATION_INVITE",+ "created_by": { "login": "[email protected]" },+ "source": { "name": "Shared Project Folder" },+ "ip_address": "198.51.100.10",+ "created_at": "2026-06-01T10:01:00Z"+ },+ {+ "event_id": "box-failed-login",+ "event_type": "FAILED_LOGIN",+ "created_by": { "login": "[email protected]" },+ "ip_address": "198.51.100.4",+ "created_at": "2026-06-01T10:02:00Z"+ },+ {+ "event_id": "box-preview",+ "event_type": "PREVIEW",+ "created_by": { "login": "[email protected]" },+ "source": { "item_name": "quarterly-report.pdf" },+ "created_at": "2026-06-01T10:03:00Z"+ },+ {+ "event_id": "box-external-download",+ "event_type": "ITEM_DOWNLOAD",+ "created_by": { "login": "[email protected]" },+ "action_by": { "login": "[email protected]" },+ "source": { "item_name": "customer-data.csv" },+ "ip_address": "203.0.113.55",+ "created_at": "2026-06-01T10:04:00Z"+ }+]diff --git a/services/connectors/tests/fixtures/datadog/sample_event.json b/services/connectors/tests/fixtures/datadog/sample_event.jsonnew file mode 100644index 000000000..0e0626188--- /dev/null+++ b/services/connectors/tests/fixtures/datadog/sample_event.json@@ -0,0 +1,62 @@+{+ "logs": [+ {+ "id": "log-critical",+ "attributes": {+ "status": "critical",+ "message": "Database connection pool exhausted",+ "host": "web-1",+ "service": "api",+ "timestamp": "2026-06-01T10:00:00Z"+ }+ },+ {+ "id": "log-error",+ "attributes": {+ "status": "error",+ "message": "Upstream timeout calling billing",+ "service": "worker"+ }+ },+ {+ "id": "log-warn",+ "attributes": {+ "level": "warn",+ "message": "Slow query > 2s"+ }+ },+ {+ "id": "log-info",+ "attributes": {+ "status": "info",+ "message": "Service started"+ }+ }+ ],+ "events": [+ {+ "id": 111,+ "alert_type": "error",+ "title": "Monitor triggered: high error rate",+ "text": "5xx rate above threshold",+ "host": "db-1",+ "date_happened": 1780000000+ },+ {+ "id": 112,+ "alert_type": "warning",+ "title": "Latency degradation"+ },+ {+ "id": 113,+ "alert_type": "info",+ "priority": "low",+ "title": "Deploy completed"+ },+ {+ "id": 114,+ "alert_type": "info",+ "title": "Routine note"+ }+ ]+}diff --git a/services/connectors/tests/fixtures/dropbox/sample_event.json b/services/connectors/tests/fixtures/dropbox/sample_event.jsonnew file mode 100644index 000000000..4e691b436--- /dev/null+++ b/services/connectors/tests/fixtures/dropbox/sample_event.json@@ -0,0 +1,38 @@+[+ {+ "event_id": "d-app-link",+ "event_type": { ".tag": "app_link_team" },+ "event_category": { ".tag": "apps" },+ "actor": { "user": { "email": "[email protected]", "display_name": "Admin User" } },+ "timestamp": "2026-06-01T10:00:00Z"+ },+ {+ "event_id": "d-admin-role",+ "event_type": { ".tag": "member_change_admin_role" },+ "event_category": { ".tag": "members" },+ "actor": { "user": { "email": "[email protected]" } },+ "timestamp": "2026-06-01T10:01:00Z"+ },+ {+ "event_id": "d-share-link",+ "event_type": { ".tag": "shared_link_create" },+ "event_category": { ".tag": "sharing" },+ "actor": { "user": { "email": "[email protected]" } },+ "timestamp": "2026-06-01T10:02:00Z"+ },+ {+ "event_id": "d-login-fail",+ "event_type": { ".tag": "login_fail" },+ "event_category": { ".tag": "logins" },+ "actor": { "user": { "email": "[email protected]" } },+ "origin": { "geo_location": { "ip_address": "203.0.113.5" } },+ "timestamp": "2026-06-01T10:03:00Z"+ },+ {+ "event_id": "d-file-request",+ "event_type": { ".tag": "file_request_create" },+ "event_category": { ".tag": "file_requests" },+ "actor": { "user": { "email": "[email protected]" } },+ "timestamp": "2026-06-01T10:04:00Z"+ }+]diff --git a/services/connectors/tests/fixtures/oci/sample_event.json b/services/connectors/tests/fixtures/oci/sample_event.jsonnew file mode 100644index 000000000..693904361--- /dev/null+++ b/services/connectors/tests/fixtures/oci/sample_event.json@@ -0,0 +1,36 @@+[+ {+ "data": {+ "eventName": "DeleteUser",+ "eventId": "oci-delete-user",+ "eventTime": "2026-06-01T10:00:00Z",+ "compartmentName": "root",+ "identity": { "principalName": "admin", "ipAddress": "203.0.113.7" }+ }+ },+ {+ "data": {+ "eventName": "CreateUser",+ "eventId": "oci-create-user",+ "eventTime": "2026-06-01T10:01:00Z",+ "identity": { "principalName": "ops" }+ }+ },+ {+ "data": {+ "eventName": "ListBuckets",+ "eventId": "oci-list-buckets",+ "eventTime": "2026-06-01T10:02:00Z",+ "identity": { "principalName": "reader" }+ }+ },+ {+ "data": {+ "eventName": "GetObject",+ "eventId": "oci-get-object-denied",+ "eventTime": "2026-06-01T10:03:00Z",+ "identity": { "principalName": "intruder", "ipAddress": "198.51.100.22" },+ "response": { "status": 403 }+ }+ }+]diff --git a/services/connectors/tests/fixtures/sublime_security/sample_event.json b/services/connectors/tests/fixtures/sublime_security/sample_event.jsonnew file mode 100644index 000000000..6c7e9be9b--- /dev/null+++ b/services/connectors/tests/fixtures/sublime_security/sample_event.json@@ -0,0 +1,52 @@+[+ {+ "id": "msg-malicious",+ "subject": "Invoice overdue — action required",+ "classification": "malicious",+ "triggered_rules": [{ "name": "Attachment: known-bad hash" }],+ "from": { "email": "[email protected]" },+ "to": "[email protected]",+ "created_at": "2026-06-01T10:00:00Z"+ },+ {+ "id": "msg-suspicious",+ "subject": "Re: payment confirmation",+ "verdict": "suspicious",+ "from": { "email": "[email protected]" },+ "to": "[email protected]",+ "created_at": "2026-06-01T10:01:00Z"+ },+ {+ "id": "msg-graymail",+ "subject": "Your weekly newsletter",+ "classification": "graymail",+ "from": { "email": "[email protected]" },+ "to": "[email protected]",+ "created_at": "2026-06-01T10:02:00Z"+ },+ {+ "id": "msg-benign",+ "subject": "Lunch tomorrow?",+ "classification": "benign",+ "from": { "email": "[email protected]" },+ "to": "[email protected]",+ "created_at": "2026-06-01T10:03:00Z"+ },+ {+ "id": "msg-bec-escalation",+ "subject": "Urgent: update wire instructions",+ "verdict": "spam",+ "triggered_rules": [{ "name": "BEC: Wire Transfer Request" }],+ "from": { "email": "[email protected]" },+ "to": "[email protected]",+ "created_at": "2026-06-01T10:04:00Z"+ },+ {+ "message_id": "msg-nested-review",+ "subject": "Account verification needed",+ "review": { "classification": "suspicious" },+ "from_email": "[email protected]",+ "recipient": "[email protected]",+ "received_at": "2026-06-01T10:05:00Z"+ }+]