mirror of
https://github.com/bytedance/deer-flow.git
synced 2026-11-27 17:00:37 +00:00
feat(auth): PAT scopes for agent, schedule and managed-subagent configuration (#8514)
* feat(auth): PAT scopes for agent, schedule and managed-subagent configuration Opens the routes a deploy pipeline needs to personal access tokens, each behind its own scope (#8310): - agents:read / agents:write on /api/agents and /api/agents/{name}; - schedules:read / schedules:write on the /api/scheduled-tasks subtree, on top of the existing threads:* / runs:create route checks; - subagents:read / subagents:write on /api/subagents; the writes stay admin-only and admit an admin's PAT only while it holds subagents:write (require_admin_user gains an opt-in pat_scope; is_admin_user stays False for every PAT, so no other admin route changes); - GET /api/v1/auth/me for any PAT, so automation can confirm its account. schedules:* and subagents:* are PAT-only scopes enforced by a scoped route rule in the PAT route policy; session callers are unaffected. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Signed-off-by: Bas Cancrinus <7222814+bascan@users.noreply.github.com> * fix(auth): allow PAT mutations for agent names shared by actions --------- Signed-off-by: Bas Cancrinus <7222814+bascan@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: Willem Jiang <willem.jiang@gmail.com>
This commit is contained in:
parent
e2b3f85421
commit
b504fe8808
@ -25,6 +25,10 @@ PAT_RANDOM_BYTES = 32
|
||||
# automation does not turn every request into a database write.
|
||||
PAT_LAST_USED_WRITE_INTERVAL_SECONDS = 300.0
|
||||
|
||||
# PAT-only scopes: not route permissions, so a session caller never needs
|
||||
# them; a PAT reaches the routes they guard only while holding them.
|
||||
PAT_ROUTE_SCOPES: frozenset[str] = frozenset({"schedules:read", "schedules:write", "subagents:read", "subagents:write"})
|
||||
|
||||
PAT_ALLOWED_SCOPES: frozenset[str] = frozenset(
|
||||
{
|
||||
"threads:read",
|
||||
@ -36,16 +40,24 @@ PAT_ALLOWED_SCOPES: frozenset[str] = frozenset(
|
||||
"projects:read",
|
||||
"projects:write",
|
||||
"projects:delete",
|
||||
# Deploying agent configuration from CI (#8310). agents:* are route
|
||||
# permissions (``@require_permission``); schedules:* and subagents:*
|
||||
# are PAT_ROUTE_SCOPES, enforced by _PAT_SCOPED_ROUTE_RULES below.
|
||||
"agents:read",
|
||||
"agents:write",
|
||||
"schedules:read",
|
||||
"schedules:write",
|
||||
"subagents:read",
|
||||
"subagents:write",
|
||||
}
|
||||
)
|
||||
|
||||
# Deliberately NOT in PAT_ALLOWED_SCOPES: the route permissions "memory:read",
|
||||
# "memory:write", "agents:read", and "agents:write" exist in authz
|
||||
# (they guard the memory/agent routers), but PATs stay on the thread/run
|
||||
# lifecycle only — _PAT_ROUTE_RULES default-denies the memory/agent routes
|
||||
# for PAT callers regardless of scopes, so admitting these scopes would not
|
||||
# even reach those routes. Opening them to PATs is a product decision that
|
||||
# must change all three of: this set, _PAT_ROUTE_RULES, and the API docs.
|
||||
# Deliberately NOT in PAT_ALLOWED_SCOPES: the route permissions "memory:read"
|
||||
# and "memory:write" exist in authz (they guard the memory router), but
|
||||
# _PAT_ROUTE_RULES default-denies the memory routes for PAT callers regardless
|
||||
# of scopes. Opening a router to PATs must change all three of: this set,
|
||||
# the route rules, and the API docs. ``agents:*`` open only /api/agents, not
|
||||
# /api/user-profile, which the same permissions guard for sessions.
|
||||
|
||||
PAT_MAX_NAME_LENGTH = 128
|
||||
|
||||
@ -54,9 +66,8 @@ PAT_MAX_NAME_LENGTH = 128
|
||||
# ``request.state.auth.permissions`` (``@require_permission``). Authenticated
|
||||
# mutation routes without that decorator — memory deletion, agent creation,
|
||||
# credential switching, channel configuration — would otherwise accept a
|
||||
# PAT holding a single read scope. A route is reachable by PAT only when it
|
||||
# is explicitly listed here, and only together with the thread/run lifecycle
|
||||
# the v1 scopes govern; everything else answers 403 regardless of scopes.
|
||||
# PAT holding a single read scope. PAT callers can reach only the routes
|
||||
# explicitly listed in this table or the scoped table below.
|
||||
_PAT_ROUTE_RULES: tuple[tuple[frozenset[str], re.Pattern[str]], ...] = (
|
||||
(frozenset({"POST"}), re.compile(r"^/api/threads$")),
|
||||
(frozenset({"POST"}), re.compile(r"^/api/threads/search$")),
|
||||
@ -127,6 +138,32 @@ _PAT_ROUTE_RULES: tuple[tuple[frozenset[str], re.Pattern[str]], ...] = (
|
||||
(frozenset({"GET"}), re.compile(r"^/api/runs/[^/]+/(messages|feedback)$")),
|
||||
)
|
||||
|
||||
# Routes a PAT reaches only while holding the named scope, on top of any
|
||||
# ``@require_permission`` check the route already has (#8310). Scheduled-task
|
||||
# routes keep their threads:* / runs:create checks, so a token without run
|
||||
# rights cannot schedule runs; the managed-subagent writes additionally stay
|
||||
# admin-only (``require_admin_user(..., pat_scope="subagents:write")``).
|
||||
_PAT_SCOPED_ROUTE_RULES: tuple[tuple[frozenset[str], re.Pattern[str], str], ...] = (
|
||||
# Own identity, so automation can confirm which account it acts as.
|
||||
# Every PAT holds at least one scope; this route needs none of them.
|
||||
(frozenset({"GET"}), re.compile(r"^/api/v1/auth/me$"), ""),
|
||||
(frozenset({"GET"}), re.compile(r"^/api/agents$"), "agents:read"),
|
||||
(frozenset({"POST"}), re.compile(r"^/api/agents$"), "agents:write"),
|
||||
(frozenset({"GET"}), re.compile(r"^/api/agents/[^/]+$"), "agents:read"),
|
||||
# The literal check (GET) and import (POST) actions use different methods.
|
||||
(frozenset({"PUT", "DELETE"}), re.compile(r"^/api/agents/[^/]+$"), "agents:write"),
|
||||
(frozenset({"GET"}), re.compile(r"^/api/scheduled-tasks$"), "schedules:read"),
|
||||
(frozenset({"POST"}), re.compile(r"^/api/scheduled-tasks$"), "schedules:write"),
|
||||
(frozenset({"POST"}), re.compile(r"^/api/scheduled-tasks/preview-cron$"), "schedules:read"),
|
||||
(frozenset({"GET"}), re.compile(r"^/api/scheduled-tasks/(?!preview-cron$)[^/]+$"), "schedules:read"),
|
||||
(frozenset({"PATCH", "DELETE"}), re.compile(r"^/api/scheduled-tasks/(?!preview-cron$)[^/]+$"), "schedules:write"),
|
||||
(frozenset({"POST"}), re.compile(r"^/api/scheduled-tasks/[^/]+/(pause|resume|trigger)$"), "schedules:write"),
|
||||
(frozenset({"GET"}), re.compile(r"^/api/scheduled-tasks/[^/]+/runs$"), "schedules:read"),
|
||||
(frozenset({"GET"}), re.compile(r"^/api/subagents$"), "subagents:read"),
|
||||
(frozenset({"POST"}), re.compile(r"^/api/subagents$"), "subagents:write"),
|
||||
(frozenset({"PUT", "DELETE"}), re.compile(r"^/api/subagents/[^/]+$"), "subagents:write"),
|
||||
)
|
||||
|
||||
_BASE62_ALPHABET = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
|
||||
|
||||
|
||||
@ -137,7 +174,20 @@ def is_pat_allowed_route(method: str, path: str) -> bool:
|
||||
redirect-style twin resolve identically.
|
||||
"""
|
||||
normalized = path.rstrip("/") or "/"
|
||||
return any(method in methods and pattern.match(normalized) for methods, pattern in _PAT_ROUTE_RULES)
|
||||
return any(method in methods and pattern.match(normalized) for methods, pattern in _PAT_ROUTE_RULES) or pat_route_scope(method, path) is not None
|
||||
|
||||
|
||||
def pat_route_scope(method: str, path: str) -> str | None:
|
||||
"""Return the scope a PAT needs for *method* + *path* beyond its route permissions.
|
||||
|
||||
``None`` means the route has no scoped rule; ``""`` means it is admitted
|
||||
for every valid PAT.
|
||||
"""
|
||||
normalized = path.rstrip("/") or "/"
|
||||
for methods, pattern, scope in _PAT_SCOPED_ROUTE_RULES:
|
||||
if method in methods and pattern.match(normalized):
|
||||
return scope
|
||||
return None
|
||||
|
||||
|
||||
@functools.cache
|
||||
|
||||
@ -161,7 +161,7 @@ class AuthMiddleware(BaseHTTPMiddleware):
|
||||
# Auth-disabled mode is an operator override of all authentication,
|
||||
# so it stays ahead of the Bearer check (a stray Authorization
|
||||
# header from a proxy must not 401 an E2E sandbox).
|
||||
from app.gateway.auth.pat import authenticate_pat, is_pat_allowed_route
|
||||
from app.gateway.auth.pat import authenticate_pat, is_pat_allowed_route, pat_route_scope
|
||||
|
||||
try:
|
||||
user, pat_scopes = await authenticate_pat(request.app, authorization)
|
||||
@ -176,7 +176,11 @@ class AuthMiddleware(BaseHTTPMiddleware):
|
||||
status_code=403,
|
||||
content={"detail": "PAT credentials are not permitted on this route"},
|
||||
)
|
||||
required_scope = pat_route_scope(request.method, get_request_route_path(request))
|
||||
if required_scope and required_scope not in pat_scopes:
|
||||
return JSONResponse(status_code=403, content={"detail": f"Permission denied: {required_scope}"})
|
||||
auth_source = AUTH_SOURCE_PAT
|
||||
request.state.pat_scopes = pat_scopes
|
||||
elif access_token:
|
||||
# Strict JWT validation: reject junk/expired tokens with 401
|
||||
# right here instead of silently passing through. This closes
|
||||
|
||||
@ -1572,13 +1572,24 @@ async def is_admin_user(request: Request) -> bool:
|
||||
return getattr(user, "system_role", None) == "admin"
|
||||
|
||||
|
||||
async def require_admin_user(request: Request, *, detail: str) -> None:
|
||||
async def require_admin_user(request: Request, *, detail: str, pat_scope: str | None = None) -> None:
|
||||
"""Require the authenticated caller to be an admin user.
|
||||
|
||||
``detail`` is the route-specific 403 message. The shared predicate keeps
|
||||
read-side redaction and write authorization on the same admin definition.
|
||||
"""
|
||||
|
||||
``pat_scope`` names the one opt-in exception to "PATs never carry admin
|
||||
capability": a route that passes it also admits a PAT whose owner is an
|
||||
admin *and* which holds that scope. Only routes that pass it are affected;
|
||||
``is_admin_user`` stays False for every PAT.
|
||||
"""
|
||||
from app.gateway.auth_disabled import AUTH_SOURCE_PAT
|
||||
|
||||
if pat_scope is not None and getattr(request.state, "auth_source", None) == AUTH_SOURCE_PAT:
|
||||
user = getattr(request.state, "user", None)
|
||||
if pat_scope in getattr(request.state, "pat_scopes", frozenset()) and getattr(user, "system_role", None) == "admin":
|
||||
return
|
||||
raise HTTPException(status_code=403, detail=detail)
|
||||
if not await is_admin_user(request):
|
||||
raise HTTPException(status_code=403, detail=detail)
|
||||
|
||||
|
||||
@ -180,7 +180,7 @@ async def list_subagents(request: Request) -> SubagentsListResponse:
|
||||
|
||||
@router.post("", response_model=SubagentResponse, status_code=201, summary="Create Managed Subagent")
|
||||
async def create_managed_subagent(request: Request, body: ManagedSubagentCreateRequest) -> SubagentResponse:
|
||||
await require_admin_user(request, detail=_ADMIN_REQUIRED_DETAIL)
|
||||
await require_admin_user(request, detail=_ADMIN_REQUIRED_DETAIL, pat_scope="subagents:write")
|
||||
_validate_path_name(body.name, for_creation=True)
|
||||
try:
|
||||
definition = ManagedSubagentDefinition(**body.model_dump(exclude_none=True))
|
||||
@ -206,7 +206,7 @@ async def create_managed_subagent(request: Request, body: ManagedSubagentCreateR
|
||||
|
||||
@router.put("/{name}", response_model=SubagentResponse, summary="Update Managed Subagent")
|
||||
async def update_managed_subagent(name: str, request: Request, body: ManagedSubagentUpdateRequest) -> SubagentResponse:
|
||||
await require_admin_user(request, detail=_ADMIN_REQUIRED_DETAIL)
|
||||
await require_admin_user(request, detail=_ADMIN_REQUIRED_DETAIL, pat_scope="subagents:write")
|
||||
name = _validate_path_name(name)
|
||||
app_config = await asyncio.to_thread(get_app_config)
|
||||
store = get_managed_subagent_store(app_config)
|
||||
@ -242,7 +242,7 @@ async def update_managed_subagent(name: str, request: Request, body: ManagedSuba
|
||||
|
||||
@router.delete("/{name}", status_code=204, summary="Delete Managed Subagent")
|
||||
async def delete_managed_subagent(name: str, request: Request) -> None:
|
||||
await require_admin_user(request, detail=_ADMIN_REQUIRED_DETAIL)
|
||||
await require_admin_user(request, detail=_ADMIN_REQUIRED_DETAIL, pat_scope="subagents:write")
|
||||
name = _validate_path_name(name)
|
||||
app_config = await asyncio.to_thread(get_app_config)
|
||||
store = get_managed_subagent_store(app_config)
|
||||
|
||||
@ -92,8 +92,11 @@ Content-Type: application/json
|
||||
```
|
||||
|
||||
- `scopes` — subset of the route permissions: `threads:read`, `threads:write`,
|
||||
`threads:delete`, `runs:create`, `runs:read`, `runs:cancel`. A PAT can only
|
||||
*narrow* its owning user's permissions, never widen them.
|
||||
`threads:delete`, `runs:create`, `runs:read`, `runs:cancel`, `projects:read`,
|
||||
`projects:write`, `projects:delete`, `agents:read`, `agents:write`; plus the
|
||||
PAT-only scopes `schedules:read`, `schedules:write`, `subagents:read`,
|
||||
`subagents:write` (see [Agent configuration](#agent-configuration-by-pat)).
|
||||
A PAT can only *narrow* its owning user's permissions, never widen them.
|
||||
- `expires_in_days` — optional (`1`–`365`); omitted means the token never expires.
|
||||
|
||||
**Response (`201`):**
|
||||
@ -149,17 +152,44 @@ Revocation is immediate.
|
||||
`GET|POST .../runs/{run_id}/stream`), plus `POST /api/runs/stream|wait` and
|
||||
`GET /api/runs/{run_id}/messages|feedback`. A route added under `/runs` is
|
||||
denied until explicitly added to the policy.
|
||||
Every other authenticated route — memory, agents, models, MCP/skills
|
||||
Besides those, only the routes under [Agent configuration by
|
||||
PAT](#agent-configuration-by-pat) are admitted, each behind its scope.
|
||||
Every other authenticated route — memory, models, MCP/skills
|
||||
config, integrations, channels, uploads — answers `403` to PAT callers
|
||||
regardless of scopes. Scope enforcement alone only constrains
|
||||
permission-decorated routes, so the allowlist is the outer boundary;
|
||||
session-cookie callers are unaffected.
|
||||
- PAT credentials never carry admin capability, even when the owning user is
|
||||
an admin. This includes extension-contributed admin routes: the extension
|
||||
principal projection suppresses every admin signal for PAT callers.
|
||||
principal projection suppresses every admin signal for PAT callers. The one
|
||||
opt-in exception is the managed-subagent writes below.
|
||||
- Revoking or deleting the owning user invalidates their PATs on the next
|
||||
request.
|
||||
|
||||
### Agent configuration by PAT
|
||||
|
||||
A pipeline that deploys agents, their managed subagents and schedules can use a
|
||||
PAT instead of a password session. Set `agents_api.enabled` to `true` in
|
||||
`config.yaml` to use the agent management API. The deployment routes require
|
||||
the scopes and permissions below.
|
||||
|
||||
| Routes | Scope | Also required |
|
||||
|---|---|---|
|
||||
| `GET /api/v1/auth/me` | any | — |
|
||||
| `GET /api/agents`, `GET /api/agents/check`, `GET /api/agents/{name}` | `agents:read` | — |
|
||||
| `POST /api/agents`, `PUT`/`DELETE /api/agents/{name}` | `agents:write` | — |
|
||||
| `GET /api/scheduled-tasks`, `GET /api/scheduled-tasks/{task_id}`, `GET .../{task_id}/runs`, `POST /api/scheduled-tasks/preview-cron` | `schedules:read` | `threads:read` |
|
||||
| `POST /api/scheduled-tasks`, `PATCH /api/scheduled-tasks/{task_id}`, `POST .../{task_id}/resume`, `POST .../{task_id}/trigger` | `schedules:write` | `threads:write`, `runs:create` |
|
||||
| `DELETE /api/scheduled-tasks/{task_id}`, `POST .../{task_id}/pause` | `schedules:write` | `threads:write` |
|
||||
| `GET /api/subagents` | `subagents:read` | — (prompts stay hidden, as for non-admins) |
|
||||
| `POST /api/subagents`, `PUT`/`DELETE /api/subagents/{name}` | `subagents:write` | the token's owner is an admin |
|
||||
|
||||
A denied scope answers `403` with `Permission denied: <scope>`. The user
|
||||
profile (`/api/user-profile`), agent import and export stay session-only.
|
||||
`subagents:write` is the only scope that carries admin capability, and only on
|
||||
the three managed-subagent write routes: an admin's token holding it still
|
||||
gets `403` on every other admin route.
|
||||
|
||||
## LangGraph-compatible API
|
||||
|
||||
Base URL: `/api/langgraph`
|
||||
|
||||
@ -802,3 +802,261 @@ def test_auth_disabled_mode_ignores_bearer_header(monkeypatch, tmp_path):
|
||||
response = disabled_client.get("/api/threads/whoami", headers={"Authorization": "Bearer dfp_garbage"})
|
||||
assert response.status_code == 200
|
||||
assert response.json()["auth_source"] == "auth_disabled"
|
||||
|
||||
|
||||
# ── Agent configuration from CI (#8310) ───────────────────────────────────
|
||||
|
||||
|
||||
def test_pat_agent_config_policy_admits_exactly_the_deploy_routes():
|
||||
"""Agents, scheduled tasks and managed subagents are reachable by PAT
|
||||
only on the routes a deploy pipeline needs, each behind its scope.
|
||||
Derived from the mounted routers, so a new route is denied until it is
|
||||
listed; user-profile, export, import and the tool-group catalog stay
|
||||
session-only even though agents:* guard them for sessions."""
|
||||
from fastapi.routing import APIRoute
|
||||
|
||||
from app.gateway.auth.pat import is_pat_allowed_route, pat_route_scope
|
||||
from app.gateway.routers import agents, scheduled_tasks, subagents
|
||||
|
||||
def concrete(path: str) -> str:
|
||||
return path.replace("{name}", "a1").replace("{task_id}", "s1").replace("{thread_id}", "t1")
|
||||
|
||||
expected = {
|
||||
("GET", "/api/agents"): "agents:read",
|
||||
("POST", "/api/agents"): "agents:write",
|
||||
("GET", "/api/agents/check"): "agents:read",
|
||||
("GET", "/api/agents/{name}"): "agents:read",
|
||||
("PUT", "/api/agents/{name}"): "agents:write",
|
||||
("DELETE", "/api/agents/{name}"): "agents:write",
|
||||
("GET", "/api/scheduled-tasks"): "schedules:read",
|
||||
("POST", "/api/scheduled-tasks"): "schedules:write",
|
||||
("POST", "/api/scheduled-tasks/preview-cron"): "schedules:read",
|
||||
("GET", "/api/scheduled-tasks/{task_id}"): "schedules:read",
|
||||
("PATCH", "/api/scheduled-tasks/{task_id}"): "schedules:write",
|
||||
("DELETE", "/api/scheduled-tasks/{task_id}"): "schedules:write",
|
||||
("POST", "/api/scheduled-tasks/{task_id}/pause"): "schedules:write",
|
||||
("POST", "/api/scheduled-tasks/{task_id}/resume"): "schedules:write",
|
||||
("POST", "/api/scheduled-tasks/{task_id}/trigger"): "schedules:write",
|
||||
("GET", "/api/scheduled-tasks/{task_id}/runs"): "schedules:read",
|
||||
("GET", "/api/subagents"): "subagents:read",
|
||||
("POST", "/api/subagents"): "subagents:write",
|
||||
("PUT", "/api/subagents/{name}"): "subagents:write",
|
||||
("DELETE", "/api/subagents/{name}"): "subagents:write",
|
||||
}
|
||||
mounted = set()
|
||||
for router in (agents.router, scheduled_tasks.router, subagents.router):
|
||||
for route in router.routes:
|
||||
if not isinstance(route, APIRoute):
|
||||
continue
|
||||
for method in sorted(route.methods - {"HEAD", "OPTIONS"}):
|
||||
mounted.add((method, route.path))
|
||||
path = concrete(route.path)
|
||||
if (method, route.path) in expected:
|
||||
assert is_pat_allowed_route(method, path), f"{method} {path} must be PAT-reachable"
|
||||
assert pat_route_scope(method, path) == expected[(method, route.path)], f"{method} {path}"
|
||||
else:
|
||||
assert not is_pat_allowed_route(method, path), f"{method} {path} must stay PAT-denied"
|
||||
assert set(expected) <= mounted, "a listed route no longer exists"
|
||||
|
||||
for method, path in [
|
||||
("POST", "/api/agents/a1"),
|
||||
("GET", "/api/scheduled-tasks/preview-cron"),
|
||||
("PATCH", "/api/scheduled-tasks/preview-cron"),
|
||||
("PUT", "/api/scheduled-tasks/s1"),
|
||||
("GET", "/api/scheduled-tasks/s1/pause"),
|
||||
("GET", "/api/subagents/a1"),
|
||||
("PATCH", "/api/subagents/a1"),
|
||||
]:
|
||||
assert not is_pat_allowed_route(method, path), f"{method} {path} is not implemented and must stay denied"
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def deploy_client(pat_env, tmp_path, monkeypatch):
|
||||
"""PAT app with the real agent and managed-subagent routers and the schedule permission checks."""
|
||||
from app.gateway.authz import require_permission
|
||||
from app.gateway.routers import agents, subagents
|
||||
from deerflow.config.agents_api_config import AgentsApiConfig
|
||||
from deerflow.config.app_config import AppConfig, reset_app_config, set_app_config
|
||||
from deerflow.config.sandbox_config import SandboxConfig
|
||||
from deerflow.persistence.managed_subagents.file import FileManagedSubagentStore
|
||||
|
||||
monkeypatch.setenv("DEER_FLOW_HOME", str(tmp_path))
|
||||
monkeypatch.setattr("deerflow.config.paths._paths", None)
|
||||
monkeypatch.setattr(agents, "get_agents_api_config", lambda: AgentsApiConfig(enabled=True))
|
||||
set_app_config(AppConfig(sandbox=SandboxConfig(use="deerflow.sandbox.local:LocalSandboxProvider")))
|
||||
store = FileManagedSubagentStore()
|
||||
monkeypatch.setattr(subagents, "get_managed_subagent_store", lambda *_: store)
|
||||
|
||||
app, _repo, engine = pat_env
|
||||
|
||||
@app.get("/api/scheduled-tasks")
|
||||
@require_permission("threads", "read")
|
||||
async def list_tasks(request: Request):
|
||||
return []
|
||||
|
||||
@app.post("/api/scheduled-tasks")
|
||||
@require_permission("threads", "write")
|
||||
@require_permission("runs", "create")
|
||||
async def create_task(request: Request):
|
||||
return {"created": True}
|
||||
|
||||
app.include_router(agents.router)
|
||||
app.include_router(subagents.router)
|
||||
try:
|
||||
with TestClient(app) as test_client:
|
||||
yield test_client
|
||||
finally:
|
||||
asyncio.run(engine.dispose())
|
||||
reset_app_config()
|
||||
|
||||
|
||||
def _bearer(created: dict) -> dict[str, str]:
|
||||
return {"Authorization": f"Bearer {created['token']}"}
|
||||
|
||||
|
||||
def test_pat_reads_its_own_identity(deploy_client):
|
||||
created = _create_pat(deploy_client, scopes=["agents:read"])
|
||||
deploy_client.cookies.clear()
|
||||
response = deploy_client.get("/api/v1/auth/me", headers=_bearer(created))
|
||||
assert response.status_code == 200
|
||||
body = response.json()
|
||||
assert body["id"] == "user-1"
|
||||
# Effective permissions are the scope intersection, not the owner's set.
|
||||
assert body["permissions"] == ["agents:read"]
|
||||
|
||||
|
||||
def test_pat_agent_scopes_narrow_agent_routes(deploy_client):
|
||||
reader = _create_pat(deploy_client, name="reader", scopes=["agents:read"])
|
||||
writer = _create_pat(deploy_client, name="writer", scopes=["agents:read", "agents:write"])
|
||||
other = _create_pat(deploy_client, name="other", scopes=["threads:read"])
|
||||
deploy_client.cookies.clear()
|
||||
|
||||
assert deploy_client.get("/api/agents", headers=_bearer(reader)).status_code == 200
|
||||
denied = deploy_client.post("/api/agents", headers=_bearer(reader))
|
||||
assert denied.status_code == 403
|
||||
assert denied.json()["detail"] == "Permission denied: agents:write"
|
||||
assert deploy_client.post("/api/agents", json={"name": "ci-agent"}, headers=_bearer(writer)).status_code == 201
|
||||
assert deploy_client.get("/api/agents", headers=_bearer(other)).status_code == 403
|
||||
# agents:* guard the user profile for sessions; it stays closed to PATs.
|
||||
profile = deploy_client.get("/api/user-profile", headers=_bearer(writer))
|
||||
assert profile.status_code == 403
|
||||
assert "PAT" in profile.json()["detail"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("name", ["check", "import"])
|
||||
@pytest.mark.parametrize(("method", "expected_status"), [("PUT", 200), ("DELETE", 204)])
|
||||
def test_pat_agent_mutations_allow_names_shared_by_other_methods(deploy_client, name, method, expected_status):
|
||||
reader = _create_pat(deploy_client, name="reader", scopes=["agents:read"])
|
||||
writer = _create_pat(deploy_client, name="writer", scopes=["agents:read", "agents:write"])
|
||||
deploy_client.cookies.clear()
|
||||
|
||||
created = deploy_client.post("/api/agents", json={"name": name}, headers=_bearer(writer))
|
||||
assert created.status_code == 201, created.text
|
||||
|
||||
path = f"/api/agents/{name}"
|
||||
payload = {"json": {"description": "Updated agent"}} if method == "PUT" else {}
|
||||
denied = deploy_client.request(method, path, headers=_bearer(reader), **payload)
|
||||
assert denied.status_code == 403
|
||||
assert denied.json()["detail"] == "Permission denied: agents:write"
|
||||
updated = deploy_client.request(method, path, headers=_bearer(writer), **payload)
|
||||
assert updated.status_code == expected_status, updated.text
|
||||
|
||||
if method == "PUT":
|
||||
assert updated.json()["description"] == "Updated agent"
|
||||
else:
|
||||
response = deploy_client.get("/api/agents/check", params={"name": name}, headers=_bearer(reader))
|
||||
assert response.status_code == 200, response.text
|
||||
assert response.json()["available"] is True
|
||||
|
||||
|
||||
def test_pat_schedule_scopes_add_to_run_permissions(deploy_client):
|
||||
full = _create_pat(deploy_client, name="full", scopes=["schedules:read", "schedules:write", "threads:read", "threads:write", "runs:create"])
|
||||
no_runs = _create_pat(deploy_client, name="no-runs", scopes=["schedules:write", "threads:write"])
|
||||
no_schedules = _create_pat(deploy_client, name="no-schedules", scopes=["threads:read", "threads:write", "runs:create"])
|
||||
reader = _create_pat(deploy_client, name="reader", scopes=["schedules:read", "threads:read"])
|
||||
deploy_client.cookies.clear()
|
||||
|
||||
assert deploy_client.post("/api/scheduled-tasks", headers=_bearer(full)).status_code == 200
|
||||
assert deploy_client.get("/api/scheduled-tasks", headers=_bearer(reader)).status_code == 200
|
||||
|
||||
response = deploy_client.post("/api/scheduled-tasks", headers=_bearer(no_runs))
|
||||
assert response.status_code == 403
|
||||
assert response.json()["detail"] == "Permission denied: runs:create"
|
||||
response = deploy_client.post("/api/scheduled-tasks", headers=_bearer(no_schedules))
|
||||
assert response.status_code == 403
|
||||
assert response.json()["detail"] == "Permission denied: schedules:write"
|
||||
response = deploy_client.get("/api/scheduled-tasks", headers=_bearer(no_schedules))
|
||||
assert response.status_code == 403
|
||||
assert response.json()["detail"] == "Permission denied: schedules:read"
|
||||
assert deploy_client.post("/api/scheduled-tasks", headers=_bearer(reader)).status_code == 403
|
||||
|
||||
|
||||
_SUBAGENT = {"name": "ci-planner", "description": "Plans work", "system_prompt": "Plan the work."}
|
||||
|
||||
|
||||
def test_admin_pat_with_subagents_write_manages_managed_subagents(deploy_client):
|
||||
created = _create_pat(deploy_client, user_id="admin-1", scopes=["subagents:read", "subagents:write"])
|
||||
deploy_client.cookies.clear()
|
||||
headers = _bearer(created)
|
||||
|
||||
response = deploy_client.post("/api/subagents", json=_SUBAGENT, headers=headers)
|
||||
assert response.status_code == 201, response.text
|
||||
response = deploy_client.put("/api/subagents/ci-planner", json={"description": "Plans more"}, headers=headers)
|
||||
assert response.status_code == 200, response.text
|
||||
assert response.json()["description"] == "Plans more"
|
||||
|
||||
catalog = deploy_client.get("/api/subagents", headers=headers)
|
||||
assert catalog.status_code == 200
|
||||
managed = [item for item in catalog.json()["subagents"] if item["name"] == "ci-planner"]
|
||||
assert managed and managed[0]["source"] == "managed"
|
||||
# The opt-in covers the writes only: the catalog still treats the PAT as
|
||||
# a non-admin and withholds prompts.
|
||||
assert managed[0].get("system_prompt") in (None, "")
|
||||
|
||||
assert deploy_client.delete("/api/subagents/ci-planner", headers=headers).status_code == 204
|
||||
|
||||
|
||||
def test_subagent_writes_need_both_scope_and_admin_owner(deploy_client):
|
||||
read_only_admin = _create_pat(deploy_client, name="admin-read", user_id="admin-1", scopes=["subagents:read"])
|
||||
non_admin = _create_pat(deploy_client, name="user-write", user_id="user-1", scopes=["subagents:read", "subagents:write"])
|
||||
admin_other_scopes = _create_pat(deploy_client, name="admin-other", user_id="admin-1", scopes=["threads:read", "threads:write", "runs:create", "agents:write"])
|
||||
deploy_client.cookies.clear()
|
||||
|
||||
response = deploy_client.post("/api/subagents", json=_SUBAGENT, headers=_bearer(read_only_admin))
|
||||
assert response.status_code == 403
|
||||
assert response.json()["detail"] == "Permission denied: subagents:write"
|
||||
response = deploy_client.post("/api/subagents", json=_SUBAGENT, headers=_bearer(non_admin))
|
||||
assert response.status_code == 403
|
||||
assert response.json()["detail"] != "Permission denied: subagents:write"
|
||||
assert deploy_client.post("/api/subagents", json=_SUBAGENT, headers=_bearer(admin_other_scopes)).status_code == 403
|
||||
assert deploy_client.get("/api/subagents", headers=_bearer(admin_other_scopes)).status_code == 403
|
||||
|
||||
|
||||
def test_subagents_write_scope_does_not_unlock_other_admin_checks(deploy_client):
|
||||
created = _create_pat(deploy_client, user_id="admin-1", scopes=["subagents:write"])
|
||||
deploy_client.cookies.clear()
|
||||
# is_admin_user stays False for every PAT; only routes that opt in with
|
||||
# pat_scope accept the scope, and the route policy keeps the rest closed.
|
||||
assert deploy_client.get("/api/admin-check", headers=_bearer(created)).status_code == 403
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_require_admin_user_pat_scope_is_checked_in_the_route_too():
|
||||
"""Defense in depth for compositions without the middleware's scoped
|
||||
rule: the route itself needs the scope on the request and an admin owner."""
|
||||
from fastapi import HTTPException
|
||||
|
||||
from app.gateway.deps import require_admin_user
|
||||
|
||||
def request(role: str, scopes: frozenset[str]):
|
||||
return SimpleNamespace(state=SimpleNamespace(auth_source=AUTH_SOURCE_PAT, user=_fake_user(system_role=role), pat_scopes=scopes))
|
||||
|
||||
await require_admin_user(request("admin", frozenset({"subagents:write"})), detail="no", pat_scope="subagents:write")
|
||||
for role, scopes, pat_scope in [
|
||||
("admin", frozenset(), "subagents:write"),
|
||||
("user", frozenset({"subagents:write"}), "subagents:write"),
|
||||
("admin", frozenset({"subagents:write"}), None),
|
||||
]:
|
||||
with pytest.raises(HTTPException) as exc:
|
||||
await require_admin_user(request(role, scopes), detail="no", pat_scope=pat_scope)
|
||||
assert exc.value.status_code == 403
|
||||
|
||||
@ -89,16 +89,23 @@ def test_validate_scopes_deduplicates_and_rejects_unknown():
|
||||
|
||||
|
||||
def test_pat_scopes_stay_aligned_with_route_permissions():
|
||||
"""Every PAT scope must be a real route permission, and the memory/agent
|
||||
permissions are deliberately excluded: PATs govern the thread/run
|
||||
lifecycle only (_PAT_ROUTE_RULES default-denies those routers for PAT
|
||||
callers regardless of scopes). Fail on drift in either direction."""
|
||||
"""Every PAT scope is either a real route permission or one of the
|
||||
PAT-only route scopes enforced by the PAT route policy, and the memory
|
||||
permissions are deliberately excluded (_PAT_ROUTE_RULES default-denies the
|
||||
memory router for PAT callers regardless of scopes). Fail on drift in
|
||||
either direction."""
|
||||
from app.gateway.auth.pat import PAT_ROUTE_SCOPES
|
||||
from app.gateway.authz import _ALL_PERMISSIONS
|
||||
|
||||
route_permissions = frozenset(_ALL_PERMISSIONS)
|
||||
assert PAT_ALLOWED_SCOPES <= route_permissions
|
||||
assert PAT_ROUTE_SCOPES <= PAT_ALLOWED_SCOPES
|
||||
assert PAT_ALLOWED_SCOPES - PAT_ROUTE_SCOPES <= route_permissions
|
||||
# PAT-only scopes must never collide with a route permission: a session
|
||||
# caller would otherwise need a scope it cannot hold.
|
||||
assert not (PAT_ROUTE_SCOPES & route_permissions)
|
||||
assert {"agents:read", "agents:write"} <= PAT_ALLOWED_SCOPES
|
||||
# The deliberate exclusions, pinned so they cannot drift silently.
|
||||
assert not (PAT_ALLOWED_SCOPES & {"memory:read", "memory:write", "agents:read", "agents:write"})
|
||||
assert not (PAT_ALLOWED_SCOPES & {"memory:read", "memory:write"})
|
||||
|
||||
|
||||
# ── Repository ────────────────────────────────────────────────────────────
|
||||
|
||||
@ -24,13 +24,18 @@ Content-Type: application/json
|
||||
{}
|
||||
```
|
||||
|
||||
Each token runs with its owning user's identity (owner filtering and per-user
|
||||
memory keep working), carries a scope set that can only narrow that user's
|
||||
permissions, and is admitted only to the thread/run lifecycle routes — every
|
||||
other route answers `403` to PAT callers, and a PAT never carries admin
|
||||
capability. Tokens can be listed and revoked at any time; revocation is
|
||||
immediate. PATs require a database backend (SQLite/PostgreSQL). Full
|
||||
reference: [API Reference — Personal Access Tokens](../../backend/docs/API.md#personal-access-tokens).
|
||||
Each token uses its owner's identity, and its scopes can narrow the owner's
|
||||
permissions. The Gateway admits PATs only to allowlisted routes, including
|
||||
thread, run, and project operations. A valid PAT can call
|
||||
`GET /api/v1/auth/me` to confirm its identity. PATs require SQLite or
|
||||
PostgreSQL. Revocation takes effect on the next request.
|
||||
[PAT API reference](../../backend/docs/API.md#personal-access-tokens)
|
||||
|
||||
A CI pipeline can deploy agents, schedules, and managed subagents with their
|
||||
respective scopes. Set `agents_api.enabled` to `true` in `config.yaml` to use
|
||||
the agent management API. The PAT exception for admin operations applies only to
|
||||
managed-subagent writes and requires `subagents:write` from an admin token owner.
|
||||
[Deployment routes and required scopes](../../backend/docs/API.md#agent-configuration-by-pat)
|
||||
|
||||
## Embedded Python Client
|
||||
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user