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
docs(connectors): hello-connector tutorial with httpbin reference example (#91)
Beenu Arorad96925ed21a0
diff --git a/apps/docs/docs/connectors/hello-connector.md b/apps/docs/docs/connectors/hello-connector.mdnew file mode 100644index 000000000..574ed7850--- /dev/null+++ b/apps/docs/docs/connectors/hello-connector.md@@ -0,0 +1,281 @@+---+sidebar_position: 2+title: Hello, connector — write your first AiSOC integration+description: A walkthrough that builds a real, runnable AiSOC connector against httpbin.org. No vendor account, no API key, just the BaseConnector contract front to back.+---++# Hello, connector++This tutorial walks you end-to-end through the work of adding a new data source to AiSOC. By the end you will have:++- A subclass of `BaseConnector` that implements every method the platform calls.+- A self-describing schema that the connector wizard renders into a configuration form.+- A `test_connection()` path that the wizard hits before it lets you save.+- A `fetch_alerts()` path that the polling scheduler hits every five minutes.+- A `normalize()` step that converts vendor JSON into AiSOC's common alert shape.+- A smoke test that pins all of the above against mocked HTTP traffic.++Everything points at [httpbin.org](https://httpbin.org), a free, no-auth HTTP testing service. The point isn't to ingest httpbin events into your SOC — the point is to walk every line of the connector contract against a backend that:++- responds without authentication,+- returns deterministic JSON shapes you can assert on,+- has been up roughly forever.++When you're ready to wire up a real vendor, copy the example, swap the URLs, and add an authentication step. The shape stays the same.++## Where the example lives++The reference implementation lives at:++```text+services/connectors/app/connectors/_examples/hello_connector.py+```++The `_examples/` directory is **deliberately not** registered in [`services/connectors/app/connectors/__init__.py`](https://github.com/beenuar/AiSOC/blob/main/services/connectors/app/connectors/__init__.py). Anything under `_examples/` exists for documentation only and never appears in the connector catalog, the polling scheduler, or the marketplace index. There is a smoke test ([`tests/test_hello_connector_example.py`](https://github.com/beenuar/AiSOC/blob/main/services/connectors/tests/test_hello_connector_example.py)) that pins this invariant — if someone accidentally promotes the example into the live registry, CI fails.++## Step 1 — Pick identity attributes++A connector identifies itself with three class-level strings:++```python+class HelloConnector(BaseConnector):+ connector_id = "hello"+ connector_name = "Hello (Tutorial)"+ connector_category = "saas"+```++- **`connector_id`** is the wire identifier. It shows up in database rows, plugin manifests, and API URLs. Treat it like a primary key: lowercase, hyphen- or underscore-separated, **never changes** after first release.+- **`connector_name`** is the human label rendered in the catalog grid.+- **`connector_category`** must be one of the existing categories: `identity`, `cloud`, `vcs`, `siem`, `edr`, `xdr`, `network`, `posture`, `saas`. The category drives grouping in the wizard and downstream routing hints in detection rules. If your tool genuinely doesn't fit one of these, raise it in a PR before inventing a new one — the taxonomy is shared with the detection layer.++## Step 2 — Declare the schema++`schema()` is what the connector wizard renders. It tells the UI which fields to draw, which ones are secret, and where to find the docs page (which is this page, in our case).++```python+@classmethod+def schema(cls) -> ConnectorSchema:+ return ConnectorSchema(+ connector_id=cls.connector_id,+ connector_name=cls.connector_name,+ category=cls.connector_category,+ description=(+ "Tutorial connector that polls httpbin.org. Use this as a "+ "reference when writing a new connector — it implements "+ "every BaseConnector method against a public, no-auth API."+ ),+ docs_url="/docs/connectors/hello-connector",+ fields=[+ Field(+ "api_token",+ "secret",+ "API Token",+ help_text=(+ "Pretend credential. httpbin doesn't actually "+ "validate it — this field exists so the tutorial "+ "exercises the credential vault."+ ),+ ),+ Field(+ "base_url",+ "string",+ "Base URL",+ required=False,+ default="https://httpbin.org",+ placeholder="https://httpbin.org",+ help_text="Override only when running against a self-hosted httpbin.",+ ),+ ],+ )+```++A few things worth pointing at:++- **`type="secret"`** on `api_token` does two things: the wizard renders a masked input, and the [credential vault](/docs/operations/credentials) encrypts the value with `Fernet` before it touches the database. The tutorial declares the field as a secret even though httpbin ignores it — the goal is to exercise that code path so you can see exactly what happens with a real vendor.+- **`required=False`** plus `default=...` on `base_url` matches a common pattern for self-hosted vendor support. The wizard shows the default in placeholder text and skips validation if the field is left blank.+- **`docs_url`** is the link the wizard surfaces as "Documentation" in the connector card. Always point it at the per-connector page, not the catalog.++## Step 3 — Declare capabilities++Capabilities are the set of action verbs the agent layer is allowed to ask the connector to perform. The tutorial connector is read-only, so it declares one:++```python+@classmethod+def capabilities(cls) -> tuple[Capability, ...]:+ return (Capability.PULL_ALERTS,)+```++Real connectors will frequently add things like `PULL_AUDIT`, `PIVOT_USER`, or `READ_AUDIT_TRAIL`. Anything **kinetic** (isolating a host, blocking a hash, deleting a session) requires a real backend that can act on those verbs and is out of scope for this example by design — the goal is to not give a brand-new contributor a half-implemented "isolate host" path that they then ship by mistake.++## Step 4 — Constructor++The constructor must match the schema field names exactly. The router decrypts `auth_config` and unpacks it as keyword arguments, so a typo here turns into a 500 at poll time:++```python+def __init__(self, api_token: str, base_url: str | None = None):+ self._api_token = api_token+ # Strip trailing slash so we can compose URLs with simple `+`.+ self._base_url = (base_url or "https://httpbin.org").rstrip("/")+```++We strip trailing slashes so URL composition stays boring (`f"{self._base_url}/anything"` always works).++## Step 5 — `test_connection()`++`test_connection()` is the pre-save liveness check. It is called by `POST /connectors/test` **before** the row is written to the database. Returning `success: false` here blocks the save, so keep this cheap and deterministic — one round trip, short timeout, no pagination:++```python+async def test_connection(self) -> dict[str, Any]:+ try:+ async with httpx.AsyncClient(timeout=10.0) as client:+ resp = await client.get(f"{self._base_url}/status/200")+ except httpx.HTTPError as exc:+ return {+ "success": False,+ "connector": self.connector_id,+ "error": f"network error: {exc.__class__.__name__}",+ }++ if resp.status_code != 200:+ return {+ "success": False,+ "connector": self.connector_id,+ "error": f"unexpected status: HTTP {resp.status_code}",+ }+ return {"success": True, "connector": self.connector_id}+```++Three rules to internalize for `test_connection()`:++1. **Always return a dict.** Never raise. The wizard uses the `success` flag to decide whether to render the error inline; an unhandled exception bubbles up as a 500 and the operator sees a useless "request failed" toast.+2. **Always include `connector: self.connector_id`.** Multiple connectors can be tested in parallel; the response key lets the UI route the result to the right card.+3. **Categorise failures.** `network error: ConnectError` is a different problem from `unexpected status: HTTP 401`. The first is an infrastructure issue; the second is a credential issue. Surface the difference so the operator knows whether to call IT or the vendor.++## Step 6 — `fetch_alerts()`++This is the polling read path. The scheduler calls it every `poll_interval_seconds` (default 300) with the elapsed window since the last successful poll. Real connectors translate `since_seconds` into a vendor-native time filter (Auth0 uses a Lucene query string, Cloudflare uses `since=<ISO-8601>`, GitHub uses cursor pagination, etc.).++httpbin doesn't store events, so the example just hits `/anything` once and treats the response body as a single synthetic event:++```python+async def fetch_alerts(self, since_seconds: int = 300) -> list[dict[str, Any]]:+ try:+ async with httpx.AsyncClient(timeout=15.0) as client:+ resp = await client.get(+ f"{self._base_url}/anything",+ params={"since_seconds": since_seconds},+ )+ except httpx.HTTPError as exc:+ logger.warning("hello.fetch_alerts.network_error", error=str(exc))+ return []++ if resp.status_code != 200:+ logger.warning(+ "hello.fetch_alerts.bad_status",+ status=resp.status_code,+ body=resp.text[:300],+ )+ return []++ try:+ payload = resp.json() or {}+ except ValueError:+ logger.warning("hello.fetch_alerts.invalid_json")+ return []++ return [self.normalize(payload)]+```++The most important thing here is the failure model: **polling failures must be non-terminal**. Network errors, 5xx responses, and bad JSON all return `[]` rather than raising. The scheduler logs the failure, records it on `health_status`, surfaces it in the UI on the connector card, and tries again next interval. If `fetch_alerts()` raises, the entire job slot is poisoned — you'll see the connector go red until the next reload (up to 30 seconds), and any other connectors sharing that thread will be delayed.++Keep the `since_seconds` parameter in the signature even if your vendor doesn't expose a time-window filter — the scheduler always passes it.++## Step 7 — `normalize()`++`normalize()` maps vendor JSON to AiSOC's common alert shape:++```python+def normalize(self, raw: dict[str, Any]) -> dict[str, Any]:+ url = raw.get("url") or "(no url)"+ return {+ "source": "hello",+ "category": self.connector_category,+ "severity": "info",+ "title": f"Hello connector: pinged {url}",+ "description": "Synthetic event from the hello-connector tutorial.",+ "alert_id": f"hello:{raw.get('origin', '?')}:{url}",+ "host": None,+ "raw": raw,+ }+```++The contract for the returned dict is documented in `services/ingest` and includes (at minimum):++| Field | Notes |+|---|---|+| `source` | Stable string, almost always `cls.connector_id`. |+| `category` | Same taxonomy as the schema. Detection rules match against this. |+| `severity` | One of `info`, `low`, `medium`, `high`. **Four tiers, not five.** Vendor 5-tier ladders (Azure, SCC, etc.) collapse here. |+| `title` | Short, human-readable. Operators read this in a list. |+| `description` | Optional context. Can be the raw event description, the actor, the IP, etc. |+| `alert_id` | Stable identifier for de-duplication. Use the vendor's ID when one exists; otherwise build a deterministic hash from event content. |+| `host` | Hostname or IP if relevant; `None` if not. |+| `raw` | **Always** include the original payload. Detection rules and the [explain endpoint](/docs/api/rest) both rely on it. |++A few patterns worth copying:++- **`severity` is hard-coded `info`** in the example because httpbin doesn't carry a severity signal. Real connectors derive severity from the vendor's risk score, status code, anomaly flag, etc. — see the [Auth0 connector](https://github.com/beenuar/AiSOC/blob/main/services/connectors/app/connectors/auth0.py) for an example of a simple rule-based mapping.+- **`alert_id` should be stable across re-fetches** when the vendor exposes a unique ID. httpbin doesn't, so the example cheats: it uses `origin + url` as a poor-but-stable hash. If you do this, document it — the next person to look will assume you forgot.+- **`raw` is forensics**. Don't summarise it, don't truncate it, don't drop fields you didn't recognise. The detection layer and the explain endpoint both treat it as the source of truth for "what actually happened".++## Step 8 — Pin the contract with a smoke test++The example is paired with a smoke test at [`services/connectors/tests/test_hello_connector_example.py`](https://github.com/beenuar/AiSOC/blob/main/services/connectors/tests/test_hello_connector_example.py). It uses [`respx`](https://lundberg.github.io/respx/) (already a dev dependency in `services/connectors/pyproject.toml`) to mock httpx and exercise every method end-to-end:++```python+async def test_test_connection_success():+ respx.get("https://httpbin.org/status/200").mock(return_value=httpx.Response(200))+ conn = HelloConnector(api_token="t")+ result = await conn.test_connection()+ assert result == {"success": True, "connector": "hello"}+```++The test file pins three different things, in order of importance:++1. **`HelloConnector` is not in the registry.** This catches the "I copied the example into the catalog by accident" failure mode.+2. **The schema shape doesn't drift.** Field names, secret flags, default values, and the docs URL are all asserted explicitly. If a tutorial reader copies the example and changes one of these without thinking, the test tells them.+3. **Every method behaves the way the tutorial says it does.** Happy path, bad status, network error, invalid JSON, and the `since_seconds` query parameter all have dedicated cases.++When you write your own connector, copy the test layout. The volume isn't large — fifteen short tests cover the entire surface — and the cost of *not* having them is that you ship a connector that silently regresses six months later when a vendor changes their JSON shape.++Run the suite locally:++```bash+cd services/connectors+.venv/bin/python -m pytest tests/test_hello_connector_example.py -v+```++You should see 15 tests pass in well under a second.++## Graduating from `_examples/` to a real connector++When you're ready to ship a real connector, here is the exact checklist:++1. **Move the file.** From `services/connectors/app/connectors/_examples/<your_connector>.py` to `services/connectors/app/connectors/<your_connector>.py`.+2. **Register it.** Add the class to `_CONNECTOR_CLASSES` in `services/connectors/app/connectors/__init__.py`. Keep the tuple alphabetised by `connector_id` to keep diffs predictable. Add the class name to the `__all__` list at the bottom of the same file.+3. **Add a marketplace manifest.** Create `plugins/<connector-id>/plugin.yaml` mirroring your `schema()`. The fields and secret flags must match. Use [`plugins/auth0/plugin.yaml`](https://github.com/beenuar/AiSOC/blob/main/plugins/auth0/plugin.yaml) as a template.+4. **Sync the marketplace.** Run `pnpm marketplace:sync` from the repo root. This regenerates the static catalog under `apps/web/public/marketplace/` so the catalog grid in the UI picks up the new entry.+5. **Write a docs page.** Add `apps/docs/docs/connectors/<your-connector>.md` and wire it into `apps/docs/sidebars.ts` under the `Connectors` category. Use [`apps/docs/docs/connectors/cloudflare.md`](https://github.com/beenuar/AiSOC/blob/main/apps/docs/docs/connectors/cloudflare.md) as a template — `What you get` table → `Prerequisites` → `Setup walkthrough` → `Polling details` → `Severity heuristics` → `Troubleshooting`.+6. **Add real tests.** Use `respx` to mock the vendor API. At minimum, exercise `test_connection()` (success + auth failure + network failure), `fetch_alerts()` (happy path + empty + 5xx + auth expiry), and `normalize()` (every severity branch).+7. **Open a PR.** The code review will check that schema fields are wizard-renderable, that secrets are marked `secret=True`, that the category fits the existing taxonomy, that polling failures are non-terminal, and that the docs page exists.++That's the full path. If any of those steps feels heavier than you expected, file a bug — the goal is for adding a connector to feel mechanical, not heroic.++## Related++- [Connectors overview](/docs/connectors/) — the catalog, polling architecture, and category taxonomy.+- [Credential vault](/docs/operations/credentials) — what `secret=True` actually does at the database layer.+- [Plugin SDK overview](/docs/plugins/overview) — for connectors distributed outside the monorepo.+- [Contributing guidelines](/docs/contributing/guidelines) — broader expectations for PRs that touch `services/connectors/`.diff --git a/apps/docs/docs/connectors/index.md b/apps/docs/docs/connectors/index.mdindex 759fcf9e5..4f4d37537 100644--- a/apps/docs/docs/connectors/index.md+++ b/apps/docs/docs/connectors/index.md@@ -141,4 +141,6 @@ Several connectors today require you to bring your own credentials (an Azure AD## Writing a new connector-See [Plugin SDK overview](/docs/plugins/overview) and [Contributing](/docs/contributing/guidelines). The short version: subclass `BaseConnector`, implement `schema()`, `test_connection()`, `fetch_alerts()`, and `normalize()`, register it in `services/connectors/app/connectors/__init__.py`, drop a `plugin.yaml` under `plugins/<id>/`, and run `pnpm marketplace:sync`.+The fastest path is the [Hello, connector tutorial](/docs/connectors/hello-connector) — a complete, runnable walkthrough that builds a `BaseConnector` against [httpbin.org](https://httpbin.org). No vendor account required.++For broader background see [Plugin SDK overview](/docs/plugins/overview) and [Contributing](/docs/contributing/guidelines). The short version: subclass `BaseConnector`, implement `schema()`, `test_connection()`, `fetch_alerts()`, and `normalize()`, register it in `services/connectors/app/connectors/__init__.py`, drop a `plugin.yaml` under `plugins/<id>/`, and run `pnpm marketplace:sync`.diff --git a/apps/docs/sidebars.ts b/apps/docs/sidebars.tsindex 213196b51..5df112d45 100644--- a/apps/docs/sidebars.ts+++ b/apps/docs/sidebars.ts@@ -36,6 +36,7 @@ const sidebars: SidebarsConfig = {label: "Connectors",items: ["connectors/index",+ "connectors/hello-connector","connectors/api-coverage","connectors/universal-capture","connectors/azure-entra",diff --git a/services/connectors/app/connectors/_examples/__init__.py b/services/connectors/app/connectors/_examples/__init__.pynew file mode 100644index 000000000..cb405e515--- /dev/null+++ b/services/connectors/app/connectors/_examples/__init__.py@@ -0,0 +1,21 @@+"""+Reference connector examples.++Modules under this package are **tutorial-only**. They are intentionally+*not* registered in ``services/connectors/app/connectors/__init__.py``+and therefore never appear in the catalog, the polling scheduler, or+the marketplace index.++The examples exist so that:++* The hello-connector tutorial in ``apps/docs/docs/connectors/hello-connector.md``+ can point at a real, importable, type-checked file rather than an inline+ code snippet that drifts from reality.+* Connector authors can copy a known-good starting point instead of+ scaffolding from one of the production connectors (which carry vendor+ quirks that obscure the required interface).++If you ever want to actually ship one of these examples as a real+connector, move it out of ``_examples/`` into ``app/connectors/`` and+register it in the parent ``__init__.py``.+"""diff --git a/services/connectors/app/connectors/_examples/hello_connector.py b/services/connectors/app/connectors/_examples/hello_connector.pynew file mode 100644index 000000000..368c52039--- /dev/null+++ b/services/connectors/app/connectors/_examples/hello_connector.py@@ -0,0 +1,269 @@+"""+HelloConnector — reference implementation for the connector tutorial.++This module backs the tutorial at+``apps/docs/docs/connectors/hello-connector.md``. It is **not** registered+in the connector registry: it lives under ``_examples/`` precisely so it+can't accidentally end up in the catalog, the scheduler, or the+marketplace index.++The connector talks to `httpbin.org <https://httpbin.org>`_, a no-auth+HTTP testing service, so the tutorial is reproducible without any vendor+account, API key, or paid tier. The point isn't to ingest httpbin events+into your SOC — it's to demonstrate every method you need to override on+:class:`BaseConnector` with a backend that:++* responds without authentication,+* returns deterministic JSON shapes you can assert on,+* never goes down (it has been up roughly forever).++Layout of this file mirrors the order a real connector usually grows:++1. Identity attributes (``connector_id`` / ``connector_name`` / ``connector_category``).+2. ``schema()`` — what the wizard renders.+3. ``capabilities()`` — what the agent layer is allowed to ask of you.+4. ``__init__`` — accept exactly the fields the schema declares.+5. ``test_connection()`` — pre-save sanity check.+6. ``fetch_alerts()`` — the polling read path.+7. ``normalize()`` — vendor JSON → AiSOC's common alert shape.++If you copy this file as a starting point for a new connector, remember+to:++* Move it out of ``_examples/`` into ``services/connectors/app/connectors/``.+* Add the class to ``_CONNECTOR_CLASSES`` in the parent ``__init__.py``.+* Drop a ``plugins/<connector-id>/plugin.yaml`` mirroring ``schema()``.+* Add a per-connector docs page under ``apps/docs/docs/connectors/``.+* Run ``pnpm marketplace:sync``.+"""++from __future__ import annotations++from typing import Any++import httpx+import structlog++from app.connectors.base import (+ BaseConnector,+ Capability,+ ConnectorSchema,+ Field,+)++logger = structlog.get_logger()++# httpbin's `/anything` endpoint echoes whatever you send back as JSON.+# We treat each response as a "synthetic event" so the connector has+# something concrete to normalize. Real connectors point at a vendor+# audit endpoint here.+_DEFAULT_BASE_URL = "https://httpbin.org"+++class HelloConnector(BaseConnector):+ """Tutorial connector that polls httpbin.org.++ Demonstrates the full :class:`BaseConnector` contract end-to-end+ against a public, no-auth backend. See the docstring at the top of+ this module for the rationale behind picking httpbin.+ """++ # ---- identity --------------------------------------------------------+ #+ # `connector_id` is the stable wire identifier — it shows up in+ # database rows, plugin manifests, and API URLs. Treat it like a+ # primary key: lowercase, hyphen- or underscore-separated, never+ # changes after first release.+ connector_id = "hello"+ connector_name = "Hello (Tutorial)"+ # `saas` is the closest-fit existing category; if you're shipping a+ # real new connector that doesn't slot into the existing taxonomy+ # (`identity` / `cloud` / `vcs` / `siem` / `edr` / `xdr` / `network`+ # / `posture` / `saas`), discuss in a PR before inventing a new one.+ connector_category = "saas"++ # ---- self-description ------------------------------------------------++ @classmethod+ def schema(cls) -> ConnectorSchema:+ """Tell the wizard which fields to render.++ ``api_token`` is marked ``secret`` so the UI uses a masked input+ and the credential vault encrypts it at rest. We don't actually+ send the token to httpbin — that's the point of the example —+ but we still declare it as a secret so the encryption code path+ is exercised exactly as it would be for a real vendor.+ """+ return ConnectorSchema(+ connector_id=cls.connector_id,+ connector_name=cls.connector_name,+ category=cls.connector_category,+ description=(+ "Tutorial connector that polls httpbin.org. Use this as a "+ "reference when writing a new connector — it implements "+ "every BaseConnector method against a public, no-auth API."+ ),+ docs_url="/docs/connectors/hello-connector",+ fields=[+ Field(+ "api_token",+ "secret",+ "API Token",+ help_text=(+ "Pretend credential. httpbin doesn't actually "+ "validate it — this field exists so the tutorial "+ "exercises the credential vault."+ ),+ ),+ Field(+ "base_url",+ "string",+ "Base URL",+ required=False,+ default=_DEFAULT_BASE_URL,+ placeholder=_DEFAULT_BASE_URL,+ help_text="Override only when running against a self-hosted httpbin.",+ ),+ ],+ )++ # ---- capabilities ----------------------------------------------------++ @classmethod+ def capabilities(cls) -> tuple[Capability, ...]:+ """Declare what the agent layer is allowed to ask us to do.++ The tutorial connector is intentionally read-only — it polls,+ normalizes, and hands events to the ingest service. Anything+ kinetic (isolating a host, blocking a hash) would require a+ real backend that can act on those verbs.+ """+ return (Capability.PULL_ALERTS,)++ # ---- construction ----------------------------------------------------++ def __init__(self, api_token: str, base_url: str | None = None):+ # The constructor signature MUST line up with the schema field+ # names. The connector router unpacks the decrypted ``auth_config``+ # dict as kwargs, so a typo here turns into a 500 at poll time.+ self._api_token = api_token+ # Strip a trailing slash so we can compose URLs with simple `+`.+ self._base_url = (base_url or _DEFAULT_BASE_URL).rstrip("/")++ # ---- runtime: pre-save test -----------------------------------------++ async def test_connection(self) -> dict[str, Any]:+ """Pre-save liveness check.++ Called by ``POST /connectors/test`` *before* the row is written+ to the database. Returning ``success: false`` here blocks the+ save, so keep this cheap and deterministic — one round trip,+ short timeout, no pagination.++ We use httpbin's ``/status/200`` which echoes back a 200 with no+ body. That's the cheapest possible "is the network path open?"+ signal you can ask for.+ """+ try:+ async with httpx.AsyncClient(timeout=10.0) as client:+ resp = await client.get(f"{self._base_url}/status/200")+ except httpx.HTTPError as exc:+ # Network errors, DNS failures, TLS handshake errors — all+ # surface here. We prefer a single, structured failure shape+ # so the UI can render it without sniffing exception types.+ logger.warning("hello.test_connection.network_error", error=str(exc))+ return {+ "success": False,+ "connector": self.connector_id,+ "error": f"network error: {exc.__class__.__name__}",+ }++ if resp.status_code != 200:+ return {+ "success": False,+ "connector": self.connector_id,+ "error": f"unexpected status: HTTP {resp.status_code}",+ }+ return {"success": True, "connector": self.connector_id}++ # ---- runtime: poll ---------------------------------------------------++ async def fetch_alerts(self, since_seconds: int = 300) -> list[dict[str, Any]]:+ """Pull a batch of "events" since the last poll.++ Real connectors translate ``since_seconds`` into a vendor-native+ time filter (Auth0 uses a Lucene query string, Cloudflare uses+ ``since=<ISO-8601>``, GitHub uses cursor pagination, etc.). We+ don't have a real time window — httpbin doesn't store events —+ so we just hit ``/anything`` once and treat the response body as+ a single synthetic event. Keep ``since_seconds`` in the signature+ anyway: the scheduler always passes it.++ On any HTTP error we log and return ``[]`` rather than raising.+ Polling failures are non-terminal — the next interval will retry+ and the failure is already surfaced via ``health_status`` once+ the scheduler records it.+ """+ try:+ async with httpx.AsyncClient(timeout=15.0) as client:+ resp = await client.get(+ f"{self._base_url}/anything",+ params={"since_seconds": since_seconds},+ )+ except httpx.HTTPError as exc:+ logger.warning("hello.fetch_alerts.network_error", error=str(exc))+ return []++ if resp.status_code != 200:+ logger.warning(+ "hello.fetch_alerts.bad_status",+ status=resp.status_code,+ body=resp.text[:300],+ )+ return []++ try:+ payload = resp.json() or {}+ except ValueError:+ logger.warning("hello.fetch_alerts.invalid_json")+ return []++ # Wrap the single response as a list-of-events so callers don't+ # have to special-case "one event per poll" vs "many events per+ # poll". Real connectors typically iterate over the vendor's+ # paginated cursor here.+ return [self.normalize(payload)]++ # ---- runtime: normalization ------------------------------------------++ def normalize(self, raw: dict[str, Any]) -> dict[str, Any]:+ """Map vendor JSON → the common alert shape AiSOC ingests.++ The contract for the returned dict is documented in+ ``services/ingest`` and includes (at minimum) ``source``,+ ``category``, ``severity``, ``title``, plus a ``raw`` blob with+ the original event preserved for forensics. We always carry the+ raw payload through — detection rules and explanation lineage+ both rely on it.++ Severity is hard-coded ``info`` because httpbin doesn't carry a+ severity signal. Real connectors derive severity from the+ vendor's risk score, status code, anomaly flag, etc. — see the+ Auth0 connector for an example of a simple rule-based mapping.+ """+ # httpbin echoes the request URL back at us — extract it for the+ # description so the event in the UI looks plausible.+ url = raw.get("url") or "(no url)"+ return {+ "source": "hello",+ "category": self.connector_category,+ "severity": "info",+ "title": f"Hello connector: pinged {url}",+ "description": "Synthetic event from the hello-connector tutorial.",+ # `alert_id` should be stable across re-fetches when the+ # vendor exposes a unique ID. httpbin doesn't, so we cheat:+ # use the request origin + URL as a poor-but-stable hash.+ "alert_id": f"hello:{raw.get('origin', '?')}:{url}",+ "host": None,+ "raw": raw,+ }diff --git a/services/connectors/tests/test_hello_connector_example.py b/services/connectors/tests/test_hello_connector_example.pynew file mode 100644index 000000000..fe58e58d1--- /dev/null+++ b/services/connectors/tests/test_hello_connector_example.py@@ -0,0 +1,253 @@+"""+Smoke test for the hello-connector tutorial example.++Two jobs:++1. Catch tutorial drift. The example file under+ ``app/connectors/_examples/hello_connector.py`` is shown verbatim in+ ``apps/docs/docs/connectors/hello-connector.md``. If someone edits+ the example, this test fails noisily, which forces the docs PR to+ re-check the snippets.++2. Prove the example is honest. Every method the tutorial walks the+ reader through (``schema``, ``capabilities``, ``test_connection``,+ ``fetch_alerts``, ``normalize``) is exercised here against mocked+ httpbin responses. The tutorial says "this works" — these tests are+ the receipts.++We deliberately *don't* assert that ``HelloConnector`` shows up in+``CONNECTOR_REGISTRY``: it must not. Test ``test_not_registered`` pins+that invariant so a well-meaning contributor doesn't accidentally+promote the tutorial example into the live catalog.+"""++from __future__ import annotations++import httpx+import pytest+import respx+from app.connectors import CONNECTOR_REGISTRY+from app.connectors._examples.hello_connector import HelloConnector+from app.connectors.base import Capability++# ---------------------------------------------------------------------------+# Identity / registration invariants+# ---------------------------------------------------------------------------+++def test_not_registered():+ """The tutorial example must NOT be in the live registry.++ If this fails, somebody added ``HelloConnector`` to+ ``_CONNECTOR_CLASSES`` in ``app/connectors/__init__.py``. Either+ revert that, or move the example out of ``_examples/`` into a real+ connector module (and update the tutorial accordingly).+ """+ assert "hello" not in CONNECTOR_REGISTRY+++def test_identity_attributes():+ """Identity attributes are the public-facing contract, so pin them."""+ assert HelloConnector.connector_id == "hello"+ assert HelloConnector.connector_name == "Hello (Tutorial)"+ assert HelloConnector.connector_category == "saas"+++# ---------------------------------------------------------------------------+# schema()+# ---------------------------------------------------------------------------+++def test_schema_shape():+ """Schema must be wizard-renderable: required fields present, secret+ fields marked, docs link populated."""+ schema = HelloConnector.schema().to_dict()++ assert schema["connector_id"] == "hello"+ assert schema["category"] == "saas"+ assert schema["docs_url"] == "/docs/connectors/hello-connector"++ field_names = [f["name"] for f in schema["fields"]]+ assert field_names == ["api_token", "base_url"]++ # The token must be marked secret so the credential vault encrypts it.+ api_token = next(f for f in schema["fields"] if f["name"] == "api_token")+ assert api_token["type"] == "secret"++ # ``base_url`` is optional with a sensible default — verify both flags.+ base_url = next(f for f in schema["fields"] if f["name"] == "base_url")+ assert base_url["required"] is False+ assert base_url["default"] == "https://httpbin.org"+++def test_capabilities_are_read_only():+ """Tutorial connector is read-only by design — the only capability+ it should declare is ``PULL_ALERTS``. Any drift here likely means+ someone added a kinetic verb to the example without thinking+ through the implications for new contributors copying it."""+ assert HelloConnector.capabilities() == (Capability.PULL_ALERTS,)+++# ---------------------------------------------------------------------------+# test_connection()+# ---------------------------------------------------------------------------+++async def test_test_connection_success():+ """200 from /status/200 → success."""+ respx.get("https://httpbin.org/status/200").mock(return_value=httpx.Response(200))+ conn = HelloConnector(api_token="t")+ result = await conn.test_connection()+ assert result == {"success": True, "connector": "hello"}+++async def test_test_connection_bad_status():+ """Non-200 → structured failure, not a raised exception. The wizard+ relies on this shape to render the error inline."""+ respx.get("https://httpbin.org/status/200").mock(return_value=httpx.Response(503))+ conn = HelloConnector(api_token="t")+ result = await conn.test_connection()+ assert result["success"] is False+ assert "503" in result["error"]+ assert result["connector"] == "hello"+++async def test_test_connection_network_error():+ """Network failures (DNS, TLS, timeout) must also surface as a+ structured failure rather than bubbling exceptions up to the API+ layer (which would render as a 500 to the operator)."""+ respx.get("https://httpbin.org/status/200").mock(side_effect=httpx.ConnectError("boom"))+ conn = HelloConnector(api_token="t")+ result = await conn.test_connection()+ assert result["success"] is False+ assert "ConnectError" in result["error"]+++async def test_test_connection_respects_base_url_override():+ """A custom base_url must actually be used. Catches the classic+ bug of saving the override into ``self._base_url`` but forgetting+ to swap out the hard-coded constant in the URL builder."""+ respx.get("https://httpbin.local/status/200").mock(return_value=httpx.Response(200))+ conn = HelloConnector(api_token="t", base_url="https://httpbin.local/")+ result = await conn.test_connection()+ assert result["success"] is True+++# ---------------------------------------------------------------------------+# fetch_alerts()+# ---------------------------------------------------------------------------+++async def test_fetch_alerts_returns_normalized_event():+ """Happy path: vendor responds, connector wraps the response in a+ single normalized event with the raw payload preserved."""+ respx.get("https://httpbin.org/anything").mock(+ return_value=httpx.Response(+ 200,+ json={+ "url": "https://httpbin.org/anything?since_seconds=300",+ "origin": "192.0.2.10",+ "headers": {"Host": "httpbin.org"},+ },+ )+ )++ conn = HelloConnector(api_token="t")+ events = await conn.fetch_alerts(since_seconds=300)++ assert len(events) == 1+ event = events[0]+ assert event["source"] == "hello"+ assert event["category"] == "saas"+ assert event["severity"] == "info"+ # Title surfaces the URL so an operator can tell two events apart.+ assert "https://httpbin.org/anything" in event["title"]+ # alert_id should be stable for the same response (the connector+ # composes it from origin + url).+ assert event["alert_id"] == "hello:192.0.2.10:https://httpbin.org/anything?since_seconds=300"+ # raw must be preserved end-to-end so detection rules and explain+ # lineage have something to chew on.+ assert event["raw"]["origin"] == "192.0.2.10"+++async def test_fetch_alerts_passes_since_seconds_as_query_param():+ """``since_seconds`` should land on the wire. The example's docstring+ explicitly tells readers "keep this in the signature, the scheduler+ always passes it" — so verify it actually flows through."""+ route = respx.get("https://httpbin.org/anything").mock(return_value=httpx.Response(200, json={"url": "x", "origin": "y"}))++ conn = HelloConnector(api_token="t")+ await conn.fetch_alerts(since_seconds=900)++ assert route.called+ qs = dict(route.calls[0].request.url.params)+ assert qs == {"since_seconds": "900"}+++async def test_fetch_alerts_swallows_http_errors():+ """5xx → empty list, no raise. Polling failures are non-terminal —+ the scheduler logs and tries again next interval."""+ respx.get("https://httpbin.org/anything").mock(return_value=httpx.Response(500))+ conn = HelloConnector(api_token="t")+ events = await conn.fetch_alerts()+ assert events == []+++async def test_fetch_alerts_swallows_network_errors():+ """Network errors must also be non-terminal."""+ respx.get("https://httpbin.org/anything").mock(side_effect=httpx.ReadTimeout("slow"))+ conn = HelloConnector(api_token="t")+ events = await conn.fetch_alerts()+ assert events == []+++async def test_fetch_alerts_swallows_invalid_json():+ """If the vendor returns 200 with garbage in the body, we must not+ crash the polling loop. ``[]`` is the right answer here — there's+ nothing to ingest, but the connector's still "alive enough"."""+ respx.get("https://httpbin.org/anything").mock(return_value=httpx.Response(200, content=b"not json at all"))+ conn = HelloConnector(api_token="t")+ events = await conn.fetch_alerts()+ assert events == []+++# ---------------------------------------------------------------------------+# normalize()+# ---------------------------------------------------------------------------+++def test_normalize_preserves_raw():+ """``normalize`` must keep the original payload accessible under+ ``raw`` — detection rules and the explain endpoint both rely on it."""+ raw = {"url": "https://httpbin.org/anything", "origin": "10.0.0.1", "extra": {"k": "v"}}+ conn = HelloConnector(api_token="t")+ norm = conn.normalize(raw)+ assert norm["raw"] is raw+ assert norm["raw"]["extra"] == {"k": "v"}+++def test_normalize_handles_missing_url():+ """Defensive shape: missing fields should not blow up normalization.+ The tutorial walks through this exact path so we pin it."""+ conn = HelloConnector(api_token="t")+ norm = conn.normalize({})+ assert norm["title"] == "Hello connector: pinged (no url)"+ assert norm["alert_id"] == "hello:?:(no url)"