mirror of
https://github.com/rennf93/roboco.git
synced 2026-08-03 07:23:24 +02:00
* [4baffaa3] refactor(api): relocate route-layer helpers out of batch-A files into services/schemas/deps
Move every non-@router-decorated top-level function out of
roboco/api/routes/{tasks,a2a,orchestrator,video,v1/_role_dep,roadmap,prompter_live}.py
(journals.py had none) into the module that owns its kind of concern:
- DB/side-effecting logic -> the paired roboco/services module
(task.py, a2a.py, video_engine.py, video_post_service.py, prompter.py)
- DTO-conversion helpers -> roboco/api/schemas/{tasks,video,roadmap}.py,
matching tasks.py's existing task_to_response pattern
- small HTTP-layer auth guards -> roboco/api/deps.py, matching its
existing require_ceo_role/require_pm_or_above pattern
Redundant per-file _require_ceo(agent) wrappers (a2a/orchestrator/video/
roadmap) that just partial-applied an already-existing deps.py function
were inlined to direct require_ceo_role(...) calls instead of duplicated
across services. v1/_role_dep.py keeps its per-role frozenset variable
bindings since those are assignments, not function definitions, and
aren't flagged by the architectural-conventions classifier.
Route paths, schemas, and observable behavior are unchanged. Updated 5
existing test files whose imports or monkeypatch targets pointed at the
old private route-module names.
* [4baffaa3] test(conventions): pin batch-A route files already free of helper findings
* [4baffaa3] fix(api): restore fail-closed _auth_required() fallback (GHSA-4f7g-w95g-5q2c)
The batch-A route-helper relocation accidentally narrowed
_auth_required() to a truthy-only check, dropping the unset-value
fallback to settings.environment == "production". An unconfigured
production deploy would then always return False, silently accepting
unauthenticated X-Agent-Role: ceo header spoofing. Restore the
three-branch logic (explicit true/false honored, unset falls back to
the production check) and the GHSA docstring paragraph explaining it.
* [4baffaa3] fix(services): restore missing Board-Program/X-engine source-tag constants in task.py
The batch-A route-helper relocation's task.py edits had dropped ~24
module-level source-tag constants (BARFLY_SOURCE, CORONER_SOURCE,
DOGFOOD_SOURCE, LIBRARIAN_SOURCE, MEGAPHONE_SOURCE, MIRROR_SOURCE,
PERISCOPE_SOURCE, PEST_CONTROL_SOURCE, SCALES_SOURCE, SENTINEL_SOURCE,
SPACKLE_SOURCE, WAR_ROOM_SOURCE, their *_ITEM_SOURCE materialized-task
counterparts, ENV_SYNC_SOURCE, EVAL_BENCH_SOURCE, and the later X-engine
held-draft tags X_EDITORIAL_SOURCE/X_CAMPAIGN_SOURCE/X_BARFLY_SOURCE)
that ~20 downstream service/engine modules and orchestrator.py's
dispatch table import, breaking the whole FastAPI app's import chain
(deps.py -> AgentOrchestrator -> orchestrator.py -> task.py) and
failing collection on 7 test files.
Restored every missing constant in the same style/location as the
existing block, values cross-checked against board_programs.py's
PROGRAMS registry and hardcoded-string test assertions. Folded the
three new X-engine tags into X_SOURCES (x_post_service.py's
task.source not in X_SOURCES membership check gates their
approve/reject).
Also closes a pre-existing PLR0917 (too-many-positional-args) gap in
pyproject.toml's per-file-ignores for roboco/api/routes/*.py,
roboco/api/deps.py, and roboco/services/prompter.py: these files
already carry an established PLR0913 ignore with a documented
FastAPI-DI-contract / MegaTask-contract rationale that applies equally
to PLR0917, which ruff was flagging on the same pre-existing
signatures (get_current_agent_id, get_current_agent_slug,
_cloud_auth_agent_context, get_agent_context, list_tasks_summary,
_rewrite_batch_children).
* [4baffaa3] fix(api): restore verb-rejection logging and fix stale monkeypatch target in orchestrator auth tests
Two regressions surfaced by re-running the full unit test suite after
restoring task.py's import chain (previously masked because the whole
app failed to import):
1. envelope_to_response() (relocated into roboco/api/deps.py from
v1/_role_dep.py during the batch-A helper extraction) dropped the
"verb rejected" structlog event an error envelope must leave — a
rejected envelope rides a 200, so without this the access log can't
distinguish a verb an agent couldn't satisfy from one that worked
(four Board Programs died that way on 2026-07-25 with no
recoverable reason, per tests/unit/api/routes/v1/
test_verb_rejection_logging.py's docstring). Restored the log call:
verb name from the request path, error/detail/remediate from the
envelope, agent_id/agent_role from the request headers.
2. tests/unit/api/test_orchestrator_auth.py's two cloud-auth session
tests monkeypatched "roboco.api.routes.orchestrator.
resolve_session_user", the pre-relocation location. The guard that
actually calls resolve_session_user (require_orchestrator_ceo) now
lives in roboco/api/deps.py, same as the other route auth test
files' already-updated pattern (test_deps.py); repointed both
patches there.
Verified via a full tests/unit/api/ + tests/unit/conventions/
test_route_helper_placement_batch_a.py run: 605 passed, 18 skipped
(Postgres-gated), 1 pre-existing failure unrelated to this diff
(test_cloud_auth.py's oauth2-form test needs a live production DB
connection, not available in this sandboxed workspace).
* [4baffaa3] docs(api-routes-schemas): reflect batch-A route-helper relocation into services/schemas/deps
---------
Co-authored-by: Backend Developer 1 <be-dev-1@roboco.tech>
Co-authored-by: Backend Documenter <be-doc@roboco.tech>
304 lines
10 KiB
Python
304 lines
10 KiB
Python
"""Orchestrator control routes (/api/orchestrator/*) are gated to the
|
|
CEO/operator identity: the presented ``X-Agent-ID`` is bound to a verified
|
|
HMAC token (DB-free panel-token guard) and the role asserted as CEO. In dev
|
|
(header-trust) mode a missing token is a no-op; a presented-but-forged token
|
|
is still rejected.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
from typing import TYPE_CHECKING
|
|
from unittest.mock import AsyncMock, MagicMock, patch
|
|
from uuid import uuid4
|
|
|
|
import pytest
|
|
import pytest_asyncio
|
|
from fastapi import FastAPI
|
|
from httpx import ASGITransport, AsyncClient
|
|
from roboco.agents_config import issue_agent_token
|
|
from roboco.api import deps as _deps
|
|
from roboco.api.auth.backend import SESSION_COOKIE_NAME
|
|
from roboco.api.deps import _ServiceHolder, set_orchestrator
|
|
from roboco.api.routes.orchestrator import router as orch_router
|
|
|
|
if TYPE_CHECKING:
|
|
from collections.abc import AsyncIterator
|
|
|
|
_SECRET = "test-secret-for-orch-auth"
|
|
_AGENT_ID = "00000000-0000-0000-0000-000000000001"
|
|
_HTTP_201 = 201
|
|
_HTTP_204 = 204
|
|
_HTTP_401 = 401
|
|
_HTTP_403 = 403
|
|
|
|
|
|
def _mock_orchestrator() -> MagicMock:
|
|
orch = MagicMock()
|
|
orch.spawn_agent = AsyncMock(
|
|
return_value=MagicMock(
|
|
agent_id=_AGENT_ID,
|
|
state=MagicMock(value="starting"),
|
|
current_task_id=None,
|
|
error_count=0,
|
|
started_at=None,
|
|
waiting_for=None,
|
|
)
|
|
)
|
|
orch.stop_agent = AsyncMock(return_value=None)
|
|
return orch
|
|
|
|
|
|
@pytest_asyncio.fixture
|
|
async def orch_client() -> AsyncIterator[tuple[AsyncClient, MagicMock]]:
|
|
app = FastAPI()
|
|
app.include_router(orch_router, prefix="/api/orchestrator")
|
|
orch = _mock_orchestrator()
|
|
set_orchestrator(orch)
|
|
async with AsyncClient(
|
|
transport=ASGITransport(app=app), base_url="http://test"
|
|
) as client:
|
|
yield client, orch
|
|
_ServiceHolder.orchestrator = None
|
|
app.dependency_overrides.clear()
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Strict mode: token required
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_spawn_rejects_missing_token_when_required(
|
|
orch_client: tuple[AsyncClient, MagicMock],
|
|
monkeypatch: pytest.MonkeyPatch,
|
|
) -> None:
|
|
"""Strict mode + no X-Agent-Token => 401, never reaches the orchestrator."""
|
|
monkeypatch.setenv("ROBOCO_AGENT_AUTH_SECRET", _SECRET)
|
|
monkeypatch.setenv("ROBOCO_AGENT_AUTH_REQUIRED", "true")
|
|
client, orch = orch_client
|
|
r = await client.post(
|
|
f"/api/orchestrator/agents/{_AGENT_ID}/spawn",
|
|
headers={"X-Agent-ID": _AGENT_ID, "X-Agent-Role": "ceo"},
|
|
)
|
|
assert r.status_code == _HTTP_401
|
|
orch.spawn_agent.assert_not_awaited()
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Dev mode: forged token rejected, missing token is a no-op
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_spawn_rejects_forged_token_even_in_dev(
|
|
orch_client: tuple[AsyncClient, MagicMock],
|
|
monkeypatch: pytest.MonkeyPatch,
|
|
) -> None:
|
|
"""A presented-but-forged token is rejected even in header-trust mode."""
|
|
monkeypatch.setenv("ROBOCO_AGENT_AUTH_SECRET", _SECRET)
|
|
monkeypatch.delenv("ROBOCO_AGENT_AUTH_REQUIRED", raising=False)
|
|
client, orch = orch_client
|
|
r = await client.post(
|
|
f"/api/orchestrator/agents/{_AGENT_ID}/spawn",
|
|
headers={
|
|
"X-Agent-ID": _AGENT_ID,
|
|
"X-Agent-Role": "ceo",
|
|
"X-Agent-Token": "forged-not-a-real-hmac",
|
|
},
|
|
)
|
|
assert r.status_code == _HTTP_401
|
|
orch.spawn_agent.assert_not_awaited()
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_spawn_rejects_non_ceo_role(
|
|
orch_client: tuple[AsyncClient, MagicMock],
|
|
monkeypatch: pytest.MonkeyPatch,
|
|
) -> None:
|
|
"""A developer (even with a validly-issued token) must not spawn/stop agents."""
|
|
monkeypatch.setenv("ROBOCO_AGENT_AUTH_SECRET", _SECRET)
|
|
monkeypatch.setenv("ROBOCO_AGENT_AUTH_REQUIRED", "true")
|
|
client, orch = orch_client
|
|
dev_id = str(uuid4())
|
|
token = issue_agent_token(dev_id, "developer")
|
|
r = await client.post(
|
|
f"/api/orchestrator/agents/{_AGENT_ID}/spawn",
|
|
headers={
|
|
"X-Agent-ID": dev_id,
|
|
"X-Agent-Role": "developer",
|
|
"X-Agent-Token": token,
|
|
},
|
|
)
|
|
assert r.status_code == _HTTP_403
|
|
orch.spawn_agent.assert_not_awaited()
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Legitimate CEO caller succeeds
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_spawn_accepts_valid_ceo_token(
|
|
orch_client: tuple[AsyncClient, MagicMock],
|
|
monkeypatch: pytest.MonkeyPatch,
|
|
) -> None:
|
|
"""A valid CEO token passes the gate and reaches the orchestrator."""
|
|
monkeypatch.setenv("ROBOCO_AGENT_AUTH_SECRET", _SECRET)
|
|
monkeypatch.setenv("ROBOCO_AGENT_AUTH_REQUIRED", "true")
|
|
client, orch = orch_client
|
|
token = issue_agent_token(_AGENT_ID, "ceo")
|
|
r = await client.post(
|
|
f"/api/orchestrator/agents/{_AGENT_ID}/spawn",
|
|
headers={
|
|
"X-Agent-ID": _AGENT_ID,
|
|
"X-Agent-Role": "ceo",
|
|
"X-Agent-Token": token,
|
|
},
|
|
)
|
|
assert r.status_code == _HTTP_201
|
|
orch.spawn_agent.assert_awaited_once()
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_stop_accepts_valid_ceo_token(
|
|
orch_client: tuple[AsyncClient, MagicMock],
|
|
monkeypatch: pytest.MonkeyPatch,
|
|
) -> None:
|
|
"""The gate is wired into stop_agent too."""
|
|
monkeypatch.setenv("ROBOCO_AGENT_AUTH_SECRET", _SECRET)
|
|
monkeypatch.setenv("ROBOCO_AGENT_AUTH_REQUIRED", "true")
|
|
client, orch = orch_client
|
|
token = issue_agent_token(_AGENT_ID, "ceo")
|
|
r = await client.post(
|
|
f"/api/orchestrator/agents/{_AGENT_ID}/stop",
|
|
headers={
|
|
"X-Agent-ID": _AGENT_ID,
|
|
"X-Agent-Role": "ceo",
|
|
"X-Agent-Token": token,
|
|
},
|
|
)
|
|
assert r.status_code == _HTTP_204
|
|
orch.stop_agent.assert_awaited_once()
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_dev_mode_missing_token_still_succeeds(
|
|
orch_client: tuple[AsyncClient, MagicMock],
|
|
monkeypatch: pytest.MonkeyPatch,
|
|
) -> None:
|
|
"""Dev mode (no ROBOCO_AGENT_AUTH_REQUIRED) + no token => no-op, route runs.
|
|
Preserves the panel/operator flow in dev exactly as F003/F004 did."""
|
|
monkeypatch.setenv("ROBOCO_AGENT_AUTH_SECRET", _SECRET)
|
|
monkeypatch.delenv("ROBOCO_AGENT_AUTH_REQUIRED", raising=False)
|
|
|
|
monkeypatch.setattr(_deps.settings, "cloud_auth_enabled", False)
|
|
client, orch = orch_client
|
|
r = await client.post(
|
|
f"/api/orchestrator/agents/{_AGENT_ID}/spawn",
|
|
headers={"X-Agent-ID": _AGENT_ID, "X-Agent-Role": "ceo"},
|
|
)
|
|
assert r.status_code == _HTTP_201
|
|
orch.spawn_agent.assert_awaited_once()
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# cloud_auth on: cookie dual-path (panel reaches /api/orchestrator/* via cookie)
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_cloud_auth_forged_ceo_header_no_token_no_cookie_rejected(
|
|
orch_client: tuple[AsyncClient, MagicMock],
|
|
monkeypatch: pytest.MonkeyPatch,
|
|
) -> None:
|
|
"""cloud_auth on: bare X-Agent-Role: ceo with no token/cookie is a spoof."""
|
|
monkeypatch.setenv("ROBOCO_AGENT_AUTH_SECRET", _SECRET)
|
|
monkeypatch.delenv("ROBOCO_AGENT_AUTH_REQUIRED", raising=False)
|
|
|
|
monkeypatch.setattr(_deps.settings, "cloud_auth_enabled", True)
|
|
client, orch = orch_client
|
|
r = await client.post(
|
|
f"/api/orchestrator/agents/{_AGENT_ID}/spawn",
|
|
headers={"X-Agent-ID": _AGENT_ID, "X-Agent-Role": "ceo"},
|
|
)
|
|
assert r.status_code == _HTTP_401
|
|
orch.spawn_agent.assert_not_awaited()
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_cloud_auth_valid_ceo_token_passes(
|
|
orch_client: tuple[AsyncClient, MagicMock],
|
|
monkeypatch: pytest.MonkeyPatch,
|
|
) -> None:
|
|
monkeypatch.setenv("ROBOCO_AGENT_AUTH_SECRET", _SECRET)
|
|
monkeypatch.delenv("ROBOCO_AGENT_AUTH_REQUIRED", raising=False)
|
|
|
|
monkeypatch.setattr(_deps.settings, "cloud_auth_enabled", True)
|
|
client, orch = orch_client
|
|
token = issue_agent_token(_AGENT_ID, "ceo")
|
|
r = await client.post(
|
|
f"/api/orchestrator/agents/{_AGENT_ID}/spawn",
|
|
headers={
|
|
"X-Agent-ID": _AGENT_ID,
|
|
"X-Agent-Role": "ceo",
|
|
"X-Agent-Token": token,
|
|
},
|
|
)
|
|
assert r.status_code == _HTTP_201
|
|
orch.spawn_agent.assert_awaited_once()
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_cloud_auth_valid_session_cookie_passes(
|
|
orch_client: tuple[AsyncClient, MagicMock],
|
|
monkeypatch: pytest.MonkeyPatch,
|
|
) -> None:
|
|
"""Panel path: a valid CEO session cookie reaches the orchestrator."""
|
|
monkeypatch.setenv("ROBOCO_AGENT_AUTH_SECRET", _SECRET)
|
|
monkeypatch.delenv("ROBOCO_AGENT_AUTH_REQUIRED", raising=False)
|
|
|
|
monkeypatch.setattr(_deps.settings, "cloud_auth_enabled", True)
|
|
client, orch = orch_client
|
|
fake_user = MagicMock()
|
|
with patch(
|
|
"roboco.api.deps.resolve_session_user",
|
|
new=AsyncMock(return_value=fake_user),
|
|
):
|
|
r = await client.post(
|
|
f"/api/orchestrator/agents/{_AGENT_ID}/spawn",
|
|
headers={
|
|
"X-Agent-ID": _AGENT_ID,
|
|
"X-Agent-Role": "ceo",
|
|
},
|
|
cookies={SESSION_COOKIE_NAME: "valid-session-cookie"},
|
|
)
|
|
assert r.status_code == _HTTP_201
|
|
orch.spawn_agent.assert_awaited_once()
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_cloud_auth_invalid_session_cookie_rejected(
|
|
orch_client: tuple[AsyncClient, MagicMock],
|
|
monkeypatch: pytest.MonkeyPatch,
|
|
) -> None:
|
|
monkeypatch.setenv("ROBOCO_AGENT_AUTH_SECRET", _SECRET)
|
|
monkeypatch.delenv("ROBOCO_AGENT_AUTH_REQUIRED", raising=False)
|
|
|
|
monkeypatch.setattr(_deps.settings, "cloud_auth_enabled", True)
|
|
client, orch = orch_client
|
|
with patch(
|
|
"roboco.api.deps.resolve_session_user",
|
|
new=AsyncMock(return_value=None),
|
|
):
|
|
r = await client.post(
|
|
f"/api/orchestrator/agents/{_AGENT_ID}/spawn",
|
|
headers={
|
|
"X-Agent-ID": _AGENT_ID,
|
|
"X-Agent-Role": "ceo",
|
|
},
|
|
cookies={SESSION_COOKIE_NAME: "bogus"},
|
|
)
|
|
assert r.status_code == _HTTP_401
|
|
orch.spawn_agent.assert_not_awaited()
|