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(actions): refuse RTR arguments that leave their quotes, and stop exempting auth in dev mode (#940)

Beenu Aroradac397234041
diff --git a/.env.example b/.env.example
index 53eef26b3..79aa82169 100644
--- a/.env.example
+++ b/.env.example
@@ -4,9 +4,10 @@
# ╔════════════════════════════════════════════════════════════════════════════╗
# ║ YOU DO NOT HAVE TO EDIT THIS FILE TO GET A WORKING STACK. ║
# ║ ║
-# ║ make up creates .env from this template and fills the three ║
+# ║ make up creates .env from this template and fills the four ║
# ║ generated secrets — AISOC_CREDENTIAL_KEY, SECRET_KEY, ║
-# ║ AISOC_SERVICE_TOKEN — with real random values. ║
+# ║ AISOC_SERVICE_TOKEN, AISOC_ACTIONS_SERVICE_TOKEN — with ║
+# ║ real random values. ║
# ║ make env does only that, if you want to look before you start. ║
# ║ ║
# ║ Those three ship EMPTY here rather than as `replace-me-…` prose. A ║
@@ -363,6 +364,13 @@ AISOC_REALTIME_URL=http://realtime:4000
# uses a per-tenant token from `make ingest-token` instead and needs nothing
# here. See apps/docs/docs/operations/ingest-authentication.md.
AISOC_SERVICE_TOKEN=
+#
+# The actions service gets its own, because it is the one that can isolate a
+# host or disable an account and should not share a credential with the
+# read-mostly services above. `make up` generates it. Without it the actions
+# service answers 503 on every mutating route, which is deliberate: it used to
+# answer 200 to anyone who could reach the port.
+AISOC_ACTIONS_SERVICE_TOKEN=
# Optional per-service overrides, if you'd rather not share one secret:
# AISOC_PURPLE_TEAM_SERVICE_TOKEN=
# AISOC_HONEYTOKENS_SERVICE_TOKEN=
diff --git a/scripts/ensure_env.py b/scripts/ensure_env.py
index 8a9de5bda..eb12ee6ca 100644
--- a/scripts/ensure_env.py
+++ b/scripts/ensure_env.py
@@ -92,6 +92,19 @@ GENERATED: dict[str, tuple[Callable[[], str], str]] = {
lambda: secrets.token_urlsafe(32),
"Shared bearer for service-to-service calls (API -> connectors, ueba, honeytokens, purple-team).",
),
+ # Distinct from AISOC_SERVICE_TOKEN: the actions service reaches vendor
+ # APIs and can isolate a host or disable an account, so it does not share
+ # a credential with the read-mostly services above.
+ #
+ # It was absent here while docker-compose.yml said it "must match" on the
+ # api and actions services, so no install had one, and the guard that
+ # reads it exempted itself whenever it was empty and AISOC_DEV_MODE was
+ # set — which it is by default. Generating it is what lets that guard
+ # fail closed without breaking the documented path.
+ "AISOC_ACTIONS_SERVICE_TOKEN": (
+ lambda: secrets.token_urlsafe(32),
+ "Shared bearer for the actions service (API -> actions). Gates every response action.",
+ ),
}
diff --git a/services/actions/app/clients/crowdstrike_rtr.py b/services/actions/app/clients/crowdstrike_rtr.py
index 7a733c39f..d1d396385 100644
--- a/services/actions/app/clients/crowdstrike_rtr.py
+++ b/services/actions/app/clients/crowdstrike_rtr.py
@@ -20,6 +20,50 @@ logger = structlog.get_logger()
_DEFAULT_BASE = "https://api.crowdstrike.com"
_TOKEN_PATH = "/oauth2/token"
+#: Characters that can leave a single-quoted RTR argument. Deliberately small.
+#:
+#: Every interpolation below sits *inside* single quotes, where `&`, `|`, `;`,
+#: `$`, `(`, `)` and `\` are literal — they were in the published payloads only
+#: because the payload closed the quote with `'` first. Refusing them too would
+#: reject `C:\Program Files (x86)\vendor\agent.exe`, an ordinary path on the
+#: platform this verb is most used against, and a containment action that
+#: refuses real Windows paths is not a usable control.
+#:
+#: So the set is the characters that actually break out:
+#: ' closes the quoted argument — the mechanism in all three reports
+#: ` delimits the -Raw=``` ``` block the runscript path wraps a body in
+#: \n \r end the command line
+#: \x00 truncates it
+_RTR_FORBIDDEN = frozenset("'`\n\r\x00")
+
+
+class RtrArgumentError(ValueError):
+ """An argument cannot be rendered as a single RTR argument.
+
+ Raised rather than sanitised. These values name a file to delete or a
+ script to run on a customer endpoint at the agent's privilege, so a
+ silently-altered path is a wrong action taken on a real host, which is
+ worse than a refusal an operator can read.
+ """
+
+
+def quote_rtr_argument(value: str, *, field: str) -> str:
+ """Render ``value`` as one single-quoted RTR argument, or refuse it.
+
+ RTR command strings are assembled as text and parsed by the agent, so an
+ unescaped value is command injection executing as SYSTEM/root on the
+ endpoint. Legitimate inputs here are filesystem paths, script names and
+ argument strings; none of them need a quote or a shell operator, so the
+ safe set is large enough to be practical and small enough to be provable.
+ """
+ if not isinstance(value, str):
+ raise RtrArgumentError(f"{field} must be a string, got {type(value).__name__}")
+ bad = sorted(_RTR_FORBIDDEN.intersection(value))
+ if bad:
+ printable = ", ".join(repr(c) for c in bad)
+ raise RtrArgumentError(f"{field} contains characters that cannot appear in an RTR argument: {printable}")
+ return f"'{value}'"
+
class CrowdStrikeRTRClient:
"""Thin async wrapper over the CrowdStrike Falcon RTR REST API."""
@@ -260,6 +304,9 @@ class CrowdStrikeRTRClient:
async def quarantine_file(self, device_id: str, file_path: str) -> dict[str, Any]:
"""Remove (quarantine) a file from the host via RTR rm command."""
+ # Before the session is opened, so a refused path costs no RTR session
+ # and the caller sees the reason rather than a half-performed action.
+ quoted_path = quote_rtr_argument(file_path, field="file_path")
async with httpx.AsyncClient(timeout=60.0) as client:
await self._ensure_token(client)
batch_id = await self._init_rtr_session(client, device_id)
@@ -270,7 +317,7 @@ class CrowdStrikeRTRClient:
json={
"base_command": "rm",
"batch_id": batch_id,
- "command_string": f"rm '{file_path}'",
+ "command_string": f"rm {quoted_path}",
"optional_hosts": [device_id],
},
)
@@ -389,7 +436,11 @@ class CrowdStrikeRTRClient:
load-bearing, which is why ``_read_only_command`` distinguishes it
from ``None``.
"""
- stdout = await self._read_only_command(device_id, "ls", f"ls '{path}'")
+ # This probe runs automatically after a quarantine and solicits no
+ # approval of its own, so an unescaped path here executes on the
+ # endpoint with nobody having agreed to it.
+ quoted_path = quote_rtr_argument(path, field="path")
+ stdout = await self._read_only_command(device_id, "ls", f"ls {quoted_path}")
if stdout is None:
return None
return bool(stdout.strip())
diff --git a/services/actions/app/executors/endpoint.py b/services/actions/app/executors/endpoint.py
index 87fc6c91f..1b395a0d2 100644
--- a/services/actions/app/executors/endpoint.py
+++ b/services/actions/app/executors/endpoint.py
@@ -34,7 +34,7 @@ from datetime import datetime
import structlog
-from app.clients.crowdstrike_rtr import CrowdStrikeRTRClient
+from app.clients.crowdstrike_rtr import CrowdStrikeRTRClient, quote_rtr_argument
# Re-exported from app.clients.factories, which is where these now live so
# app.services.rollback can import them without creating a cycle back into
@@ -439,7 +439,18 @@ class RunScriptExecutor(BaseExecutor):
# PowerShell body, not a registered script_name +
# args. We accept either shape from the playbook
# layer and prefer raw content when supplied.
- body = script_content or f"runscript -CloudFile='{script_name}' -CommandLine='{script_args}'"
+ #
+ # Both halves are quoted or refused. `script_content` is not:
+ # it is a script body by definition, its contract is
+ # MANDATORY_HUMAN approval, and there is no subset of
+ # PowerShell that is safe to allow and useful to run.
+ # `script_name` and `script_args` are different — they name a
+ # pre-staged script and its arguments, so a quote in either is
+ # an attempt to reach past the argument, not a legitimate value.
+ body = script_content or (
+ f"runscript -CloudFile={quote_rtr_argument(script_name, field='script_name')} "
+ f"-CommandLine={quote_rtr_argument(script_args, field='script_args')}"
+ )
result = await cs.run_script(device_id, body)
return ActionResult(
action_id=request.id,
diff --git a/services/actions/app/security/authz.py b/services/actions/app/security/authz.py
index fcc264574..a7dc7566b 100644
--- a/services/actions/app/security/authz.py
+++ b/services/actions/app/security/authz.py
@@ -107,11 +107,17 @@ async def require_service_auth(authorization: str | None = Header(default=None))
settings = get_settings()
token = settings.AISOC_ACTIONS_SERVICE_TOKEN.strip()
if not token:
- if settings.AISOC_DEV_MODE:
- return
+ # No dev-mode exemption. This branch used to return early when
+ # AISOC_DEV_MODE was set, and AISOC_DEV_MODE defaults to 1 in the
+ # shipped compose file while nothing generated the token — so the
+ # exemption was not a developer convenience, it was the state every
+ # stock install ran in, leaving isolate_host, disable_user, block_ip
+ # and run_script dispatchable by anything that could reach the port.
raise HTTPException(
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
- detail="actions service auth is not configured",
+ detail=(
+ "actions service auth is not configured: set AISOC_ACTIONS_SERVICE_TOKEN (run `make env`, which generates it, and restart)"
+ ),
)
expected = f"Bearer {token}"
if not authorization or not hmac.compare_digest(authorization, expected):
diff --git a/services/actions/tests/test_approval_doors_agree.py b/services/actions/tests/test_approval_doors_agree.py
index 93bbf2029..03301f40b 100644
--- a/services/actions/tests/test_approval_doors_agree.py
+++ b/services/actions/tests/test_approval_doors_agree.py
@@ -107,6 +107,10 @@ def client(monkeypatch: pytest.MonkeyPatch, touches: _VendorTouches) -> TestClie
test — authz, both gates, the contract, the tier resolution — is the real
production code path.
"""
+ # A real caller authenticates; these tests pin the REST contract, so they
+ # hold a token rather than relying on a dev-mode exemption that no longer
+ # exists (GHSA-g4h7-p63q-r8r4). The auth boundary has its own tests.
+ monkeypatch.setenv("AISOC_ACTIONS_SERVICE_TOKEN", "test-actions-service-token")
monkeypatch.setenv("AISOC_DEV_MODE", "true")
class _LegacyRecorder:
@@ -146,7 +150,7 @@ def client(monkeypatch: pytest.MonkeyPatch, touches: _VendorTouches) -> TestClie
app = FastAPI()
app.include_router(legacy_router)
app.include_router(live_router)
- return TestClient(app)
+ return TestClient(app, headers={"Authorization": "Bearer test-actions-service-token"})
@pytest.fixture(autouse=True)
diff --git a/services/actions/tests/test_authz.py b/services/actions/tests/test_authz.py
index 613fbccc9..fbab9d3ae 100644
--- a/services/actions/tests/test_authz.py
+++ b/services/actions/tests/test_authz.py
@@ -117,9 +117,15 @@ def test_route_requires_token_when_configured(monkeypatch):
assert ok.status_code != 401
-def test_route_open_in_dev_without_token(monkeypatch):
+def test_route_is_not_open_in_dev_without_token(monkeypatch):
+ """GHSA-g4h7-p63q-r8r4. This asserted 200 and was the vulnerability.
+
+ Dev mode is not a reason to skip authentication on a route that dispatches
+ containment, because dev mode is on by default in the shipped compose file
+ and the token it looks for was never generated.
+ """
client = _client(monkeypatch, AISOC_DEV_MODE="true")
- assert client.post("/actions", json=_BODY).status_code == 200
+ assert client.post("/actions", json=_BODY).status_code == 503
def test_route_fails_closed_in_prod_without_token(monkeypatch):
diff --git a/services/actions/tests/test_live_action_router.py b/services/actions/tests/test_live_action_router.py
index 99f958c17..b3b56b4fd 100644
--- a/services/actions/tests/test_live_action_router.py
+++ b/services/actions/tests/test_live_action_router.py
@@ -89,13 +89,16 @@ def client(monkeypatch: pytest.MonkeyPatch) -> Iterator[TestClient]:
this router dispatches real vendor containment and until now carried no
authentication at all.
"""
- monkeypatch.delenv("AISOC_ACTIONS_SERVICE_TOKEN", raising=False)
+ # A real caller authenticates; these tests pin the REST contract, so they
+ # hold a token rather than relying on a dev-mode exemption that no longer
+ # exists (GHSA-g4h7-p63q-r8r4). The auth boundary has its own tests.
+ monkeypatch.setenv("AISOC_ACTIONS_SERVICE_TOKEN", "test-actions-service-token")
monkeypatch.setenv("AISOC_DEV_MODE", "true")
get_settings.cache_clear()
reset_for_tests()
register_executor(_StubIsolateHost(), source="builtin")
register_executor(_StubBlockIP(), source="builtin")
- with TestClient(app) as c:
+ with TestClient(app, headers={"Authorization": "Bearer test-actions-service-token"}) as c:
# The startup hook re-registered the real builtins on top of our
# stubs. Wipe again and re-seed so the assertions below see only
# what we expect.
diff --git a/services/actions/tests/test_live_action_router_auth.py b/services/actions/tests/test_live_action_router_auth.py
index 0119fac48..e7190c290 100644
--- a/services/actions/tests/test_live_action_router_auth.py
+++ b/services/actions/tests/test_live_action_router_auth.py
@@ -79,9 +79,18 @@ def test_unconfigured_token_fails_closed_in_production(monkeypatch: pytest.Monke
assert client.post("/live-actions/dispatch", json=_BODY).status_code == 503
-def test_dev_mode_keeps_the_local_stack_usable(monkeypatch: pytest.MonkeyPatch):
+def test_dev_mode_does_not_open_the_route_when_no_token_is_set(monkeypatch: pytest.MonkeyPatch):
+ """GHSA-g4h7-p63q-r8r4. This asserted 200 and was the vulnerability.
+
+ Dev mode used to exempt the route entirely when the token was empty. That
+ reads as a local convenience, but `docker-compose.yml` defaults
+ `AISOC_DEV_MODE` to 1 and nothing generated the token, so it was the state
+ every stock install ran in — `isolate_host` and `run_script` dispatchable
+ by anything that could reach the port. The local stack stays usable
+ because `make up` now generates the token, not because the guard yields.
+ """
client = _client(monkeypatch, AISOC_DEV_MODE="true")
- assert client.post("/live-actions/dispatch", json=_BODY).status_code == 200
+ assert client.post("/live-actions/dispatch", json=_BODY).status_code == 503
def test_the_dry_run_route_is_protected_too(monkeypatch: pytest.MonkeyPatch):
diff --git a/services/actions/tests/test_replay_history_route.py b/services/actions/tests/test_replay_history_route.py
index c44153c0e..7c383bea2 100644
--- a/services/actions/tests/test_replay_history_route.py
+++ b/services/actions/tests/test_replay_history_route.py
@@ -62,11 +62,14 @@ def client(monkeypatch: pytest.MonkeyPatch) -> TestClient:
# so the tests exercise the handler rather than the shared auth dependency,
# which has its own coverage.
monkeypatch.setenv("AISOC_DEV_MODE", "1")
- monkeypatch.setenv("AISOC_ACTIONS_SERVICE_TOKEN", "")
+ # A real caller authenticates; these tests pin the REST contract, so they
+ # hold a token rather than relying on a dev-mode exemption that no longer
+ # exists (GHSA-g4h7-p63q-r8r4). The auth boundary has its own tests.
+ monkeypatch.setenv("AISOC_ACTIONS_SERVICE_TOKEN", "test-actions-service-token")
from app.core.config import get_settings
get_settings.cache_clear()
- yield TestClient(app)
+ yield TestClient(app, headers={"Authorization": "Bearer test-actions-service-token"})
get_settings.cache_clear()
diff --git a/services/actions/tests/test_rtr_command_injection.py b/services/actions/tests/test_rtr_command_injection.py
new file mode 100644
index 000000000..c67bfd646
--- /dev/null
+++ b/services/actions/tests/test_rtr_command_injection.py
@@ -0,0 +1,116 @@
+"""GHSA-7q37-2wfw-xrx7: RTR command strings are built by interpolation.
+
+Three sinks in this service interpolated caller-supplied values into a command
+string that the Falcon agent executes on the endpoint as SYSTEM/root, with no
+escaping:
+
+ crowdstrike_rtr.py rm '{file_path}'
+ crowdstrike_rtr.py ls '{path}' (the post-quarantine probe, which
+ solicits no approval of its own)
+ endpoint.py runscript -CloudFile='{script_name}' -CommandLine='{script_args}'
+
+Each interpolation sits inside a single-quoted argument, so one `'` in the
+value closes the argument and the rest is parsed as further RTR syntax.
+
+The tests below use the exact payloads from the report. They assert two things
+that have to hold together, because either alone is satisfiable by a useless
+implementation: the payloads are refused, *and* ordinary Windows paths still
+pass. A validator that rejects `C:\\Program Files (x86)\\...` is safe and makes
+the containment verb unusable on the platform it is mostly used against.
+"""
+
+from __future__ import annotations
+
+import pytest
+from app.clients.crowdstrike_rtr import RtrArgumentError, quote_rtr_argument
+
+#: Verbatim from the advisory's PoC §2.
+PUBLISHED_PAYLOADS = [
+ "/tmp/quarterly-report.pdf' & powershell -enc SQBFAFgA & echo '",
+ "-Name x' & whoami & echo '",
+ "/tmp/x' & id & echo '",
+]
+
+
+class TestThePublishedPayloadsAreRefused:
+ @pytest.mark.parametrize("payload", PUBLISHED_PAYLOADS)
+ def test_each_reported_payload_is_refused(self, payload: str) -> None:
+ with pytest.raises(RtrArgumentError):
+ quote_rtr_argument(payload, field="file_path")
+
+ def test_the_error_names_the_field_so_an_operator_can_act_on_it(self) -> None:
+ with pytest.raises(RtrArgumentError, match="script_args"):
+ quote_rtr_argument(PUBLISHED_PAYLOADS[1], field="script_args")
+
+ @pytest.mark.parametrize(
+ "payload",
+ [
+ "a\nrm -rf /", # a newline ends the command line
+ "a\rb",
+ "x```whoami```", # backticks delimit the -Raw block runscript uses
+ "a\x00b", # truncation
+ ],
+ )
+ def test_the_other_ways_out_of_the_argument_are_refused_too(self, payload: str) -> None:
+ with pytest.raises(RtrArgumentError):
+ quote_rtr_argument(payload, field="path")
+
+
+class TestOrdinaryValuesStillWork:
+ """A containment action that refuses real paths is not a control.
+
+ These are the values the verb exists to handle. Inside a single-quoted
+ argument `\\`, `(`, `)`, `$` and `&` are literal — they appeared in the
+ published payloads only because the payload closed the quote first — so
+ refusing them would buy nothing and break Windows.
+ """
+
+ @pytest.mark.parametrize(
+ "value",
+ [
+ r"C:\Program Files (x86)\Vendor\agent.exe",
+ r"C:\Users\j.smith\AppData\Local\Temp\evil.dll",
+ "/var/lib/docker/overlay2/x$y/diff/bin/sh",
+ "/tmp/report (final).pdf",
+ "cleanup.ps1",
+ r"-Name Foo -Force -Path C:\tmp",
+ "",
+ ],
+ )
+ def test_a_real_path_or_argument_is_quoted_not_refused(self, value: str) -> None:
+ assert quote_rtr_argument(value, field="file_path") == f"'{value}'"
+
+
+class TestTheSinksUseIt:
+ """The helper existing is not the fix; the sinks calling it is.
+
+ Asserted against the rendered command string rather than by inspecting
+ source, because a sink that stopped calling the helper would still pass a
+ source-level check that only looked for the import.
+ """
+
+ @pytest.mark.asyncio
+ async def test_quarantine_refuses_before_it_opens_an_rtr_session(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ from app.clients import crowdstrike_rtr
+
+ client = crowdstrike_rtr.CrowdStrikeRTRClient("id", "secret", "https://example.invalid")
+
+ async def _fail(*_a: object, **_k: object) -> None:
+ raise AssertionError("an RTR session was opened for a payload that should have been refused")
+
+ monkeypatch.setattr(client, "_ensure_token", _fail)
+ with pytest.raises(RtrArgumentError):
+ await client.quarantine_file("device-1", PUBLISHED_PAYLOADS[0])
+
+ @pytest.mark.asyncio
+ async def test_the_unapproved_ls_probe_refuses_too(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ from app.clients import crowdstrike_rtr
+
+ client = crowdstrike_rtr.CrowdStrikeRTRClient("id", "secret", "https://example.invalid")
+
+ async def _fail(*_a: object, **_k: object) -> None:
+ raise AssertionError("the probe ran a command for a payload that should have been refused")
+
+ monkeypatch.setattr(client, "_read_only_command", _fail)
+ with pytest.raises(RtrArgumentError):
+ await client.path_exists("device-1", PUBLISHED_PAYLOADS[2])
diff --git a/services/actions/tests/test_service_auth_fails_closed.py b/services/actions/tests/test_service_auth_fails_closed.py
new file mode 100644
index 000000000..2aaf9c51f
--- /dev/null
+++ b/services/actions/tests/test_service_auth_fails_closed.py
@@ -0,0 +1,103 @@
+"""GHSA-g4h7-p63q-r8r4: the actions service was unauthenticated by default.
+
+`require_service_auth` returned early — performing no authentication at all —
+when `AISOC_ACTIONS_SERVICE_TOKEN` was empty and `AISOC_DEV_MODE` was set. Read
+alone that is a developer convenience. It was not, because of three facts that
+only matter together:
+
+ * `docker-compose.yml` defaults `AISOC_DEV_MODE` to `1`,
+ * `scripts/ensure_env.py` never generated `AISOC_ACTIONS_SERVICE_TOKEN`,
+ * `.env.example` never mentioned it.
+
+So the exemption was not the exceptional path, it was the only path a stock
+install ever took: `isolate_host`, `disable_user`, `block_ip`, `kill_process`
+and `run_script` were dispatchable by anything that could reach the port,
+including any other container on the compose network.
+
+The fix is in two halves and both are tested here, because either alone leaves
+the product broken or insecure: the guard no longer exempts itself, and the
+token is generated so the documented path still works.
+"""
+
+from __future__ import annotations
+
+import ast
+import pathlib
+
+import pytest
+from app.security.authz import require_service_auth
+from fastapi import HTTPException
+
+REPO = pathlib.Path(__file__).resolve().parents[3]
+
+
+class TestTheGuardNoLongerExemptsItself:
+ @pytest.mark.asyncio
+ async def test_an_unset_token_refuses_even_in_dev_mode(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ """The exact configuration of a stock `make up` before this fix."""
+ from app.core import config
+
+ settings = config.get_settings()
+ monkeypatch.setattr(settings, "AISOC_ACTIONS_SERVICE_TOKEN", "", raising=False)
+ monkeypatch.setattr(settings, "AISOC_DEV_MODE", True, raising=False)
+
+ with pytest.raises(HTTPException) as exc:
+ await require_service_auth(authorization=None)
+ assert exc.value.status_code == 503
+
+ @pytest.mark.asyncio
+ async def test_the_refusal_says_how_to_fix_it(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ """A 503 an operator cannot act on turns a fix into an outage."""
+ from app.core import config
+
+ settings = config.get_settings()
+ monkeypatch.setattr(settings, "AISOC_ACTIONS_SERVICE_TOKEN", "", raising=False)
+ monkeypatch.setattr(settings, "AISOC_DEV_MODE", True, raising=False)
+
+ with pytest.raises(HTTPException) as exc:
+ await require_service_auth(authorization=None)
+ detail = str(exc.value.detail)
+ assert "AISOC_ACTIONS_SERVICE_TOKEN" in detail
+ assert "make env" in detail
+
+ @pytest.mark.asyncio
+ async def test_a_configured_token_still_authenticates_normally(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ from app.core import config
+
+ settings = config.get_settings()
+ monkeypatch.setattr(settings, "AISOC_ACTIONS_SERVICE_TOKEN", "a-real-token", raising=False)
+ monkeypatch.setattr(settings, "AISOC_DEV_MODE", True, raising=False)
+
+ # Returns None on success; asserting "did not raise" is the contract.
+ await require_service_auth(authorization="Bearer a-real-token")
+
+ with pytest.raises(HTTPException) as exc:
+ await require_service_auth(authorization="Bearer wrong")
+ assert exc.value.status_code == 401
+
+
+class TestTheTokenIsGeneratedSoTheDocumentedPathStillWorks:
+ """Failing closed is only safe if `make up` supplies the token.
+
+ `ensure_env.py` backfills every key in GENERATED into an existing `.env`,
+ not just a new one, so this also repairs installs created before the fix.
+ """
+
+ def test_ensure_env_generates_the_actions_token(self) -> None:
+ source = (REPO / "scripts" / "ensure_env.py").read_text(encoding="utf-8")
+ tree = ast.parse(source)
+ generated: list[str] = []
+ for node in ast.walk(tree):
+ if isinstance(node, ast.AnnAssign) and getattr(node.target, "id", None) == "GENERATED":
+ value = node.value
+ if isinstance(value, ast.Dict):
+ generated = [k.value for k in value.keys if isinstance(k, ast.Constant) and isinstance(k.value, str)]
+ assert generated, "could not read the GENERATED table out of ensure_env.py"
+ assert "AISOC_ACTIONS_SERVICE_TOKEN" in generated, (
+ "ensure_env.py does not generate AISOC_ACTIONS_SERVICE_TOKEN, so a stock install has "
+ "no token and the guard above will 503 on every response action"
+ )
+
+ def test_the_variable_is_documented_in_env_example(self) -> None:
+ text = (REPO / ".env.example").read_text(encoding="utf-8")
+ assert "AISOC_ACTIONS_SERVICE_TOKEN" in text, "an operator reading the documented configuration has no instruction to set it"