Skip to content

armgit / AiSOC

Public Imported from GitHub
0

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.

fix(agents): SSRF guard for playbook http_request and notify (P2-W7) (#120)

Beenu Aroraf4782c50de13
diff --git a/apps/docs/docs/deployment/env-vars.md b/apps/docs/docs/deployment/env-vars.md
index 2aed60d22..a68a59694 100644
--- a/apps/docs/docs/deployment/env-vars.md
+++ b/apps/docs/docs/deployment/env-vars.md
@@ -141,6 +141,9 @@ Source: [`services/agents/app/`](https://github.com/beenuar/AiSOC/tree/main/serv
| `JAEGER_HOST` / `JAEGER_PORT` | `localhost` / `6831` | Jaeger agent endpoint (used when `OTEL_EXPORTER=jaeger`) |
| `OTEL_EXPORTER_OTLP_ENDPOINT` | — | OTLP collector endpoint |
| `OTEL_EXPORTER` | `otlp` | One of `otlp`, `jaeger`, `console` |
+| `AISOC_SSRF_ALLOWED_SCHEMES` | `http,https` | Comma-separated list of URL schemes allowed for outbound `http_request` and `notify` playbook steps. Anything else is rejected. |
+| `AISOC_SSRF_ALLOW_PRIVATE` | `false` | When `true`, lets playbook steps reach loopback / RFC1918 / link-local destinations. Leave off in production; enable only for self-hosted webhooks on a private network. |
+| `AISOC_SSRF_EXTRA_BLOCKED_HOSTS` | — | Comma-separated extra hosts or IPs to deny in addition to the built-in cloud-metadata block list (`169.254.169.254`, `metadata.google.internal`, …). |
---
diff --git a/apps/docs/docs/operations/security.md b/apps/docs/docs/operations/security.md
index 7d2b91103..2501a31fc 100644
--- a/apps/docs/docs/operations/security.md
+++ b/apps/docs/docs/operations/security.md
@@ -161,6 +161,20 @@ For service-to-service traffic between the API, ingest, fusion, and agents, mTLS
The ingest service exposes the public `/v1/ingest/batch` endpoint that connectors push into. It requires either a connector-scoped API key or a signed JWT with the `connector` role; raw events from unauthenticated callers are rejected at the gateway.
+## Playbook outbound traffic — SSRF guard
+
+Playbook `http_request` and `notify` steps run inside the agents service and can reach arbitrary URLs supplied by playbook authors. To keep this from being abused as a metadata-service or internal-network pivot, every outbound URL is validated by the SSRF guard before any socket is opened:
+
+- Only `http://` and `https://` are allowed by default (override with `AISOC_SSRF_ALLOWED_SCHEMES` if you genuinely need `https` only or an additional scheme).
+- URLs that embed credentials (`https://user:pass@host`) are rejected outright.
+- The hostname is resolved through `socket.getaddrinfo`; every resolved IP must be a global-unicast address. Loopback (`127.0.0.0/8`, `::1`), RFC1918 ranges, link-local, multicast, and the IETF reserved blocks are blocked.
+- Cloud metadata endpoints — `169.254.169.254`, `fd00:ec2::254`, `metadata.google.internal`, `metadata.azure.com`, `metadata`, `metadata.aws` — are blocked even if `AISOC_SSRF_ALLOW_PRIVATE=true`.
+- Operators can extend the deny list with `AISOC_SSRF_EXTRA_BLOCKED_HOSTS=internal-only.example.com,10.0.0.5`.
+
+If a playbook needs to reach a private webhook (Slack on a private network, an internal Jira, etc.), set `AISOC_SSRF_ALLOW_PRIVATE=true` **only** on the agents service and keep network-level egress controls in place. The metadata block list always applies.
+
+The guard is a single chokepoint at `services/agents/app/playbook/ssrf_guard.py`; both `_handle_http` and `_handle_notify` call it before the HTTP client makes any request. New action handlers that perform outbound HTTP should call `validate_outbound_url` first.
+
## Hardening checklist
When you move from `pnpm aisoc:demo` to a production deployment, walk through this list:
diff --git a/services/agents/app/playbook/engine.py b/services/agents/app/playbook/engine.py
index 1abd53f74..8fe73572c 100644
--- a/services/agents/app/playbook/engine.py
+++ b/services/agents/app/playbook/engine.py
@@ -24,6 +24,7 @@ from typing import Any
import httpx
from .models import Playbook, PlaybookStep, StepCondition, StepType
+from .ssrf_guard import SSRFError, validate_outbound_url
logger = logging.getLogger("aisoc.playbook.engine")
@@ -355,6 +356,12 @@ async def _handle_notify(step: PlaybookStep, context: dict[str, Any], http: http
message = message.replace(f"{{{{{k}}}}}", str(v))
if channel == "webhook" and url:
+ # SSRF guard: webhook URLs are author-controlled; reject loopback,
+ # cloud-metadata, and other unsafe destinations before dispatching.
+ try:
+ validate_outbound_url(url)
+ except SSRFError as exc:
+ raise SSRFError(f"notify step rejected: {exc}") from exc
r = await http.post(url, json={"text": message}, timeout=step.timeout_seconds)
return {"status": r.status_code}
return {"channel": channel, "message": message, "delivered": False, "reason": "no url"}
@@ -365,6 +372,12 @@ async def _handle_http(step: PlaybookStep, context: dict[str, Any], http: httpx.
url = step.params.get("url", "")
body = step.params.get("body", {})
headers = step.params.get("headers", {})
+ # SSRF guard: arbitrary HTTP calls from playbooks must not reach
+ # loopback, RFC1918, link-local, or cloud-metadata endpoints by default.
+ try:
+ validate_outbound_url(url)
+ except SSRFError as exc:
+ raise SSRFError(f"http step rejected: {exc}") from exc
r = await http.request(method, url, json=body, headers=headers, timeout=step.timeout_seconds)
return {"status": r.status_code, "body": r.text[:500]}
diff --git a/services/agents/app/playbook/ssrf_guard.py b/services/agents/app/playbook/ssrf_guard.py
new file mode 100644
index 000000000..d7e975356
--- /dev/null
+++ b/services/agents/app/playbook/ssrf_guard.py
@@ -0,0 +1,239 @@
+"""
+SSRF guard for playbook outbound HTTP steps.
+
+Playbooks let analysts configure ``http`` and ``notify`` steps that make
+outbound HTTP requests to arbitrary URLs. Without validation, a playbook
+author can target cloud instance metadata services (e.g. AWS
+``169.254.169.254``, GCP ``metadata.google.internal``), loopback / private
+RFC1918 addresses, or non-HTTP schemes like ``file://`` — a classic
+Server-Side Request Forgery (SSRF) class of bug.
+
+This module provides :func:`validate_outbound_url`, called by playbook step
+handlers before they hand a URL to ``httpx``. It rejects:
+
+* Schemes other than ``http`` / ``https`` (overridable via
+ ``AISOC_SSRF_ALLOWED_SCHEMES``).
+* URLs with userinfo (``http://user:pw@host/...``) — these are a common
+ credential-smuggling and host-spoofing vector.
+* Hostnames or IP literals that resolve to loopback, link-local, private,
+ reserved, unspecified, or multicast ranges.
+* A blocklist of well-known cloud metadata endpoints (AWS, GCP, Azure,
+ Alibaba, Oracle) even if their hostnames happen to resolve to a public IP.
+* Hostnames where *any* of the returned addresses is unsafe (defence in
+ depth against DNS records that mix one public and one private answer).
+
+Operators can:
+
+* Set ``AISOC_SSRF_ALLOW_PRIVATE=1`` to relax the private/loopback check
+ for on-prem deployments where playbooks must reach internal services
+ (still rejects cloud-metadata literals and link-local/multicast).
+* Set ``AISOC_SSRF_EXTRA_BLOCKED_HOSTS=foo.internal,bar.svc`` to extend
+ the metadata host blocklist.
+
+Failures raise :class:`SSRFError`, which propagates up to the engine and
+marks the step as failed via the normal exception path.
+"""
+
+from __future__ import annotations
+
+import ipaddress
+import logging
+import os
+import socket
+from urllib.parse import urlsplit
+
+logger = logging.getLogger("aisoc.playbook.ssrf_guard")
+
+
+class SSRFError(ValueError):
+ """Raised when an outbound URL is blocked by the SSRF guard."""
+
+
+# ---------------------------------------------------------------------------
+# Static blocklists
+# ---------------------------------------------------------------------------
+
+# Hostnames that must never be reached regardless of DNS resolution, e.g.
+# operators sometimes wire ``metadata.google.internal`` to a public proxy.
+# Comparison is case-insensitive against the URL's hostname (no port).
+_DEFAULT_BLOCKED_HOSTS: frozenset[str] = frozenset(
+ {
+ # AWS / Alibaba IMDS literal
+ "169.254.169.254",
+ # GCP IMDS
+ "metadata.google.internal",
+ "metadata",
+ # Azure IMDS — its IP literal is the same as AWS; hostname forms vary.
+ "metadata.azure.com",
+ # Alibaba Cloud
+ "100.100.100.200",
+ # Oracle Cloud Infrastructure
+ "169.254.169.254.nip.io",
+ }
+)
+
+_DEFAULT_ALLOWED_SCHEMES: frozenset[str] = frozenset({"http", "https"})
+
+
+def _env_set(name: str) -> frozenset[str]:
+ """Read a comma-separated env var into a lowercase frozenset."""
+ raw = os.getenv(name, "") or ""
+ return frozenset(part.strip().lower() for part in raw.split(",") if part.strip())
+
+
+def _allowed_schemes() -> frozenset[str]:
+ extra = _env_set("AISOC_SSRF_ALLOWED_SCHEMES")
+ return extra or _DEFAULT_ALLOWED_SCHEMES
+
+
+def _blocked_hosts() -> frozenset[str]:
+ return _DEFAULT_BLOCKED_HOSTS | _env_set("AISOC_SSRF_EXTRA_BLOCKED_HOSTS")
+
+
+def _allow_private_by_default() -> bool:
+ return os.getenv("AISOC_SSRF_ALLOW_PRIVATE", "").strip().lower() in {"1", "true", "yes"}
+
+
+# ---------------------------------------------------------------------------
+# IP classification
+# ---------------------------------------------------------------------------
+
+
+def _is_disallowed_address(ip: ipaddress._BaseAddress, *, allow_private: bool) -> tuple[bool, str]:
+ """Return ``(blocked, reason)`` for an IP address.
+
+ When ``allow_private`` is True we still reject loopback, link-local,
+ unspecified, multicast, and reserved addresses — only the
+ private/RFC1918 + ULA bands are loosened.
+ """
+ if ip.is_loopback:
+ return True, "loopback address"
+ if ip.is_link_local:
+ return True, "link-local address (cloud metadata range)"
+ if ip.is_unspecified:
+ return True, "unspecified address"
+ if ip.is_multicast:
+ return True, "multicast address"
+ if ip.is_reserved:
+ return True, "reserved address"
+ # Block IPv4-mapped/IPv4-compatible IPv6 against private v4 ranges.
+ if isinstance(ip, ipaddress.IPv6Address):
+ mapped = getattr(ip, "ipv4_mapped", None)
+ if mapped is not None:
+ return _is_disallowed_address(mapped, allow_private=allow_private)
+ if not allow_private and ip.is_private:
+ return True, "private/RFC1918 address"
+ return False, ""
+
+
+def _coerce_ip(value: str) -> ipaddress._BaseAddress | None:
+ """Try to parse ``value`` as an IP address (v4 or v6), return None if not."""
+ try:
+ return ipaddress.ip_address(value)
+ except ValueError:
+ return None
+
+
+def _resolve_host_addresses(host: str) -> list[ipaddress._BaseAddress]:
+ """Resolve ``host`` via ``getaddrinfo`` and return all unique IP objects.
+
+ Raises :class:`SSRFError` if the host cannot be resolved.
+ """
+ try:
+ infos = socket.getaddrinfo(host, None, type=socket.SOCK_STREAM)
+ except OSError as exc:
+ raise SSRFError(f"could not resolve hostname {host!r}: {exc}") from exc
+
+ addrs: list[ipaddress._BaseAddress] = []
+ seen: set[str] = set()
+ for info in infos:
+ sockaddr = info[4]
+ addr_str = sockaddr[0] if sockaddr else ""
+ # IPv6 sockaddrs can include zone IDs ("fe80::1%eth0"); strip them.
+ addr_str = addr_str.split("%", 1)[0]
+ if not addr_str or addr_str in seen:
+ continue
+ seen.add(addr_str)
+ ip = _coerce_ip(addr_str)
+ if ip is not None:
+ addrs.append(ip)
+ if not addrs:
+ raise SSRFError(f"hostname {host!r} resolved to no usable addresses")
+ return addrs
+
+
+# ---------------------------------------------------------------------------
+# Public API
+# ---------------------------------------------------------------------------
+
+
+def validate_outbound_url(url: str, *, allow_private: bool | None = None) -> str:
+ """Validate ``url`` for outbound HTTP calls from playbook steps.
+
+ Parameters
+ ----------
+ url:
+ The candidate URL string.
+ allow_private:
+ Override the env-driven default. ``True`` permits private/RFC1918
+ addresses (still blocks loopback, link-local, metadata literals,
+ and explicit blocklist entries). ``None`` falls back to
+ ``AISOC_SSRF_ALLOW_PRIVATE``.
+
+ Returns
+ -------
+ str
+ The original URL on success.
+
+ Raises
+ ------
+ SSRFError
+ If the URL is blocked for any reason.
+ """
+ if not isinstance(url, str) or not url.strip():
+ raise SSRFError("URL is empty")
+
+ try:
+ parts = urlsplit(url.strip())
+ except ValueError as exc:
+ raise SSRFError(f"could not parse URL: {exc}") from exc
+
+ scheme = (parts.scheme or "").lower()
+ if scheme not in _allowed_schemes():
+ raise SSRFError(f"scheme {scheme!r} is not allowed (must be one of {sorted(_allowed_schemes())})")
+
+ # Reject userinfo to avoid credential smuggling and host-confusion attacks.
+ if parts.username or parts.password:
+ raise SSRFError("URL must not include userinfo (user:password@host)")
+
+ host = (parts.hostname or "").strip().lower()
+ if not host:
+ raise SSRFError("URL has no hostname")
+
+ # Explicit blocklist takes precedence over IP / DNS checks.
+ blocked = _blocked_hosts()
+ if host in blocked:
+ raise SSRFError(f"hostname {host!r} is on the SSRF blocklist (cloud metadata or operator-blocked)")
+
+ if allow_private is None:
+ allow_private = _allow_private_by_default()
+
+ # If host is an IP literal, validate it directly.
+ literal_ip = _coerce_ip(host)
+ if literal_ip is not None:
+ blocked_flag, reason = _is_disallowed_address(literal_ip, allow_private=allow_private)
+ if blocked_flag:
+ raise SSRFError(f"host {host!r} is blocked: {reason}")
+ return url
+
+ # Otherwise, resolve the hostname and validate every returned address.
+ addresses = _resolve_host_addresses(host)
+ for ip in addresses:
+ blocked_flag, reason = _is_disallowed_address(ip, allow_private=allow_private)
+ if blocked_flag:
+ raise SSRFError(f"hostname {host!r} resolves to a blocked address {ip} ({reason})")
+
+ return url
+
+
+__all__ = ["SSRFError", "validate_outbound_url"]
diff --git a/services/agents/tests/test_playbook_ssrf_guard.py b/services/agents/tests/test_playbook_ssrf_guard.py
new file mode 100644
index 000000000..c020fef19
--- /dev/null
+++ b/services/agents/tests/test_playbook_ssrf_guard.py
@@ -0,0 +1,428 @@
+"""Tests for the playbook SSRF guard (services/agents/app/playbook/ssrf_guard.py)."""
+
+from __future__ import annotations
+
+import ipaddress
+import socket
+from collections.abc import Iterable
+from unittest.mock import AsyncMock, MagicMock
+
+import pytest
+from app.playbook.engine import _handle_http, _handle_notify
+from app.playbook.models import PlaybookStep, StepType
+from app.playbook.ssrf_guard import SSRFError, validate_outbound_url
+
+# ---------------------------------------------------------------------------
+# Helpers
+# ---------------------------------------------------------------------------
+
+
+def _addrinfo_for(*ips: str) -> list[tuple]:
+ """Build a ``getaddrinfo``-shaped list for the given IP strings.
+
+ Each tuple is ``(family, type, proto, canonname, sockaddr)``. Family is
+ IPv4 unless the IP contains ``:``.
+ """
+ result: list[tuple] = []
+ for ip in ips:
+ if ":" in ip:
+ family = socket.AF_INET6
+ sockaddr: tuple = (ip, 0, 0, 0)
+ else:
+ family = socket.AF_INET
+ sockaddr = (ip, 0)
+ result.append((family, socket.SOCK_STREAM, 0, "", sockaddr))
+ return result
+
+
+def _patch_dns(monkeypatch: pytest.MonkeyPatch, mapping: dict[str, Iterable[str]]) -> None:
+ """Patch ``socket.getaddrinfo`` inside the ssrf_guard module to return fixed answers."""
+
+ def fake(host: str, *_args, **_kwargs):
+ host = host.lower()
+ if host in mapping:
+ return _addrinfo_for(*mapping[host])
+ raise socket.gaierror(-2, "Name or service not known")
+
+ monkeypatch.setattr("app.playbook.ssrf_guard.socket.getaddrinfo", fake)
+
+
+# ---------------------------------------------------------------------------
+# Happy path
+# ---------------------------------------------------------------------------
+
+
+class TestValidateOutboundUrlPositive:
+ def test_public_hostname_https(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ _patch_dns(monkeypatch, {"example.com": ["8.8.8.8"]})
+ assert validate_outbound_url("https://example.com/webhook") == "https://example.com/webhook"
+
+ def test_public_hostname_http(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ _patch_dns(monkeypatch, {"hooks.example.com": ["1.1.1.1"]})
+ url = "http://hooks.example.com/path?x=1"
+ assert validate_outbound_url(url) == url
+
+ def test_public_ipv4_literal(self) -> None:
+ url = "https://8.8.8.8/healthz"
+ assert validate_outbound_url(url) == url
+
+ def test_public_ipv6_literal(self) -> None:
+ url = "https://[2001:4860:4860::8888]/"
+ assert validate_outbound_url(url) == url
+
+ def test_mixed_public_addresses_pass(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ _patch_dns(
+ monkeypatch,
+ {"multi.example.com": ["8.8.8.8", "2001:4860:4860::8888"]},
+ )
+ url = "https://multi.example.com/"
+ assert validate_outbound_url(url) == url
+
+ def test_port_is_preserved(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ _patch_dns(monkeypatch, {"hook.example.com": ["8.8.4.4"]})
+ url = "https://hook.example.com:8443/incoming"
+ assert validate_outbound_url(url) == url
+
+
+# ---------------------------------------------------------------------------
+# Empty / malformed input
+# ---------------------------------------------------------------------------
+
+
+class TestValidateOutboundUrlRejectsMalformed:
+ @pytest.mark.parametrize("url", ["", " ", None])
+ def test_empty_or_whitespace(self, url: object) -> None:
+ with pytest.raises(SSRFError):
+ validate_outbound_url(url) # type: ignore[arg-type]
+
+ def test_non_http_scheme_file(self) -> None:
+ with pytest.raises(SSRFError, match="scheme"):
+ validate_outbound_url("file:///etc/passwd")
+
+ def test_non_http_scheme_ftp(self) -> None:
+ with pytest.raises(SSRFError, match="scheme"):
+ validate_outbound_url("ftp://example.com/")
+
+ def test_non_http_scheme_gopher(self) -> None:
+ with pytest.raises(SSRFError, match="scheme"):
+ validate_outbound_url("gopher://example.com/_")
+
+ def test_non_http_scheme_data(self) -> None:
+ with pytest.raises(SSRFError, match="scheme"):
+ validate_outbound_url("data:text/plain,hello")
+
+ def test_no_hostname(self) -> None:
+ with pytest.raises(SSRFError):
+ validate_outbound_url("http:///path")
+
+ def test_userinfo_blocked(self) -> None:
+ with pytest.raises(SSRFError, match="userinfo"):
+ validate_outbound_url("http://user:[email protected]/")
+
+ def test_username_only_blocked(self) -> None:
+ with pytest.raises(SSRFError, match="userinfo"):
+ validate_outbound_url("http://[email protected]/")
+
+
+# ---------------------------------------------------------------------------
+# IP literal blocking
+# ---------------------------------------------------------------------------
+
+
+class TestIpLiteralBlocking:
+ @pytest.mark.parametrize(
+ "host",
+ [
+ "127.0.0.1",
+ "127.5.5.5",
+ "0.0.0.0",
+ "10.0.0.1",
+ "10.255.255.1",
+ "192.168.1.1",
+ "172.16.0.1",
+ "172.31.255.255",
+ "169.254.169.254", # AWS IMDS
+ "169.254.0.1", # link-local
+ "100.100.100.200", # Alibaba IMDS
+ "224.0.0.1", # multicast
+ "240.0.0.1", # reserved
+ ],
+ )
+ def test_blocked_ipv4_literals(self, host: str) -> None:
+ with pytest.raises(SSRFError):
+ validate_outbound_url(f"http://{host}/")
+
+ @pytest.mark.parametrize(
+ "host",
+ [
+ "[::1]", # loopback
+ "[::]", # unspecified
+ "[fe80::1]", # link-local
+ "[fc00::1]", # unique-local
+ "[fd00::1]", # unique-local
+ "[ff02::1]", # multicast
+ "[::ffff:127.0.0.1]", # v4-mapped loopback
+ "[::ffff:10.0.0.1]", # v4-mapped private
+ ],
+ )
+ def test_blocked_ipv6_literals(self, host: str) -> None:
+ with pytest.raises(SSRFError):
+ validate_outbound_url(f"http://{host}/")
+
+
+# ---------------------------------------------------------------------------
+# Hostname blocking via blocklist + DNS resolution
+# ---------------------------------------------------------------------------
+
+
+class TestHostnameBlocking:
+ @pytest.mark.parametrize(
+ "host",
+ [
+ "metadata.google.internal",
+ "metadata",
+ "metadata.azure.com",
+ "169.254.169.254.nip.io",
+ ],
+ )
+ def test_metadata_hostnames_blocked(self, host: str) -> None:
+ with pytest.raises(SSRFError, match="blocklist"):
+ validate_outbound_url(f"http://{host}/computeMetadata/v1/")
+
+ def test_dns_to_loopback_blocked(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ _patch_dns(monkeypatch, {"evil.example": ["127.0.0.1"]})
+ with pytest.raises(SSRFError, match="loopback"):
+ validate_outbound_url("https://evil.example/")
+
+ def test_dns_to_private_blocked(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ _patch_dns(monkeypatch, {"sneaky.example": ["10.0.0.5"]})
+ with pytest.raises(SSRFError, match="private"):
+ validate_outbound_url("https://sneaky.example/")
+
+ def test_dns_to_link_local_blocked(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ _patch_dns(monkeypatch, {"meta.example": ["169.254.169.254"]})
+ with pytest.raises(SSRFError, match="link-local"):
+ validate_outbound_url("https://meta.example/latest/meta-data/")
+
+ def test_dns_mixed_answers_blocked(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ """If any returned address is unsafe, reject — defends against
+ DNS-pinning bypasses where one record is public and another is private.
+ """
+ _patch_dns(
+ monkeypatch,
+ {"mixed.example": ["8.8.8.8", "10.0.0.1"]},
+ )
+ with pytest.raises(SSRFError):
+ validate_outbound_url("https://mixed.example/")
+
+ def test_unresolvable_hostname_blocked(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ _patch_dns(monkeypatch, {}) # nothing resolves
+ with pytest.raises(SSRFError, match="could not resolve"):
+ validate_outbound_url("https://nope.invalid/")
+
+
+# ---------------------------------------------------------------------------
+# allow_private toggle
+# ---------------------------------------------------------------------------
+
+
+class TestAllowPrivate:
+ def test_allow_private_arg_permits_rfc1918(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ _patch_dns(monkeypatch, {"internal.example": ["10.0.0.5"]})
+ url = "https://internal.example/health"
+ assert validate_outbound_url(url, allow_private=True) == url
+
+ def test_allow_private_arg_still_blocks_loopback(self) -> None:
+ with pytest.raises(SSRFError, match="loopback"):
+ validate_outbound_url("http://127.0.0.1/", allow_private=True)
+
+ def test_allow_private_arg_still_blocks_metadata_hostname(self) -> None:
+ with pytest.raises(SSRFError, match="blocklist"):
+ validate_outbound_url("http://metadata.google.internal/", allow_private=True)
+
+ def test_allow_private_env_var(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setenv("AISOC_SSRF_ALLOW_PRIVATE", "1")
+ _patch_dns(monkeypatch, {"intra.example": ["192.168.1.10"]})
+ url = "https://intra.example/"
+ assert validate_outbound_url(url) == url
+
+ def test_allow_private_env_var_off_blocks(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.delenv("AISOC_SSRF_ALLOW_PRIVATE", raising=False)
+ _patch_dns(monkeypatch, {"intra.example": ["192.168.1.10"]})
+ with pytest.raises(SSRFError, match="private"):
+ validate_outbound_url("https://intra.example/")
+
+ def test_allow_private_arg_overrides_env(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setenv("AISOC_SSRF_ALLOW_PRIVATE", "1")
+ _patch_dns(monkeypatch, {"intra.example": ["192.168.1.10"]})
+ # Caller explicitly disables, env should not win.
+ with pytest.raises(SSRFError, match="private"):
+ validate_outbound_url("https://intra.example/", allow_private=False)
+
+
+# ---------------------------------------------------------------------------
+# Operator extension via env var
+# ---------------------------------------------------------------------------
+
+
+class TestOperatorExtensions:
+ def test_extra_blocked_hosts_env(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setenv("AISOC_SSRF_EXTRA_BLOCKED_HOSTS", "secrets.internal,vault.svc")
+ _patch_dns(monkeypatch, {"secrets.internal": ["8.8.8.8"]})
+ with pytest.raises(SSRFError, match="blocklist"):
+ validate_outbound_url("https://secrets.internal/api/v1/secret")
+
+ def test_allowed_schemes_env_extension(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ # Sanity check: operator can broaden allowed schemes if needed.
+ monkeypatch.setenv("AISOC_SSRF_ALLOWED_SCHEMES", "https")
+ with pytest.raises(SSRFError, match="scheme"):
+ validate_outbound_url("http://example.com/")
+
+
+# ---------------------------------------------------------------------------
+# Engine integration
+# ---------------------------------------------------------------------------
+
+
+class TestHandlerIntegration:
+ async def test_handle_http_blocks_metadata(self) -> None:
+ step = PlaybookStep(
+ name="http-bad",
+ type=StepType.HTTP,
+ params={"url": "http://169.254.169.254/latest/meta-data/", "method": "GET"},
+ )
+ client = MagicMock()
+ client.request = AsyncMock()
+ with pytest.raises(SSRFError):
+ await _handle_http(step, {}, client)
+ client.request.assert_not_awaited()
+
+ async def test_handle_http_blocks_empty_url(self) -> None:
+ step = PlaybookStep(name="http-empty", type=StepType.HTTP, params={"url": ""})
+ client = MagicMock()
+ client.request = AsyncMock()
+ with pytest.raises(SSRFError):
+ await _handle_http(step, {}, client)
+ client.request.assert_not_awaited()
+
+ async def test_handle_http_blocks_loopback(self) -> None:
+ step = PlaybookStep(
+ name="http-loop",
+ type=StepType.HTTP,
+ params={"url": "http://127.0.0.1:8000/internal", "method": "POST"},
+ )
+ client = MagicMock()
+ client.request = AsyncMock()
+ with pytest.raises(SSRFError):
+ await _handle_http(step, {}, client)
+ client.request.assert_not_awaited()
+
+ async def test_handle_http_passes_for_public(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ _patch_dns(monkeypatch, {"ok.example": ["8.8.8.8"]})
+ step = PlaybookStep(
+ name="http-good",
+ type=StepType.HTTP,
+ params={"url": "https://ok.example/api", "method": "POST", "body": {"a": 1}},
+ )
+ response = MagicMock()
+ response.status_code = 202
+ response.text = "ok"
+ client = MagicMock()
+ client.request = AsyncMock(return_value=response)
+ out = await _handle_http(step, {}, client)
+ assert out["status"] == 202
+ client.request.assert_awaited_once()
+
+ async def test_handle_notify_no_url_passthrough(self) -> None:
+ step = PlaybookStep(
+ name="notify-empty",
+ type=StepType.NOTIFY,
+ params={"channel": "webhook", "url": "", "message": "hi"},
+ )
+ client = MagicMock()
+ client.post = AsyncMock()
+ out = await _handle_notify(step, {}, client)
+ # Empty URL → handler returns informational stub; never calls http.
+ assert out["delivered"] is False
+ client.post.assert_not_awaited()
+
+ async def test_handle_notify_blocks_bad_webhook(self) -> None:
+ step = PlaybookStep(
+ name="notify-bad",
+ type=StepType.NOTIFY,
+ params={"channel": "webhook", "url": "http://10.0.0.1/hook", "message": "x"},
+ )
+ client = MagicMock()
+ client.post = AsyncMock()
+ with pytest.raises(SSRFError):
+ await _handle_notify(step, {}, client)
+ client.post.assert_not_awaited()
+
+ async def test_handle_notify_passes_for_public(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ _patch_dns(monkeypatch, {"hooks.example": ["1.1.1.1"]})
+ step = PlaybookStep(
+ name="notify-good",
+ type=StepType.NOTIFY,
+ params={"channel": "webhook", "url": "https://hooks.example/x", "message": "hi"},
+ )
+ response = MagicMock()
+ response.status_code = 200
+ client = MagicMock()
+ client.post = AsyncMock(return_value=response)
+ out = await _handle_notify(step, {}, client)
+ assert out["status"] == 200
+ client.post.assert_awaited_once()
+
+
+# ---------------------------------------------------------------------------
+# Defence in depth: _is_disallowed_address direct tests
+# ---------------------------------------------------------------------------
+
+
+class TestIsDisallowedAddress:
+ @pytest.mark.parametrize(
+ "ip_str",
+ [
+ "127.0.0.1",
+ "0.0.0.0",
+ "169.254.1.1",
+ "224.0.0.1",
+ "240.0.0.1",
+ "::1",
+ "::",
+ "fe80::1",
+ "ff02::1",
+ ],
+ )
+ def test_always_blocked_even_with_allow_private(self, ip_str: str) -> None:
+ from app.playbook.ssrf_guard import _is_disallowed_address
+
+ blocked, reason = _is_disallowed_address(ipaddress.ip_address(ip_str), allow_private=True)
+ assert blocked is True
+ assert reason # non-empty reason string
+
+ @pytest.mark.parametrize(
+ "ip_str",
+ [
+ "10.0.0.1",
+ "192.168.1.1",
+ "172.16.0.1",
+ "fc00::1",
+ ],
+ )
+ def test_private_blocked_by_default_but_allowed_when_flag(self, ip_str: str) -> None:
+ from app.playbook.ssrf_guard import _is_disallowed_address
+
+ ip = ipaddress.ip_address(ip_str)
+ blocked_default, _ = _is_disallowed_address(ip, allow_private=False)
+ blocked_allowed, _ = _is_disallowed_address(ip, allow_private=True)
+ assert blocked_default is True
+ assert blocked_allowed is False
+
+ @pytest.mark.parametrize("ip_str", ["8.8.8.8", "1.1.1.1", "2001:4860:4860::8888"])
+ def test_public_addresses_pass(self, ip_str: str) -> None:
+ from app.playbook.ssrf_guard import _is_disallowed_address
+
+ blocked, _ = _is_disallowed_address(ipaddress.ip_address(ip_str), allow_private=False)
+ assert blocked is False