diff --git a/backend/app/gateway/app.py b/backend/app/gateway/app.py index 347175426b..c29418d119 100644 --- a/backend/app/gateway/app.py +++ b/backend/app/gateway/app.py @@ -40,6 +40,7 @@ from app.gateway.routers import ( integrations, knowledge, mcp, + mcp_agent_auth, mcp_tasks, mcp_user_oauth, memory, @@ -1374,6 +1375,8 @@ This gateway provides runtime endpoints for agent runs plus custom endpoints for # MCP API is mounted at /api/mcp app.include_router(capabilities.router) + # Runtime MCP agent credential grants (admin) at /api/mcp/agent-auth + app.include_router(mcp_agent_auth.router) app.include_router(mcp.router) app.include_router(personal_mcp.router) app.include_router(mcp_user_oauth.router) diff --git a/backend/app/gateway/routers/mcp_agent_auth.py b/backend/app/gateway/routers/mcp_agent_auth.py new file mode 100644 index 0000000000..b77c00637e --- /dev/null +++ b/backend/app/gateway/routers/mcp_agent_auth.py @@ -0,0 +1,274 @@ +"""Administrator API for runtime MCP agent credential grants. + +``config.yaml`` keeps which server is protected and which OAuth client each +binding uses. For a binding declared with ``grants: runtime``, administrators +maintain the owners and approved definition digests here; each change applies +to the next call and run without a Gateway restart. A grant covers the agent, +server, destination and OAuth client the binding had when it was approved; if +``config.yaml`` later changes one of them, the grant admits nobody (``approval: +stale``) until an administrator replaces it. A grant whose binding was removed +from ``config.yaml`` is listed as ``approval: retired``. Stale and retired +grants, and grants of disabled bindings, keep their owners reserved for the +agent and server they were approved for, because a configuration rollback or +re-enabling the binding can make them current again; deleting the grant +releases them. +""" + +from __future__ import annotations + +import asyncio +from typing import Literal + +from fastapi import APIRouter, HTTPException, Query, Request, Response +from pydantic import BaseModel + +from app.gateway.deps import require_admin_user +from app.gateway.persistent_writes import run_drained_write +from deerflow.config.app_config import AppConfig, get_app_config +from deerflow.config.mcp_agent_auth_config import BindingId, McpAgentCredentialBinding, McpAgentGrant, StoredMcpAgentGrant +from deerflow.config.paths import get_paths +from deerflow.mcp.agent_auth import grant_subject +from deerflow.persistence.mcp_agent_grants import make_mcp_agent_grant_store + +router = APIRouter(prefix="/api/mcp/agent-auth", tags=["mcp"]) +_ADMIN_REQUIRED_DETAIL = "Admin privileges required to manage MCP agent credentials." + + +class _InvalidOwner(ValueError): + """An owner id that file-backed agent storage cannot hold.""" + + +class McpAgentStoredGrantResponse(BaseModel): + """A runtime grant still stored for a binding that now keeps its grants in config.yaml.""" + + server: str + agent: str + owners: list[str] + definition_digests: list[str] + + +class McpAgentBindingResponse(BaseModel): + binding: str + server: str + agent: str + enabled: bool + grants: Literal["config", "runtime"] + # config: owners and digests come from config.yaml. current: the runtime + # grant is in force. stale: it was approved for another agent, server, + # destination or OAuth client and admits nobody. none: no runtime grant. + # retired: a stored grant whose binding is no longer configured; server and + # agent are the ones it was approved for. + approval: Literal["config", "current", "stale", "none", "retired"] + owners: list[str] + definition_digests: list[str] + # A grants: config binding whose earlier runtime grant is still stored: it + # admits nobody but keeps its owners reserved for the server and agent it was + # approved for until it is deleted. None otherwise. + stored_grant: McpAgentStoredGrantResponse | None = None + + +class McpAgentBindingsResponse(BaseModel): + bindings: list[McpAgentBindingResponse] + + +class McpAgentDefinitionDigestResponse(BaseModel): + binding: str + agent: str + owner: str + definition_digest: str + + +def _config() -> AppConfig: + return get_app_config(use_runtime_override=False) + + +def _binding(config: AppConfig, binding_id: str) -> McpAgentCredentialBinding: + binding = config.mcp_agent_auth.get(binding_id) + if binding is None: + raise HTTPException(status_code=404, detail=f"MCP agent binding '{binding_id}' is not configured") + return binding + + +def _runtime_binding(config: AppConfig, binding_id: str) -> McpAgentCredentialBinding: + binding = _binding(config, binding_id) + if binding.grants != "runtime": + raise HTTPException(status_code=409, detail=f"MCP agent binding '{binding_id}' keeps its grants in config.yaml (grants: config)") + return binding + + +def _response(config: AppConfig, binding_id: str, binding: McpAgentCredentialBinding, grant: StoredMcpAgentGrant | None) -> McpAgentBindingResponse: + """Owners and digests as configured or stored; ``approval`` says whether a stored grant is in force.""" + stored_grant = None + if binding.grants == "config" and grant is not None: + stored_grant = McpAgentStoredGrantResponse( + server=grant.approved_for.server, + agent=grant.approved_for.agent, + owners=list(grant.owners), + definition_digests=list(grant.definition_digests), + ) + if binding.grants == "config": + owners, digests, approval = binding.owners, binding.definition_digests, "config" + elif grant is None: + owners, digests, approval = [], [], "none" + else: + owners, digests = grant.owners, grant.definition_digests + approval = "current" if grant.approved_for == grant_subject(config, binding) else "stale" + return McpAgentBindingResponse( + binding=binding_id, + server=binding.server, + agent=binding.agent, + enabled=binding.enabled, + grants=binding.grants, + approval=approval, + owners=list(owners), + definition_digests=list(digests), + stored_grant=stored_grant, + ) + + +def _retired_response(binding_id: str, grant: StoredMcpAgentGrant) -> McpAgentBindingResponse: + """A stored grant whose binding is no longer configured, described by what it was approved for.""" + return McpAgentBindingResponse( + binding=binding_id, + server=grant.approved_for.server, + agent=grant.approved_for.agent, + enabled=False, + grants="runtime", + approval="retired", + owners=list(grant.owners), + definition_digests=list(grant.definition_digests), + ) + + +def _overlapping_binding(config: AppConfig, binding_id: str, binding: McpAgentCredentialBinding, grant: McpAgentGrant) -> str | None: + """Return another binding that grants, or may grant again, one of these owners the same server and agent. + + A stored runtime grant reserves its owners for the agent and server it was + approved for even while it is stale or its binding is gone from + ``config.yaml``: a configuration rollback can make it current again, and + two matching grants would then reject the agent at admission. Deleting the + grant releases the owners. A disabled binding reserves its owners too, and + writing a grant to a disabled binding is checked the same way: enabling it + again must not make admission reject both bindings. + """ + owners = set(grant.owners) + for other_id, other in config.mcp_agent_auth.items(): + if other_id == binding_id or other.grants != "config": + continue + if other.server == binding.server and other.agent == binding.agent and owners & set(other.owners): + return other_id + for other_id, other_grant in make_mcp_agent_grant_store(config).list().items(): + if other_id == binding_id: + continue + subject = other_grant.approved_for + if subject.server == binding.server and subject.agent == binding.agent and owners & set(other_grant.owners): + return other_id + return None + + +@router.get("", response_model=McpAgentBindingsResponse, summary="List MCP Agent Credential Bindings") +async def list_bindings(request: Request) -> McpAgentBindingsResponse: + """List every configured binding with the owners and digests in force, then retired grants; OAuth settings are never returned.""" + await require_admin_user(request, detail=_ADMIN_REQUIRED_DETAIL) + config = await asyncio.to_thread(_config) + stored = await asyncio.to_thread(lambda: make_mcp_agent_grant_store(config).list()) + bindings = [_response(config, binding_id, binding, stored.get(binding_id)) for binding_id, binding in sorted(config.mcp_agent_auth.items())] + bindings += [_retired_response(binding_id, grant) for binding_id, grant in sorted(stored.items()) if binding_id not in config.mcp_agent_auth] + return McpAgentBindingsResponse(bindings=bindings) + + +@router.get("/{binding_id}", response_model=McpAgentBindingResponse, summary="Get MCP Agent Credential Binding") +async def get_binding(binding_id: BindingId, request: Request) -> McpAgentBindingResponse: + await require_admin_user(request, detail=_ADMIN_REQUIRED_DETAIL) + config = await asyncio.to_thread(_config) + binding = config.mcp_agent_auth.get(binding_id) + if binding is None: + retired = await asyncio.to_thread(lambda: make_mcp_agent_grant_store(config).get(binding_id)) + if retired is None: + raise HTTPException(status_code=404, detail=f"MCP agent binding '{binding_id}' is not configured") + return _retired_response(binding_id, retired) + grant = await asyncio.to_thread(lambda: make_mcp_agent_grant_store(config).get(binding_id)) + return _response(config, binding_id, binding, grant) + + +@router.put("/{binding_id}/grants", response_model=McpAgentBindingResponse, summary="Replace Runtime MCP Agent Grant") +async def put_grant(binding_id: BindingId, grant: McpAgentGrant, request: Request) -> McpAgentBindingResponse: + """Replace the owners and approved digests of a ``grants: runtime`` binding. + + Removing an owner denies that owner's next call; removing a digest stops + new runs of that definition, while admitted runs keep the definition they + started with. The grant is recorded for the binding's current agent, + server, destination and OAuth client, and stays in force only while they + are unchanged; rotating the client secret keeps it. + """ + await require_admin_user(request, detail=_ADMIN_REQUIRED_DETAIL) + config = await asyncio.to_thread(_config) + binding = _runtime_binding(config, binding_id) + subject = grant_subject(config, binding) + if subject is None: + raise HTTPException(status_code=409, detail=f"MCP server '{binding.server}' of binding '{binding_id}' is not configured") + stored = StoredMcpAgentGrant(**grant.model_dump(), approved_for=subject) + overlap = await asyncio.to_thread(_overlapping_binding, config, binding_id, binding, grant) + if overlap is not None: + raise HTTPException(status_code=409, detail=f"Owners overlap with MCP agent binding '{overlap}' for the same server and agent") + try: + await run_drained_write("Replace MCP agent grant", lambda: make_mcp_agent_grant_store(config).put(binding_id, stored), (ValueError,)) + except ValueError as exc: + raise HTTPException(status_code=422, detail=str(exc)) from None + return _response(config, binding_id, binding, stored) + + +@router.delete("/{binding_id}/grants", status_code=204, summary="Delete Runtime MCP Agent Grant") +async def delete_grant(binding_id: BindingId, request: Request) -> Response: + """Delete the grant; the binding then admits nobody. + + A stored grant left behind after its binding was removed from + ``config.yaml`` or moved to ``grants: config`` can be deleted too; that + releases the owners it reserves. + """ + await require_admin_user(request, detail=_ADMIN_REQUIRED_DETAIL) + config = await asyncio.to_thread(_config) + if await run_drained_write("Delete MCP agent grant", lambda: make_mcp_agent_grant_store(config).delete(binding_id)): + return Response(status_code=204) + binding = config.mcp_agent_auth.get(binding_id) + if binding is None: + raise HTTPException(status_code=404, detail=f"MCP agent binding '{binding_id}' is not configured and has no stored grant") + _runtime_binding(config, binding_id) + raise HTTPException(status_code=404, detail=f"MCP agent binding '{binding_id}' has no runtime grant") + + +@router.get("/{binding_id}/definition-digest", response_model=McpAgentDefinitionDigestResponse, summary="Compute an Agent Definition Digest") +async def definition_digest(binding_id: BindingId, request: Request, owner: str = Query(min_length=1)) -> McpAgentDefinitionDigestResponse: + """Digest of ``owner``'s stored copy of the binding's agent, as run admission computes it. + + Review that copy before approving its digest: approval covers its settings + and exact SOUL, and any user holding an identical copy who is an owner. + """ + await require_admin_user(request, detail=_ADMIN_REQUIRED_DETAIL) + config = await asyncio.to_thread(_config) + binding = _binding(config, binding_id) + + def compute() -> str | None: + from deerflow.config.agents_config import load_agent_config, load_agent_soul + from deerflow.mcp.agent_auth import agent_definition_digest + + if config.agent_storage.backend != "db": + # File-backed agents live under the owner's user directory, so an + # owner id that cannot name one (e.g. "../alice") has no agent there. + try: + get_paths().user_dir(owner) + except ValueError as exc: + raise _InvalidOwner(str(exc)) from None + try: + agent_config = load_agent_config(binding.agent, user_id=owner) + except FileNotFoundError: + return None + return agent_definition_digest(agent_config, load_agent_soul(binding.agent, user_id=owner) or "") + + try: + digest = await asyncio.to_thread(compute) + except _InvalidOwner as exc: + raise HTTPException(status_code=422, detail=f"Invalid owner for file-backed agent storage: {exc}") from None + if digest is None: + raise HTTPException(status_code=404, detail=f"User '{owner}' has no agent '{binding.agent}'") + return McpAgentDefinitionDigestResponse(binding=binding_id, agent=binding.agent, owner=owner, definition_digest=digest) diff --git a/backend/docs/API.md b/backend/docs/API.md index eb0445122f..b32fe91c6b 100644 --- a/backend/docs/API.md +++ b/backend/docs/API.md @@ -1067,6 +1067,38 @@ write, the Gateway resolves environment variables in a copy and validates the same expanded document the runtime will load while persisting the original raw placeholders. +#### Runtime MCP Agent Grants + +Owners and approved definition digests of `mcp_agent_auth` bindings declared +with `grants: runtime` (admin only; PATs are not accepted). Changes apply to +the next run and call without a restart. See +[Per-agent credentials](MCP_SERVER.md#runtime-grants). + +```http +GET /api/mcp/agent-auth +GET /api/mcp/agent-auth/{binding} +GET /api/mcp/agent-auth/{binding}/definition-digest?owner={user_id} +PUT /api/mcp/agent-auth/{binding}/grants +DELETE /api/mcp/agent-auth/{binding}/grants +``` + +```json +{"owners": [""], "definition_digests": ["<64-character SHA-256 digest>"]} +``` + +A grant covers the agent, server, destination and OAuth client the binding had +when it was written; after `config.yaml` changes one of them, responses show +`"approval": "stale"` and the grant admits nobody until it is written again. +A grant whose binding was removed from `config.yaml` is listed with +`"approval": "retired"` and can still be read and deleted by its binding ID. +Stale and retired grants, and grants of disabled bindings, keep their owners +reserved for the agent and server they were approved for until they are +replaced or deleted; owners listed by a disabled `grants: config` binding stay +reserved too. A binding moved to `grants: config` whose runtime grant is +still stored returns it as `stored_grant`, so the owners it reserves are visible +until the grant is deleted. A write to a disabled binding is checked for overlaps like any +other, so enabling it again cannot make admission reject both bindings. + #### Reset MCP Tools Cache Publish a shared cache generation, then clear cached MCP tools and persistent diff --git a/backend/docs/MCP_SERVER.md b/backend/docs/MCP_SERVER.md index 2f8a454088..31a583866d 100644 --- a/backend/docs/MCP_SERVER.md +++ b/backend/docs/MCP_SERVER.md @@ -610,6 +610,74 @@ membership for identical per-user copies. Wildcards, group matching, static per-agent tokens and refresh-token grants are not supported. Enabled bindings must not overlap for the same server, agent and owner. +### Runtime grants + +A use case deployed by CI changes its definition digest with every release, +and a sync job that copies one agent into many accounts changes the owners +with every member. With the grants in `config.yaml`, each such change is a +configuration rollout. Declare the binding with `grants: runtime` to keep the +server and OAuth client in `config.yaml` and let an administrator maintain the +owners and digests through the Gateway API instead: + +```yaml +mcp_agent_auth: + research-tickets: + server: ticketing + agent: research-bot + grants: runtime # owners and definition_digests come from the admin API + oauth: + grant_type: client_credentials + token_url: https://idp.example/realms/work/protocol/openid-connect/token + client_id: research-bot + client_secret: $RESEARCH_BOT_CLIENT_SECRET +``` + +A runtime binding admits nobody until it has a grant, and `config.yaml` must +not list owners or digests for it. Grants are stored with the same backend as +custom agents (`agent_storage.backend`: the database, or one JSON file per +binding under the data root). All routes require an administrator; PATs are +not accepted. + +| Method and path | Effect | +|---|---| +| `GET /api/mcp/agent-auth` | Every binding with the owners and digests in force, then retired grants; never the OAuth settings | +| `GET /api/mcp/agent-auth/{binding}` | One binding | +| `GET /api/mcp/agent-auth/{binding}/definition-digest?owner=` | The digest of that user's stored copy of the agent, computed as run admission does | +| `PUT /api/mcp/agent-auth/{binding}/grants` | Replace the grant: `{"owners": [...], "definition_digests": [...]}` | +| `DELETE /api/mcp/agent-auth/{binding}/grants` | Remove the grant; the binding admits nobody. Also removes a retired grant | + +A write to a `grants: config` binding returns 409, as does a grant whose owners +another enabled binding already covers for the same server and agent. A stored +grant covers its owners for the agent and server it was approved for even when +it is `stale` or `retired`, because rolling `config.yaml` back makes it current +again; delete it to release them. + +Changes apply without a restart. The next run admits against the new owners +and digests, and every protected call rechecks the owners, so removing an +owner denies that owner's next call, poll or cancellation. Removing a digest +stops new runs of that definition; runs and durable tasks already admitted +keep the definition version they started with. If the grant store cannot be +read, admission and calls are denied. + +A `PUT` records what the grant is approved for: the binding's agent and +server, the server's destination (transport and URL) and its OAuth client +(every OAuth setting except the secret). If `config.yaml` later changes any of +them, the stored grant admits nobody and the API reports it with +`"approval": "stale"` until an administrator replaces it. Rotating the client +secret of the same account keeps the grant. `approval` is otherwise `current` +(the grant is in force), `none` (no grant), `config` (`grants: config`) or +`retired`: the binding was removed from `config.yaml` and the grant is still +stored, shown with the agent and server it was approved for. +A binding moved to `grants: config` while its runtime grant is still stored +also returns that grant as `stored_grant` (the server and agent it was +approved for, its owners and digests): it admits nobody but keeps those +owners reserved until it is deleted. + +A deploy pipeline adds the new digest right after it deploys (read it from the +deploy account's copy with `definition-digest`, after reviewing that copy), +then removes the old one once every copy is updated. A membership sync replaces +the owners. + ### Approve a definition Generate the digest in the Gateway environment with the same DeerFlow version @@ -662,7 +730,8 @@ references; rotating the same account's client secret keeps them valid and refreshes the cache. Missing grants or failed token acquisition never fall back to user or server credentials. -Grant edits are hot-reloaded independently of the server connection snapshot. +Grant edits are hot-reloaded independently of the server connection snapshot; +runtime grants need no reload at all. As with other task-tool connection settings, changing the server's `agent_auth` flag requires a Gateway restart when it has `task_toolsets`. Environment secrets are resolved at configuration load; roll out a config diff --git a/backend/packages/harness/deerflow/config/mcp_agent_auth_config.py b/backend/packages/harness/deerflow/config/mcp_agent_auth_config.py index 935b36adb5..dad4308775 100644 --- a/backend/packages/harness/deerflow/config/mcp_agent_auth_config.py +++ b/backend/packages/harness/deerflow/config/mcp_agent_auth_config.py @@ -1,6 +1,6 @@ """Operator-owned grants for named agents on deployment MCP servers.""" -from typing import Annotated, Self +from typing import Annotated, Literal, Self from pydantic import BaseModel, ConfigDict, Field, StringConstraints, field_validator, model_validator @@ -10,14 +10,25 @@ DefinitionDigest = Annotated[str, StringConstraints(pattern=r"^[0-9a-f]{64}$")] BindingId = Annotated[str, StringConstraints(pattern=r"^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$")] +def validate_grant_owners(value: list[str]) -> list[str]: + if any(not owner.strip() or owner != owner.strip() or owner == "*" for owner in value): + raise ValueError("MCP agent bindings require explicit, nonblank owner IDs") + if len(value) != len(set(value)): + raise ValueError("MCP agent binding owner IDs must be unique") + return value + + class McpAgentCredentialBinding(BaseModel): model_config = ConfigDict(extra="forbid", hide_input_in_errors=True) enabled: bool = True server: str = Field(min_length=1) agent: str = Field(min_length=1) - owners: list[str] - definition_digests: list[DefinitionDigest] = Field(min_length=1) + # "config": owners and digests below. "runtime": an administrator maintains + # them through the Gateway admin API; until then the binding admits nobody. + grants: Literal["config", "runtime"] = "config" + owners: list[str] = Field(default_factory=list) + definition_digests: list[DefinitionDigest] = Field(default_factory=list) oauth: McpOAuthConfig = Field(repr=False) @field_validator("agent") @@ -31,16 +42,57 @@ class McpAgentCredentialBinding(BaseModel): @field_validator("owners") @classmethod def _explicit_owners(cls, value: list[str]) -> list[str]: - if any(not owner.strip() or owner != owner.strip() or owner == "*" for owner in value): - raise ValueError("MCP agent bindings require explicit, nonblank owner IDs") - if len(value) != len(set(value)): - raise ValueError("MCP agent binding owner IDs must be unique") - return value + return validate_grant_owners(value) @model_validator(mode="after") def _client_credentials(self) -> Self: + if self.grants == "config" and not self.definition_digests: + raise ValueError("An MCP agent binding with grants: config requires definition_digests") + if self.grants == "runtime" and (self.owners or self.definition_digests): + raise ValueError("An MCP agent binding with grants: runtime takes owners and definition_digests from the admin API, not config.yaml") if self.oauth.grant_type != "client_credentials": raise ValueError("MCP agent bindings support OAuth client_credentials") if self.enabled and (not self.oauth.enabled or not self.oauth.client_id or not self.oauth.client_secret): raise ValueError("An enabled MCP agent binding requires enabled OAuth with a client ID and secret") return self + + +class McpAgentGrant(BaseModel): + """The runtime part of a ``grants: runtime`` binding, written by an administrator.""" + + model_config = ConfigDict(extra="forbid", hide_input_in_errors=True) + + owners: list[str] = Field(max_length=10000) + definition_digests: list[DefinitionDigest] = Field(max_length=100) + + @field_validator("owners") + @classmethod + def _explicit_owners(cls, value: list[str]) -> list[str]: + return validate_grant_owners(value) + + @field_validator("definition_digests") + @classmethod + def _unique_digests(cls, value: list[str]) -> list[str]: + return list(dict.fromkeys(value)) + + +class McpAgentGrantSubject(BaseModel): + """What an administrator approved a runtime grant for. + + The grant applies only while the binding still names this agent and server, + the server keeps this destination, and the binding keeps this OAuth client + (a nonsecret digest, so rotating the secret of the same account keeps it). + """ + + model_config = ConfigDict(extra="forbid", frozen=True, hide_input_in_errors=True) + + agent: str + server: str + destination_digest: DefinitionDigest + credential_digest: DefinitionDigest + + +class StoredMcpAgentGrant(McpAgentGrant): + """A runtime grant as stored: the administrator's grant and what it was approved for.""" + + approved_for: McpAgentGrantSubject diff --git a/backend/packages/harness/deerflow/mcp/AGENTS.md b/backend/packages/harness/deerflow/mcp/AGENTS.md index 3181eb4d9e..617f254a63 100644 --- a/backend/packages/harness/deerflow/mcp/AGENTS.md +++ b/backend/packages/harness/deerflow/mcp/AGENTS.md @@ -54,7 +54,9 @@ make test-blocking-io - **Background task calls have no request.** `McpTaskToolCaller` binds the task owner's identity for the call and restores the previous value afterwards. - **Agent grants are live policy, not run snapshots.** Every protected call - rechecks the operator binding even with a cached token. Durable references + rechecks the operator binding, and for `grants: runtime` the stored grant + (in force only while its recorded agent, server, destination and OAuth client match), + even with a cached token. An unreadable grant store denies the call. Durable references retain the admitted definition revision; definition rollouts preserve them, while grant revocation denies them. See the per-agent section in the MCP guide. diff --git a/backend/packages/harness/deerflow/mcp/agent_auth.py b/backend/packages/harness/deerflow/mcp/agent_auth.py index 75adc1a2bc..4b9310da9b 100644 --- a/backend/packages/harness/deerflow/mcp/agent_auth.py +++ b/backend/packages/harness/deerflow/mcp/agent_auth.py @@ -18,7 +18,7 @@ from pydantic import BaseModel, ConfigDict, TypeAdapter, ValidationError from deerflow.config.agents_config import AgentConfig, load_agent_soul from deerflow.config.extensions_config import ExtensionsConfig, McpServerConfig, get_extensions_config -from deerflow.config.mcp_agent_auth_config import BindingId, DefinitionDigest, McpAgentCredentialBinding +from deerflow.config.mcp_agent_auth_config import BindingId, DefinitionDigest, McpAgentCredentialBinding, McpAgentGrantSubject, StoredMcpAgentGrant from deerflow.mcp.headers import apply_header_overrides, header_spellings from deerflow.mcp.oauth import OAuthTokenManager from deerflow.runtime.context_keys import AGENT_AUTH_CONTEXT_KEY @@ -66,6 +66,50 @@ def agent_definition_digest(config: AgentConfig, soul: str | None) -> str: return canonical_hash({"version": 1, "config": config.model_dump(mode="json"), "soul": soul or ""}) +def grant_subject(app_config: Any, binding: McpAgentCredentialBinding) -> McpAgentGrantSubject | None: + """What a runtime grant for ``binding`` is approved for under the current configuration.""" + server = app_config.extensions.mcp_servers.get(binding.server) + if server is None: + return None + return McpAgentGrantSubject(agent=binding.agent, server=binding.server, destination_digest=_destination_digest(server), credential_digest=_credential_digest(binding)) + + +def runtime_grant_in_force(app_config: Any, binding_id: str, binding: McpAgentCredentialBinding, grant: StoredMcpAgentGrant | None) -> tuple[frozenset[str], frozenset[str]]: + """Owners and digests of a stored runtime grant, or none when it no longer applies. + + An approval covers the agent, server, destination and OAuth client it was + given for. Pointing the binding at another agent, server or client, or the + server at another destination, leaves the grant stored but in force for + nobody until an administrator approves it again. + """ + if grant is None: + return frozenset(), frozenset() + if grant.approved_for != grant_subject(app_config, binding): + logger.warning("MCP agent grant for binding=%s was approved for a different agent, server, destination or OAuth client; it admits nobody until approved again", binding_id) + return frozenset(), frozenset() + return frozenset(grant.owners), frozenset(grant.definition_digests) + + +def binding_grant(app_config: Any, binding_id: str, binding: McpAgentCredentialBinding) -> tuple[frozenset[str], frozenset[str]]: + """Return the owners and approved digests in force for one binding. + + ``grants: runtime`` bindings read the administrator's grant from the + database (or file store) on each call, so a change applies without a + restart. A binding without a stored grant, or whose grant was approved for + another agent, server, destination or OAuth client, admits nobody. + """ + if binding.grants == "config": + return frozenset(binding.owners), frozenset(binding.definition_digests) + from deerflow.persistence.mcp_agent_grants import make_mcp_agent_grant_store + + try: + grant = make_mcp_agent_grant_store(app_config).get(binding_id) + except Exception: + logger.warning("MCP agent grant store unavailable for binding=%s", binding_id, exc_info=True) + raise ToolException("MCP agent credential policy is unavailable") from None + return runtime_grant_in_force(app_config, binding_id, binding, grant) + + def _credential_digest(binding: McpAgentCredentialBinding) -> str: # Rotating a secret preserves the account. Replacing the endpoint, client, # scope or other request settings requires a new admission. @@ -95,15 +139,25 @@ def capture_agent_authority(app_config: Any, *, user_id: str, agent_config: Agen matches = [] for binding_id, binding in app_config.mcp_agent_auth.items(): server = app_config.extensions.mcp_servers.get(binding.server) - if binding.enabled and binding.agent == agent_config.name and user_id in binding.owners and server is not None and server.enabled and server.agent_auth: - matches.append((binding_id, binding)) + if not (binding.enabled and binding.agent == agent_config.name and server is not None and server.enabled and server.agent_auth): + continue + try: + owners, digests = binding_grant(app_config, binding_id, binding) + except ToolException as exc: + raise McpAgentAuthorizationError(str(exc)) from None + if user_id in owners: + matches.append((binding_id, binding, digests)) if not matches: return None + if len({binding.server for _, binding, _ in matches}) != len(matches): + # Config validation rejects overlaps, and the admin API rejects them on + # write; two concurrent runtime writes could still race. Fail closed. + raise McpAgentAuthorizationError(f"MCP agent bindings overlap for agent '{agent_config.name}'") soul = load_agent_soul(agent_config.name, user_id=user_id) or "" digest = agent_definition_digest(agent_config, soul) references = [] - for binding_id, binding in matches: - if digest not in binding.definition_digests: + for binding_id, binding, digests in matches: + if digest not in digests: raise McpAgentAuthorizationError(f"Agent definition is not approved for MCP binding '{binding_id}'") references.append( AgentCredentialReference( @@ -169,7 +223,7 @@ def _current_binding(reference: AgentCredentialReference, user_id: str) -> McpAg if ( binding is None or not binding.enabled - or user_id not in binding.owners + or user_id not in binding_grant(config, reference.binding, binding)[0] or binding.server != reference.server or binding.agent != reference.agent or server is None diff --git a/backend/packages/harness/deerflow/persistence/mcp_agent_grants/__init__.py b/backend/packages/harness/deerflow/persistence/mcp_agent_grants/__init__.py new file mode 100644 index 0000000000..3eca862c98 --- /dev/null +++ b/backend/packages/harness/deerflow/persistence/mcp_agent_grants/__init__.py @@ -0,0 +1,57 @@ +"""Runtime grants for ``grants: runtime`` MCP agent credential bindings.""" + +from __future__ import annotations + +import abc +from typing import TYPE_CHECKING + +from deerflow.config.mcp_agent_auth_config import McpAgentGrant, StoredMcpAgentGrant +from deerflow.persistence.mcp_agent_grants.model import McpAgentGrantRow + +if TYPE_CHECKING: + from deerflow.config.app_config import AppConfig + +__all__ = ["McpAgentGrant", "McpAgentGrantRow", "McpAgentGrantStore", "StoredMcpAgentGrant", "make_mcp_agent_grant_store"] + + +class McpAgentGrantStore(abc.ABC): + """Owners, approved definition digests and their approval subject per binding ID. + + Readers run on every protected MCP call, so a store error must propagate: + callers deny the call rather than guess a grant. + """ + + @abc.abstractmethod + def get(self, binding_id: str) -> StoredMcpAgentGrant | None: + """Return the grant, or ``None`` when the binding has none.""" + + @abc.abstractmethod + def list(self) -> dict[str, StoredMcpAgentGrant]: + """Return every stored grant by binding ID.""" + + @abc.abstractmethod + def put(self, binding_id: str, grant: StoredMcpAgentGrant) -> None: + """Create or replace the grant of one binding.""" + + @abc.abstractmethod + def delete(self, binding_id: str) -> bool: + """Delete one grant and return whether it existed.""" + + +_file_store_singleton: McpAgentGrantStore | None = None + + +def make_mcp_agent_grant_store(config: AppConfig) -> McpAgentGrantStore: + """Use the same backend as custom agent definitions and managed subagents.""" + if config.agent_storage.backend == "db": + if config.database.backend not in ("sqlite", "postgres"): + raise ValueError("MCP agent grant database storage requires database.backend to be 'sqlite' or 'postgres'.") + from deerflow.persistence.mcp_agent_grants.sql import SqlMcpAgentGrantStore + + return SqlMcpAgentGrantStore(config.database.app_sync_sqlalchemy_url) + global _file_store_singleton + if _file_store_singleton is None: + from deerflow.persistence.mcp_agent_grants.file import FileMcpAgentGrantStore + + _file_store_singleton = FileMcpAgentGrantStore() + return _file_store_singleton diff --git a/backend/packages/harness/deerflow/persistence/mcp_agent_grants/file.py b/backend/packages/harness/deerflow/persistence/mcp_agent_grants/file.py new file mode 100644 index 0000000000..1d77b69a12 --- /dev/null +++ b/backend/packages/harness/deerflow/persistence/mcp_agent_grants/file.py @@ -0,0 +1,88 @@ +"""File-backed runtime MCP agent grants, one JSON file per binding.""" + +from __future__ import annotations + +import json +import os +import tempfile +import threading +from pathlib import Path + +from deerflow.config.mcp_agent_auth_config import StoredMcpAgentGrant +from deerflow.config.paths import get_paths +from deerflow.persistence.mcp_agent_grants import McpAgentGrantStore +from deerflow.utils.atomic_write import cleanup_failed_atomic_write +from deerflow.utils.host_paths import windows_incompatible_segment + +_write_lock = threading.RLock() + + +class FileMcpAgentGrantStore(McpAgentGrantStore): + @staticmethod + def _root() -> Path: + return get_paths().base_dir / "mcp-agent-grants" + + def _read(self, path: Path) -> tuple[str, StoredMcpAgentGrant] | None: + """Read one grant file; None when a concurrent delete removed it. + + Parse errors and other I/O failures still raise. + """ + try: + text = path.read_text(encoding="utf-8") + except FileNotFoundError: + return None + document = json.loads(text) + return document.pop("binding"), StoredMcpAgentGrant.model_validate(document) + + def get(self, binding_id: str) -> StoredMcpAgentGrant | None: + entry = self._read(self._root() / f"{binding_id}.json") + if entry is None: + return None + stored_id, grant = entry + # A case-insensitive filesystem maps "A" and "a" to one file; a grant + # never applies to a binding it was not written for. + return grant if stored_id == binding_id else None + + def list(self) -> dict[str, StoredMcpAgentGrant]: + root = self._root() + if not root.exists(): + return {} + entries = (self._read(path) for path in root.glob("*.json")) + return dict(sorted(entry for entry in entries if entry is not None)) + + def put(self, binding_id: str, grant: StoredMcpAgentGrant) -> None: + reason = windows_incompatible_segment(binding_id) + if reason is not None: + raise ValueError(f"Binding ID {binding_id!r} cannot be stored as a file: {reason}") + root = self._root() + payload = json.dumps({"binding": binding_id, **grant.model_dump(mode="json")}, indent=2) + "\n" + with _write_lock: + root.mkdir(parents=True, exist_ok=True) + path = root / f"{binding_id}.json" + existing = self._read(path) + if existing is not None and existing[0] != binding_id: + raise ValueError(f"Binding ID {binding_id!r} collides with a stored grant that differs only in case") + tmp_path: Path | None = None + try: + with tempfile.NamedTemporaryFile("w", encoding="utf-8", newline="", dir=root, suffix=".tmp", delete=False) as handle: + tmp_path = Path(handle.name) + handle.write(payload) + handle.flush() + os.fsync(handle.fileno()) + os.replace(tmp_path, path) + tmp_path = None + finally: + if tmp_path is not None: + cleanup_failed_atomic_write(tmp_path) + + def delete(self, binding_id: str) -> bool: + path = self._root() / f"{binding_id}.json" + with _write_lock: + existing = self._read(path) + if existing is None or existing[0] != binding_id: + return False + try: + path.unlink() + except FileNotFoundError: + return False + return True diff --git a/backend/packages/harness/deerflow/persistence/mcp_agent_grants/model.py b/backend/packages/harness/deerflow/persistence/mcp_agent_grants/model.py new file mode 100644 index 0000000000..88852162f1 --- /dev/null +++ b/backend/packages/harness/deerflow/persistence/mcp_agent_grants/model.py @@ -0,0 +1,22 @@ +"""ORM model for runtime MCP agent grants.""" + +from __future__ import annotations + +from datetime import UTC, datetime + +from sqlalchemy import JSON, DateTime, String +from sqlalchemy.orm import Mapped, mapped_column + +from deerflow.persistence.base import Base + + +class McpAgentGrantRow(Base): + __tablename__ = "mcp_agent_grants" + + binding_id: Mapped[str] = mapped_column(String(128), primary_key=True) + grant: Mapped[dict] = mapped_column(JSON, default=dict) + updated_at: Mapped[datetime] = mapped_column( + DateTime(timezone=True), + default=lambda: datetime.now(UTC), + onupdate=lambda: datetime.now(UTC), + ) diff --git a/backend/packages/harness/deerflow/persistence/mcp_agent_grants/sql.py b/backend/packages/harness/deerflow/persistence/mcp_agent_grants/sql.py new file mode 100644 index 0000000000..76a972948b --- /dev/null +++ b/backend/packages/harness/deerflow/persistence/mcp_agent_grants/sql.py @@ -0,0 +1,44 @@ +"""SQL-backed runtime MCP agent grants.""" + +from __future__ import annotations + +from datetime import UTC, datetime + +from sqlalchemy import delete, select +from sqlalchemy.dialects.postgresql import insert as postgres_insert +from sqlalchemy.dialects.sqlite import insert as sqlite_insert + +from deerflow.config.mcp_agent_auth_config import StoredMcpAgentGrant +from deerflow.persistence.agents.sql import get_sync_sessionmaker +from deerflow.persistence.mcp_agent_grants import McpAgentGrantStore +from deerflow.persistence.mcp_agent_grants.model import McpAgentGrantRow + + +class SqlMcpAgentGrantStore(McpAgentGrantStore): + def __init__(self, url: str) -> None: + self._Session = get_sync_sessionmaker(url) + + def get(self, binding_id: str) -> StoredMcpAgentGrant | None: + with self._Session() as session: + document = session.execute(select(McpAgentGrantRow.grant).where(McpAgentGrantRow.binding_id == binding_id)).scalar_one_or_none() + return None if document is None else StoredMcpAgentGrant.model_validate(document) + + def list(self) -> dict[str, StoredMcpAgentGrant]: + with self._Session() as session: + rows = session.execute(select(McpAgentGrantRow.binding_id, McpAgentGrantRow.grant).order_by(McpAgentGrantRow.binding_id.asc())).all() + return {binding_id: StoredMcpAgentGrant.model_validate(document) for binding_id, document in rows} + + def put(self, binding_id: str, grant: StoredMcpAgentGrant) -> None: + values = {"binding_id": binding_id, "grant": grant.model_dump(mode="json"), "updated_at": datetime.now(UTC)} + with self._Session() as session: + insert = postgres_insert if session.get_bind().dialect.name == "postgresql" else sqlite_insert + # Two first writers can both miss a SELECT; upsert on the key instead. + stmt = insert(McpAgentGrantRow).values(**values) + session.execute(stmt.on_conflict_do_update(index_elements=["binding_id"], set_={"grant": stmt.excluded.grant, "updated_at": stmt.excluded.updated_at})) + session.commit() + + def delete(self, binding_id: str) -> bool: + with self._Session() as session: + result = session.execute(delete(McpAgentGrantRow).where(McpAgentGrantRow.binding_id == binding_id)) + session.commit() + return result.rowcount > 0 diff --git a/backend/packages/harness/deerflow/persistence/migrations/versions/0062_mcp_agent_grants.py b/backend/packages/harness/deerflow/persistence/migrations/versions/0062_mcp_agent_grants.py new file mode 100644 index 0000000000..05af12f0dc --- /dev/null +++ b/backend/packages/harness/deerflow/persistence/migrations/versions/0062_mcp_agent_grants.py @@ -0,0 +1,26 @@ +"""Store runtime grants for MCP agent credential bindings.""" + +import sqlalchemy as sa +from alembic import op + +revision = "0062_mcp_agent_grants" +down_revision = "0061_coordination_coordinator" +branch_labels = None +depends_on = None + +_TABLE = "mcp_agent_grants" + + +def upgrade() -> None: + if not sa.inspect(op.get_bind()).has_table(_TABLE): + op.create_table( + _TABLE, + sa.Column("binding_id", sa.String(128), primary_key=True), + sa.Column("grant", sa.JSON(), nullable=False), + sa.Column("updated_at", sa.DateTime(timezone=True), nullable=False), + ) + + +def downgrade() -> None: + if sa.inspect(op.get_bind()).has_table(_TABLE): + op.drop_table(_TABLE) diff --git a/backend/packages/harness/deerflow/persistence/models/__init__.py b/backend/packages/harness/deerflow/persistence/models/__init__.py index f950e0520a..24858e6392 100644 --- a/backend/packages/harness/deerflow/persistence/models/__init__.py +++ b/backend/packages/harness/deerflow/persistence/models/__init__.py @@ -29,6 +29,7 @@ from deerflow.persistence.extension_leases.model import ExtensionExecutionLeaseR from deerflow.persistence.feedback.model import FeedbackRow from deerflow.persistence.login_throttle.model import LoginThrottleRow from deerflow.persistence.managed_subagents.model import ManagedSubagentRow +from deerflow.persistence.mcp_agent_grants.model import McpAgentGrantRow from deerflow.persistence.mcp_oauth_tokens.model import McpOAuthTokenRow from deerflow.persistence.mcp_tasks.model import McpTaskRow from deerflow.persistence.models.run_event import RunEventRow, RunEventThreadSeqRow @@ -70,6 +71,7 @@ __all__ = [ "CoordinationTaskRow", "FeedbackRow", "LoginThrottleRow", + "McpAgentGrantRow", "McpOAuthTokenRow", "McpTaskRow", "ManagedSubagentRow", diff --git a/backend/tests/test_mcp_agent_auth.py b/backend/tests/test_mcp_agent_auth.py index e48f975e34..e877d8a3bf 100644 --- a/backend/tests/test_mcp_agent_auth.py +++ b/backend/tests/test_mcp_agent_auth.py @@ -6,19 +6,30 @@ import json import sys from datetime import UTC, datetime, timedelta from pathlib import Path +from types import SimpleNamespace import httpx import pytest +import sqlalchemy as sa +from alembic import command +from fastapi import HTTPException from langchain_core.tools import ToolException from langchain_mcp_adapters.interceptors import MCPToolCallRequest from langgraph.runtime import Runtime from pydantic import ValidationError +from sqlalchemy.ext.asyncio import create_async_engine from support.mcp_agent_auth import agent_auth_env as agent_auth_env from support.mcp_agent_auth import agent_mcp_transport as agent_mcp_transport from deerflow.config.agents_config import AgentConfig from deerflow.config.app_config import AppConfig, pop_current_app_config, push_current_app_config, reset_app_config, set_app_config from deerflow.config.extensions_config import McpServerConfig +from deerflow.config.mcp_agent_auth_config import McpAgentCredentialBinding, McpAgentGrant, McpAgentGrantSubject, StoredMcpAgentGrant +from deerflow.persistence import bootstrap +from deerflow.persistence.base import Base +from deerflow.persistence.mcp_agent_grants import McpAgentGrantRow, make_mcp_agent_grant_store +from deerflow.persistence.mcp_agent_grants.file import FileMcpAgentGrantStore +from deerflow.persistence.mcp_agent_grants.sql import SqlMcpAgentGrantStore @pytest.mark.parametrize( @@ -619,3 +630,531 @@ async def test_delegation_inherits_parent_identity_including_durable_recovery(ag await restarted.stop() reset_extensions_config() await close_engine() + + +# --- runtime grants (grants: runtime) ------------------------------------------- + + +@pytest.fixture +def runtime_env(agent_auth_env): + """The shared agent_auth fixture, with its binding switched to runtime grants.""" + from deerflow.mcp.agent_auth import agent_definition_digest + + data = agent_auth_env.config.model_dump() + binding = data["mcp_agent_auth"]["research-tickets"] + binding.update(grants="runtime", owners=[], definition_digests=[]) + config = AppConfig.model_validate(data) + set_app_config(config) + store = make_mcp_agent_grant_store(config) + digest = agent_definition_digest(agent_auth_env.agent, agent_auth_env.soul) + + def approve(binding_id, grant, app_config=None): + """Store ``grant`` as an administrator approves it for the binding's current identity.""" + from deerflow.mcp.agent_auth import grant_subject + + app_config = app_config or config + store.put(binding_id, StoredMcpAgentGrant(**grant.model_dump(), approved_for=grant_subject(app_config, app_config.mcp_agent_auth[binding_id]))) + + return SimpleNamespace(**{**vars(agent_auth_env), "config": config, "store": store, "digest": digest, "approve": approve}) + + +def _grant(owners=("alice",), digests=()): + return McpAgentGrant(owners=list(owners), definition_digests=list(digests)) + + +_SUBJECT = McpAgentGrantSubject(agent="research-bot", server="tickets", destination_digest="d" * 64, credential_digest="e" * 64) + + +def _stored(owners=("alice",), digests=()): + return StoredMcpAgentGrant(owners=list(owners), definition_digests=list(digests), approved_for=_SUBJECT) + + +@pytest.mark.parametrize("updates", [{"owners": ["alice"]}, {"definition_digests": ["a" * 64]}]) +def test_runtime_bindings_take_no_grants_from_config(agent_auth_env, updates): + binding = agent_auth_env.config.mcp_agent_auth["research-tickets"].model_dump() + binding.update(grants="runtime", owners=[], definition_digests=[]) + McpAgentCredentialBinding.model_validate(binding) + with pytest.raises(ValidationError, match="admin API"): + McpAgentCredentialBinding.model_validate({**binding, **updates}) + + +@pytest.mark.parametrize("grant", [{"owners": ["*"], "definition_digests": []}, {"owners": ["a", "a"], "definition_digests": []}, {"owners": [], "definition_digests": ["unreviewed"]}, {"owners": []}]) +def test_invalid_runtime_grants_are_rejected(grant): + with pytest.raises(ValidationError): + McpAgentGrant.model_validate(grant) + + +def test_runtime_binding_without_a_grant_admits_nobody(runtime_env): + from deerflow.mcp.agent_auth import capture_agent_authority + + assert capture_agent_authority(runtime_env.config, user_id="alice", agent_config=runtime_env.agent) is None + + +def test_runtime_grant_applies_to_the_next_admission(runtime_env): + from deerflow.mcp.agent_auth import McpAgentAuthorizationError, capture_agent_authority + + env = runtime_env + env.approve("research-tickets", _grant(digests=["0" * 64])) + with pytest.raises(McpAgentAuthorizationError, match="not approved"): + capture_agent_authority(env.config, user_id="alice", agent_config=env.agent) + env.approve("research-tickets", _grant(digests=["0" * 64, env.digest])) + authority = capture_agent_authority(env.config, user_id="alice", agent_config=env.agent) + assert [ref.binding for ref in authority.references] == ["research-tickets"] + assert capture_agent_authority(env.config, user_id="bob", agent_config=env.agent) is None + assert capture_agent_authority(env.config, user_id="alice", agent_config=AgentConfig(name="other")) is None + + +@pytest.mark.asyncio +async def test_removing_a_runtime_owner_denies_the_next_call_with_a_cached_token(runtime_env, monkeypatch): + from deerflow.mcp.agent_auth import AGENT_AUTH_CONTEXT_KEY, build_agent_auth_interceptor, capture_agent_authority + + env = runtime_env + env.approve("research-tickets", _grant(owners=["alice", "bob"], digests=[env.digest])) + authority = capture_agent_authority(env.config, user_id="alice", agent_config=env.agent) + runtime = Runtime(context={"user_id": "alice", AGENT_AUTH_CONTEXT_KEY: authority}) + interceptor = build_agent_auth_interceptor(env.config.extensions) + token_requests, calls = [], [] + + def token_response(request): + token_requests.append(request) + return httpx.Response(200, json={"access_token": "agent-access-token", "expires_in": 3600}) + + real_client = httpx.AsyncClient + monkeypatch.setattr(httpx, "AsyncClient", lambda **kwargs: real_client(transport=httpx.MockTransport(token_response), **kwargs)) + + async def handler(request): + calls.append(request) + return "ok" + + request = MCPToolCallRequest(name="search", args={}, server_name="tickets", runtime=runtime) + assert await interceptor(request, handler) == "ok" + # Approving a new digest leaves admitted runs alone. + env.approve("research-tickets", _grant(owners=["alice", "bob"], digests=["0" * 64])) + assert await interceptor(request, handler) == "ok" + env.approve("research-tickets", _grant(owners=["bob"], digests=[env.digest])) + with pytest.raises(ToolException, match="revoked"): + await interceptor(request, handler) + env.store.delete("research-tickets") + with pytest.raises(ToolException, match="revoked"): + await interceptor(request, handler) + assert len(calls) == 2 and len(token_requests) == 1 + + +@pytest.mark.asyncio +async def test_an_unavailable_grant_store_fails_closed(runtime_env, monkeypatch): + from deerflow.mcp import agent_auth + from deerflow.mcp.agent_auth import AGENT_AUTH_CONTEXT_KEY, McpAgentAuthorizationError, build_agent_auth_interceptor, capture_agent_authority + + env = runtime_env + env.approve("research-tickets", _grant(digests=[env.digest])) + authority = capture_agent_authority(env.config, user_id="alice", agent_config=env.agent) + + class Broken: + def get(self, binding_id): + raise OSError("database is down") + + monkeypatch.setattr("deerflow.persistence.mcp_agent_grants.make_mcp_agent_grant_store", lambda config: Broken()) + with pytest.raises(McpAgentAuthorizationError, match="unavailable"): + capture_agent_authority(env.config, user_id="alice", agent_config=env.agent) + + async def handler(request): + pytest.fail("A call reached the MCP transport without a readable grant") + + monkeypatch.setattr(agent_auth, "_token_manager", lambda *args: pytest.fail("token requested without a grant")) + runtime = Runtime(context={"user_id": "alice", AGENT_AUTH_CONTEXT_KEY: authority}) + with pytest.raises(ToolException, match="unavailable"): + await build_agent_auth_interceptor(env.config.extensions)(MCPToolCallRequest(name="search", args={}, server_name="tickets", runtime=runtime), handler) + + +def test_overlapping_runtime_grants_fail_admission(runtime_env): + from deerflow.mcp.agent_auth import McpAgentAuthorizationError, capture_agent_authority + + env = runtime_env + data = env.config.model_dump() + data["mcp_agent_auth"]["second-grant"] = data["mcp_agent_auth"]["research-tickets"] + config = AppConfig.model_validate(data) + for binding_id in ("research-tickets", "second-grant"): + env.approve(binding_id, _grant(digests=[env.digest]), config) + with pytest.raises(McpAgentAuthorizationError, match="overlap"): + capture_agent_authority(config, user_id="alice", agent_config=env.agent) + + +def _repoint_agent(config): + binding = config.mcp_agent_auth["research-tickets"] + config.mcp_agent_auth["research-tickets"] = binding.model_copy(update={"agent": "other-bot"}) + return "other-bot" + + +def _repoint_server(config): + config.extensions.mcp_servers["tickets-2"] = config.extensions.mcp_servers["tickets"].model_copy(deep=True) + binding = config.mcp_agent_auth["research-tickets"] + config.mcp_agent_auth["research-tickets"] = binding.model_copy(update={"server": "tickets-2"}) + + +def _move_destination(config): + config.extensions.mcp_servers["tickets"].url = "https://other-mcp.example" + + +def _change_oauth(**updates): + def change(config): + binding = config.mcp_agent_auth["research-tickets"] + config.mcp_agent_auth["research-tickets"] = binding.model_copy(update={"oauth": binding.oauth.model_copy(update=updates)}) + + return change + + +@pytest.mark.parametrize( + ("change", "in_force"), + [ + pytest.param(_repoint_agent, False, id="agent"), + pytest.param(_repoint_server, False, id="server"), + pytest.param(_move_destination, False, id="destination"), + pytest.param(_change_oauth(client_id="other-client"), False, id="oauth-client"), + pytest.param(_change_oauth(token_url="https://other-idp.example/token"), False, id="oauth-endpoint"), + pytest.param(_change_oauth(client_secret="rotated-client-secret"), True, id="secret-rotation"), + ], +) +def test_a_runtime_grant_admits_only_for_the_identity_it_was_approved_for(runtime_env, change, in_force): + from deerflow.mcp.agent_auth import agent_definition_digest, capture_agent_authority + + env = runtime_env + other_digest = agent_definition_digest(AgentConfig(name="other-bot"), "") + env.approve("research-tickets", _grant(digests=[env.digest, other_digest])) + config = env.config.model_copy(deep=True) + renamed = change(config) + set_app_config(config) + authority = capture_agent_authority(config, user_id="alice", agent_config=AgentConfig(name=renamed) if renamed else env.agent) + assert (authority is not None) == in_force + if in_force: + assert [ref.binding for ref in authority.references] == ["research-tickets"] + + +# --- stores ------------------------------------------------------------------ + + +@pytest.fixture(params=["file", "sqlite"]) +def store(request, tmp_path, monkeypatch): + if request.param == "file": + monkeypatch.setenv("DEER_FLOW_HOME", str(tmp_path)) + monkeypatch.setattr("deerflow.config.paths._paths", None) + yield FileMcpAgentGrantStore() + return + store = SqlMcpAgentGrantStore(f"sqlite:///{tmp_path}/grants.db") + engine = store._Session.kw["bind"] + try: + Base.metadata.create_all(engine, tables=[McpAgentGrantRow.__table__]) + yield store + finally: + engine.dispose() + + +def test_store_replaces_lists_and_deletes(store): + assert store.get("b1") is None and store.list() == {} + store.put("b1", _stored(owners=["alice"], digests=["a" * 64])) + store.put("b1", _stored(owners=["bob"], digests=["b" * 64])) + store.put("b0", _stored(owners=[])) + assert store.get("b1") == _stored(owners=["bob"], digests=["b" * 64]) + assert list(store.list()) == ["b0", "b1"] + assert store.delete("b1") is True + assert store.delete("b1") is False + assert store.get("b1") is None + + +def test_file_store_never_applies_a_grant_to_another_binding(tmp_path, monkeypatch): + monkeypatch.setenv("DEER_FLOW_HOME", str(tmp_path)) + monkeypatch.setattr("deerflow.config.paths._paths", None) + store = FileMcpAgentGrantStore() + store.put("Tickets", _stored()) + # Simulate a case-insensitive filesystem resolving "tickets" to the same file. + (tmp_path / "mcp-agent-grants" / "tickets.json").write_text((tmp_path / "mcp-agent-grants" / "Tickets.json").read_text()) + assert store.get("tickets") is None + assert store.delete("tickets") is False + with pytest.raises(ValueError, match="differs only in case"): + store.put("tickets", _stored()) + with pytest.raises(ValueError): + store.put("CON", _stored()) + assert json.loads((tmp_path / "mcp-agent-grants" / "Tickets.json").read_text())["binding"] == "Tickets" + + +def test_file_store_treats_a_grant_removed_during_a_read_as_absent(tmp_path, monkeypatch): + monkeypatch.setenv("DEER_FLOW_HOME", str(tmp_path)) + monkeypatch.setattr("deerflow.config.paths._paths", None) + store = FileMcpAgentGrantStore() + store.put("b1", _stored(owners=["alice"])) + store.put("b2", _stored(owners=["bob"])) + root = tmp_path / "mcp-agent-grants" + real_glob = Path.glob + + def glob_then_revoke(self, pattern): + paths = list(real_glob(self, pattern)) + (root / "b1.json").unlink(missing_ok=True) # a concurrent revoke after discovery + return iter(paths) + + monkeypatch.setattr(Path, "glob", glob_then_revoke) + assert list(store.list()) == ["b2"] + assert store.get("b1") is None and store.delete("b1") is False + (root / "b3.json").write_text("{") + with pytest.raises(json.JSONDecodeError): + store.list() + + +@pytest.mark.asyncio +async def test_migration_creates_and_drops_the_table(tmp_path): + engine = create_async_engine(f"sqlite+aiosqlite:///{tmp_path / 'migration.db'}") + cfg = bootstrap._get_alembic_config(engine, postgres_schema="") + + async def tables(): + async with engine.connect() as conn: + return await conn.run_sync(lambda sync: set(sa.inspect(sync).get_table_names())) + + try: + await asyncio.to_thread(command.upgrade, cfg, "0061_coordination_coordinator") + assert "mcp_agent_grants" not in await tables() + await asyncio.to_thread(command.upgrade, cfg, "0062_mcp_agent_grants") + assert "mcp_agent_grants" in await tables() + await asyncio.to_thread(command.downgrade, cfg, "0061_coordination_coordinator") + assert "mcp_agent_grants" not in await tables() + finally: + await engine.dispose() + + +# --- admin API --------------------------------------------------------------- + + +def _request(role: str): + return SimpleNamespace(state=SimpleNamespace(user=SimpleNamespace(system_role=role))) + + +@pytest.fixture +def api_env(runtime_env, monkeypatch): + from app.gateway.routers import mcp_agent_auth as router + + async def drained(action, func, expected_errors=(), /, *args, **kwargs): + return func(*args, **kwargs) + + monkeypatch.setattr(router, "run_drained_write", drained) + data = runtime_env.config.model_dump() + data["mcp_agent_auth"]["config-grant"] = {**data["mcp_agent_auth"]["research-tickets"], "agent": "other-bot", "grants": "config", "owners": ["carol"], "definition_digests": ["c" * 64]} + config = AppConfig.model_validate(data) + set_app_config(config) + return SimpleNamespace(router=router, env=runtime_env, config=config) + + +@pytest.mark.asyncio +async def test_admin_api_requires_an_admin(api_env): + router = api_env.router + for call in ( + router.list_bindings(_request("user")), + router.get_binding("research-tickets", _request("user")), + router.put_grant("research-tickets", _grant(), _request("user")), + router.delete_grant("research-tickets", _request("user")), + router.definition_digest("research-tickets", _request("user"), owner="alice"), + ): + with pytest.raises(HTTPException) as exc: + await call + assert exc.value.status_code == 403 + assert api_env.env.store.get("research-tickets") is None + + +@pytest.mark.asyncio +async def test_admin_api_maintains_runtime_grants(api_env): + router, env = api_env.router, api_env.env + admin = _request("admin") + listed = (await router.list_bindings(admin)).model_dump()["bindings"] + assert [(b["binding"], b["grants"], b["approval"], b["owners"]) for b in listed] == [("config-grant", "config", "config", ["carol"]), ("research-tickets", "runtime", "none", [])] + assert all("oauth" not in b and "client_secret" not in json.dumps(b) for b in listed) + + digest = await router.definition_digest("research-tickets", admin, owner="alice") + assert digest.definition_digest == env.digest + response = await router.put_grant("research-tickets", _grant(owners=["alice"], digests=[digest.definition_digest]), admin) + assert response.owners == ["alice"] and response.definition_digests == [env.digest] and response.approval == "current" + assert (await router.get_binding("research-tickets", admin)).owners == ["alice"] + + from deerflow.mcp.agent_auth import capture_agent_authority + + assert capture_agent_authority(api_env.config, user_id="alice", agent_config=env.agent) is not None + assert (await router.delete_grant("research-tickets", admin)).status_code == 204 + assert capture_agent_authority(api_env.config, user_id="alice", agent_config=env.agent) is None + + +@pytest.mark.asyncio +async def test_admin_api_reports_and_replaces_a_stale_grant(api_env): + from deerflow.mcp.agent_auth import capture_agent_authority + + router, env = api_env.router, api_env.env + admin = _request("admin") + assert (await router.get_binding("research-tickets", admin)).approval == "none" + assert (await router.put_grant("research-tickets", _grant(owners=["alice"], digests=[env.digest]), admin)).approval == "current" + moved = api_env.config.model_copy(deep=True) + _change_oauth(client_id="other-client")(moved) + set_app_config(moved) + stale = await router.get_binding("research-tickets", admin) + assert (stale.approval, stale.owners) == ("stale", ["alice"]) + assert capture_agent_authority(moved, user_id="alice", agent_config=env.agent) is None + # A stale grant admits nobody but keeps its owners reserved: a rollback makes it current again. + data = moved.model_dump() + data["mcp_agent_auth"]["research-tickets-2"] = {**data["mcp_agent_auth"]["research-tickets"]} + with_second = AppConfig.model_validate(data) + set_app_config(with_second) + with pytest.raises(HTTPException) as exc: + await router.put_grant("research-tickets-2", _grant(owners=["alice"]), admin) + assert exc.value.status_code == 409 and "research-tickets'" in exc.value.detail + set_app_config(api_env.config) # roll the OAuth client back + assert (await router.get_binding("research-tickets", admin)).approval == "current" + assert capture_agent_authority(api_env.config, user_id="alice", agent_config=env.agent) is not None + # Deleting the stale grant releases its owners. + set_app_config(with_second) + assert (await router.delete_grant("research-tickets", admin)).status_code == 204 + assert (await router.put_grant("research-tickets-2", _grant(owners=["alice"]), admin)).approval == "current" + with pytest.raises(HTTPException) as exc: + await router.put_grant("research-tickets", _grant(owners=["alice"], digests=[env.digest]), admin) + assert exc.value.status_code == 409 + assert (await router.put_grant("research-tickets", _grant(owners=["bob"], digests=[env.digest]), admin)).approval == "current" + + +@pytest.mark.asyncio +async def test_admin_api_lists_reserves_and_deletes_a_retired_grant(api_env): + router, env = api_env.router, api_env.env + admin = _request("admin") + await router.put_grant("research-tickets", _grant(owners=["alice"], digests=[env.digest]), admin) + # GitOps renames the binding: the old grant is retired, not gone. + data = api_env.config.model_dump() + data["mcp_agent_auth"]["tickets"] = data["mcp_agent_auth"].pop("research-tickets") + set_app_config(AppConfig.model_validate(data)) + listed = (await router.list_bindings(admin)).model_dump()["bindings"] + assert [(b["binding"], b["approval"], b["agent"], b["owners"]) for b in listed][-1] == ("research-tickets", "retired", env.agent.name, ["alice"]) + assert (await router.get_binding("research-tickets", admin)).approval == "retired" + with pytest.raises(HTTPException) as exc: + await router.put_grant("tickets", _grant(owners=["alice"], digests=[env.digest]), admin) + assert exc.value.status_code == 409 and "research-tickets" in exc.value.detail + assert (await router.delete_grant("research-tickets", admin)).status_code == 204 + assert (await router.put_grant("tickets", _grant(owners=["alice"], digests=[env.digest]), admin)).approval == "current" + with pytest.raises(HTTPException) as exc: + await router.get_binding("research-tickets", admin) + assert exc.value.status_code == 404 + with pytest.raises(HTTPException) as exc: + await router.delete_grant("research-tickets", admin) + assert exc.value.status_code == 404 + + +@pytest.mark.asyncio +async def test_admin_api_shows_a_stored_grant_after_a_switch_to_config_grants(api_env): + router, env = api_env.router, api_env.env + admin = _request("admin") + await router.put_grant("research-tickets", _grant(owners=["alice"], digests=[env.digest]), admin) + # GitOps moves the binding to config grants; the runtime grant stays stored and keeps alice reserved. + data = api_env.config.model_dump() + data["mcp_agent_auth"]["research-tickets"] |= {"grants": "config", "owners": ["bob"], "definition_digests": [env.digest]} + data["mcp_agent_auth"]["research-tickets-2"] = {**api_env.config.model_dump()["mcp_agent_auth"]["research-tickets"]} + set_app_config(AppConfig.model_validate(data)) + expected = {"server": "tickets", "agent": env.agent.name, "owners": ["alice"], "definition_digests": [env.digest]} + shown = (await router.get_binding("research-tickets", admin)).model_dump() + assert (shown["approval"], shown["owners"], shown["stored_grant"]) == ("config", ["bob"], expected) + listed = {b["binding"]: b for b in (await router.list_bindings(admin)).model_dump()["bindings"]} + assert listed["research-tickets"]["stored_grant"] == expected + assert listed["config-grant"]["stored_grant"] is None and listed["research-tickets-2"]["stored_grant"] is None + # The 409 names a binding whose details now show the reserved owner. + with pytest.raises(HTTPException) as exc: + await router.put_grant("research-tickets-2", _grant(owners=["alice"]), admin) + assert exc.value.status_code == 409 and "research-tickets'" in exc.value.detail + assert (await router.delete_grant("research-tickets", admin)).status_code == 204 + assert (await router.get_binding("research-tickets", admin)).stored_grant is None + assert (await router.put_grant("research-tickets-2", _grant(owners=["alice"]), admin)).owners == ["alice"] + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + ("call", "status"), + [ + (lambda r, admin: r.put_grant("config-grant", _grant(), admin), 409), + (lambda r, admin: r.delete_grant("config-grant", admin), 409), + (lambda r, admin: r.put_grant("missing", _grant(), admin), 404), + (lambda r, admin: r.get_binding("missing", admin), 404), + (lambda r, admin: r.delete_grant("research-tickets", admin), 404), + (lambda r, admin: r.definition_digest("research-tickets", admin, owner="bob"), 404), + ], +) +async def test_admin_api_refuses_what_it_does_not_own(api_env, call, status): + with pytest.raises(HTTPException) as exc: + await call(api_env.router, _request("admin")) + assert exc.value.status_code == status + assert api_env.config.mcp_agent_auth["config-grant"].owners == ["carol"] + + +@pytest.mark.asyncio +async def test_admin_api_rejects_owners_granted_by_another_binding(api_env): + router, env = api_env.router, api_env.env + data = api_env.config.model_dump() + data["mcp_agent_auth"]["research-tickets-2"] = {**data["mcp_agent_auth"]["research-tickets"]} + data["mcp_agent_auth"]["config-grant"]["agent"] = env.agent.name + set_app_config(AppConfig.model_validate(data)) + admin = _request("admin") + await router.put_grant("research-tickets", _grant(owners=["alice"], digests=[env.digest]), admin) + for binding_id, owners in (("research-tickets-2", ["bob", "alice"]), ("research-tickets", ["carol"])): + with pytest.raises(HTTPException) as exc: + await router.put_grant(binding_id, _grant(owners=owners), admin) + assert exc.value.status_code == 409 and "overlap" in exc.value.detail + await router.put_grant("research-tickets-2", _grant(owners=["bob"]), admin) + + +@pytest.mark.asyncio +async def test_admin_api_keeps_owners_reserved_while_a_binding_is_disabled(api_env): + router, env = api_env.router, api_env.env + data = api_env.config.model_dump() + data["mcp_agent_auth"]["research-tickets-2"] = {**data["mcp_agent_auth"]["research-tickets"]} + data["mcp_agent_auth"]["config-grant"]["agent"] = env.agent.name + set_app_config(AppConfig.model_validate(data)) + admin = _request("admin") + await router.put_grant("research-tickets", _grant(owners=["alice"], digests=[env.digest]), admin) + + def disable(*binding_ids): + changed = AppConfig.model_validate(data).model_dump() + for binding_id in binding_ids: + changed["mcp_agent_auth"][binding_id]["enabled"] = False + set_app_config(AppConfig.model_validate(changed)) + + # Disabling the binding that holds the grant keeps its owner reserved. + disable("research-tickets") + with pytest.raises(HTTPException) as exc: + await router.put_grant("research-tickets-2", _grant(owners=["alice"]), admin) + assert exc.value.status_code == 409 and "research-tickets'" in exc.value.detail + # A grant written to a disabled binding is checked too, against stored and configured owners. + disable("research-tickets-2") + for owners, holder in ((["alice"], "research-tickets'"), (["carol"], "config-grant'")): + with pytest.raises(HTTPException) as exc: + await router.put_grant("research-tickets-2", _grant(owners=owners), admin) + assert exc.value.status_code == 409 and holder in exc.value.detail + # A disabled config binding keeps its owners reserved as well. + disable("config-grant") + with pytest.raises(HTTPException) as exc: + await router.put_grant("research-tickets-2", _grant(owners=["carol"]), admin) + assert exc.value.status_code == 409 and "config-grant'" in exc.value.detail + # Deleting the grant releases its owner. + assert (await router.delete_grant("research-tickets", admin)).status_code == 204 + assert (await router.put_grant("research-tickets-2", _grant(owners=["alice"]), admin)).owners == ["alice"] + + +def test_admin_api_routes_validate_over_http(api_env): + from fastapi import FastAPI + from fastapi.testclient import TestClient + + app = FastAPI() + app.include_router(api_env.router.router) + + @app.middleware("http") + async def as_admin(request, call_next): + request.state.user = SimpleNamespace(system_role="admin") + return await call_next(request) + + client = TestClient(app) + digest = api_env.env.digest + assert client.put("/api/mcp/agent-auth/research-tickets/grants", json={"owners": ["alice"], "definition_digests": [digest]}).status_code == 200 + assert client.get("/api/mcp/agent-auth/research-tickets").json()["owners"] == ["alice"] + assert client.put("/api/mcp/agent-auth/research-tickets/grants", json={"owners": ["*"], "definition_digests": []}).status_code == 422 + assert client.put("/api/mcp/agent-auth/research-tickets/grants", json={"owners": [], "definition_digests": [], "extra": 1}).status_code == 422 + assert client.get("/api/mcp/agent-auth/-bad").status_code == 422 + assert client.get("/api/mcp/agent-auth/research-tickets/definition-digest", params={"owner": "alice"}).json()["definition_digest"] == digest + for owner in ("alice@example.com", "../alice"): # file-backed storage cannot hold these owners + assert client.get("/api/mcp/agent-auth/research-tickets/definition-digest", params={"owner": owner}).status_code == 422 + assert client.get("/api/mcp/agent-auth/research-tickets/definition-digest", params={"owner": "nobody"}).status_code == 404 + assert client.delete("/api/mcp/agent-auth/research-tickets/grants").status_code == 204 diff --git a/backend/tests/test_migration_0047_mcp_oauth_tokens.py b/backend/tests/test_migration_0047_mcp_oauth_tokens.py index 84ff431f94..e1b7876856 100644 --- a/backend/tests/test_migration_0047_mcp_oauth_tokens.py +++ b/backend/tests/test_migration_0047_mcp_oauth_tokens.py @@ -21,7 +21,8 @@ from deerflow.persistence.mcp_oauth_tokens import McpOAuthTokenRow from deerflow.persistence.postgres_schema import build_asyncpg_connect_args REVISION = "0047_mcp_oauth_tokens" -HEAD = "0061_coordination_coordinator" +HEAD = "0062_mcp_agent_grants" +COORDINATOR_REVISION = "0061_coordination_coordinator" COORDINATION_RUN_SETTINGS_REVISION = "0060_coordination_run_settings" COORDINATION_GRANTS_REVISION = "0059_coordination_grants" BROWSER_OAUTH_REVISION = "0058_mcp_browser_oauth" @@ -51,7 +52,8 @@ async def test_0047_remains_in_the_single_migration_chain(): assert bootstrap._get_head_revision() == HEAD script = ScriptDirectory(str(bootstrap._MIGRATIONS_DIR)) assert script.get_heads() == [HEAD] - assert script.get_revision(HEAD).down_revision == COORDINATION_RUN_SETTINGS_REVISION + assert script.get_revision(HEAD).down_revision == COORDINATOR_REVISION + assert script.get_revision(COORDINATOR_REVISION).down_revision == COORDINATION_RUN_SETTINGS_REVISION assert script.get_revision(COORDINATION_RUN_SETTINGS_REVISION).down_revision == COORDINATION_GRANTS_REVISION assert script.get_revision(COORDINATION_GRANTS_REVISION).down_revision == BROWSER_OAUTH_REVISION assert script.get_revision(BROWSER_OAUTH_REVISION).down_revision == "0057_coordination_workers" diff --git a/config.example.yaml b/config.example.yaml index 067c8fdfe5..a5a3509da6 100644 --- a/config.example.yaml +++ b/config.example.yaml @@ -3109,6 +3109,8 @@ mcp_agent_auth: {} # agent: research-bot # owners: ["member-user-id"] # Explicit IDs; one list may cover shared copies. # definition_digests: [""] +# # Or grants: runtime (no owners/definition_digests here): an administrator +# # maintains them via /api/mcp/agent-auth without a restart. # oauth: # grant_type: client_credentials # token_url: https://idp.example/realms/work/protocol/openid-connect/token