Enterprise agent platform for building, deploying, and operating AI teammates.
feat(v1): list an agent's runtime keys and revoke one of them (#3789)
Alex Liu5f508390cb20
diff --git a/src/xagent/web/api/v1/agents.py b/src/xagent/web/api/v1/agents.pyindex 0ab851882..313ab74ba 100644--- a/src/xagent/web/api/v1/agents.py+++ b/src/xagent/web/api/v1/agents.py@@ -1,8 +1,10 @@"""SDK management endpoints for user-owned agents."""-from fastapi import APIRouter, Depends, Path, Request+from fastapi import APIRouter, Depends, Path, Query, Requestfrom ...schemas.v1 import (+ AgentRuntimeKeyItem,+ AgentRuntimeKeyRevokeResponse,RuntimeKeyResponse,V1AgentConnectorsResponse,V1AgentConnectorsUpdateRequest,@@ -32,7 +34,12 @@ from ...services.agent_management import (TemplateNotFoundError,WorkforceTemplateNotSupportedError,)-from ...services.api_keys import KeyRotationConflict+from ...services.api_keys import (+ AgentKeyMetadata,+ AgentKeyRevocation,+ AgentRuntimeKeyNotFoundError,+ KeyRotationConflict,+)from .deps import (PersonalApiKeySnapshot,UserPrincipalSnapshot,@@ -51,6 +58,30 @@ def _runtime_key_response(api_key: RuntimeKeySnapshot) -> RuntimeKeyResponse:)+def _runtime_key_item(key: AgentKeyMetadata) -> AgentRuntimeKeyItem:+ return AgentRuntimeKeyItem(+ id=key.id,+ label=key.label,+ key_prefix=key.key_prefix,+ masked_key=key.masked_key,+ status=key.status,+ created_at=key.created_at,+ last_used_at=key.last_used_at,+ revoked_at=key.revoked_at,+ )+++def _runtime_key_revoke_response(+ revocation: AgentKeyRevocation,+) -> AgentRuntimeKeyRevokeResponse:+ return AgentRuntimeKeyRevokeResponse(+ id=revocation.key_id,+ key_prefix=revocation.key_prefix,+ revoked=revocation.revoked,+ revoked_at=revocation.revoked_at,+ )++def _agent_response(agent: AgentResponseSnapshot) -> V1AgentResponse:return V1AgentResponse.model_validate(agent.to_response_dict())@@ -223,6 +254,61 @@ async def rotate_agent_runtime_key(return _runtime_key_response(api_key)[email protected]("/{agent_id}/api-keys", response_model=list[AgentRuntimeKeyItem])+async def list_agent_runtime_keys(+ # ``agents.id`` is a 32-bit integer column.+ agent_id: int = Path(gt=0, le=2**31 - 1),+ include_revoked: bool = Query(False),+ authed: tuple[UserPrincipalSnapshot, PersonalApiKeySnapshot] = Depends(+ get_user_from_personal_key+ ),+) -> list[AgentRuntimeKeyItem]:+ """List the runtime keys of an agent the key holder can manage.++ Revoked keys are left out unless ``include_revoked`` is set. No response+ carries a key's secret.+ """+ user, _key = authed+ keys = await AgentManagementRuntime().list_agent_runtime_keys(+ user_id=int(user.id), agent_id=agent_id, include_revoked=include_revoked+ )+ if keys is None:+ raise V1ApiError(V1ErrorCode.AGENT_NOT_FOUND, 404)+ return [_runtime_key_item(key) for key in keys]+++ "/{agent_id}/api-keys/{key_id}", response_model=AgentRuntimeKeyRevokeResponse+)+async def revoke_agent_runtime_key(+ # ``agents.id`` and ``agent_api_keys.id`` are 32-bit integer columns.+ agent_id: int = Path(gt=0, le=2**31 - 1),+ key_id: int = Path(gt=0, le=2**31 - 1),+ authed: tuple[UserPrincipalSnapshot, PersonalApiKeySnapshot] = Depends(+ get_user_from_personal_key+ ),+) -> AgentRuntimeKeyRevokeResponse:+ """Revoke one runtime key of an agent the key holder can manage.++ The agent's other keys keep working. Revoking an already revoked key is+ a no-op that reports ``revoked=false``. A key id that is not bound to+ this agent is ``api_key_not_found`` whether or not it exists elsewhere.+ """+ user, key = authed+ try:+ revocation = await AgentManagementRuntime().revoke_agent_runtime_key(+ user_id=int(user.id),+ credential_ref=f"personal_key:{key.key_prefix}",+ agent_id=agent_id,+ key_id=key_id,+ )+ except AgentRuntimeKeyNotFoundError:+ raise V1ApiError(V1ErrorCode.API_KEY_NOT_FOUND, 404)+ if revocation is None:+ raise V1ApiError(V1ErrorCode.AGENT_NOT_FOUND, 404)+ return _runtime_key_revoke_response(revocation)++@router.get("/{agent_id}/skills", response_model=V1AgentSkillsResponse)async def get_agent_skills(# ``agents.id`` is a 32-bit integer column.diff --git a/src/xagent/web/api/v1/errors.py b/src/xagent/web/api/v1/errors.pyindex 8789f3db2..be9eebff9 100644--- a/src/xagent/web/api/v1/errors.py+++ b/src/xagent/web/api/v1/errors.py@@ -109,6 +109,12 @@ class V1ErrorCode(str, Enum):# Template id is unknown or unavailable to the caller.TEMPLATE_NOT_FOUND = "template_not_found"+ # The agent is manageable by the caller but has no runtime key with the+ # requested id. 404 -- distinct from agent_not_found so SDK clients can+ # tell "bad key id" from "bad agent id". A key bound to another agent or+ # to a workforce is reported the same way as an id that does not exist.+ API_KEY_NOT_FOUND = "api_key_not_found"+# No skill the key holder can see has this name (GET), or the name does# not address a personal skill the holder owns (PUT / DELETE). 404.SKILL_NOT_FOUND = "skill_not_found"@@ -283,6 +289,7 @@ _DEFAULT_MESSAGES: dict[V1ErrorCode, str] = {"This task's conversation was removed under the retention policy."),V1ErrorCode.TEMPLATE_NOT_FOUND: "Template not found.",+ V1ErrorCode.API_KEY_NOT_FOUND: "API key not found for this agent.",V1ErrorCode.SKILL_NOT_FOUND: "Skill not found.",V1ErrorCode.SKILL_ALREADY_EXISTS: "A skill with this name already exists.",V1ErrorCode.TASK_BUSY: "Task is currently running; retry after it completes.",diff --git a/src/xagent/web/schemas/v1.py b/src/xagent/web/schemas/v1.pyindex b814c0147..34a9fc95e 100644--- a/src/xagent/web/schemas/v1.py+++ b/src/xagent/web/schemas/v1.py@@ -256,6 +256,39 @@ class RuntimeKeyResponse(BaseModel):created_at: datetime+class AgentRuntimeKeyItem(BaseModel):+ """One runtime key of an agent, as listed by+ ``GET /v1/agents/{agent_id}/api-keys``.++ Never carries the secret: ``masked_key`` shows the public prefix followed+ by a fixed number of bullets, and the full key is only ever returned once,+ by the call that created it.+ """++ id: int+ label: Optional[str] = None+ key_prefix: str+ masked_key: str+ status: Literal["active", "paused", "revoked"]+ created_at: datetime+ last_used_at: Optional[datetime] = None+ revoked_at: Optional[datetime] = None+++class AgentRuntimeKeyRevokeResponse(BaseModel):+ """Result of ``DELETE /v1/agents/{agent_id}/api-keys/{key_id}``.++ ``revoked`` is ``True`` when this call revoked the key and ``False`` when+ it had already been revoked; ``revoked_at`` is when the key was revoked+ either way. ``key_prefix`` identifies the secret that was revoked.+ """++ id: int+ key_prefix: str+ revoked: bool+ revoked_at: datetime++class V1AgentCreateRequest(BaseModel):"""Body for ``POST /v1/agents``."""diff --git a/src/xagent/web/services/agent_management.py b/src/xagent/web/services/agent_management.pyindex 1df69e528..935e9fa39 100644--- a/src/xagent/web/services/agent_management.py+++ b/src/xagent/web/services/agent_management.py@@ -43,6 +43,8 @@ from ..services.agent_store import (from .agent_team_scope import get_agent_team_scopefrom .api_keys import (AgentApiKeyService,+ AgentKeyMetadata,+ AgentKeyRevocation,ApiKeyCandidate,KeyRotationConflict,RuntimeKeyDeliveryError,@@ -1483,6 +1485,114 @@ class AgentManagementRuntime:)return _connector_selection(stored, names.visible)+ async def list_agent_runtime_keys(+ self,+ *,+ user_id: int,+ agent_id: int,+ include_revoked: bool = False,+ ) -> tuple[AgentKeyMetadata, ...] | None:+ """The runtime keys of an agent the user can manage, newest first.++ Returns ``None`` when the user cannot manage the agent; that is+ decided before any key is read. An agent without matching keys is an+ empty tuple. Revoked keys are left out unless ``include_revoked``.+ A failed read propagates.+ """+ return await run_db_io_cancellation_safe(+ lambda: self._list_agent_runtime_keys_sync(+ user_id=user_id,+ agent_id=agent_id,+ include_revoked=include_revoked,+ )+ )++ @staticmethod+ def _list_agent_runtime_keys_sync(+ *, user_id: int, agent_id: int, include_revoked: bool+ ) -> tuple[AgentKeyMetadata, ...] | None:+ SessionLocal = get_session_local()+ with SessionLocal() as db:+ team_scope = get_agent_team_scope(db, user_id)+ if AgentStore(db).get_owned_agent(user_id, agent_id, team_scope) is None:+ return None+ return tuple(+ AgentApiKeyService(db).list_keys_for_agent(+ agent_id, include_revoked=include_revoked+ )+ )++ async def revoke_agent_runtime_key(+ self,+ *,+ user_id: int,+ credential_ref: str,+ agent_id: int,+ key_id: int,+ ) -> AgentKeyRevocation | None:+ """Revoke one runtime key of an agent the user can manage.++ Returns ``None`` when the user cannot manage the agent. That is+ checked before the agent row is locked and before any key is read,+ and again under the agent's runtime-key transition fence with a+ freshly resolved team scope, which is the check that decides. Raises+ :class:`~.api_keys.AgentRuntimeKeyNotFoundError` when the agent has no key with+ this id. Revoking an already revoked key changes nothing and reports+ ``revoked=False`` with the original time. A failed commit propagates+ and leaves the key as it was.++ ``credential_ref`` names the credential the request was made with and+ is only written to the log line of an effective revocation.+ """+ return await run_db_io_cancellation_safe(+ lambda: self._revoke_agent_runtime_key_sync(+ user_id=user_id,+ credential_ref=credential_ref,+ agent_id=agent_id,+ key_id=key_id,+ )+ )++ @staticmethod+ def _revoke_agent_runtime_key_sync(+ *, user_id: int, credential_ref: str, agent_id: int, key_id: int+ ) -> AgentKeyRevocation | None:+ SessionLocal = get_session_local()+ with SessionLocal() as db:+ store = AgentStore(db)+ if (+ store.get_owned_agent(+ user_id, agent_id, get_agent_team_scope(db, user_id)+ )+ is None+ ):+ return None+ if not acquire_runtime_key_transition_fence(db, agent_id):+ return None+ # The fence serializes changes to the agent row. Resolve the team+ # scope again so a membership change committed since the first+ # check is honored as well.+ if (+ store.get_owned_agent(+ user_id, agent_id, get_agent_team_scope(db, user_id)+ )+ is None+ ):+ return None+ revocation = AgentApiKeyService(db).revoke_key_for_agent(agent_id, key_id)+ db.commit()+ if revocation.revoked:+ logger.info(+ "runtime key revoked: credential=%s user_id=%d agent_id=%d "+ "key_id=%d key_prefix=%s",+ credential_ref,+ user_id,+ agent_id,+ revocation.key_id,+ revocation.key_prefix,+ )+ return revocation+@staticmethoddef _run_runtime_key_session_operation(operation: Callable[diff --git a/src/xagent/web/services/api_keys.py b/src/xagent/web/services/api_keys.pyindex 93c3c254c..0af5851cc 100644--- a/src/xagent/web/services/api_keys.py+++ b/src/xagent/web/services/api_keys.py@@ -6,7 +6,7 @@ import loggingfrom dataclasses import dataclassfrom datetime import datetime, timezonefrom types import TracebackType-from typing import Any, Callable, NamedTuple, TypeVar+from typing import Any, Callable, NamedTuple, TypeVar, castfrom sqlalchemy import func, or_, select, textfrom sqlalchemy.exc import IntegrityError, NoResultFound@@ -59,6 +59,34 @@ class RuntimeKeyReceipt:raise ValueError("Replaced runtime keys require a rotation timestamp.")+@dataclass(frozen=True)+class AgentKeyMetadata:+ """Detached, secret-free description of one key of an agent."""++ id: int+ label: str | None+ key_prefix: str+ masked_key: str+ status: str+ created_at: datetime+ last_used_at: datetime | None+ revoked_at: datetime | None+++@dataclass(frozen=True)+class AgentKeyRevocation:+ """Outcome of revoking one key of one agent.++ ``revoked`` is True when this call revoked the key and False when it was+ already revoked; ``revoked_at`` is the stored timestamp either way.+ """++ key_id: int+ key_prefix: str+ revoked: bool+ revoked_at: datetime++class RuntimeKeyDeliveryError(Exception):"""Carry a possibly committed key transition through worker teardown.@@ -85,6 +113,10 @@ class KeyRotationConflict(RuntimeError):"""A key-prefix conflict that was rolled back before delivery."""+class AgentRuntimeKeyNotFoundError(LookupError):+ """The agent has no runtime key with the requested id."""++def acquire_runtime_key_transition_fence(db: Session, agent_id: int) -> bool:"""Serialize runtime-key transitions for one agent in every database.@@ -116,6 +148,10 @@ def _key_status(row: AgentApiKey) -> str:return "active"+def _normalized_or_none(value: Any) -> datetime | None:+ return None if value is None else normalize_datetime_from_db(value)++def _masked_key(row: AgentApiKey) -> str:return f"xag_{row.key_prefix}_••••••••"@@ -360,6 +396,97 @@ class AgentApiKeyService:logger.info("Revoked runtime API key for agent %s", agent_id)return APIKeyRevokeResponse(revoked=True, revoked_at=now)+ def list_keys_for_agent(+ self, agent_id: int, *, include_revoked: bool = False+ ) -> list[AgentKeyMetadata]:+ """The keys bound to one agent, newest first, without any secret.++ Performs no authorization: the caller must already have established+ that the requester may manage ``agent_id``. Only rows whose+ ``agent_id`` matches are returned, so a workforce-bound key or+ another agent's key is never part of the result. Paused keys are+ always returned; revoked keys only when ``include_revoked`` is set.+ """+ query = self.db.query(AgentApiKey).filter(AgentApiKey.agent_id == agent_id)+ if not include_revoked:+ query = query.filter(AgentApiKey.revoked_at.is_(None))+ rows = query.order_by(+ AgentApiKey.created_at.desc(), AgentApiKey.id.desc()+ ).all()+ return [+ AgentKeyMetadata(+ id=int(row.id),+ label=cast("str | None", row.label),+ key_prefix=str(row.key_prefix),+ masked_key=_masked_key(row),+ status=_key_status(row),+ created_at=normalize_datetime_from_db(cast(datetime, row.created_at)),+ last_used_at=_normalized_or_none(row.last_used_at),+ revoked_at=_normalized_or_none(row.revoked_at),+ )+ for row in rows+ ]++ def revoke_key_for_agent(self, agent_id: int, key_id: int) -> AgentKeyRevocation:+ """Stage the revocation of one key of one agent.++ Performs no authorization and does NOT commit: the caller must have+ established, under the agent's runtime-key transition fence, that the+ requester may manage ``agent_id``, and owns the transaction boundary.++ The write is one conditional UPDATE matching the key id, the agent id+ and ``revoked_at IS NULL`` together, so it can neither revoke a key+ bound elsewhere nor overwrite an earlier revocation timestamp. A key+ that was already revoked is reported with ``revoked=False`` and its+ original timestamp.++ Known window: because an already revoked key is left untouched, this+ does not turn a rotation's revocation into an explicit one. If a+ rotation revoked the key and is later compensated (its new key could+ not be delivered), the compensation restores every replaced key whose+ ``revoked_at`` still equals the rotation timestamp, including a key+ for which this method reported ``revoked=False`` in between. A caller+ that must be certain should list the agent's keys again once the+ rotation has settled.++ Raises :class:`AgentRuntimeKeyNotFoundError` when ``agent_id`` has no+ key with this id.+ """+ now = datetime.now(timezone.utc)+ updated_count = (+ self.db.query(AgentApiKey)+ .filter(+ AgentApiKey.id == key_id,+ AgentApiKey.agent_id == agent_id,+ AgentApiKey.revoked_at.is_(None),+ )+ .update(+ {AgentApiKey.revoked_at: now, AgentApiKey.updated_at: now},+ synchronize_session=False,+ )+ )+ row = (+ self.db.query(AgentApiKey.key_prefix, AgentApiKey.revoked_at)+ .filter(AgentApiKey.id == key_id, AgentApiKey.agent_id == agent_id)+ .first()+ )+ if row is None:+ raise AgentRuntimeKeyNotFoundError(+ f"Agent {int(agent_id)} has no key {int(key_id)}."+ )+ key_prefix, revoked_at = row+ if revoked_at is None:+ raise RuntimeError(+ f"Key {int(key_id)} of agent {int(agent_id)} is still active "+ "after its revocation was staged."+ )+ return AgentKeyRevocation(+ key_id=int(key_id),+ key_prefix=str(key_prefix),+ revoked=updated_count == 1,+ revoked_at=normalize_datetime_from_db(revoked_at),+ )+# ===== Multi-key admin operations (centralized "API Keys" page) =====## Unlike the rotate/get/revoke trio above -- which enforce "at most onediff --git a/tests/web/api/v1/test_agent_runtime_keys.py b/tests/web/api/v1/test_agent_runtime_keys.pynew file mode 100644index 000000000..badd41f83--- /dev/null+++ b/tests/web/api/v1/test_agent_runtime_keys.py@@ -0,0 +1,709 @@+"""Integration tests for listing and revoking an agent's runtime keys over /v1."""++import logging+from datetime import datetime, timedelta, timezone++import pytest+from sqlalchemy import event+from sqlalchemy.orm import Session++from xagent.core.utils.api_key import ApiKeyKind, generate_api_key+from xagent.web.models.agent import AgentOrigin+from xagent.web.models.agent_api_key import AgentApiKey+from xagent.web.models.database import get_engine+from xagent.web.models.workforce import Workforce+from xagent.web.services import agent_management+from xagent.web.services.agent_team_scope import (+ AgentTeamScope,+ set_agent_team_scope_hook,+)+from xagent.web.services.api_keys import (+ AgentApiKeyService,+ AgentRuntimeKeyNotFoundError,+)++from ..conftest import _admin_headers, _direct_db_session, _register_second_user, client+from .test_agent_skills import _seed_agent, _set_visibility, _user_id+from .test_management import _bearer, _personal_key+from .test_skills import _error++pytestmark = pytest.mark.usefixtures("_test_db")++_ITEM_FIELDS = {+ "id",+ "label",+ "key_prefix",+ "masked_key",+ "status",+ "created_at",+ "last_used_at",+ "revoked_at",+}+_REVOCATION_FIELDS = {"id", "key_prefix", "revoked", "revoked_at"}+_MISSING_ID = 999_999+++def team_scopes():+ """Team scopes by user id, as an application that groups users installs."""+ scopes: dict[int, AgentTeamScope] = {}+ set_agent_team_scope_hook(lambda _db, user_id: scopes.get(int(user_id)))+ yield scopes+ set_agent_team_scope_hook(None)+++# ===== helpers =====+++class _Key:+ def __init__(self, key_id: int, full_key: str, key_prefix: str, key_hash: str):+ self.id = key_id+ self.full_key = full_key+ self.key_prefix = key_prefix+ self.key_hash = key_hash+++def _seed_key(+ agent_id: int | None = None,+ *,+ workforce_id: int | None = None,+ label: str | None = None,+ paused: bool = False,+ revoked_at: datetime | None = None,+ created_at: datetime | None = None,+ last_used_at: datetime | None = None,+) -> _Key:+ db = _direct_db_session()+ try:+ full_key, key_prefix, key_hash = generate_api_key(db, kind=ApiKeyKind.AGENT)+ row = AgentApiKey(+ agent_id=agent_id,+ workforce_id=workforce_id,+ label=label,+ key_prefix=key_prefix,+ key_hash=key_hash,+ paused_at=datetime.now(timezone.utc) if paused else None,+ revoked_at=revoked_at,+ last_used_at=last_used_at,+ )+ if created_at is not None:+ row.created_at = created_at+ db.add(row)+ db.commit()+ return _Key(int(row.id), full_key, key_prefix, key_hash)+ finally:+ db.close()+++def _seed_workforce_key(owner: str = "admin") -> _Key:+ manager_id = _seed_agent(+ owner, origin=AgentOrigin.WORKFORCE_GENERATED_MANAGER.value+ )+ db = _direct_db_session()+ try:+ workforce = Workforce(+ owner_user_id=_user_id(owner),+ scope_id=str(_user_id(owner)),+ name="crew",+ manager_agent_id=manager_id,+ )+ db.add(workforce)+ db.commit()+ workforce_id = int(workforce.id)+ finally:+ db.close()+ return _seed_key(workforce_id=workforce_id)+++def _key_table() -> list[tuple]:+ db = _direct_db_session()+ try:+ return [+ (+ row.id,+ row.agent_id,+ row.workforce_id,+ row.label,+ row.key_prefix,+ row.key_hash,+ row.paused_at,+ row.revoked_at,+ row.updated_at,+ )+ for row in db.query(AgentApiKey).order_by(AgentApiKey.id).all()+ ]+ finally:+ db.close()+++def _stored(key_id: int) -> AgentApiKey:+ db = _direct_db_session()+ try:+ row = db.get(AgentApiKey, key_id)+ db.expunge(row)+ return row+ finally:+ db.close()+++def _list(key: str | None, agent_id: int, **params):+ return client.get(+ f"/v1/agents/{agent_id}/api-keys",+ headers=_bearer(key) if key is not None else {},+ params=params,+ )+++def _revoke(key: str | None, agent_id: int, key_id: int):+ return client.delete(+ f"/v1/agents/{agent_id}/api-keys/{key_id}",+ headers=_bearer(key) if key is not None else {},+ )+++def _authenticates(runtime_key: str) -> bool:+ """Whether a runtime key is still accepted by a runtime-key route."""+ resp = client.get(f"/v1/chat/tasks/{_MISSING_ID}", headers=_bearer(runtime_key))+ assert resp.status_code in (401, 404), resp.text+ return resp.status_code == 404+++def _unmanageable_agent(kind: str, team_scopes: dict) -> int:+ """An agent id the admin caller must not be able to manage."""+ if kind == "missing":+ return _MISSING_ID+ if kind == "workforce-manager":+ return _seed_agent(origin=AgentOrigin.WORKFORCE_GENERATED_MANAGER.value)+ _register_second_user("bob")+ if kind == "another-users-agent":+ return _seed_agent("bob")+ team_scopes[_user_id()] = AgentTeamScope(team_id=1, is_team_admin=False)+ if kind == "another-teams-agent":+ return _seed_agent("bob", team_id=2)+ assert kind == "teammates-restricted-agent"+ return _seed_agent("bob", team_id=1, visibility="admins")+++_UNMANAGEABLE = [+ "another-users-agent",+ "another-teams-agent",+ "teammates-restricted-agent",+ "missing",+ "workforce-manager",+]+++# ===== listing =====+++def test_lists_keys_of_own_agent():+ key = _personal_key()+ agent_id = _seed_agent()+ now = datetime.now(timezone.utc)+ older = _seed_key(agent_id, label="ci", created_at=now - timedelta(hours=1))+ newer = _seed_key(agent_id, created_at=now)++ resp = _list(key, agent_id)++ assert resp.status_code == 200, resp.text+ body = resp.json()+ assert [item["id"] for item in body] == [newer.id, older.id]+ assert body[1]["label"] == "ci"+ assert body[1]["key_prefix"] == older.key_prefix+ assert body[1]["masked_key"] == f"xag_{older.key_prefix}_••••••••"+ assert body[1]["status"] == "active"+ assert body[1]["last_used_at"] is None+ assert body[1]["revoked_at"] is None+++def test_list_orders_keys_created_together_by_descending_id():+ key = _personal_key()+ agent_id = _seed_agent()+ created = datetime(2026, 1, 2, 3, 4, 5, tzinfo=timezone.utc)+ first = _seed_key(agent_id, created_at=created)+ second = _seed_key(agent_id, created_at=created)+ third = _seed_key(agent_id, created_at=created)++ resp = _list(key, agent_id)++ assert resp.status_code == 200, resp.text+ assert [item["id"] for item in resp.json()] == [third.id, second.id, first.id]+++def test_list_reports_timestamps_as_aware_utc_values():+ key = _personal_key()+ agent_id = _seed_agent()+ created = datetime(2026, 1, 2, 3, 4, 5, tzinfo=timezone.utc)+ used = created + timedelta(hours=1)+ revoked = created + timedelta(hours=2)+ _seed_key(agent_id, created_at=created, last_used_at=used, revoked_at=revoked)++ resp = _list(key, agent_id, include_revoked=True)++ assert resp.status_code == 200, resp.text+ (item,) = resp.json()+ for field, expected in (+ ("created_at", created),+ ("last_used_at", used),+ ("revoked_at", revoked),+ ):+ reported = datetime.fromisoformat(item[field])+ assert reported.tzinfo is not None, field+ assert reported == expected, field+++def test_agent_without_keys_lists_empty():+ key = _personal_key()++ resp = _list(key, _seed_agent())++ assert resp.status_code == 200, resp.text+ assert resp.json() == []+++def test_list_exposes_only_the_documented_fields():+ key = _personal_key()+ agent_id = _seed_agent()+ live = _seed_key(agent_id)+ gone = _seed_key(agent_id, revoked_at=datetime.now(timezone.utc))++ listed = _list(key, agent_id, include_revoked=True)+ revoked = _revoke(key, agent_id, live.id)++ assert listed.status_code == 200, listed.text+ assert [set(item) for item in listed.json()] == [_ITEM_FIELDS, _ITEM_FIELDS]+ assert revoked.status_code == 200, revoked.text+ assert set(revoked.json()) == _REVOCATION_FIELDS+ for text in (listed.text, revoked.text):+ for seeded in (live, gone):+ assert seeded.full_key not in text+ assert seeded.key_hash not in text+++def test_list_hides_revoked_keys_unless_asked():+ key = _personal_key()+ agent_id = _seed_agent()+ live = _seed_key(agent_id)+ gone = _seed_key(agent_id, revoked_at=datetime.now(timezone.utc))++ default = _list(key, agent_id).json()+ everything = _list(key, agent_id, include_revoked=True).json()++ assert [item["id"] for item in default] == [live.id]+ assert {item["id"]: item["status"] for item in everything} == {+ live.id: "active",+ gone.id: "revoked",+ }+ assert next(i for i in everything if i["id"] == gone.id)["revoked_at"] is not None++[email protected]("include_revoked", [False, True])+def test_list_reports_paused_keys(include_revoked):+ key = _personal_key()+ agent_id = _seed_agent()+ paused = _seed_key(agent_id, paused=True)++ body = _list(key, agent_id, include_revoked=include_revoked).json()++ assert [(item["id"], item["status"]) for item in body] == [(paused.id, "paused")]+++def test_list_never_includes_other_owners_keys():+ key = _personal_key()+ agent_id = _seed_agent()+ own = _seed_key(agent_id)+ _seed_key(_seed_agent())+ _seed_workforce_key()+ _register_second_user("bob")+ _seed_key(_seed_agent("bob"))++ body = _list(key, agent_id, include_revoked=True).json()++ assert [item["id"] for item in body] == [own.id]+++# ===== revoking =====+++def test_revoke_disables_only_the_named_key():+ key = _personal_key()+ agent_id = _seed_agent()+ target = _seed_key(agent_id)+ sibling = _seed_key(agent_id)+ elsewhere = _seed_key(_seed_agent())+ assert _authenticates(target.full_key)++ resp = _revoke(key, agent_id, target.id)++ assert resp.status_code == 200, resp.text+ body = resp.json()+ assert body["id"] == target.id+ assert body["key_prefix"] == target.key_prefix+ assert body["revoked"] is True+ assert body["revoked_at"] is not None+ assert _stored(target.id).revoked_at is not None+ assert not _authenticates(target.full_key)+ assert _authenticates(sibling.full_key)+ assert _authenticates(elsewhere.full_key)+ assert [item["id"] for item in _list(key, agent_id).json()] == [sibling.id]+++def test_revoke_applies_to_a_paused_key():+ key = _personal_key()+ agent_id = _seed_agent()+ paused = _seed_key(agent_id, paused=True)+ paused_at = _stored(paused.id).paused_at++ resp = _revoke(key, agent_id, paused.id)++ assert resp.status_code == 200, resp.text+ assert resp.json()["revoked"] is True+ stored = _stored(paused.id)+ assert stored.revoked_at is not None+ assert stored.paused_at == paused_at+++def test_revoke_is_idempotent(caplog):+ key = _personal_key()+ agent_id = _seed_agent()+ target = _seed_key(agent_id)+ first = _revoke(key, agent_id, target.id)+ before = _key_table()+ caplog.set_level(logging.INFO, logger=agent_management.__name__)+ caplog.clear()++ second = _revoke(key, agent_id, target.id)++ assert second.status_code == 200, second.text+ assert second.json() == {**first.json(), "revoked": False}+ assert _key_table() == before+ assert "runtime key revoked" not in caplog.text+++def test_revoke_logs_the_calling_credential(caplog):+ headers = _admin_headers()+ created = client.post("/api/me/personal-keys", headers=headers).json()+ agent_id = _seed_agent()+ target = _seed_key(agent_id)+ caplog.set_level(logging.INFO, logger=agent_management.__name__)++ assert _revoke(created["full_key"], agent_id, target.id).status_code == 200++ lines = [r.getMessage() for r in caplog.records if "runtime key revoked" in r.msg]+ assert lines == [+ f"runtime key revoked: credential=personal_key:{created['key_prefix']} "+ f"user_id={_user_id()} agent_id={agent_id} key_id={target.id} "+ f"key_prefix={target.key_prefix}"+ ]+ assert target.full_key not in caplog.text+ assert created["full_key"] not in caplog.text+++def test_revoke_reports_a_failed_commit_as_an_error(monkeypatch, caplog):+ key = _personal_key()+ agent_id = _seed_agent()+ target = _seed_key(agent_id)+ real_stage = AgentApiKeyService.revoke_key_for_agent+ real_commit = Session.commit+ staged: list[Session] = []++ def stage(self, *args, **kwargs):+ staged.append(self.db)+ return real_stage(self, *args, **kwargs)++ def commit(self):+ if self in staged:+ raise RuntimeError("commit failed")+ return real_commit(self)++ monkeypatch.setattr(AgentApiKeyService, "revoke_key_for_agent", stage)+ monkeypatch.setattr(Session, "commit", commit)+ caplog.set_level(logging.INFO, logger=agent_management.__name__)++ resp = _revoke(key, agent_id, target.id)++ assert staged, "the revocation was staged before the commit failed"+ assert resp.status_code == 500, resp.text+ assert "runtime key revoked" not in caplog.text+ assert _stored(target.id).revoked_at is None+ assert _authenticates(target.full_key)++[email protected]("bound_to", ["another-agent", "workforce"])+def test_staged_revocation_never_writes_a_key_bound_elsewhere(bound_to):+ _admin_headers()+ agent_id = _seed_agent()+ _seed_key(agent_id)+ other = (+ _seed_key(_seed_agent())+ if bound_to == "another-agent"+ else _seed_workforce_key()+ )+ before = _key_table()+ db = _direct_db_session()+ try:+ with pytest.raises(AgentRuntimeKeyNotFoundError):+ AgentApiKeyService(db).revoke_key_for_agent(agent_id, other.id)+ # Commit instead of rolling back: nothing may have been staged.+ db.commit()+ finally:+ db.close()++ assert _key_table() == before+++# ===== who may manage an agent's keys =====++[email protected]("kind", _UNMANAGEABLE)+def test_unmanageable_agent_is_agent_not_found(kind, team_scopes):+ key = _personal_key()+ own_key = _seed_key(_seed_agent())+ agent_id = _unmanageable_agent(kind, team_scopes)+ its_key = own_key if kind == "missing" else _seed_key(agent_id)+ before = _key_table()++ listed = _list(key, agent_id, include_revoked=True)+ with_real_key = _revoke(key, agent_id, its_key.id)+ with_own_key = _revoke(key, agent_id, own_key.id)+ with_missing_key = _revoke(key, agent_id, _MISSING_ID)++ for resp in (listed, with_real_key, with_own_key, with_missing_key):+ _error(resp, 404, "agent_not_found")+ assert with_real_key.content == with_missing_key.content == with_own_key.content+ assert _key_table() == before+ assert _authenticates(own_key.full_key)++[email protected]("kind", _UNMANAGEABLE)+def test_unmanageable_agent_never_touches_the_key_table(kind, team_scopes):+ key = _personal_key()+ own_agent = _seed_agent()+ own_key = _seed_key(own_agent)+ agent_id = _unmanageable_agent(kind, team_scopes)+ statements: list[str] = []++ def record(_conn, _cursor, statement, *_rest):+ statements.append(statement)++ def recorded(send) -> list[str]:+ statements.clear()+ send()+ return list(statements)++ engine = get_engine()+ event.listen(engine, "before_cursor_execute", record)+ try:+ refused = recorded(lambda: _list(key, agent_id)) + recorded(+ lambda: _revoke(key, agent_id, own_key.id)+ )+ allowed = recorded(lambda: _list(key, own_agent))+ finally:+ event.remove(engine, "before_cursor_execute", record)++ assert any("agents" in statement for statement in refused)+ assert not [s for s in refused if "agent_api_keys" in s]+ assert [s for s in allowed if "agent_api_keys" in s]++[email protected]("kind", _UNMANAGEABLE)+def test_unmanageable_agent_row_is_never_locked(kind, team_scopes, monkeypatch):+ key = _personal_key()+ own_agent = _seed_agent()+ own_key = _seed_key(own_agent)+ agent_id = _unmanageable_agent(kind, team_scopes)+ real = agent_management.acquire_runtime_key_transition_fence+ locked: list[int] = []++ def record(db, locked_agent_id):+ locked.append(locked_agent_id)+ return real(db, locked_agent_id)++ monkeypatch.setattr(+ agent_management, "acquire_runtime_key_transition_fence", record+ )++ _error(_revoke(key, agent_id, own_key.id), 404, "agent_not_found")+ assert locked == []+ assert _revoke(key, own_agent, own_key.id).status_code == 200+ assert locked == [own_agent]+++ "outside",+ ["missing", "own-other-agent", "another-users-agent", "workforce"],+)+def test_key_outside_the_agent_is_api_key_not_found(outside):+ key = _personal_key()+ agent_id = _seed_agent()+ _seed_key(agent_id)+ reference = _revoke(key, agent_id, _MISSING_ID)+ if outside == "missing":+ other = None+ elif outside == "own-other-agent":+ other = _seed_key(_seed_agent())+ elif outside == "another-users-agent":+ _register_second_user("bob")+ other = _seed_key(_seed_agent("bob"))+ else:+ other = _seed_workforce_key()+ before = _key_table()++ resp = _revoke(key, agent_id, other.id if other is not None else _MISSING_ID)++ _error(resp, 404, "api_key_not_found")+ assert resp.content == reference.content+ assert _key_table() == before+ if other is not None:+ assert _stored(other.id).revoked_at is None+++ ("scope", "stored_as", "reachable"),+ [+ (+ AgentTeamScope(team_id=1, is_team_admin=False),+ {"team_id": 1, "visibility": "team"},+ True,+ ),+ (+ AgentTeamScope(team_id=1, is_team_admin=False),+ {"team_id": 1, "visibility": "admins"},+ False,+ ),+ (+ AgentTeamScope(team_id=1, is_team_admin=True),+ {"team_id": 1, "visibility": "admins"},+ True,+ ),+ (None, {"owner": "admin", "team_id": 1, "visibility": "team"}, True),+ ],+ ids=[+ "member-team-visible",+ "member-restricted",+ "team-admin-restricted",+ "no-membership-own-team-agent",+ ],+)+def test_team_access_follows_the_agent_ownership_rule(+ scope, stored_as, reachable, team_scopes+):+ key = _personal_key()+ _register_second_user("bob")+ if scope is not None:+ team_scopes[_user_id()] = scope+ agent_id = _seed_agent(stored_as.pop("owner", "bob"), **stored_as)+ target = _seed_key(agent_id)++ listed = _list(key, agent_id)+ revoked = _revoke(key, agent_id, target.id)++ if reachable:+ assert [item["id"] for item in listed.json()] == [target.id]+ assert revoked.status_code == 200, revoked.text+ assert _stored(target.id).revoked_at is not None+ else:+ _error(listed, 404, "agent_not_found")+ _error(revoked, 404, "agent_not_found")+ assert _stored(target.id).revoked_at is None++[email protected]("lost", ["agent-restricted", "caller-demoted"])+def test_revoke_rechecks_ownership_under_the_agent_lock(lost, team_scopes, monkeypatch):+ key = _personal_key()+ _register_second_user("bob")+ if lost == "agent-restricted":+ team_scopes[_user_id()] = AgentTeamScope(team_id=1, is_team_admin=False)+ agent_id = _seed_agent("bob", team_id=1, visibility="team")+ else:+ team_scopes[_user_id()] = AgentTeamScope(team_id=1, is_team_admin=True)+ agent_id = _seed_agent("bob", team_id=1, visibility="admins")+ target = _seed_key(agent_id)+ before = _key_table()+ real = agent_management.acquire_runtime_key_transition_fence++ def lose_access_then_lock(db, locked_agent_id):+ if lost == "agent-restricted":+ _set_visibility(agent_id, "admins")+ else:+ team_scopes[_user_id()] = AgentTeamScope(team_id=1, is_team_admin=False)+ return real(db, locked_agent_id)++ monkeypatch.setattr(+ agent_management, "acquire_runtime_key_transition_fence", lose_access_then_lock+ )++ _error(_revoke(key, agent_id, target.id), 404, "agent_not_found")+ assert _key_table() == before+ assert _authenticates(target.full_key)+++def test_revoke_reports_an_earlier_revocation_unchanged(monkeypatch):+ key = _personal_key()+ agent_id = _seed_agent()+ target = _seed_key(agent_id)+ earlier = datetime(2026, 1, 2, 3, 4, 5, tzinfo=timezone.utc)+ real = agent_management.acquire_runtime_key_transition_fence++ def revoke_elsewhere_then_lock(db, locked_agent_id):+ other = _direct_db_session()+ try:+ other.get(AgentApiKey, target.id).revoked_at = earlier+ other.commit()+ finally:+ other.close()+ return real(db, locked_agent_id)++ monkeypatch.setattr(+ agent_management,+ "acquire_runtime_key_transition_fence",+ revoke_elsewhere_then_lock,+ )++ resp = _revoke(key, agent_id, target.id)++ assert resp.status_code == 200, resp.text+ assert resp.json()["revoked"] is False+ assert datetime.fromisoformat(resp.json()["revoked_at"]) == earlier+ assert _stored(target.id).revoked_at.replace(tzinfo=timezone.utc) == earlier+++# ===== credentials and path bounds =====+++ "credential", ["none", "malformed", "runtime-key", "revoked-personal-key"]+)+def test_requires_a_usable_personal_key(credential):+ headers = _admin_headers()+ agent_id = _seed_agent()+ target = _seed_key(agent_id)+ if credential == "none":+ presented = None+ elif credential == "malformed":+ presented = "xag_personal_nope"+ elif credential == "runtime-key":+ presented = target.full_key+ else:+ created = client.post("/api/me/personal-keys", headers=headers).json()+ deleted = client.delete(+ f"/api/me/personal-keys/{created['id']}", headers=headers+ )+ assert deleted.json()["revoked"] is True+ presented = created["full_key"]+ before = _key_table()++ _error(_list(presented, agent_id), 401, "invalid_api_key")+ _error(_revoke(presented, agent_id, target.id), 401, "invalid_api_key")+ assert _key_table() == before+++ ("agent_id", "key_id"), [(0, 1), (2**31, 1), (1, 0), (1, 2**31)]+)+def test_ids_outside_the_column_range_are_rejected(agent_id, key_id):+ key = _personal_key()++ assert _revoke(key, agent_id, key_id).status_code == 422+ if key_id == 1:+ assert _list(key, agent_id).status_code == 422diff --git a/tests/web/api/v1/test_personal_key_principal_policy.py b/tests/web/api/v1/test_personal_key_principal_policy.pyindex f45029a4b..51ead3d4b 100644--- a/tests/web/api/v1/test_personal_key_principal_policy.py+++ b/tests/web/api/v1/test_personal_key_principal_policy.py@@ -129,9 +129,15 @@ def test_personal_key_policy_runs_only_after_the_key_verifies() -> None:@pytest.mark.usefixtures("_template_manager")def test_personal_key_policy_applies_to_every_personal_key_route() -> None:routes = _personal_key_routes()- # The 24 management routes (me, agents, templates, skills, MCP connectors, agent- # connectors), the 12 /v1/chat task routes and the features route.- assert len(routes) == 37, routes+ # One long-standing route of each router. The walk finds every other route+ # by itself, so this only guards against it coming back empty or partial+ # and the loop below passing without checking anything.+ assert {+ ("GET", "/v1/me"),+ ("POST", "/v1/agents"),+ ("POST", "/v1/chat/tasks"),+ ("GET", "/v1/features"),+ } <= set(routes), routesheaders = _bearer(_create_personal_key()[0])for method, template in routes:diff --git a/tests/web/api/v1/test_status_only_projection.py b/tests/web/api/v1/test_status_only_projection.pyindex e0e39592b..0ed6ed1b7 100644--- a/tests/web/api/v1/test_status_only_projection.py+++ b/tests/web/api/v1/test_status_only_projection.py@@ -335,6 +335,8 @@ EXCLUDE = {("POST", "/v1/agents"),("POST", "/v1/agents/from-template"),("POST", "/v1/agents/{agent_id}/api-key"),+ ("GET", "/v1/agents/{agent_id}/api-keys"),+ ("DELETE", "/v1/agents/{agent_id}/api-keys/{key_id}"),("GET", "/v1/agents/{agent_id}/skills"),("PUT", "/v1/agents/{agent_id}/skills"),("GET", "/v1/agents/{agent_id}/connectors"),