Buckets:

download
raw
324 kB
""" Offline integration tests for the control-plane-backend product API. Ref: docs/backlog/BACKLOG.md §3d — managed agent CRUD, enrollment, update, tuning field validation (type/enum/min-max/pattern), MCP server selection as `mcp:<server>` capabilities (#1978, RFC AGENT-CAPABILITY-RFC.md §3.8) — see test_capability_selection_1974.py for the generic capability-selection contract (unknown id -> 422, pod round-trip, prune/reset semantics); §3d.9 (P1) — prompt template validation at persistence boundary (unknown tokens → 422); §6.4.D — PATCH session endpoint (updated_at, title). """ from __future__ import annotations from datetime import datetime, timezone from pathlib import Path from types import SimpleNamespace from typing import Any, Optional, cast import httpx import pytest from control_plane_backend.agent_instances.store import ( AgentInstanceRecord, AgentInstanceStore, ) from control_plane_backend.app.dependencies import get_application_container_from_app from control_plane_backend.bootstrap.store import PlatformBootstrapStore from control_plane_backend.config.models import ( InfoBanner, InfoBannerLink, ManagedAgentFieldSpec, ManagedAgentTuning, RuntimeCatalogSourceConfig, ) from control_plane_backend.main import create_app from control_plane_backend.models.base import Base as CPBase from control_plane_backend.product import service as product_service from control_plane_backend.product.dependencies import ( ProductServiceDependencies, build_product_service_dependencies, ) from control_plane_backend.product.schemas import CreateSessionRequest from control_plane_backend.product.service import ( SessionAttachmentRequestError, _delete_knowledge_flow_attachment, _RuntimeTemplatePayload, ) from control_plane_backend.prompts.category_store import PromptCategoryRecord from control_plane_backend.prompts.store import PromptRecord from control_plane_backend.sessions.attachment_store import SessionAttachmentRecord from control_plane_backend.sessions.store import SessionMetadataRecord from control_plane_backend.teams.schemas import Team from control_plane_backend.users.schemas import UserSummary from fred_core import ( JoiningMode, KeycloakUser, OrganizationPermission, RelationType, SessionSchema, TeamPermission, TeamVisibility, get_current_user, ) from fred_core.common import TeamId, personal_team_id from fred_core.security import oidc from fred_core.security.rebac.noop_engine import NoopRebacEngine from fred_core.teams.metadata_store import TeamMetadata from fred_sdk.contracts.capability import ( CapabilityCatalogEntry, ChatControlItem, ChatControlsResponse, ChatControlsResult, ) from fred_sdk.contracts.models import FieldSpec from httpx import ASGITransport, AsyncClient from sqlalchemy import text from sqlalchemy.ext.asyncio import create_async_engine @pytest.fixture(autouse=True) def _use_test_configuration(monkeypatch: pytest.MonkeyPatch) -> None: monkeypatch.setenv("CONFIG_FILE", "./config/configuration_test.yaml") _PERSONAL_TEAM_ID = personal_team_id("admin") def _make_record( *, agent_instance_id: str = "instance-1", team_id: str = "personal", template_id: str = "runtime-a:rags.sample.echo", source_runtime_id: str = "runtime-a", source_agent_id: str = "rags.sample.echo", display_name: str = "Echo Team Agent", description: str | None = "Managed echo agent", enabled: bool = True, created_by: str | None = "internal-admin", ) -> AgentInstanceRecord: return AgentInstanceRecord( agent_instance_id=agent_instance_id, team_id=TeamId(team_id), template_id=template_id, source_runtime_id=source_runtime_id, source_agent_id=source_agent_id, display_name=display_name, description=description, enabled=enabled, created_by=created_by, tuning=ManagedAgentTuning( role=display_name, description=description or display_name, ), ) def _make_prompt_record( *, prompt_id: str = "prompt-1", team_id: str = "personal", name: str = "Daily brief", description: str | None = "Ops baseline", category_id: str | None = None, emoji: str | None = None, tags: list[str] | None = None, text: str = "Today is {today}.", created_by: str | None = "internal-admin", ) -> PromptRecord: return PromptRecord( prompt_id=prompt_id, team_id=TeamId(team_id), name=name, description=description, category_id=category_id, emoji=emoji, tags=tags, text=text, created_by=created_by, ) class _FakeAgentInstanceStore: """In-memory stand-in for AgentInstanceStore used in offline tests.""" def __init__(self, records: list[AgentInstanceRecord] | None = None) -> None: self._records: list[AgentInstanceRecord] = list(records or []) async def list_by_team(self, team_id: TeamId) -> list[AgentInstanceRecord]: return [r for r in self._records if r.team_id == team_id] async def get(self, agent_instance_id: str) -> AgentInstanceRecord | None: return next( (r for r in self._records if r.agent_instance_id == agent_instance_id), None, ) async def get_for_team( self, agent_instance_id: str, team_id: TeamId ) -> AgentInstanceRecord | None: return next( ( r for r in self._records if r.agent_instance_id == agent_instance_id and r.team_id == team_id ), None, ) async def create(self, record: AgentInstanceRecord) -> AgentInstanceRecord: self._records.append(record) return record async def update( self, agent_instance_id: str, team_id: TeamId, *, display_name: str | None = None, description: str | None = None, enabled: bool | None = None, tuning: ManagedAgentTuning | None = None, updated_by: str | None = None, ) -> AgentInstanceRecord | None: record = next( ( r for r in self._records if r.agent_instance_id == agent_instance_id and r.team_id == team_id ), None, ) if record is None: return None if display_name is not None: record.display_name = display_name if description is not None: record.description = description if enabled is not None: record.enabled = enabled if tuning is not None: record.tuning = tuning if updated_by is not None: record.updated_by = updated_by return record async def list_all(self) -> list[AgentInstanceRecord]: return list(self._records) async def set_suspension( self, agent_instance_id: str, team_id: TeamId, *, reason: str | None, ) -> AgentInstanceRecord | None: record = next( ( r for r in self._records if r.agent_instance_id == agent_instance_id and r.team_id == team_id ), None, ) if record is None: return None record.suspension_reason = reason return record async def delete(self, agent_instance_id: str, team_id: TeamId) -> bool: before = len(self._records) self._records = [ r for r in self._records if not (r.agent_instance_id == agent_instance_id and r.team_id == team_id) ] return len(self._records) < before def _patch_store( monkeypatch: pytest.MonkeyPatch, store: _FakeAgentInstanceStore, ) -> None: monkeypatch.setattr( "control_plane_backend.app.context.ApplicationContext.get_agent_instance_store", lambda _self: store, ) class _FakeSessionMetadataStore: """In-memory stand-in for SessionMetadataStore used in offline tests.""" def __init__(self, records: list[SessionMetadataRecord] | None = None) -> None: self._records: list[SessionMetadataRecord] = list(records or []) async def create(self, record: SessionMetadataRecord) -> SessionMetadataRecord: from control_plane_backend.sessions.store import ( SessionMetadataAlreadyExistsError, ) if any(r.session_id == record.session_id for r in self._records): raise SessionMetadataAlreadyExistsError(record.session_id) self._records.append(record) return record async def update_last_activity( self, session_id: str, team_id: TeamId, updated_at: datetime, ) -> SessionMetadataRecord | None: for record in self._records: if record.session_id == session_id and record.team_id == team_id: record.updated_at = updated_at return record return None async def update_metadata( self, session_id: str, team_id: TeamId, user_id: str, *, title: str | None = None, updated_at: datetime | None = None, ) -> SessionMetadataRecord | None: for record in self._records: if ( record.session_id == session_id and record.team_id == team_id and record.user_id == user_id ): if title is not None: record.title = title if updated_at is not None: record.updated_at = updated_at return record return None async def replace_context_prompts( self, session_id: str, team_id: TeamId, user_id: str, prompt_ids: list[str], ) -> tuple[SessionMetadataRecord, list[str]] | None: ordered_ids: list[str] = [] for prompt_id in prompt_ids: if prompt_id not in ordered_ids: ordered_ids.append(prompt_id) for record in self._records: if ( record.session_id == session_id and record.team_id == team_id and record.user_id == user_id ): previous = set(record.context_prompt_ids) newly_attached = [pid for pid in ordered_ids if pid not in previous] record.context_prompt_ids = ordered_ids return record, newly_attached return None async def get(self, session_id: str) -> SessionMetadataRecord | None: return next((r for r in self._records if r.session_id == session_id), None) async def mark_deleted( self, session_id: str, team_id: TeamId, user_id: str, deleted_at: datetime, ) -> bool: for record in self._records: if ( record.session_id == session_id and record.team_id == team_id and record.user_id == user_id ): record.deleted_at = deleted_at # type: ignore[attr-defined] return True return False async def delete(self, session_id: str, team_id: TeamId, user_id: str) -> bool: before = len(self._records) self._records = [ r for r in self._records if not ( r.session_id == session_id and r.team_id == team_id and r.user_id == user_id ) ] return len(self._records) < before class _DuplicateSessionMetadataStore: """Offline stand-in that always reproduces one duplicate session conflict.""" async def create(self, _record: SessionMetadataRecord) -> SessionMetadataRecord: """Raise the duplicate-session store error expected by the API layer.""" from control_plane_backend.sessions.store import ( SessionMetadataAlreadyExistsError, ) raise SessionMetadataAlreadyExistsError("session-duplicate") def _patch_session_store( monkeypatch: pytest.MonkeyPatch, store: _FakeSessionMetadataStore, ) -> None: monkeypatch.setattr( "control_plane_backend.app.context.ApplicationContext.get_session_metadata_store", lambda _self: store, ) class _FakeSessionAttachmentStore: """In-memory stand-in for SessionAttachmentStore used in offline tests.""" def __init__(self, records: list[SessionAttachmentRecord] | None = None) -> None: self._records: list[SessionAttachmentRecord] = list(records or []) async def save(self, record: SessionAttachmentRecord) -> None: self._records = [ existing for existing in self._records if not ( existing.session_id == record.session_id and existing.attachment_id == record.attachment_id ) ] self._records.append(record) async def list_for_session(self, session_id: str) -> list[SessionAttachmentRecord]: return [record for record in self._records if record.session_id == session_id] async def delete(self, session_id: str, attachment_id: str) -> None: self._records = [ record for record in self._records if not ( record.session_id == session_id and record.attachment_id == attachment_id ) ] async def delete_for_session(self, session_id: str) -> None: self._records = [ record for record in self._records if record.session_id != session_id ] async def count_for_sessions(self, session_ids: list[str]) -> int: return len([r for r in self._records if r.session_id in session_ids]) def _patch_session_attachment_store( monkeypatch: pytest.MonkeyPatch, store: _FakeSessionAttachmentStore, ) -> None: monkeypatch.setattr( "control_plane_backend.app.context.ApplicationContext.get_session_attachment_store", lambda _self: store, ) class _FakePromptStore: """In-memory stand-in for PromptStore used in offline tests.""" def __init__(self, records: list[PromptRecord] | None = None) -> None: self._records: list[PromptRecord] = list(records or []) async def create(self, record: PromptRecord) -> PromptRecord: if any( existing.team_id == record.team_id and existing.name == record.name for existing in self._records ): from control_plane_backend.prompts.store import PromptAlreadyExistsError raise PromptAlreadyExistsError(record.name) self._records.append(record) return record async def list_by_team( self, team_id: TeamId, *, limit: int = 100, ) -> list[PromptRecord]: records = [record for record in self._records if record.team_id == team_id] return records[:limit] async def get(self, prompt_id: str) -> PromptRecord | None: return next((r for r in self._records if r.prompt_id == prompt_id), None) async def get_for_team( self, prompt_id: str, team_id: TeamId, ) -> PromptRecord | None: return next( ( r for r in self._records if r.prompt_id == prompt_id and r.team_id == team_id ), None, ) async def update( self, prompt_id: str, team_id: TeamId, *, name: str, description: str | None, category_id: str | None = None, emoji: str | None = None, tags: list[str] | None = None, text: str, ) -> PromptRecord | None: record = await self.get_for_team(prompt_id, team_id) if record is None: return None if any( existing.prompt_id != prompt_id and existing.team_id == team_id and existing.name == name for existing in self._records ): from control_plane_backend.prompts.store import PromptAlreadyExistsError raise PromptAlreadyExistsError(name) record.name = name record.description = description record.text = text record.version += 1 return record async def delete(self, prompt_id: str, team_id: TeamId) -> bool: before = len(self._records) self._records = [ r for r in self._records if not (r.prompt_id == prompt_id and r.team_id == team_id) ] return len(self._records) < before async def increment_import_count(self, prompt_id: str, team_id: TeamId) -> None: for r in self._records: if r.prompt_id == prompt_id and r.team_id == team_id: r.import_count += 1 async def increment_session_count(self, prompt_id: str, team_id: TeamId) -> None: for r in self._records: if r.prompt_id == prompt_id and r.team_id == team_id: r.session_count += 1 async def count_by_category(self, team_id: TeamId, category_id: str) -> int: return sum( 1 for r in self._records if r.team_id == team_id and r.category_id == category_id ) async def update_score( self, prompt_id: str, team_id: TeamId, score: float ) -> PromptRecord | None: record = await self.get_for_team(prompt_id, team_id) if record is None: return None record.score = score return record async def list_context_prompts( self, personal_team_id: TeamId, team_id: TeamId, ) -> list: from control_plane_backend.prompts.store import ContextPromptRecord # Mirrors the real store: personal prompts only in the personal space. scope = "personal" if str(personal_team_id) == str(team_id) else "team" seen_ids: set[str] = set() results = [] for r in self._records: if r.team_id == str(team_id) and r.prompt_id not in seen_ids: seen_ids.add(r.prompt_id) results.append( ContextPromptRecord( prompt_id=r.prompt_id, name=r.name, description=r.description, scope=scope, category_id=r.category_id, version=r.version, session_count=r.session_count, score=r.score, ) ) results.sort(key=lambda r: (-r.session_count, r.name)) return results def _patch_prompt_store( monkeypatch: pytest.MonkeyPatch, store: _FakePromptStore, ) -> None: monkeypatch.setattr( "control_plane_backend.app.context.ApplicationContext.get_prompt_store", lambda _self: store, ) class _FakePromptCategoryStore: """In-memory stand-in for PromptCategoryStore used in offline tests.""" def __init__(self, records: list[PromptCategoryRecord] | None = None) -> None: self._records: list[PromptCategoryRecord] = list(records or []) async def create(self, record: PromptCategoryRecord) -> PromptCategoryRecord: if any( existing.team_id == record.team_id and existing.name == record.name for existing in self._records ): from control_plane_backend.prompts.category_store import ( PromptCategoryAlreadyExistsError, ) raise PromptCategoryAlreadyExistsError(record.name) self._records.append(record) return record async def list_by_team(self, team_id: TeamId) -> list[PromptCategoryRecord]: return sorted( (r for r in self._records if r.team_id == team_id), key=lambda r: r.name, ) async def get_for_team( self, category_id: str, team_id: TeamId ) -> PromptCategoryRecord | None: return next( ( r for r in self._records if r.category_id == category_id and r.team_id == team_id ), None, ) async def update( self, category_id: str, team_id: TeamId, *, name: str ) -> PromptCategoryRecord | None: record = await self.get_for_team(category_id, team_id) if record is None: return None if any( existing.category_id != category_id and existing.team_id == team_id and existing.name == name for existing in self._records ): from control_plane_backend.prompts.category_store import ( PromptCategoryAlreadyExistsError, ) raise PromptCategoryAlreadyExistsError(name) record.name = name return record async def delete(self, category_id: str, team_id: TeamId) -> bool: before = len(self._records) self._records = [ r for r in self._records if not (r.category_id == category_id and r.team_id == team_id) ] return len(self._records) < before def _patch_prompt_category_store( monkeypatch: pytest.MonkeyPatch, store: _FakePromptCategoryStore, ) -> None: monkeypatch.setattr( "control_plane_backend.app.context.ApplicationContext.get_prompt_category_store", lambda _self: store, ) async def _fake_require_team_access( _user: Any, _team_id: Any, _deps: Any | None = None, required_permissions: Any = None, **_kwargs: Any, ) -> TeamId: return TeamId(_team_id) @pytest.mark.asyncio async def test_healthz_endpoint() -> None: app = create_app() async with AsyncClient( transport=ASGITransport(app=app), base_url="http://test" ) as client: resp = await client.get("/control-plane/v1/healthz") assert resp.status_code == 200 assert resp.json()["status"] == "ok" def test_create_app_initializes_application_container_once( monkeypatch: pytest.MonkeyPatch, ) -> None: """ Verify the app factory builds and wires one application container. Why this test exists: - Slice 1 moves startup registration out of `ApplicationContext.__init__()` and into explicit composition-root wiring - the FastAPI factory should still build only one container and attach it to the app state for future DI-based dependencies How to use it: - run with the offline `control-plane-backend` test suite Example: - `pytest tests/test_main.py -q` """ created_configurations: list[object] = [] initialized_containers: list[object] = [] class _FakeContainer: def __init__(self, configuration: object) -> None: created_configurations.append(configuration) def get_kpi_writer(self): from fred_core.kpi.noop_kpi_writer import NoOpKPIWriter return NoOpKPIWriter() def start_metrics_exporter(self) -> None: return None async def shutdown(self) -> None: return None def _build_application_container(configuration: object) -> _FakeContainer: return _FakeContainer(configuration) monkeypatch.setattr( "control_plane_backend.main.build_application_container", _build_application_container, ) monkeypatch.setattr( "control_plane_backend.main.initialize_shared_stores", lambda container: initialized_containers.append(container), ) app = create_app() assert len(created_configurations) == 1 assert len(initialized_containers) == 1 assert get_application_container_from_app(app) is initialized_containers[0] @pytest.mark.asyncio async def test_resolve_purge_policy_team_override() -> None: app = create_app() async with AsyncClient( transport=ASGITransport(app=app), base_url="http://test" ) as client: resp = await client.post( "/control-plane/v1/policies/purge/resolve", json={"team_id": "swiftpost", "trigger": "member_removed"}, ) assert resp.status_code == 200 payload = resp.json() assert payload["retention"] == "PT60S" assert payload["matched_rule_id"] == "purge.team.swiftpost" @pytest.mark.asyncio async def test_list_users_returns_empty_without_keycloak_m2m() -> None: app = create_app() async with AsyncClient( transport=ASGITransport(app=app), base_url="http://test" ) as client: resp = await client.get("/control-plane/v1/users") assert resp.status_code == 200 assert resp.json() == [] @pytest.mark.asyncio async def test_get_users_by_ids_degrades_to_id_only_without_keycloak() -> None: """/users/by-ids answers one entry per unique id, in order, even with no Keycloak (#1952).""" app = create_app() async with AsyncClient( transport=ASGITransport(app=app), base_url="http://test" ) as client: resp = await client.get( "/control-plane/v1/users/by-ids", params=[("ids", "u-1"), ("ids", "u-2"), ("ids", "u-1")], ) assert resp.status_code == 200 assert resp.json() == [{"id": "u-1"}, {"id": "u-2"}] @pytest.mark.asyncio async def test_create_user_requires_keycloak_m2m() -> None: app = create_app() async with AsyncClient( transport=ASGITransport(app=app), base_url="http://test" ) as client: resp = await client.post( "/control-plane/v1/users", json={ "username": "test-user", "email": "test-user@app.local", "password": "Password123!", # pragma: allowlist secret }, ) assert resp.status_code == 503 assert ( resp.json()["detail"] == "Keycloak M2M is disabled; cannot perform user operations." ) @pytest.mark.asyncio async def test_delete_user_requires_keycloak_m2m() -> None: app = create_app() async with AsyncClient( transport=ASGITransport(app=app), base_url="http://test" ) as client: resp = await client.delete("/control-plane/v1/users/user-001") assert resp.status_code == 503 assert ( resp.json()["detail"] == "Keycloak M2M is disabled; cannot perform user operations." ) @pytest.mark.asyncio async def test_list_teams_returns_personal_when_team_metadata_registry_is_empty() -> ( None ): """AUTHZ-05 review item 9: `list_teams` now sources collaborative teams from `team_metadata_store.list_all()` instead of Keycloak root groups — with an empty registry (nothing created yet), only the reserved personal team shows.""" app = create_app() async with AsyncClient( transport=ASGITransport(app=app), base_url="http://test" ) as client: resp = await client.get("/control-plane/v1/teams") assert resp.status_code == 200 assert resp.json() == [ { "id": _PERSONAL_TEAM_ID, "name": "Equipe personnelle", "member_count": 1, "admins": [], "is_member": True, "my_relations": ["team_editor"], "joining_mode": "invite_only", # #2433: a personal space is stated private explicitly — it is # never marketplace-listed and unreadable to non-members. "visibility": "private", "max_resources_storage_size": 5368709120, "current_resources_storage_size": 0, } ] @pytest.mark.asyncio async def test_frontend_bootstrap_returns_typed_phase_3a_surface() -> None: app = create_app() container = get_application_container_from_app(app) container.configuration.app.gcu_version = "V1" async with AsyncClient( transport=ASGITransport(app=app), base_url="http://test" ) as client: resp = await client.get("/control-plane/v1/frontend/bootstrap") assert resp.status_code == 200 payload = resp.json() assert payload["current_user"]["id"] == "admin" assert payload["active_team"]["id"] == _PERSONAL_TEAM_ID assert payload["available_teams"][0]["id"] == _PERSONAL_TEAM_ID assert payload["gcu_version"] == "V1" assert payload["feature_flags"]["enableK8Features"] is False assert payload["feature_flags"]["enableApplications"] is False assert "ui_settings" not in payload # AUTHZ-05 review item 11: `permissions` only ever carries the two # OpenFGA-derived flags now — the Keycloak-role-derived `items` list and # its six always-empty `can_*` booleans were removed as dead weight. assert set(payload["permissions"]) == {"is_platform_admin", "is_platform_observer"} # Rebac disabled in test config -> NoopRebacEngine authorizes everything. assert payload["permissions"]["is_platform_admin"] is True assert payload["permissions"]["is_platform_observer"] is True @pytest.mark.asyncio async def test_applications_feature_flag_keeps_contract_mounted_but_fails_closed() -> ( None ): app = create_app() path = "/control-plane/v1/teams/{team_id}/applications" assert path in app.openapi()["paths"] async with AsyncClient( transport=ASGITransport(app=app), base_url="http://test" ) as client: disabled = await client.get("/control-plane/v1/teams/personal/applications") assert disabled.status_code == 404 assert disabled.json() == {"detail": "Not Found"} container = get_application_container_from_app(app) container.configuration.platform.frontend.feature_flags.enableApplications = ( True ) enabled = await client.get("/control-plane/v1/teams/personal/applications") assert enabled.status_code == 200 assert enabled.json()["items"] == [] @pytest.mark.asyncio async def test_frontend_bootstrap_permission_summary_derives_platform_admin_from_rebac( monkeypatch: pytest.MonkeyPatch, ) -> None: """AUTHZ-05 review item 4: `is_platform_admin` must come from the OpenFGA `platform_admin` relation (via `CAN_MANAGE_PLATFORM`), not from the caller's Keycloak roles. A user with no Keycloak `admin` role but an OpenFGA `platform_admin` relation must still see `is_platform_admin=True`, and a distinct `CAN_READ_KPI` check must drive `is_platform_observer` independently. """ class _FakePlatformAdminRebac: async def has_user_permission( self, _user, permission, _resource_id, *, consistency_token=None ) -> bool: return permission == OrganizationPermission.CAN_MANAGE_PLATFORM # AUTHZ-05 review item 9: `_list_teams` (called from bootstrap's team # listing) now also touches these collaborators. async def ensure_team_organization_relations(self, _team_ids) -> str | None: return None # TEAM-09: `_list_teams` also lazily backfills marketplace visibility. async def ensure_team_public_relations(self, _team_ids) -> str | None: return None # TEAM-10: and lazily revokes it for teams marked private. async def revoke_team_public_relations(self, _team_ids) -> str | None: return None async def lookup_user_resources( self, _user, _permission, *, consistency_token=None ): from fred_core import RebacDisabledResult return RebacDisabledResult() monkeypatch.setattr( "control_plane_backend.app.context.ApplicationContext.get_rebac_engine", lambda _self: _FakePlatformAdminRebac(), ) app = create_app() app.dependency_overrides[get_current_user] = lambda: KeycloakUser( uid="bob", username="bob", roles=[] ) async with AsyncClient( transport=ASGITransport(app=app), base_url="http://test" ) as client: resp = await client.get("/control-plane/v1/frontend/bootstrap") app.dependency_overrides.clear() assert resp.status_code == 200 permissions = resp.json()["permissions"] assert permissions["is_platform_admin"] is True assert permissions["is_platform_observer"] is False @pytest.mark.asyncio async def test_bootstrap_platform_admin_returns_401_without_bearer_token( monkeypatch: pytest.MonkeyPatch, ) -> None: """The real route — not just the service function — must enforce authentication. With Keycloak genuinely enabled and no bearer token supplied, the real `get_current_user` (not the no-security mock admin every other route in this test config gets by default) must reject the call with 401 before the bootstrap service ever runs (AUTHZ-07).""" app = create_app() # create_app() calls initialize_user_security() from the loaded test # config (security.user.enabled=False), so KEYCLOAK_ENABLED must be # flipped *after* create_app(), not before — otherwise create_app() # overwrites it right back to False. monkeypatch.setattr(oidc, "KEYCLOAK_ENABLED", True) container = get_application_container_from_app(app) container.configuration.security.user.enabled = True async with AsyncClient( transport=ASGITransport(app=app), base_url="http://test" ) as client: resp = await client.post( "/control-plane/v1/bootstrap/platform-admin", json={"token": "irrelevant-but-16-chars"}, ) assert resp.status_code == 401 @pytest.mark.asyncio async def test_bootstrap_platform_admin_returns_503_when_auth_disabled( tmp_path: Path, ) -> None: """`BootstrapAuthDisabledError` end-to-end through the real route, not just the service function. With a correctly configured secret (so the token check itself passes) but `security.user.enabled=False`, the route must surface 503 with the fail-closed message rather than falling through to a grant (AUTHZ-07, RFC Part 8 §42.1).""" token_path = tmp_path / "token" token_path.write_text("secret-token-9f3a2b1c") app = create_app() container = get_application_container_from_app(app) container.configuration.app.bootstrap_token_file = str(token_path) container.configuration.security.user.enabled = False app.dependency_overrides[get_current_user] = lambda: KeycloakUser( uid="bob", username="bob", roles=[] ) try: async with AsyncClient( transport=ASGITransport(app=app), base_url="http://test" ) as client: resp = await client.post( "/control-plane/v1/bootstrap/platform-admin", json={"token": "secret-token-9f3a2b1c"}, ) finally: app.dependency_overrides.clear() assert resp.status_code == 503 assert "Authentication is disabled" in resp.json()["detail"] @pytest.mark.asyncio async def test_bootstrap_platform_admin_happy_path_through_real_route( tmp_path: Path, monkeypatch: pytest.MonkeyPatch ) -> None: """One minimal proof that the real route, dependency wiring, and registered exception handlers cooperate end-to-end on success — the business logic itself (token comparison, self-promotion-only, durable marker, write ordering, ...) is already covered exhaustively at the service-function level in test_bootstrap_platform_admin.py (AUTHZ-07).""" class _FakeRebac: enabled = True def __init__(self) -> None: self.added_relations: list[object] = [] async def add_relation(self, relation, **kwargs: object): self.added_relations.append(relation) return None fake_rebac = _FakeRebac() monkeypatch.setattr( "control_plane_backend.app.context.ApplicationContext.get_rebac_engine", lambda _self: fake_rebac, ) token_path = tmp_path / "token" token_path.write_text("secret-token-9f3a2b1c") app = create_app() container = get_application_container_from_app(app) container.configuration.app.bootstrap_token_file = str(token_path) container.configuration.security.user.enabled = True app.dependency_overrides[get_current_user] = lambda: KeycloakUser( uid="carol-sub", username="carol", roles=[] ) try: async with AsyncClient( transport=ASGITransport(app=app), base_url="http://test" ) as client: resp = await client.post( "/control-plane/v1/bootstrap/platform-admin", json={"token": "secret-token-9f3a2b1c"}, ) finally: app.dependency_overrides.clear() assert resp.status_code == 200 payload = resp.json() assert payload["user_id"] == "carol-sub" assert payload["username"] == "carol" assert len(fake_rebac.added_relations) == 1 @pytest.mark.asyncio async def test_frontend_config_disabled_omits_oidc_client() -> None: """Public pre-auth config reports disabled user auth and hides OIDC client.""" app = create_app() container = get_application_container_from_app(app) container.configuration.security.user.enabled = False # Even with a configured version, gating is effectively off when user auth is # disabled — the public surface must report `None` so the frontend never # routes a standalone/dev deployment to the acceptance screen. container.configuration.app.gcu_version = "V1" async with AsyncClient( transport=ASGITransport(app=app), base_url="http://test" ) as client: resp = await client.get("/control-plane/v1/frontend/config") assert resp.status_code == 200 payload = resp.json() assert payload["user_auth"]["enabled"] is False assert "realm_url" not in payload["user_auth"] assert "client_id" not in payload["user_auth"] # `response_model_exclude_none=True` omits the key entirely when gating is off. assert payload.get("gcu_version") is None # No `platform.frontend.info_banner` configured → the key is omitted and # the frontend renders no banner. assert "info_banner" not in payload @pytest.mark.asyncio async def test_frontend_config_exposes_configured_info_banner() -> None: """The public pre-auth config carries `platform.frontend.info_banner` so the global banner can render on every page — including the GCU-acceptance and root-bootstrap screens, which render before the authenticated `/frontend/bootstrap` can succeed.""" app = create_app() container = get_application_container_from_app(app) container.configuration.platform.frontend.info_banner = InfoBanner( color="#00BBDD", auto_hide_seconds=30, titles={"en": "New version available"}, messages={ "en": "Access the Fred documentation & blog", "fr": "Accédez à la doc", }, links=[ InfoBannerLink( url="https://fredk8.dev", labels={"en": "Go to the Fred blog"} ) ], ) async with AsyncClient( transport=ASGITransport(app=app), base_url="http://test" ) as client: resp = await client.get("/control-plane/v1/frontend/config") assert resp.status_code == 200 banner = resp.json()["info_banner"] assert banner["color"] == "#00BBDD" assert banner["auto_hide_seconds"] == 30 assert banner["titles"] == {"en": "New version available"} assert banner["messages"]["fr"] == "Accédez à la doc" assert banner["links"] == [ {"url": "https://fredk8.dev", "labels": {"en": "Go to the Fred blog"}} ] @pytest.mark.asyncio async def test_frontend_config_enabled_returns_oidc_client() -> None: """When user auth is enabled, the public config exposes realm and client id.""" app = create_app() container = get_application_container_from_app(app) container.configuration.security.user.enabled = True async with AsyncClient( transport=ASGITransport(app=app), base_url="http://test" ) as client: resp = await client.get("/control-plane/v1/frontend/config") assert resp.status_code == 200 user_auth = resp.json()["user_auth"] assert user_auth["enabled"] is True assert user_auth["realm_url"] == str( container.configuration.security.user.realm_url ) assert user_auth["client_id"] == container.configuration.security.user.client_id @pytest.mark.asyncio async def test_frontend_config_exposes_gcu_version_when_gating_enabled() -> None: """The public pre-auth config carries the active CGU version so the frontend guard can render the acceptance page without first calling the GCU-gated authenticated bootstrap (chicken-and-egg fix, FRONT-10).""" app = create_app() container = get_application_container_from_app(app) container.configuration.security.user.enabled = True container.configuration.app.gcu_version = "V1" async with AsyncClient( transport=ASGITransport(app=app), base_url="http://test" ) as client: resp = await client.get("/control-plane/v1/frontend/config") assert resp.status_code == 200 assert resp.json()["gcu_version"] == "V1" @pytest.mark.asyncio async def test_frontend_config_root_bootstrap_completed_false_on_fresh_store( tmp_path: Path, ) -> None: """`root_bootstrap_completed` is False when root bootstrap (AUTHZ-07) has never run on this deployment, mirroring `PlatformBootstrapStore.is_completed()` on a store with no durable marker row. Uses a dedicated per-test engine (same real-SQLite-engine pattern as `test_metadata_stores.py`'s `test_platform_bootstrap_store_*` tests) rather than the shared container engine: `test_bootstrap_platform_admin_happy_path_through_real_route` permanently completes bootstrap on that shared store within the same test session, so asserting "fresh" against it would be order-dependent. """ engine = create_async_engine( f"sqlite+aiosqlite:///{tmp_path / 'root-bootstrap-fresh.sqlite3'}" ) async with engine.begin() as conn: await conn.run_sync(CPBase.metadata.create_all) try: store = PlatformBootstrapStore(engine) app = create_app() container = get_application_container_from_app(app) container.get_platform_bootstrap_store = lambda: store # type: ignore[method-assign] async with AsyncClient( transport=ASGITransport(app=app), base_url="http://test" ) as client: resp = await client.get("/control-plane/v1/frontend/config") assert resp.status_code == 200 assert resp.json()["root_bootstrap_completed"] is False finally: await engine.dispose() @pytest.mark.asyncio async def test_frontend_config_root_bootstrap_completed_true_after_mark_completed( tmp_path: Path, ) -> None: """`root_bootstrap_completed` flips to True once the durable `PlatformBootstrapStore` marker has been set — same real-SQLite-engine pattern as `test_metadata_stores.py`'s `test_platform_bootstrap_store_*` tests, wired through `create_app()`'s container so the assertion goes through the actual public `/frontend/config` route rather than calling `build_frontend_config` directly. A dedicated per-test engine (rather than the shared container engine) keeps this test from leaking the permanent marker into the rest of the suite.""" engine = create_async_engine( f"sqlite+aiosqlite:///{tmp_path / 'root-bootstrap-completed.sqlite3'}" ) async with engine.begin() as conn: await conn.run_sync(CPBase.metadata.create_all) try: store = PlatformBootstrapStore(engine) await store.mark_completed(completed_by="benjamin-sub") app = create_app() container = get_application_container_from_app(app) container.get_platform_bootstrap_store = lambda: store # type: ignore[method-assign] async with AsyncClient( transport=ASGITransport(app=app), base_url="http://test" ) as client: resp = await client.get("/control-plane/v1/frontend/config") assert resp.status_code == 200 assert resp.json()["root_bootstrap_completed"] is True finally: await engine.dispose() @pytest.mark.asyncio async def test_frontend_config_root_bootstrap_required_true_when_auth_and_rebac_enabled_and_incomplete( tmp_path: Path, monkeypatch: pytest.MonkeyPatch ) -> None: """`root_bootstrap_required` is the authoritative frontend gating decision: true only when auth is enabled, ReBAC is enabled, and root bootstrap has never completed — the one case where `POST /bootstrap/platform-admin` can actually succeed.""" class _FakeEnabledRebac: enabled = True engine = create_async_engine( f"sqlite+aiosqlite:///{tmp_path / 'root-bootstrap-required-true.sqlite3'}" ) async with engine.begin() as conn: await conn.run_sync(CPBase.metadata.create_all) try: store = PlatformBootstrapStore(engine) monkeypatch.setattr( "control_plane_backend.app.context.ApplicationContext.get_rebac_engine", lambda _self: _FakeEnabledRebac(), ) app = create_app() container = get_application_container_from_app(app) container.configuration.security.user.enabled = True container.get_platform_bootstrap_store = lambda: store # type: ignore[method-assign] async with AsyncClient( transport=ASGITransport(app=app), base_url="http://test" ) as client: resp = await client.get("/control-plane/v1/frontend/config") assert resp.status_code == 200 payload = resp.json() assert payload["root_bootstrap_completed"] is False assert payload["root_bootstrap_required"] is True finally: await engine.dispose() @pytest.mark.asyncio async def test_frontend_config_root_bootstrap_not_required_once_completed( tmp_path: Path, monkeypatch: pytest.MonkeyPatch ) -> None: """Once root bootstrap has durably completed, `root_bootstrap_required` flips to False even though auth and ReBAC remain enabled — the guard must stop gating once the one-time grant has happened.""" class _FakeEnabledRebac: enabled = True engine = create_async_engine( f"sqlite+aiosqlite:///{tmp_path / 'root-bootstrap-required-completed.sqlite3'}" ) async with engine.begin() as conn: await conn.run_sync(CPBase.metadata.create_all) try: store = PlatformBootstrapStore(engine) await store.mark_completed(completed_by="dana-sub") monkeypatch.setattr( "control_plane_backend.app.context.ApplicationContext.get_rebac_engine", lambda _self: _FakeEnabledRebac(), ) app = create_app() container = get_application_container_from_app(app) container.configuration.security.user.enabled = True container.get_platform_bootstrap_store = lambda: store # type: ignore[method-assign] async with AsyncClient( transport=ASGITransport(app=app), base_url="http://test" ) as client: resp = await client.get("/control-plane/v1/frontend/config") assert resp.status_code == 200 payload = resp.json() assert payload["root_bootstrap_completed"] is True assert payload["root_bootstrap_required"] is False finally: await engine.dispose() @pytest.mark.asyncio async def test_frontend_config_root_bootstrap_not_required_when_auth_disabled( tmp_path: Path, ) -> None: """`root_bootstrap_required` stays False when user authentication is disabled — `POST /bootstrap/platform-admin` refuses with 503 there, so the guard must never trap this deployment on a form that can never succeed, even though the durable `root_bootstrap_completed` marker is False. Uses a dedicated per-test engine (same rationale as the `root_bootstrap_completed` tests above): the shared container store can carry a permanent `True` marker left by other tests in the same session. """ engine = create_async_engine( f"sqlite+aiosqlite:///{tmp_path / 'root-bootstrap-not-required-auth-disabled.sqlite3'}" ) async with engine.begin() as conn: await conn.run_sync(CPBase.metadata.create_all) try: store = PlatformBootstrapStore(engine) app = create_app() container = get_application_container_from_app(app) container.configuration.security.user.enabled = False container.get_platform_bootstrap_store = lambda: store # type: ignore[method-assign] async with AsyncClient( transport=ASGITransport(app=app), base_url="http://test" ) as client: resp = await client.get("/control-plane/v1/frontend/config") assert resp.status_code == 200 payload = resp.json() assert payload["root_bootstrap_completed"] is False assert payload["root_bootstrap_required"] is False finally: await engine.dispose() @pytest.mark.asyncio async def test_frontend_config_root_bootstrap_not_required_when_rebac_disabled( tmp_path: Path, ) -> None: """`root_bootstrap_required` stays False when ReBAC is disabled — the test container's default `NoopRebacEngine` (`enabled=False`) mirrors the same deployment shape `POST /bootstrap/platform-admin` refuses with 503, so the guard must not trap this deployment either. Uses a dedicated per-test engine for the same reason as the sibling test above — the shared container store is not safe to assert "fresh" against once other tests have run in the same session. """ engine = create_async_engine( f"sqlite+aiosqlite:///{tmp_path / 'root-bootstrap-not-required-rebac-disabled.sqlite3'}" ) async with engine.begin() as conn: await conn.run_sync(CPBase.metadata.create_all) try: store = PlatformBootstrapStore(engine) app = create_app() container = get_application_container_from_app(app) container.configuration.security.user.enabled = True container.get_platform_bootstrap_store = lambda: store # type: ignore[method-assign] async with AsyncClient( transport=ASGITransport(app=app), base_url="http://test" ) as client: resp = await client.get("/control-plane/v1/frontend/config") assert resp.status_code == 200 payload = resp.json() assert payload["root_bootstrap_completed"] is False assert payload["root_bootstrap_required"] is False finally: await engine.dispose() @pytest.mark.asyncio async def test_get_personal_team_returns_shared_system_team_contract() -> None: app = create_app() async with AsyncClient( transport=ASGITransport(app=app), base_url="http://test" ) as client: resp = await client.get(f"/control-plane/v1/teams/{_PERSONAL_TEAM_ID}") assert resp.status_code == 200 assert resp.json() == { "id": _PERSONAL_TEAM_ID, "name": "Equipe personnelle", "member_count": 1, "admins": [], "is_member": True, "joining_mode": "invite_only", # #2433: a personal space is stated private explicitly. "visibility": "private", "permissions": [ "can_read", "can_update_resources", "can_update_agents", "can_access_files", ], "my_relations": ["team_editor"], "max_resources_storage_size": 5368709120, "current_resources_storage_size": 0, } @pytest.mark.asyncio async def test_user_details_reuses_shared_personal_team_contract() -> None: app = create_app() async with AsyncClient( transport=ASGITransport(app=app), base_url="http://test" ) as client: resp = await client.get("/control-plane/v1/user") assert resp.status_code == 200 assert resp.json()["personalTeam"]["id"] == _PERSONAL_TEAM_ID assert resp.json()["personalTeam"]["permissions"] == [ "can_read", "can_update_resources", "can_update_agents", "can_access_files", ] @pytest.mark.asyncio async def test_team_agent_templates_returns_empty_without_runtime_sources() -> None: app = create_app() async with AsyncClient( transport=ASGITransport(app=app), base_url="http://test" ) as client: resp = await client.get( f"/control-plane/v1/teams/{_PERSONAL_TEAM_ID}/agent-templates" ) assert resp.status_code == 200 assert resp.json() == [] @pytest.mark.asyncio async def test_team_agent_templates_aggregates_runtime_catalog( monkeypatch: pytest.MonkeyPatch, ) -> None: async def _fake_fetch_runtime_templates( _base_url: str, include_non_public: bool = False ): return [ _RuntimeTemplatePayload( template_agent_id="rags.sample.echo", title="Echo Agent", description="Echo test agent", kind="assistant", ) ] monkeypatch.setattr( "control_plane_backend.product.service._fetch_runtime_templates", _fake_fetch_runtime_templates, ) app = create_app() container = get_application_container_from_app(app) container.configuration.platform.runtime_catalog_sources = [ RuntimeCatalogSourceConfig( runtime_id="runtime-a", base_url="http://runtime-a/pod/v1", enabled=True, ) ] async with AsyncClient( transport=ASGITransport(app=app), base_url="http://test" ) as client: resp = await client.get( f"/control-plane/v1/teams/{_PERSONAL_TEAM_ID}/agent-templates" ) assert resp.status_code == 200 payload = resp.json() assert payload == [ { "template_id": "runtime-a:rags.sample.echo", "source_runtime_id": "runtime-a", "source_agent_id": "rags.sample.echo", "display_name": "Echo Agent", "description": "Echo test agent", "category": "assistant", "tags": [], "capabilities": ["assistant"], "team_instantiable": True, "status": "available", "default_tuning_fields": [], "available_capabilities": [], "supports_capabilities": True, "default_capability_ids": [], # #2473: a template declaring neither reasoning field reports both # false — the platform default, and what a pod predating #2473 # sends. "reasoning_enabled": False, "reasoning_default_on": False, } ] @pytest.mark.asyncio async def test_team_agent_instances_returns_managed_identity( monkeypatch: pytest.MonkeyPatch, ) -> None: store = _FakeAgentInstanceStore([_make_record(team_id=_PERSONAL_TEAM_ID)]) app = create_app() _patch_store(monkeypatch, store) async with AsyncClient( transport=ASGITransport(app=app), base_url="http://test" ) as client: list_resp = await client.get( f"/control-plane/v1/teams/{_PERSONAL_TEAM_ID}/agent-instances" ) assert list_resp.status_code == 200 assert list_resp.json() == [ { "agent_instance_id": "instance-1", "team_id": _PERSONAL_TEAM_ID, "template_id": "runtime-a:rags.sample.echo", "display_name": "Echo Team Agent", "description": "Managed echo agent", "role": "Echo Team Agent", "usage_statement": "", # REASON-01 level 3 — a plain agent property, default off. "reasoning_enabled": False, # Amendment B — where the composer's toggle starts, also default off. "reasoning_default_on": False, "status": "enabled", "created_by": "internal-admin", "tuning_field_values": {}, "runtime_status": "unavailable", "catalog_warnings": [], "capability_config": {}, } ] @pytest.mark.asyncio async def test_team_runtime_binding_endpoint_resolves_for_member( monkeypatch: pytest.MonkeyPatch, ) -> None: """RUNTIME-07 rev. 2: the team-scoped resolution endpoint returns the runtime binding for a team member (ReBAC CAN_READ), replacing the admin-only path (F2).""" monkeypatch.setattr( "control_plane_backend.product.api.require_team_access", _fake_require_team_access, ) store = _FakeAgentInstanceStore([_make_record()]) app = create_app() _patch_store(monkeypatch, store) async with AsyncClient( transport=ASGITransport(app=app), base_url="http://test" ) as client: runtime_resp = await client.get( "/control-plane/v1/teams/personal/agent-instances/instance-1/runtime" ) assert runtime_resp.status_code == 200 assert runtime_resp.json()["agent_instance_id"] == "instance-1" assert runtime_resp.json()["template_agent_id"] == "rags.sample.echo" assert runtime_resp.json()["owner_team_id"] == "personal" @pytest.mark.asyncio async def test_prepare_execution_returns_ingress_relative_urls( monkeypatch: pytest.MonkeyPatch, ) -> None: monkeypatch.setattr( "control_plane_backend.product.api.require_team_access", _fake_require_team_access, ) store = _FakeAgentInstanceStore( [ _make_record( agent_instance_id="inst-42", source_runtime_id="agents-v2", template_id="agents-v2:rags.sample.echo", source_agent_id="rags.sample.echo", display_name="Echo Agent", description="Test", ) ] ) app = create_app() _patch_store(monkeypatch, store) container = get_application_container_from_app(app) container.configuration.platform.runtime_catalog_sources = [ RuntimeCatalogSourceConfig( runtime_id="agents-v2", base_url="http://agents-v2-svc.fred.svc.cluster.local/api/v1", enabled=True, ingress_prefix="/runtime/agents-v2", ) ] async with AsyncClient( transport=ASGITransport(app=app), base_url="http://test" ) as client: resp = await client.post( "/control-plane/v1/teams/personal/agent-instances/inst-42/prepare-execution" ) assert resp.status_code == 200 payload = resp.json() assert payload["agent_instance_id"] == "inst-42" assert payload["team_id"] == "personal" assert payload["runtime_id"] == "agents-v2" assert payload["execution_transport"] == "sse" assert payload["execute_url"] == "/runtime/agents-v2/agents/execute" assert payload["execute_stream_url"] == "/runtime/agents-v2/agents/execute/stream" assert ( payload["messages_url_template"] == "/runtime/agents-v2/agents/sessions/{session_id}/messages" ) assert payload["supports_streaming"] is True assert payload["supports_hitl"] is True # #1976: no selected capabilities → no computed chat controls. assert payload["chat_controls"] == [] # RUNTIME-07 rev. 2: no signed grant in the response — the control-plane issues # no capability; the pod authenticates via Keycloak and authorizes via OpenFGA. assert "execution_grant" not in payload for url_field in ("execute_url", "execute_stream_url", "messages_url_template"): assert "svc.cluster.local" not in payload[url_field] assert payload[url_field].startswith("/") # #1979: no capabilities selected on this instance → empty map. assert payload["capability_base_urls"] == {} def test_runtime_template_payload_accepts_new_and_legacy_chat_input_metadata() -> None: """Rolling upgrades accept template responses with or without the policy.""" base = { "template_agent_id": "rags.sample.echo", "title": "Echo", "description": "Echo agent", "kind": "assistant", } assert _RuntimeTemplatePayload.model_validate(base).max_chat_input_chars is None assert ( _RuntimeTemplatePayload.model_validate( {**base, "max_chat_input_chars": 321} ).max_chat_input_chars == 321 ) for malformed in (True, False, "321", 0, -1): assert ( _RuntimeTemplatePayload.model_validate( {**base, "max_chat_input_chars": malformed} ).max_chat_input_chars is None ) @pytest.mark.asyncio @pytest.mark.parametrize("published_limit", [321, None]) async def test_prepare_execution_propagates_optional_runtime_chat_input_limit( monkeypatch: pytest.MonkeyPatch, published_limit: int | None, ) -> None: """Preparation reuses one template fetch and tolerates an older runtime.""" monkeypatch.setattr( "control_plane_backend.product.api.require_team_access", _fake_require_team_access, ) store = _FakeAgentInstanceStore( [ _make_record( agent_instance_id="inst-limit", source_runtime_id="agents-v2", template_id="agents-v2:rags.sample.echo", source_agent_id="rags.sample.echo", ) ] ) app = create_app() _patch_store(monkeypatch, store) container = get_application_container_from_app(app) container.configuration.platform.runtime_catalog_sources = [ RuntimeCatalogSourceConfig( runtime_id="agents-v2", base_url="http://agents-v2-svc.fred.svc.cluster.local/api/v1", enabled=True, ingress_prefix="/runtime/agents-v2", ) ] fetch_calls = 0 async def _fake_fetch_runtime_templates( _base_url: str, include_non_public: bool = False ) -> list[_RuntimeTemplatePayload]: nonlocal fetch_calls fetch_calls += 1 assert include_non_public is True return [ _RuntimeTemplatePayload( template_agent_id="rags.sample.echo", title="Echo", description="Echo agent", kind="assistant", max_chat_input_chars=published_limit, ) ] monkeypatch.setattr( product_service, "_fetch_runtime_templates", _fake_fetch_runtime_templates, ) async with AsyncClient( transport=ASGITransport(app=app), base_url="http://test" ) as client: response = await client.post( "/control-plane/v1/teams/personal/agent-instances/inst-limit/prepare-execution" ) assert response.status_code == 200 assert fetch_calls == 1 if published_limit is None: assert "max_chat_input_chars" not in response.json() else: assert response.json()["max_chat_input_chars"] == published_limit @pytest.mark.asyncio async def test_prepare_execution_advertises_capability_base_urls( monkeypatch: pytest.MonkeyPatch, ) -> None: """#1979 (RFC §9.1): the instance-bound prep carries each selected capability's ingress-relative router base URL, so the in-session UI calls the pod routes directly (no proxy).""" monkeypatch.setattr( "control_plane_backend.product.api.require_team_access", _fake_require_team_access, ) record = _make_record( agent_instance_id="inst-cap", source_runtime_id="agents-v2", template_id="agents-v2:rags.sample.echo", source_agent_id="rags.sample.echo", display_name="Echo Agent", description="Test", ) record.tuning = ManagedAgentTuning( role="Echo Agent", description="Test", selected_capability_ids=["demo_echo"], ) store = _FakeAgentInstanceStore([record]) app = create_app() _patch_store(monkeypatch, store) container = get_application_container_from_app(app) container.configuration.platform.runtime_catalog_sources = [ RuntimeCatalogSourceConfig( runtime_id="agents-v2", base_url="http://agents-v2-svc.fred.svc.cluster.local/api/v1", enabled=True, ingress_prefix="/runtime/agents-v2", ) ] async with AsyncClient( transport=ASGITransport(app=app), base_url="http://test" ) as client: resp = await client.post( "/control-plane/v1/teams/personal/agent-instances/inst-cap/prepare-execution" ) assert resp.status_code == 200 assert resp.json()["capability_base_urls"] == { "demo_echo": "/runtime/agents-v2/capabilities/demo_echo" } @pytest.mark.asyncio async def test_agent_instance_mutations_require_can_update_agents( monkeypatch: pytest.MonkeyPatch, ) -> None: """RUNTIME-07 (bundled): enroll/patch/delete of agent instances must authorize on CAN_UPDATE_AGENTS (manager/owner), not CAN_READ — so a plain team member is refused in a collaborative team (REBAC.md). We assert each endpoint asks the team service for that exact permission.""" from fred_core import TeamPermission captured: dict[str, object] = {} async def _spy(user, team_id, deps=None, required_permissions=None, **_kw): captured["perms"] = required_permissions return TeamId(str(team_id)) monkeypatch.setattr("control_plane_backend.product.api.require_team_access", _spy) app = create_app() _patch_store(monkeypatch, _FakeAgentInstanceStore([])) async with AsyncClient( transport=ASGITransport(app=app), base_url="http://test" ) as client: # enroll await client.post( "/control-plane/v1/teams/fredlab/agent-instances", json={ "usage_statement": "Test usage statement covering purpose, users, data, and error impact.", "template_id": "runtime-a:foo", "display_name": "x", }, ) assert captured["perms"] == [TeamPermission.CAN_UPDATE_AGENTS] # delete captured.clear() await client.delete("/control-plane/v1/teams/fredlab/agent-instances/inst-1") assert captured["perms"] == [TeamPermission.CAN_UPDATE_AGENTS] @pytest.mark.asyncio async def test_prepare_execution_concatenates_attached_context_prompts( monkeypatch: pytest.MonkeyPatch, ) -> None: """Attached prompts resolve in position order and concatenate with '\\n\\n'.""" monkeypatch.setattr( "control_plane_backend.product.api.require_team_access", _fake_require_team_access, ) store = _FakeAgentInstanceStore( [ _make_record( agent_instance_id="inst-42", source_runtime_id="agents-v2", template_id="agents-v2:rags.sample.echo", source_agent_id="rags.sample.echo", display_name="Echo Agent", description="Test", ) ] ) session_store = _FakeSessionMetadataStore( [ SessionMetadataRecord( session_id="sess-1", team_id=TeamId("personal"), agent_instance_id="inst-42", user_id="admin", title=None, context_prompt_ids=["p1", "p2"], ) ] ) prompt_store = _FakePromptStore( [ _make_prompt_record(prompt_id="p1", team_id="personal", text="First."), _make_prompt_record(prompt_id="p2", team_id="personal", text="Second."), ] ) app = create_app() _patch_store(monkeypatch, store) _patch_session_store(monkeypatch, session_store) _patch_prompt_store(monkeypatch, prompt_store) container = get_application_container_from_app(app) container.configuration.platform.runtime_catalog_sources = [ RuntimeCatalogSourceConfig( runtime_id="agents-v2", base_url="http://agents-v2-svc.fred.svc.cluster.local/api/v1", enabled=True, ingress_prefix="/runtime/agents-v2", ) ] async with AsyncClient( transport=ASGITransport(app=app), base_url="http://test" ) as client: resp = await client.post( "/control-plane/v1/teams/personal/agent-instances/inst-42/prepare-execution", params={"session_id": "sess-1"}, ) assert resp.status_code == 200 assert resp.json()["context_prompt_text"] == "First.\n\nSecond." @pytest.mark.asyncio async def test_prepare_execution_skips_stale_context_prompt_ids( monkeypatch: pytest.MonkeyPatch, ) -> None: """A deleted/unknown attached id is skipped, not surfaced as an error.""" monkeypatch.setattr( "control_plane_backend.product.api.require_team_access", _fake_require_team_access, ) store = _FakeAgentInstanceStore( [ _make_record( agent_instance_id="inst-42", source_runtime_id="agents-v2", template_id="agents-v2:rags.sample.echo", source_agent_id="rags.sample.echo", display_name="Echo Agent", description="Test", ) ] ) session_store = _FakeSessionMetadataStore( [ SessionMetadataRecord( session_id="sess-1", team_id=TeamId("personal"), agent_instance_id="inst-42", user_id="admin", title=None, context_prompt_ids=["gone", "p2"], ) ] ) prompt_store = _FakePromptStore( [_make_prompt_record(prompt_id="p2", team_id="personal", text="Second.")] ) app = create_app() _patch_store(monkeypatch, store) _patch_session_store(monkeypatch, session_store) _patch_prompt_store(monkeypatch, prompt_store) container = get_application_container_from_app(app) container.configuration.platform.runtime_catalog_sources = [ RuntimeCatalogSourceConfig( runtime_id="agents-v2", base_url="http://agents-v2-svc.fred.svc.cluster.local/api/v1", enabled=True, ingress_prefix="/runtime/agents-v2", ) ] async with AsyncClient( transport=ASGITransport(app=app), base_url="http://test" ) as client: resp = await client.post( "/control-plane/v1/teams/personal/agent-instances/inst-42/prepare-execution", params={"session_id": "sess-1"}, ) assert resp.status_code == 200 assert resp.json()["context_prompt_text"] == "Second." @pytest.mark.asyncio async def test_prepare_execution_resolves_context_prompts_within_caller_scope( monkeypatch: pytest.MonkeyPatch, ) -> None: """Chat-context prompt resolution is scoped to the caller's authorized teams. Executing in a shared team, this exercises all three scope behaviors at once (PROMPTS.md §4): a prompt owned by the active team resolves; a prompt owned by the caller's *personal* team resolves via the personal fallback; a prompt owned by an unrelated team is skipped, never resolved — so no cross-team text leaks in. The caller is ``admin`` (``personal_team_id("admin") == _PERSONAL_TEAM_ID``), so this asserts the real ``personal-{uid}`` id resolves, not a literal. """ monkeypatch.setattr( "control_plane_backend.product.api.require_team_access", _fake_require_team_access, ) store = _FakeAgentInstanceStore( [ _make_record( agent_instance_id="inst-42", team_id="team-shared", source_runtime_id="agents-v2", template_id="agents-v2:rags.sample.echo", source_agent_id="rags.sample.echo", display_name="Echo Agent", description="Test", ) ] ) session_store = _FakeSessionMetadataStore( [ SessionMetadataRecord( session_id="sess-1", team_id=TeamId("team-shared"), agent_instance_id="inst-42", user_id="admin", title=None, context_prompt_ids=["p_team", "p_personal", "p_foreign"], ) ] ) prompt_store = _FakePromptStore( [ _make_prompt_record( prompt_id="p_team", team_id="team-shared", name="Team prompt", text="FromTeam.", ), _make_prompt_record( prompt_id="p_personal", team_id=_PERSONAL_TEAM_ID, name="Personal prompt", text="FromPersonal.", ), _make_prompt_record( prompt_id="p_foreign", team_id="other-team", name="Foreign prompt", text="Leaked.", ), ] ) app = create_app() _patch_store(monkeypatch, store) _patch_session_store(monkeypatch, session_store) _patch_prompt_store(monkeypatch, prompt_store) container = get_application_container_from_app(app) container.configuration.platform.runtime_catalog_sources = [ RuntimeCatalogSourceConfig( runtime_id="agents-v2", base_url="http://agents-v2-svc.fred.svc.cluster.local/api/v1", enabled=True, ingress_prefix="/runtime/agents-v2", ) ] async with AsyncClient( transport=ASGITransport(app=app), base_url="http://test" ) as client: resp = await client.post( "/control-plane/v1/teams/team-shared/agent-instances/inst-42/prepare-execution", params={"session_id": "sess-1"}, ) assert resp.status_code == 200 # Active-team prompt and personal-team prompt both resolve, in order; the # unrelated team's prompt is skipped — its text never appears. assert resp.json()["context_prompt_text"] == "FromTeam.\n\nFromPersonal." @pytest.mark.asyncio async def test_prepare_execution_rejects_session_owned_by_another_user( monkeypatch: pytest.MonkeyPatch, ) -> None: """A session created by a different user must never lend its context prompts to this caller's execution — even within the same team and for the same agent instance. Regression test for the finding: prior code did a raw, unchecked `session_id` fetch with no ownership check at all.""" monkeypatch.setattr( "control_plane_backend.product.api.require_team_access", _fake_require_team_access, ) store = _FakeAgentInstanceStore( [ _make_record( agent_instance_id="inst-42", source_runtime_id="agents-v2", template_id="agents-v2:rags.sample.echo", ) ] ) session_store = _FakeSessionMetadataStore( [ SessionMetadataRecord( session_id="sess-1", team_id=TeamId("personal"), agent_instance_id="inst-42", user_id="someone-else", title=None, context_prompt_ids=["p1"], ) ] ) prompt_store = _FakePromptStore( [_make_prompt_record(prompt_id="p1", team_id="personal", text="Secret.")] ) app = create_app() _patch_store(monkeypatch, store) _patch_session_store(monkeypatch, session_store) _patch_prompt_store(monkeypatch, prompt_store) container = get_application_container_from_app(app) container.configuration.platform.runtime_catalog_sources = [ RuntimeCatalogSourceConfig( runtime_id="agents-v2", base_url="http://agents-v2-svc.fred.svc.cluster.local/api/v1", enabled=True, ingress_prefix="/runtime/agents-v2", ) ] async with AsyncClient( transport=ASGITransport(app=app), base_url="http://test" ) as client: resp = await client.post( "/control-plane/v1/teams/personal/agent-instances/inst-42/prepare-execution", params={"session_id": "sess-1"}, ) assert resp.status_code == 404 # Never leak the prompt text or the owning identity in the error. assert "Secret." not in resp.text assert "someone-else" not in resp.text @pytest.mark.asyncio async def test_prepare_execution_rejects_session_with_no_recorded_owner( monkeypatch: pytest.MonkeyPatch, ) -> None: """A session row with `user_id=None` (no owner ever recorded — e.g. a row predating the column) must be denied by default, not treated as accessible to whoever asks. `_session_usable_for_execution` deliberately diverges here from the more permissive attachment-CRUD ownership check (`_get_owned_session_record`, which does allow an unowned row through) — see `_record_owned_by_user`'s `allow_unowned` doc in product/service.py.""" monkeypatch.setattr( "control_plane_backend.product.api.require_team_access", _fake_require_team_access, ) store = _FakeAgentInstanceStore( [ _make_record( agent_instance_id="inst-42", source_runtime_id="agents-v2", template_id="agents-v2:rags.sample.echo", ) ] ) session_store = _FakeSessionMetadataStore( [ SessionMetadataRecord( session_id="sess-1", team_id=TeamId("personal"), agent_instance_id="inst-42", user_id=None, title=None, context_prompt_ids=["p1"], ) ] ) prompt_store = _FakePromptStore( [_make_prompt_record(prompt_id="p1", team_id="personal", text="Secret.")] ) app = create_app() _patch_store(monkeypatch, store) _patch_session_store(monkeypatch, session_store) _patch_prompt_store(monkeypatch, prompt_store) container = get_application_container_from_app(app) container.configuration.platform.runtime_catalog_sources = [ RuntimeCatalogSourceConfig( runtime_id="agents-v2", base_url="http://agents-v2-svc.fred.svc.cluster.local/api/v1", enabled=True, ingress_prefix="/runtime/agents-v2", ) ] async with AsyncClient( transport=ASGITransport(app=app), base_url="http://test" ) as client: resp = await client.post( "/control-plane/v1/teams/personal/agent-instances/inst-42/prepare-execution", params={"session_id": "sess-1"}, ) assert resp.status_code == 404 assert "Secret." not in resp.text def test_record_owned_by_user_diverges_on_unowned_row_by_policy() -> None: """Locks in both sides of the deliberate `allow_unowned` divergence between `_get_owned_session_record` (attachment CRUD, allow_unowned=True) and `_session_usable_for_execution` (execution context, allow_unowned=False), so a future edit can't silently re-merge the two policies.""" from control_plane_backend.product.service import _record_owned_by_user unowned = SessionMetadataRecord( session_id="sess-1", team_id=TeamId("personal"), agent_instance_id="inst-1", user_id=None, title=None, ) assert _record_owned_by_user(unowned, user_id="admin", allow_unowned=True) is True assert _record_owned_by_user(unowned, user_id="admin", allow_unowned=False) is False owned = SessionMetadataRecord( session_id="sess-2", team_id=TeamId("personal"), agent_instance_id="inst-1", user_id="admin", title=None, ) assert _record_owned_by_user(owned, user_id="admin", allow_unowned=True) is True assert _record_owned_by_user(owned, user_id="admin", allow_unowned=False) is True assert ( _record_owned_by_user(owned, user_id="someone-else", allow_unowned=True) is False ) @pytest.mark.asyncio async def test_prepare_execution_rejects_session_owned_by_another_team( monkeypatch: pytest.MonkeyPatch, ) -> None: """A session belonging to a different team must never lend its context prompts to this caller's execution, even though `prepare_execution` already scopes prompt *resolution* to the caller's own team — the session load itself must reject first.""" monkeypatch.setattr( "control_plane_backend.product.api.require_team_access", _fake_require_team_access, ) store = _FakeAgentInstanceStore( [ _make_record( agent_instance_id="inst-42", source_runtime_id="agents-v2", template_id="agents-v2:rags.sample.echo", ) ] ) session_store = _FakeSessionMetadataStore( [ SessionMetadataRecord( session_id="sess-1", team_id=TeamId("other-team"), agent_instance_id="inst-42", user_id="admin", title=None, context_prompt_ids=["p1"], ) ] ) prompt_store = _FakePromptStore( [_make_prompt_record(prompt_id="p1", team_id="other-team", text="Secret.")] ) app = create_app() _patch_store(monkeypatch, store) _patch_session_store(monkeypatch, session_store) _patch_prompt_store(monkeypatch, prompt_store) container = get_application_container_from_app(app) container.configuration.platform.runtime_catalog_sources = [ RuntimeCatalogSourceConfig( runtime_id="agents-v2", base_url="http://agents-v2-svc.fred.svc.cluster.local/api/v1", enabled=True, ingress_prefix="/runtime/agents-v2", ) ] async with AsyncClient( transport=ASGITransport(app=app), base_url="http://test" ) as client: resp = await client.post( "/control-plane/v1/teams/personal/agent-instances/inst-42/prepare-execution", params={"session_id": "sess-1"}, ) assert resp.status_code == 404 assert "Secret." not in resp.text @pytest.mark.asyncio async def test_prepare_execution_rejects_session_scoped_to_another_agent_instance( monkeypatch: pytest.MonkeyPatch, ) -> None: """A session explicitly created for a different agent instance must not lend its context prompts here, even for the same user and team. A session with no `agent_instance_id` at all (agent-agnostic) is unaffected — see `test_prepare_execution_resolves_context_prompts_within_caller_scope` for that path.""" monkeypatch.setattr( "control_plane_backend.product.api.require_team_access", _fake_require_team_access, ) store = _FakeAgentInstanceStore( [ _make_record( agent_instance_id="inst-42", source_runtime_id="agents-v2", template_id="agents-v2:rags.sample.echo", ) ] ) session_store = _FakeSessionMetadataStore( [ SessionMetadataRecord( session_id="sess-1", team_id=TeamId("personal"), agent_instance_id="inst-other", user_id="admin", title=None, context_prompt_ids=["p1"], ) ] ) prompt_store = _FakePromptStore( [_make_prompt_record(prompt_id="p1", team_id="personal", text="Secret.")] ) app = create_app() _patch_store(monkeypatch, store) _patch_session_store(monkeypatch, session_store) _patch_prompt_store(monkeypatch, prompt_store) container = get_application_container_from_app(app) container.configuration.platform.runtime_catalog_sources = [ RuntimeCatalogSourceConfig( runtime_id="agents-v2", base_url="http://agents-v2-svc.fred.svc.cluster.local/api/v1", enabled=True, ingress_prefix="/runtime/agents-v2", ) ] async with AsyncClient( transport=ASGITransport(app=app), base_url="http://test" ) as client: resp = await client.post( "/control-plane/v1/teams/personal/agent-instances/inst-42/prepare-execution", params={"session_id": "sess-1"}, ) assert resp.status_code == 404 assert "Secret." not in resp.text @pytest.mark.asyncio async def test_prepare_execution_returns_404_for_unknown_instance( monkeypatch: pytest.MonkeyPatch, ) -> None: monkeypatch.setattr( "control_plane_backend.product.api.require_team_access", _fake_require_team_access, ) store = _FakeAgentInstanceStore([]) app = create_app() _patch_store(monkeypatch, store) async with AsyncClient( transport=ASGITransport(app=app), base_url="http://test" ) as client: resp = await client.post( "/control-plane/v1/teams/personal/agent-instances/no-such/prepare-execution" ) assert resp.status_code == 404 @pytest.mark.asyncio async def test_prepare_execution_returns_409_for_disabled_instance( monkeypatch: pytest.MonkeyPatch, ) -> None: monkeypatch.setattr( "control_plane_backend.product.api.require_team_access", _fake_require_team_access, ) store = _FakeAgentInstanceStore( [_make_record(agent_instance_id="inst-disabled", enabled=False)] ) app = create_app() _patch_store(monkeypatch, store) async with AsyncClient( transport=ASGITransport(app=app), base_url="http://test" ) as client: resp = await client.post( "/control-plane/v1/teams/personal/agent-instances/inst-disabled/prepare-execution" ) assert resp.status_code == 409 @pytest.mark.asyncio async def test_prepare_execution_returns_503_when_ingress_prefix_missing( monkeypatch: pytest.MonkeyPatch, ) -> None: monkeypatch.setattr( "control_plane_backend.product.api.require_team_access", _fake_require_team_access, ) store = _FakeAgentInstanceStore( [ _make_record( agent_instance_id="inst-no-prefix", source_runtime_id="agents-v2", template_id="agents-v2:rags.sample.echo", ) ] ) app = create_app() _patch_store(monkeypatch, store) container = get_application_container_from_app(app) container.configuration.platform.runtime_catalog_sources = [ RuntimeCatalogSourceConfig( runtime_id="agents-v2", base_url="http://agents-v2-svc.fred.svc.cluster.local/api/v1", enabled=True, ) ] async with AsyncClient( transport=ASGITransport(app=app), base_url="http://test" ) as client: resp = await client.post( "/control-plane/v1/teams/personal/agent-instances/inst-no-prefix/prepare-execution" ) assert resp.status_code == 503 @pytest.mark.asyncio async def test_prepare_execution_team_mismatch_returns_404( monkeypatch: pytest.MonkeyPatch, ) -> None: monkeypatch.setattr( "control_plane_backend.product.api.require_team_access", _fake_require_team_access, ) store = _FakeAgentInstanceStore( [ _make_record( agent_instance_id="inst-other-team", team_id="team-b", source_runtime_id="agents-v2", template_id="agents-v2:rags.sample.echo", ) ] ) app = create_app() _patch_store(monkeypatch, store) container = get_application_container_from_app(app) container.configuration.platform.runtime_catalog_sources = [ RuntimeCatalogSourceConfig( runtime_id="agents-v2", base_url="http://agents-v2-svc/api/v1", enabled=True, ingress_prefix="/runtime/agents-v2", ) ] async with AsyncClient( transport=ASGITransport(app=app), base_url="http://test" ) as client: resp = await client.post( "/control-plane/v1/teams/personal/agent-instances/inst-other-team/prepare-execution" ) assert resp.status_code == 404 @pytest.mark.asyncio async def test_enroll_agent_instance_creates_db_record( monkeypatch: pytest.MonkeyPatch, ) -> None: monkeypatch.setattr( "control_plane_backend.product.api.require_team_access", _fake_require_team_access, ) store = _FakeAgentInstanceStore([]) app = create_app() _patch_store(monkeypatch, store) container = get_application_container_from_app(app) container.configuration.platform.runtime_catalog_sources = [ RuntimeCatalogSourceConfig( runtime_id="runtime-a", base_url="http://runtime-a/pod/v1", enabled=True, ingress_prefix="/runtime/runtime-a", ) ] async def _fake_fetch_runtime_templates( _base_url: str, include_non_public: bool = False ): return [ _RuntimeTemplatePayload( template_agent_id="rags.sample.echo", title="Echo Agent", description="Echo template description", kind="assistant", default_tuning=ManagedAgentTuning( role="Echo Agent", description="Echo template description", tags=["ops"], ), ) ] monkeypatch.setattr( "control_plane_backend.product.service._fetch_runtime_templates", _fake_fetch_runtime_templates, ) async with AsyncClient( transport=ASGITransport(app=app), base_url="http://test" ) as client: resp = await client.post( "/control-plane/v1/teams/personal/agent-instances", json={ "usage_statement": "Test usage statement covering purpose, users, data, and error impact.", "template_id": "runtime-a:rags.sample.echo", "display_name": "My Echo Agent", "description": "A test echo agent", }, ) assert resp.status_code == 201 payload = resp.json() assert payload["team_id"] == "personal" assert payload["template_id"] == "runtime-a:rags.sample.echo" assert payload["display_name"] == "My Echo Agent" assert payload["description"] == "A test echo agent" assert payload["status"] == "enabled" assert payload["created_by"] == "admin" assert "agent_instance_id" in payload assert len(store._records) == 1 assert store._records[0].source_runtime_id == "runtime-a" assert store._records[0].source_agent_id == "rags.sample.echo" assert store._records[0].tuning.tags == ["ops"] # No explicit selection at enroll time -> resolved against the template's # default capability ids (none declared by this fixture template) and # materialized as an explicit list, never left `None` (CAPAB-01 / #1980, # RFC §8.1 amendment — a `None` selection previously skipped ReBAC # enforcement entirely). assert store._records[0].tuning.selected_capability_ids == [] @pytest.mark.asyncio async def test_enroll_agent_instance_unreachable_runtime_returns_503( monkeypatch: pytest.MonkeyPatch, ) -> None: monkeypatch.setattr( "control_plane_backend.product.api.require_team_access", _fake_require_team_access, ) store = _FakeAgentInstanceStore([]) app = create_app() _patch_store(monkeypatch, store) container = get_application_container_from_app(app) container.configuration.platform.runtime_catalog_sources = [ RuntimeCatalogSourceConfig( runtime_id="runtime-a", base_url="http://runtime-a/pod/v1", enabled=True, ingress_prefix="/runtime/runtime-a", ) ] async def _raise_connect_error(self, url, params=None): # noqa: ANN001 raise httpx.ConnectError("All connection attempts failed") monkeypatch.setattr(httpx.AsyncClient, "get", _raise_connect_error) async with AsyncClient( transport=ASGITransport(app=app), base_url="http://test" ) as client: resp = await client.post( "/control-plane/v1/teams/personal/agent-instances", json={ "usage_statement": "Test usage statement covering purpose, users, data, and error impact.", "template_id": "runtime-a:rags.sample.echo", "display_name": "My Echo Agent", "description": "A test echo agent", }, ) assert resp.status_code == 503 detail = resp.json()["detail"] assert "runtime-a" in detail assert "not reachable" in detail assert len(store._records) == 0 @pytest.mark.asyncio async def test_agent_instance_store_create_overrides_sqlite_now_default( tmp_path: Path, ) -> None: db_path = tmp_path / "agent-instance.sqlite3" engine = create_async_engine(f"sqlite+aiosqlite:///{db_path}") async with engine.begin() as conn: await conn.execute( text( """ CREATE TABLE agent_instance ( agent_instance_id VARCHAR NOT NULL PRIMARY KEY, team_id VARCHAR NOT NULL, template_id VARCHAR NOT NULL, source_runtime_id VARCHAR NOT NULL, source_agent_id VARCHAR NOT NULL, display_name VARCHAR(255) NOT NULL, description VARCHAR(500), enabled BOOLEAN NOT NULL, suspension_reason VARCHAR(64), created_by VARCHAR, updated_by VARCHAR, tuning_json TEXT, prompt_refs_json TEXT, created_at DATETIME NOT NULL DEFAULT (now()), updated_at DATETIME NOT NULL DEFAULT (now()) ) """ ) ) try: store = AgentInstanceStore(engine) created = await store.create( AgentInstanceRecord( agent_instance_id="inst-sqlite-now", team_id=TeamId("personal"), template_id="runtime-a:rags.sample.echo", source_runtime_id="runtime-a", source_agent_id="rags.sample.echo", display_name="SQLite-safe agent", description="Created with Python timestamps", enabled=True, created_by="admin", tuning=ManagedAgentTuning( role="SQLite-safe agent", description="Created with Python timestamps", ), ) ) assert created is not None assert created.agent_instance_id == "inst-sqlite-now" assert created.created_at is not None assert created.updated_at is not None finally: await engine.dispose() @pytest.mark.asyncio async def test_patch_team_session_updates_last_activity( monkeypatch: pytest.MonkeyPatch, ) -> None: monkeypatch.setattr( "control_plane_backend.product.api.require_team_access", _fake_require_team_access, ) initial = datetime.fromisoformat("2026-04-23T08:00:00+00:00") refreshed = datetime.fromisoformat("2026-04-23T08:05:00+00:00") store = _FakeSessionMetadataStore( [ SessionMetadataRecord( session_id="session-1", team_id=TeamId("personal"), agent_instance_id="instance-1", user_id="admin", title="First turn", created_at=initial, updated_at=initial, ) ] ) _patch_session_store(monkeypatch, store) app = create_app() async with AsyncClient( transport=ASGITransport(app=app), base_url="http://test" ) as client: resp = await client.patch( "/control-plane/v1/teams/personal/sessions/session-1", json={"updated_at": refreshed.isoformat()}, ) assert resp.status_code == 200 payload = resp.json() assert payload["session_id"] == "session-1" assert payload["team_id"] == "personal" assert payload["updated_at"] == "2026-04-23T08:05:00Z" assert store._records[0].updated_at == refreshed @pytest.mark.asyncio async def test_patch_team_session_returns_404_for_other_team_session( monkeypatch: pytest.MonkeyPatch, ) -> None: monkeypatch.setattr( "control_plane_backend.product.api.require_team_access", _fake_require_team_access, ) store = _FakeSessionMetadataStore( [ SessionMetadataRecord( session_id="session-1", team_id=TeamId("other-team"), agent_instance_id="instance-1", user_id="admin", title=None, ) ] ) _patch_session_store(monkeypatch, store) app = create_app() async with AsyncClient( transport=ASGITransport(app=app), base_url="http://test" ) as client: resp = await client.patch( "/control-plane/v1/teams/personal/sessions/session-1", json={"updated_at": "2026-04-23T08:05:00+00:00"}, ) assert resp.status_code == 404 @pytest.mark.asyncio async def test_patch_team_session_returns_404_for_other_user_session( monkeypatch: pytest.MonkeyPatch, ) -> None: monkeypatch.setattr( "control_plane_backend.product.api.require_team_access", _fake_require_team_access, ) store = _FakeSessionMetadataStore( [ SessionMetadataRecord( session_id="session-1", team_id=TeamId("personal"), agent_instance_id="instance-1", user_id="alice", title="Owned by Alice", ) ] ) _patch_session_store(monkeypatch, store) app = create_app() async with AsyncClient( transport=ASGITransport(app=app), base_url="http://test" ) as client: resp = await client.patch( "/control-plane/v1/teams/personal/sessions/session-1", json={"title": "Should fail"}, ) assert resp.status_code == 404 assert store._records[0].title == "Owned by Alice" @pytest.mark.asyncio async def test_patch_team_session_updates_title( monkeypatch: pytest.MonkeyPatch, ) -> None: monkeypatch.setattr( "control_plane_backend.product.api.require_team_access", _fake_require_team_access, ) store = _FakeSessionMetadataStore( [ SessionMetadataRecord( session_id="session-1", team_id=TeamId("personal"), agent_instance_id="instance-1", user_id="admin", title=None, ) ] ) _patch_session_store(monkeypatch, store) app = create_app() async with AsyncClient( transport=ASGITransport(app=app), base_url="http://test" ) as client: resp = await client.patch( "/control-plane/v1/teams/personal/sessions/session-1", json={"title": "Analysis of Q1 report"}, ) assert resp.status_code == 200 payload = resp.json() assert payload["title"] == "Analysis of Q1 report" assert store._records[0].title == "Analysis of Q1 report" @pytest.mark.asyncio async def test_patch_team_session_updates_title_and_activity( monkeypatch: pytest.MonkeyPatch, ) -> None: monkeypatch.setattr( "control_plane_backend.product.api.require_team_access", _fake_require_team_access, ) initial = datetime.fromisoformat("2026-04-23T08:00:00+00:00") refreshed = datetime.fromisoformat("2026-04-23T08:10:00+00:00") store = _FakeSessionMetadataStore( [ SessionMetadataRecord( session_id="session-1", team_id=TeamId("personal"), agent_instance_id="instance-1", user_id="admin", title=None, updated_at=initial, ) ] ) _patch_session_store(monkeypatch, store) app = create_app() async with AsyncClient( transport=ASGITransport(app=app), base_url="http://test" ) as client: resp = await client.patch( "/control-plane/v1/teams/personal/sessions/session-1", json={"title": "My analysis", "updated_at": refreshed.isoformat()}, ) assert resp.status_code == 200 payload = resp.json() assert payload["title"] == "My analysis" assert payload["updated_at"] == "2026-04-23T08:10:00Z" assert store._records[0].title == "My analysis" assert store._records[0].updated_at == refreshed @pytest.mark.asyncio async def test_post_team_session_returns_conflict_for_duplicate_session( monkeypatch: pytest.MonkeyPatch, ) -> None: """ Verify duplicate control-plane session creation returns HTTP 409. Why this test exists: - API conflict handling should rely on explicit store/domain errors instead of brittle string parsing of SQL exceptions How to use it: - run with the offline `control-plane-backend` test suite Example: - `pytest tests/test_main.py -q` """ monkeypatch.setattr( "control_plane_backend.product.api.require_team_access", _fake_require_team_access, ) _patch_session_store( monkeypatch, cast(Any, _DuplicateSessionMetadataStore()), ) app = create_app() async with AsyncClient( transport=ASGITransport(app=app), base_url="http://test" ) as client: resp = await client.post( "/control-plane/v1/teams/personal/sessions", json={ "session_id": "session-duplicate", "agent_instance_id": "instance-1", "title": "Existing session", }, ) assert resp.status_code == 409 assert resp.json()["detail"] == "Session 'session-duplicate' already exists." @pytest.mark.asyncio async def test_delete_team_session_returns_404_for_other_user_session( monkeypatch: pytest.MonkeyPatch, ) -> None: monkeypatch.setattr( "control_plane_backend.product.api.require_team_access", _fake_require_team_access, ) store = _FakeSessionMetadataStore( [ SessionMetadataRecord( session_id="session-1", team_id=TeamId("personal"), agent_instance_id="instance-1", user_id="alice", title="Owned by Alice", ) ] ) _patch_session_store(monkeypatch, store) app = create_app() async with AsyncClient( transport=ASGITransport(app=app), base_url="http://test" ) as client: resp = await client.delete( "/control-plane/v1/teams/personal/sessions/session-1" ) assert resp.status_code == 404 assert len(store._records) == 1 assert store._records[0].session_id == "session-1" assert store._records[0].user_id == "alice" assert store._records[0].title == "Owned by Alice" @pytest.mark.asyncio async def test_create_session_persists_source_runtime_id_from_live_instance() -> None: """`create_session` must capture `source_runtime_id` from the (currently live) agent instance, so erasure can later resolve the runtime even if the instance is deleted before the session is (issue #2089, RFC §7).""" session_store = _FakeSessionMetadataStore([]) deps = _build_erasure_deps( session_store, _FakeSessionAttachmentStore([]), agent_instance_store=_FakeAgentInstanceStore( [ _make_record( agent_instance_id="instance-1", source_runtime_id="runtime-a" ) ] ), ) await product_service.create_session( KeycloakUser(uid="admin", username="admin", roles=[]), TeamId("personal"), CreateSessionRequest( session_id="session-1", agent_instance_id="instance-1", title="New chat" ), deps, ) assert len(session_store._records) == 1 assert session_store._records[0].source_runtime_id == "runtime-a" @pytest.mark.asyncio async def test_create_session_leaves_source_runtime_id_none_without_agent_instance() -> ( None ): """No `agent_instance_id` on the request → no instance lookup, no `source_runtime_id` — matches a personal-space session with no managed agent bound yet.""" session_store = _FakeSessionMetadataStore([]) deps = _build_erasure_deps( session_store, _FakeSessionAttachmentStore([]), agent_instance_store=_FakeAgentInstanceStore([]), ) await product_service.create_session( KeycloakUser(uid="admin", username="admin", roles=[]), TeamId("personal"), CreateSessionRequest(session_id="session-1", title="New chat"), deps, ) assert session_store._records[0].source_runtime_id is None def _patch_runtime_erase_ok(monkeypatch: pytest.MonkeyPatch) -> None: """Make erase_session's runtime step succeed for HTTP delete tests. These tests build the app from the test config, which declares no runtime catalog sources — so the runtime erase can't resolve, and under the retry-safe ordering (RFC §2.1) the metadata row is correctly RETAINED on a partial failure. To exercise the intended *happy path* (delete fully erases and removes the session), stub the runtime resolution + calls to succeed. """ async def _resolve( self: Any, *, team_id: Any, agent_instance_id: Any, source_runtime_id: Any = None, ) -> tuple[str, None]: return "http://runtime-a.internal", None monkeypatch.setattr( "control_plane_backend.sessions.erasure_service." "ConversationErasureService._resolve_runtime_base_url", _resolve, ) monkeypatch.setattr( "control_plane_backend.sessions.erasure_service.httpx.AsyncClient", _make_runtime_client([]), ) @pytest.mark.asyncio async def test_delete_team_session_deletes_owned_session( monkeypatch: pytest.MonkeyPatch, ) -> None: monkeypatch.setattr( "control_plane_backend.product.api.require_team_access", _fake_require_team_access, ) store = _FakeSessionMetadataStore( [ SessionMetadataRecord( session_id="session-1", team_id=TeamId("personal"), agent_instance_id="instance-1", user_id="admin", title="Owned by admin", ) ] ) _patch_session_store(monkeypatch, store) _patch_runtime_erase_ok(monkeypatch) app = create_app() async with AsyncClient( transport=ASGITransport(app=app), base_url="http://test" ) as client: resp = await client.delete( "/control-plane/v1/teams/personal/sessions/session-1" ) assert resp.status_code == 204 assert store._records == [] @pytest.mark.asyncio async def test_delete_team_session_cleans_up_all_session_attachments( monkeypatch: pytest.MonkeyPatch, ) -> None: monkeypatch.setattr( "control_plane_backend.product.api.require_team_access", _fake_require_team_access, ) session_store = _FakeSessionMetadataStore( [ SessionMetadataRecord( session_id="session-1", team_id=TeamId("personal"), agent_instance_id="instance-1", user_id="admin", title="Owned by admin", ) ] ) attachment_store = _FakeSessionAttachmentStore( [ SessionAttachmentRecord( session_id="session-1", attachment_id="attachment-1", name="notes.md", summary_md="# Notes", document_uid="doc-1", storage_key="uploads/notes.md", ), SessionAttachmentRecord( session_id="session-1", attachment_id="attachment-2", name="diagram.png", summary_md="![diagram](diagram.png)", document_uid="doc-2", storage_key="uploads/diagram.png", ), ] ) cleanup_calls: list[dict[str, str | None]] = [] async def _fake_cleanup(**kwargs: Any) -> None: cleanup_calls.append( { "document_uid": kwargs["document_uid"], "storage_key": kwargs["storage_key"], "session_id": kwargs["session_id"], } ) monkeypatch.setattr( "control_plane_backend.product.service._delete_knowledge_flow_attachment", _fake_cleanup, ) _patch_session_store(monkeypatch, session_store) _patch_session_attachment_store(monkeypatch, attachment_store) _patch_runtime_erase_ok(monkeypatch) app = create_app() async with AsyncClient( transport=ASGITransport(app=app), base_url="http://test" ) as client: resp = await client.delete( "/control-plane/v1/teams/personal/sessions/session-1", headers={"Authorization": "Bearer test-token"}, ) assert resp.status_code == 204 assert session_store._records == [] assert attachment_store._records == [] assert cleanup_calls == [ { "document_uid": "doc-1", "storage_key": "uploads/notes.md", "session_id": "session-1", }, { "document_uid": "doc-2", "storage_key": "uploads/diagram.png", "session_id": "session-1", }, ] class _FakeKPIStore: """In-memory stand-in for the OpenSearch KPI store (A3). `anonymise_for_session` records the calls and returns a fixed count, or raises when `fail` is set (to exercise per-store isolation). """ def __init__(self, *, updated: int = 4, fail: bool = False) -> None: self.updated = updated self.fail = fail self.calls: list[str] = [] def anonymise_for_session(self, session_id: str) -> int: self.calls.append(session_id) if self.fail: raise RuntimeError("opensearch down") return self.updated def _build_erasure_deps( session_store: _FakeSessionMetadataStore, attachment_store: _FakeSessionAttachmentStore, *, agent_instance_store: _FakeAgentInstanceStore | None = None, configuration: Any = None, kpi_store: _FakeKPIStore | None = None, policy_catalog: Any = None, team_metadata_store: Any = None, purge_queue_store: Any = None, task_service: Any = None, ) -> ProductServiceDependencies: """Minimal deps bundle wiring only the collaborators erase_session uses. `agent_instance_store` + `configuration` are the A2 additions used to resolve a session's runtime; A1 callers omit them (runtime stays unresolved, recorded ok=false). `kpi_store` is the A3 addition; when omitted the KPI store is absent (a no-op ok entry, nothing to anonymise). """ return ProductServiceDependencies( configuration=configuration, # type: ignore[arg-type] team_dependencies=None, # type: ignore[arg-type] get_agent_instance_store=lambda: agent_instance_store, # type: ignore[arg-type,return-value] get_team_capability_settings_store=lambda: None, # type: ignore[arg-type,return-value] get_team_routing_policy_store=lambda: None, # type: ignore[arg-type,return-value] get_platform_model_binding_store=lambda: None, # type: ignore[arg-type,return-value] get_platform_prompt_store=lambda: None, # type: ignore[arg-type,return-value] get_model_reasoning_store=lambda: None, # type: ignore[arg-type,return-value] get_session_metadata_store=lambda: session_store, # type: ignore[arg-type,return-value] get_team_metadata_store=lambda: team_metadata_store, # type: ignore[arg-type,return-value] get_session_attachment_store=lambda: attachment_store, # type: ignore[arg-type,return-value] get_prompt_store=lambda: None, # type: ignore[arg-type,return-value] get_prompt_category_store=lambda: None, # type: ignore[arg-type,return-value] get_kpi_writer=lambda: None, # type: ignore[arg-type,return-value] get_kpi_store=lambda: kpi_store, # type: ignore[arg-type,return-value] get_policy_catalog=lambda: policy_catalog, # type: ignore[arg-type,return-value] get_purge_queue_store=lambda: purge_queue_store, # type: ignore[arg-type,return-value] get_task_service=lambda: task_service or _NoopTaskService(), # type: ignore[arg-type,return-value] get_platform_bootstrap_store=lambda: None, # type: ignore[arg-type,return-value] ) class _NoopTaskService: """No-op task service for erase tests that don't assert task emission. `schedule_erasure_task` / the worker call into the task service best-effort; this satisfies those calls without recording anything, so the delete-window and erase tests can ignore the erasure-task bookkeeping. """ async def start(self, *_a: Any, **_k: Any) -> Any: return SimpleNamespace(task_id="noop-task") async def record(self, *_a: Any, **_k: Any) -> None: return None async def list_tasks(self, *_a: Any, **_k: Any) -> Any: return SimpleNamespace(tasks=[]) class _RecordingErasureTaskService: """Task service that records started tasks and surfaces them via list_tasks. Realistic enough for the CTRLP-12 anti-duplication / self-heal tests: a task created by `start` becomes a non-terminal task that `find_active_erasure_task_id` can then find (matched on `target.id`). `starts` counts creations. """ def __init__(self, seeded_targets: list[str] | None = None) -> None: self.starts = 0 # Pre-seed active tasks NOT minted through `start` (starts stays 0) — used # to assert an existing task suppresses recreation. self._active: list[Any] = [ SimpleNamespace(task_id=f"seed-{sid}", target=SimpleNamespace(id=sid)) for sid in (seeded_targets or []) ] async def start(self, *_a: Any, target: Any = None, **_k: Any) -> Any: self.starts += 1 task_id = f"task-{self.starts}" self._active.append(SimpleNamespace(task_id=task_id, target=target)) return SimpleNamespace(task_id=task_id) async def record(self, *_a: Any, **_k: Any) -> None: return None async def list_tasks(self, *_a: Any, **_k: Any) -> Any: return SimpleNamespace(tasks=list(self._active)) def _runtime_config( *, runtime_id: str = "runtime-a", base_url: str = "http://runtime-a.internal" ) -> Any: """A stub configuration exposing one enabled runtime catalog source.""" from control_plane_backend.config.models import RuntimeCatalogSourceConfig return SimpleNamespace( platform=SimpleNamespace( runtime_catalog_sources=[ RuntimeCatalogSourceConfig( runtime_id=runtime_id, base_url=base_url, enabled=True ) ] ) ) def _make_runtime_client( calls: list[tuple[str, dict[str, str]]], *, history_deleted: int = 3, checkpoint_deleted: int = 1, history_error: bool = False, checkpoint_error: bool = False, ) -> type: """Build a fake httpx.AsyncClient recording runtime DELETEs into `calls`. Checkpoint DELETE → 200 `{"deleted": checkpoint_deleted}` (or a 502 when `checkpoint_error` is set, to exercise the orphan fix); transcript DELETE → 200 `{"deleted": history_deleted}`, or a 502 failure when `history_error` is set (to exercise per-store isolation). """ class _RuntimeClient: def __init__(self, *args: Any, **kwargs: Any) -> None: self.timeout = kwargs.get("timeout") async def __aenter__(self) -> "_RuntimeClient": return self async def __aexit__(self, exc_type: Any, exc: Any, tb: Any) -> None: return None async def delete(self, url: str, *, headers: dict[str, str]) -> httpx.Response: calls.append((url, headers)) request = httpx.Request("DELETE", url, headers=headers) if "/agents/checkpoints/" in url: if checkpoint_error: return httpx.Response(502, text="boom", request=request) return httpx.Response( 200, json={"deleted": checkpoint_deleted}, request=request ) if history_error: return httpx.Response(502, text="boom", request=request) return httpx.Response( 200, json={"deleted": history_deleted}, request=request ) return _RuntimeClient @pytest.mark.asyncio async def test_erase_session_receipt_lists_attachment_and_metadata_stores( monkeypatch: pytest.MonkeyPatch, ) -> None: """erase_session returns a per-store receipt for the stores it erases (A1).""" from control_plane_backend.sessions.erasure_service import ( ConversationErasureService, ) session_store = _FakeSessionMetadataStore( [ SessionMetadataRecord( session_id="session-1", team_id=TeamId("personal"), agent_instance_id="instance-1", user_id="admin", title="Owned by admin", ) ] ) attachment_store = _FakeSessionAttachmentStore( [ SessionAttachmentRecord( session_id="session-1", attachment_id="attachment-1", name="notes.md", summary_md="# Notes", document_uid="doc-1", storage_key="uploads/notes.md", ), SessionAttachmentRecord( session_id="session-1", attachment_id="attachment-2", name="diagram.png", summary_md="![diagram](diagram.png)", document_uid="doc-2", storage_key="uploads/diagram.png", ), ] ) cleanup_calls: list[str | None] = [] async def _fake_cleanup(**kwargs: Any) -> None: cleanup_calls.append(kwargs["document_uid"]) monkeypatch.setattr( "control_plane_backend.product.service._delete_knowledge_flow_attachment", _fake_cleanup, ) runtime_calls: list[tuple[str, dict[str, str]]] = [] monkeypatch.setattr( "control_plane_backend.sessions.erasure_service.httpx.AsyncClient", _make_runtime_client(runtime_calls), ) deps = _build_erasure_deps( session_store, attachment_store, agent_instance_store=_FakeAgentInstanceStore( [ _make_record( agent_instance_id="instance-1", source_runtime_id="runtime-a" ) ] ), configuration=_runtime_config( runtime_id="runtime-a", base_url="http://runtime-a.internal" ), ) receipt = await ConversationErasureService(deps).erase_session( team_id=TeamId("personal"), session_id="session-1", user_id="admin", authorization="Bearer test-token", ) assert receipt.ok is True by_store = {r.store: r for r in receipt.stores} assert by_store["attachments"].deleted_count == 2 assert by_store["attachments"].ok is True assert by_store["session_metadata"].deleted_count == 1 assert by_store["session_metadata"].ok is True # Same deletes as the former delete_session — no more, no fewer, in order. assert cleanup_calls == ["doc-1", "doc-2"] assert attachment_store._records == [] assert session_store._records == [] @pytest.mark.asyncio async def test_erase_session_noop_session_yields_all_zero_ok_receipt( monkeypatch: pytest.MonkeyPatch, ) -> None: """A session with nothing to erase yields an all-zero, still-ok receipt (A1). Under A2 the runtime is still reached — it returns `{"deleted": 0}` for an already-gone/non-owned session, so idempotent re-erase stays ok=True. """ from control_plane_backend.sessions.erasure_service import ( ConversationErasureService, ) # Legacy/unowned session (user_id=None): the ownership check passes but the # owner-scoped metadata delete matches no row, and there are no attachments, # so every store erases zero — erase of nothing still succeeds (ok=True). session_store = _FakeSessionMetadataStore( [ SessionMetadataRecord( session_id="session-1", team_id=TeamId("personal"), agent_instance_id="instance-1", user_id=None, title="Legacy session", ) ] ) attachment_store = _FakeSessionAttachmentStore([]) runtime_calls: list[tuple[str, dict[str, str]]] = [] monkeypatch.setattr( "control_plane_backend.sessions.erasure_service.httpx.AsyncClient", _make_runtime_client(runtime_calls, history_deleted=0), ) deps = _build_erasure_deps( session_store, attachment_store, agent_instance_store=_FakeAgentInstanceStore( [ _make_record( agent_instance_id="instance-1", source_runtime_id="runtime-a" ) ] ), configuration=_runtime_config(runtime_id="runtime-a"), ) receipt = await ConversationErasureService(deps).erase_session( team_id=TeamId("personal"), session_id="session-1", user_id="admin", authorization="Bearer test-token", ) assert receipt.ok is True by_store = {r.store: r for r in receipt.stores} assert by_store["attachments"].deleted_count == 0 assert by_store["session_metadata"].deleted_count == 0 assert by_store["runtime_history"].deleted_count == 0 assert by_store["runtime_checkpoint"].ok is True @pytest.mark.asyncio async def test_erase_session_deletes_checkpoint_before_history_on_resolved_runtime( monkeypatch: pytest.MonkeyPatch, ) -> None: """A2: runtime erasure hits checkpoint BEFORE history, on the resolved base_url, with the caller's Authorization; the receipt gains both entries.""" from control_plane_backend.config.models import RuntimeCatalogSourceConfig from control_plane_backend.sessions.erasure_service import ( ConversationErasureService, ) session_store = _FakeSessionMetadataStore( [ SessionMetadataRecord( session_id="session-1", team_id=TeamId("personal"), agent_instance_id="instance-1", user_id="admin", title="Owned by admin", ) ] ) attachment_store = _FakeSessionAttachmentStore([]) runtime_calls: list[tuple[str, dict[str, str]]] = [] monkeypatch.setattr( "control_plane_backend.sessions.erasure_service.httpx.AsyncClient", _make_runtime_client(runtime_calls, history_deleted=7), ) # instance-1 lives on runtime-a; a decoy source proves per-session # resolution picks the right base_url rather than the first/only one. deps = _build_erasure_deps( session_store, attachment_store, agent_instance_store=_FakeAgentInstanceStore( [ _make_record( agent_instance_id="instance-1", source_runtime_id="runtime-a" ) ] ), configuration=SimpleNamespace( platform=SimpleNamespace( runtime_catalog_sources=[ RuntimeCatalogSourceConfig( runtime_id="runtime-z", base_url="http://decoy.internal", enabled=True, ), RuntimeCatalogSourceConfig( runtime_id="runtime-a", base_url="http://runtime-a.internal", enabled=True, ), ] ) ), ) receipt = await ConversationErasureService(deps).erase_session( team_id=TeamId("personal"), session_id="session-1", user_id="admin", authorization="Bearer test-token", ) # Ordering: checkpoint DELETE strictly precedes history DELETE. assert [url for url, _ in runtime_calls] == [ "http://runtime-a.internal/agents/checkpoints/session-1", "http://runtime-a.internal/agents/sessions/session-1", ] # base_url resolved from agent_instance_id (runtime-a, not the decoy) and # the caller Authorization threaded through on every call. assert all( headers == {"Authorization": "Bearer test-token"} for _, headers in runtime_calls ) by_store = {r.store: r for r in receipt.stores} assert by_store["runtime_checkpoint"].ok is True assert by_store["runtime_history"].ok is True assert by_store["runtime_history"].deleted_count == 7 assert receipt.ok is True @pytest.mark.asyncio async def test_erase_session_history_failure_isolated_others_still_erased( monkeypatch: pytest.MonkeyPatch, ) -> None: """A2 + retry-safety (RFC §2.1): a failing history DELETE records ok=false for that store only; attachments and checkpoint still erase, but the session metadata row is RETAINED (not deleted) so a retry can re-resolve and converge. receipt.ok is False.""" from control_plane_backend.sessions.erasure_service import ( ConversationErasureService, ) session_store = _FakeSessionMetadataStore( [ SessionMetadataRecord( session_id="session-1", team_id=TeamId("personal"), agent_instance_id="instance-1", user_id="admin", title="Owned by admin", ) ] ) attachment_store = _FakeSessionAttachmentStore( [ SessionAttachmentRecord( session_id="session-1", attachment_id="attachment-1", name="notes.md", summary_md="# Notes", document_uid="doc-1", storage_key="uploads/notes.md", ) ] ) cleanup_calls: list[str | None] = [] async def _fake_cleanup(**kwargs: Any) -> None: cleanup_calls.append(kwargs["document_uid"]) monkeypatch.setattr( "control_plane_backend.product.service._delete_knowledge_flow_attachment", _fake_cleanup, ) runtime_calls: list[tuple[str, dict[str, str]]] = [] monkeypatch.setattr( "control_plane_backend.sessions.erasure_service.httpx.AsyncClient", _make_runtime_client(runtime_calls, history_error=True), ) deps = _build_erasure_deps( session_store, attachment_store, agent_instance_store=_FakeAgentInstanceStore( [ _make_record( agent_instance_id="instance-1", source_runtime_id="runtime-a" ) ] ), configuration=_runtime_config(runtime_id="runtime-a"), ) receipt = await ConversationErasureService(deps).erase_session( team_id=TeamId("personal"), session_id="session-1", user_id="admin", authorization="Bearer test-token", ) by_store = {r.store: r for r in receipt.stores} # The failing store is isolated… assert by_store["runtime_history"].ok is False assert by_store["runtime_history"].error is not None # …the others still completed. assert cleanup_calls == ["doc-1"] assert attachment_store._records == [] assert by_store["attachments"].ok is True assert by_store["runtime_checkpoint"].ok is True # Retry-safety: metadata is retained (deleted last, only on full success), so # the row survives and a re-run can re-resolve the runtime and finish. assert by_store["session_metadata"].ok is False assert session_store._records != [] # Checkpoint was still attempted before the failing history call. assert [url for url, _ in runtime_calls] == [ "http://runtime-a.internal/agents/checkpoints/session-1", "http://runtime-a.internal/agents/sessions/session-1", ] assert receipt.ok is False @pytest.mark.asyncio async def test_erase_session_partial_failure_converges_on_retry( monkeypatch: pytest.MonkeyPatch, ) -> None: """RFC §2.1 (the retry-safety guarantee): a partial failure leaves the session metadata row intact; a re-run against a healthy runtime re-resolves, converges to a fully-ok receipt, and finally deletes the row. No orphaned store, no stuck queue entry — the defect C-1 fixes.""" from control_plane_backend.sessions.erasure_service import ( ConversationErasureService, ) session_store = _FakeSessionMetadataStore( [ SessionMetadataRecord( session_id="session-1", team_id=TeamId("personal"), agent_instance_id="instance-1", user_id="admin", title="Owned by admin", ) ] ) async def _fake_cleanup(**_kwargs: Any) -> None: return None monkeypatch.setattr( "control_plane_backend.product.service._delete_knowledge_flow_attachment", _fake_cleanup, ) deps = _build_erasure_deps( session_store, _FakeSessionAttachmentStore([]), agent_instance_store=_FakeAgentInstanceStore( [ _make_record( agent_instance_id="instance-1", source_runtime_id="runtime-a" ) ] ), configuration=_runtime_config(runtime_id="runtime-a"), ) service = ConversationErasureService(deps) # Attempt 1 — the runtime's history DELETE is down → partial receipt. The # metadata row that anchors ownership + runtime resolution MUST survive. monkeypatch.setattr( "control_plane_backend.sessions.erasure_service.httpx.AsyncClient", _make_runtime_client([], history_error=True), ) first = await service.erase_session( team_id=TeamId("personal"), session_id="session-1", user_id="admin", authorization="Bearer test-token", ) assert first.ok is False assert session_store._records != [] # retained for retry — not orphaned # Attempt 2 — the runtime is healthy again. Because the row survived, the # retry re-resolves the runtime, every store converges, and metadata is # finally deleted. monkeypatch.setattr( "control_plane_backend.sessions.erasure_service.httpx.AsyncClient", _make_runtime_client([]), ) second = await service.erase_session( team_id=TeamId("personal"), session_id="session-1", user_id="admin", authorization="Bearer test-token", ) assert second.ok is True assert session_store._records == [] # converged — fully erased @pytest.mark.asyncio async def test_erase_session_unresolved_runtime_records_ok_false_no_http( monkeypatch: pytest.MonkeyPatch, ) -> None: """A2 edge case: a session with no agent_instance_id cannot resolve a runtime — checkpoint+history are recorded ok=false and NO HTTP is made.""" from control_plane_backend.sessions.erasure_service import ( ConversationErasureService, ) session_store = _FakeSessionMetadataStore( [ SessionMetadataRecord( session_id="session-1", team_id=TeamId("personal"), agent_instance_id=None, user_id="admin", title="Orphan session", ) ] ) attachment_store = _FakeSessionAttachmentStore([]) runtime_calls: list[tuple[str, dict[str, str]]] = [] monkeypatch.setattr( "control_plane_backend.sessions.erasure_service.httpx.AsyncClient", _make_runtime_client(runtime_calls), ) deps = _build_erasure_deps( session_store, attachment_store, agent_instance_store=_FakeAgentInstanceStore([]), configuration=_runtime_config(runtime_id="runtime-a"), ) receipt = await ConversationErasureService(deps).erase_session( team_id=TeamId("personal"), session_id="session-1", user_id="admin", authorization="Bearer test-token", ) # No runtime to guess → no HTTP call at all. assert runtime_calls == [] by_store = {r.store: r for r in receipt.stores} assert by_store["runtime_checkpoint"].ok is False assert "unresolved" in (by_store["runtime_checkpoint"].error or "") assert by_store["runtime_history"].ok is False assert "unresolved" in (by_store["runtime_history"].error or "") # Retry-safety: with the runtime unreachable, metadata is retained (deleted # last, only on full success) so a later retry can re-resolve and converge. assert by_store["session_metadata"].ok is False assert receipt.ok is False @pytest.mark.asyncio async def test_erase_session_runtime_instance_not_found_records_ok_false_no_http( monkeypatch: pytest.MonkeyPatch, ) -> None: """_resolve_runtime_base_url: the session names an agent instance, but it is not found for the team -> checkpoint+history recorded ok=false, no HTTP.""" from control_plane_backend.sessions.erasure_service import ( ConversationErasureService, ) session_store = _FakeSessionMetadataStore( [ SessionMetadataRecord( session_id="session-1", team_id=TeamId("personal"), agent_instance_id="instance-1", user_id="admin", title="Session", ) ] ) runtime_calls: list[tuple[str, dict[str, str]]] = [] monkeypatch.setattr( "control_plane_backend.sessions.erasure_service.httpx.AsyncClient", _make_runtime_client(runtime_calls), ) deps = _build_erasure_deps( session_store, _FakeSessionAttachmentStore([]), # Instance store is empty → get_for_team returns None for "instance-1". agent_instance_store=_FakeAgentInstanceStore([]), configuration=_runtime_config(runtime_id="runtime-a"), ) receipt = await ConversationErasureService(deps).erase_session( team_id=TeamId("personal"), session_id="session-1", user_id="admin", authorization="Bearer test-token", ) assert runtime_calls == [] by_store = {r.store: r for r in receipt.stores} assert by_store["runtime_checkpoint"].ok is False assert "not found for team" in (by_store["runtime_checkpoint"].error or "") assert by_store["runtime_history"].ok is False # Retry-safety: metadata retained (deleted last, only on full success). assert by_store["session_metadata"].ok is False assert receipt.ok is False @pytest.mark.asyncio async def test_erase_session_survives_agent_instance_deletion( monkeypatch: pytest.MonkeyPatch, ) -> None: """Issue #2089 / RFC §7 regression: deleting an agent instance must not permanently block erasure of sessions that used it. Reproduces the live bug exactly: an agent instance is deleted (its `agent_instance_store` row is gone, unlike `test_erase_session_runtime_instance_not_found_records_ok_false_no_http` above, which covers the still-permanent case of a pre-migration session with no stored `source_runtime_id`). Here the session carries the `source_runtime_id` captured at `create_session` time, so `_resolve_runtime_base_url` must resolve the runtime from that stored value instead of re-deriving it from the now-deleted instance row — erasure converges instead of leaving the session permanently un-erasable. """ from control_plane_backend.sessions.erasure_service import ( ConversationErasureService, ) session_store = _FakeSessionMetadataStore( [ SessionMetadataRecord( session_id="session-1", team_id=TeamId("personal"), agent_instance_id="instance-1", source_runtime_id="runtime-a", user_id="admin", title="Session on a since-deleted agent instance", ) ] ) runtime_calls: list[tuple[str, dict[str, str]]] = [] monkeypatch.setattr( "control_plane_backend.sessions.erasure_service.httpx.AsyncClient", _make_runtime_client(runtime_calls), ) deps = _build_erasure_deps( session_store, _FakeSessionAttachmentStore([]), # The agent instance is gone (unenrolled) — empty store, exactly like # a real deleted instance: `get_for_team` returns None. agent_instance_store=_FakeAgentInstanceStore([]), configuration=_runtime_config(runtime_id="runtime-a"), ) receipt = await ConversationErasureService(deps).erase_session( team_id=TeamId("personal"), session_id="session-1", user_id="admin", authorization="Bearer test-token", ) # The runtime WAS resolved (from the session's stored source_runtime_id) # and its checkpoint/history WERE actually purged — not just skipped. assert len(runtime_calls) == 2 by_store = {r.store: r for r in receipt.stores} assert by_store["runtime_checkpoint"].ok is True assert by_store["runtime_history"].ok is True assert by_store["session_metadata"].ok is True assert receipt.ok is True # Convergence: the erase actually completes and the row is gone — this is # the part that never happened before the fix (it retried forever). assert session_store._records == [] @pytest.mark.asyncio async def test_erase_session_runtime_source_disabled_records_ok_false_no_http( monkeypatch: pytest.MonkeyPatch, ) -> None: """_resolve_runtime_base_url: the instance resolves but its runtime source is disabled/missing -> checkpoint+history recorded ok=false, no HTTP.""" from control_plane_backend.config.models import RuntimeCatalogSourceConfig from control_plane_backend.sessions.erasure_service import ( ConversationErasureService, ) session_store = _FakeSessionMetadataStore( [ SessionMetadataRecord( session_id="session-1", team_id=TeamId("personal"), agent_instance_id="instance-1", user_id="admin", title="Session", ) ] ) runtime_calls: list[tuple[str, dict[str, str]]] = [] monkeypatch.setattr( "control_plane_backend.sessions.erasure_service.httpx.AsyncClient", _make_runtime_client(runtime_calls), ) # The instance points at runtime-a, but that catalog source is DISABLED. disabled_config = SimpleNamespace( platform=SimpleNamespace( runtime_catalog_sources=[ RuntimeCatalogSourceConfig( runtime_id="runtime-a", base_url="http://runtime-a.internal", enabled=False, ) ] ) ) deps = _build_erasure_deps( session_store, _FakeSessionAttachmentStore([]), agent_instance_store=_FakeAgentInstanceStore( [ _make_record( agent_instance_id="instance-1", source_runtime_id="runtime-a" ) ] ), configuration=disabled_config, ) receipt = await ConversationErasureService(deps).erase_session( team_id=TeamId("personal"), session_id="session-1", user_id="admin", authorization="Bearer test-token", ) assert runtime_calls == [] by_store = {r.store: r for r in receipt.stores} assert by_store["runtime_checkpoint"].ok is False assert "disabled or missing" in (by_store["runtime_checkpoint"].error or "") assert by_store["runtime_history"].ok is False # Retry-safety: metadata retained (deleted last, only on full success). assert by_store["session_metadata"].ok is False assert receipt.ok is False def _kpi_session() -> "_FakeSessionMetadataStore": """A single owned session on a resolvable runtime, for the KPI tests.""" return _FakeSessionMetadataStore( [ SessionMetadataRecord( session_id="session-1", team_id=TeamId("personal"), agent_instance_id="instance-1", user_id="admin", title="Owned by admin", ) ] ) @pytest.mark.asyncio async def test_erase_session_anonymises_kpi_rows( monkeypatch: pytest.MonkeyPatch, ) -> None: """A3: erase_session anonymises the session's KPI rows and records a STORE_KPI receipt entry with the row count (anonymised, not deleted).""" from control_plane_backend.sessions.erasure_service import ( STORE_KPI, ConversationErasureService, ) kpi_store = _FakeKPIStore(updated=5) monkeypatch.setattr( "control_plane_backend.sessions.erasure_service.httpx.AsyncClient", _make_runtime_client([]), ) deps = _build_erasure_deps( _kpi_session(), _FakeSessionAttachmentStore([]), agent_instance_store=_FakeAgentInstanceStore( [ _make_record( agent_instance_id="instance-1", source_runtime_id="runtime-a" ) ] ), configuration=_runtime_config(runtime_id="runtime-a"), kpi_store=kpi_store, ) receipt = await ConversationErasureService(deps).erase_session( team_id=TeamId("personal"), session_id="session-1", user_id="admin", authorization="Bearer test-token", ) # The KPI store was asked to anonymise exactly this session… assert kpi_store.calls == ["session-1"] by_store = {r.store: r for r in receipt.stores} # …and the receipt records the anonymised (not deleted) row count. assert by_store[STORE_KPI].ok is True assert by_store[STORE_KPI].deleted_count == 5 assert receipt.ok is True @pytest.mark.asyncio async def test_erase_session_absent_kpi_store_is_noop_ok( monkeypatch: pytest.MonkeyPatch, ) -> None: """A3: a deployment without an OpenSearch KPI store yields a no-op ok KPI entry (nothing to anonymise), not an error.""" from control_plane_backend.sessions.erasure_service import ( STORE_KPI, ConversationErasureService, ) monkeypatch.setattr( "control_plane_backend.sessions.erasure_service.httpx.AsyncClient", _make_runtime_client([]), ) deps = _build_erasure_deps( _kpi_session(), _FakeSessionAttachmentStore([]), agent_instance_store=_FakeAgentInstanceStore( [ _make_record( agent_instance_id="instance-1", source_runtime_id="runtime-a" ) ] ), configuration=_runtime_config(runtime_id="runtime-a"), kpi_store=None, # no OpenSearch KPI store in this deployment ) receipt = await ConversationErasureService(deps).erase_session( team_id=TeamId("personal"), session_id="session-1", user_id="admin", authorization="Bearer test-token", ) by_store = {r.store: r for r in receipt.stores} assert by_store[STORE_KPI].ok is True assert by_store[STORE_KPI].deleted_count == 0 assert receipt.ok is True @pytest.mark.asyncio async def test_erase_session_kpi_failure_isolated_others_still_erased( monkeypatch: pytest.MonkeyPatch, ) -> None: """A3: a failing KPI anonymise records ok=false for that store only; the other stores are still erased, and receipt.ok is False.""" from control_plane_backend.sessions.erasure_service import ( STORE_KPI, ConversationErasureService, ) kpi_store = _FakeKPIStore(fail=True) runtime_calls: list[tuple[str, dict[str, str]]] = [] monkeypatch.setattr( "control_plane_backend.sessions.erasure_service.httpx.AsyncClient", _make_runtime_client(runtime_calls), ) session_store = _kpi_session() deps = _build_erasure_deps( session_store, _FakeSessionAttachmentStore([]), agent_instance_store=_FakeAgentInstanceStore( [ _make_record( agent_instance_id="instance-1", source_runtime_id="runtime-a" ) ] ), configuration=_runtime_config(runtime_id="runtime-a"), kpi_store=kpi_store, ) receipt = await ConversationErasureService(deps).erase_session( team_id=TeamId("personal"), session_id="session-1", user_id="admin", authorization="Bearer test-token", ) by_store = {r.store: r for r in receipt.stores} # The failing store is isolated… assert by_store[STORE_KPI].ok is False assert by_store[STORE_KPI].error is not None # …the others still completed, but metadata is retained (deleted last, only # on full success) so the erase stays retryable. assert by_store["session_metadata"].ok is False assert by_store["runtime_checkpoint"].ok is True assert by_store["runtime_history"].ok is True assert receipt.ok is False @pytest.mark.asyncio async def test_erase_session_attachment_failure_isolated_others_still_erased( monkeypatch: pytest.MonkeyPatch, ) -> None: """CTRLP-12: a failing Knowledge Flow attachment cleanup records ok=false for the attachments store only; session_metadata, KPI and the runtime checkpoint/history are still attempted and receipted (the fan-out is NOT aborted), and receipt.ok is False.""" from control_plane_backend.sessions.erasure_service import ( STORE_KPI, ConversationErasureService, ) attachment_store = _FakeSessionAttachmentStore( [ SessionAttachmentRecord( session_id="session-1", attachment_id="attachment-1", name="notes.md", summary_md="# Notes", document_uid="doc-1", storage_key="uploads/notes.md", ) ] ) async def _failing_cleanup(**kwargs: Any) -> None: raise RuntimeError("knowledge flow down") monkeypatch.setattr( "control_plane_backend.product.service._delete_knowledge_flow_attachment", _failing_cleanup, ) kpi_store = _FakeKPIStore(updated=5) runtime_calls: list[tuple[str, dict[str, str]]] = [] monkeypatch.setattr( "control_plane_backend.sessions.erasure_service.httpx.AsyncClient", _make_runtime_client(runtime_calls), ) session_store = _kpi_session() deps = _build_erasure_deps( session_store, attachment_store, agent_instance_store=_FakeAgentInstanceStore( [ _make_record( agent_instance_id="instance-1", source_runtime_id="runtime-a" ) ] ), configuration=_runtime_config(runtime_id="runtime-a"), kpi_store=kpi_store, ) receipt = await ConversationErasureService(deps).erase_session( team_id=TeamId("personal"), session_id="session-1", user_id="admin", authorization="Bearer test-token", ) by_store = {r.store: r for r in receipt.stores} # The failing store is isolated… assert by_store["attachments"].ok is False assert by_store["attachments"].error is not None # …the fan-out was NOT aborted: every downstream store was still attempted, # but metadata is retained (deleted last, only on full success) for retry. assert by_store["session_metadata"].ok is False assert session_store._records != [] assert kpi_store.calls == ["session-1"] assert by_store[STORE_KPI].ok is True assert by_store["runtime_checkpoint"].ok is True assert by_store["runtime_history"].ok is True # The runtime checkpoint+history DELETEs were still issued. assert [url for url, _ in runtime_calls] == [ "http://runtime-a.internal/agents/checkpoints/session-1", "http://runtime-a.internal/agents/sessions/session-1", ] assert receipt.ok is False # --- CTRLP-12 A5: delete = deferred erase (team + personal windows) ----------- def _delete_window_catalog( *, personal_delete_grace: str | None = None, team_delete_grace: str | None = None, ) -> Any: """Policy catalog exposing the two A5 delete windows (both platform-level).""" from control_plane_backend.scheduler.policies.policy_models import ( ConversationPolicyCatalog, ) purge: dict[str, Any] = {} if personal_delete_grace is not None: purge["personal_delete_grace"] = personal_delete_grace if team_delete_grace is not None: purge["default"] = {"team_delete_grace": team_delete_grace} return ConversationPolicyCatalog.model_validate( {"conversation_policies": {"purge": purge}} ) class _FakePurgeQueueStore: """In-memory stand-in recording deferred USER_DELETED enqueues (A5).""" def __init__(self) -> None: self.entries: list[dict[str, Any]] = [] async def enqueue( self, *, session_id: str, team_id: str, user_id: str, due_at: datetime ) -> bool: # Mirror the real store's idempotent contract: no-op (return False) when a # pending entry already exists for the session, insert (return True) once. if any(e["session_id"] == session_id for e in self.entries): return False self.entries.append( { "session_id": session_id, "team_id": team_id, "user_id": user_id, "due_at": due_at, } ) return True class _FakeTeamMetadataStore: """In-memory stand-in exposing get_by_team_id for retention resolution. CTRLP-12 rev. 2 / Phase R: per-team retention lives on team_metadata now, so the delete-window resolver reads its `team_delete_grace`/`max_idle` off this record instead of a separate override store. """ def __init__(self, record: Any) -> None: self.record = record async def get_by_team_id(self, *_args: Any, **_kwargs: Any) -> Any: return self.record class _RaisingTeamMetadataStore: """Metadata store that fails if consulted — proves the personal delete path never reads a team retention value to size its window (A5).""" async def get_by_team_id(self, *_args: Any, **_kwargs: Any) -> Any: raise AssertionError( "personal delete must not consult the team metadata retention fields" ) @pytest.mark.asyncio async def test_team_delete_defers_erase_and_enqueues_user_deleted() -> None: """Team that OPTED IN to retention: delete → hidden (`deleted_at`), history retained, USER_DELETED queue entry due at `now + team_delete_grace` (CTRLP-12 D1: deferral applies only when the team has set its own value).""" from control_plane_backend.product.service import delete_or_defer_session from control_plane_backend.scheduler.policies.policy_models import ( parse_iso8601_duration, ) session_store = _FakeSessionMetadataStore( [ SessionMetadataRecord( session_id="session-1", team_id=TeamId("northbridge"), agent_instance_id="instance-1", user_id="admin", title="Team chat", ) ] ) queue = _FakePurgeQueueStore() deps = _build_erasure_deps( session_store, _FakeSessionAttachmentStore([]), policy_catalog=_delete_window_catalog(team_delete_grace="P30D"), # The team explicitly set a retention window (≤ the platform cap). team_metadata_store=_FakeTeamMetadataStore( TeamMetadata( id=TeamId("northbridge"), name="Northbridge", team_delete_grace="P30D" ) ), purge_queue_store=queue, ) before = datetime.now(timezone.utc) await delete_or_defer_session( team_id=TeamId("northbridge"), session_id="session-1", user_id="admin", authorization="Bearer test-token", deps=deps, ) after = datetime.now(timezone.utc) # Hidden, not erased: the row survives (history stays readable for the window). assert len(session_store._records) == 1 record = session_store._records[0] assert record.deleted_at is not None # type: ignore[attr-defined] # Exactly one USER_DELETED queue entry due at now + team_delete_grace (P30D). assert len(queue.entries) == 1 entry = queue.entries[0] assert entry["session_id"] == "session-1" assert entry["user_id"] == "admin" window = parse_iso8601_duration("P30D") assert before + window <= entry["due_at"] <= after + window @pytest.mark.asyncio async def test_deferred_delete_retry_does_not_duplicate_erasure_task() -> None: """CTRLP-12 (P2): a retried / double-clicked deferred delete must not create a second scheduled erasure task. The purge-queue enqueue is idempotent for an already-pending session, and the lifecycle worker advances only the first active task per session — so minting a fresh task on every call would leave duplicates stuck pending in the admin schedule forever. The task is created only alongside a NEW queue row. """ from control_plane_backend.product.service import delete_or_defer_session session_store = _FakeSessionMetadataStore( [ SessionMetadataRecord( session_id="session-1", team_id=TeamId("northbridge"), agent_instance_id="instance-1", user_id="admin", title="Team chat", ) ] ) queue = _FakePurgeQueueStore() task_service = _RecordingErasureTaskService() deps = _build_erasure_deps( session_store, _FakeSessionAttachmentStore([]), policy_catalog=_delete_window_catalog(team_delete_grace="P30D"), team_metadata_store=_FakeTeamMetadataStore( TeamMetadata( id=TeamId("northbridge"), name="Northbridge", team_delete_grace="P30D" ) ), purge_queue_store=queue, task_service=task_service, ) async def _defer_once() -> None: await delete_or_defer_session( team_id=TeamId("northbridge"), session_id="session-1", user_id="admin", authorization="Bearer test-token", deps=deps, ) # Two deferred deletes for the same conversation (retry / double-click). await _defer_once() await _defer_once() # Idempotent: exactly one queue entry and exactly one scheduled erasure task # (the second call finds the first call's still-active task and does not dup). assert len(queue.entries) == 1 assert task_service.starts == 1 @pytest.mark.asyncio async def test_deferred_delete_recreates_erasure_task_when_missing() -> None: """CTRLP-12 (P2 residual): heal the 'queue exists, task absent' gap. `schedule_erasure_task` is best-effort — if the original creation failed, a pending queue row exists with no observable task. A subsequent deferred delete sees `enqueue` no-op (False) but must still recreate the task so the admin schedule is not left blind, without duplicating when a task already exists. """ from control_plane_backend.product.service import delete_or_defer_session session_store = _FakeSessionMetadataStore( [ SessionMetadataRecord( session_id="session-1", team_id=TeamId("northbridge"), agent_instance_id="instance-1", user_id="admin", title="Team chat", ) ] ) # Queue already has a pending row for this session (a prior deferred delete), # so enqueue no-ops (returns False) on this call… queue = _FakePurgeQueueStore() queue.entries.append( { "session_id": "session-1", "team_id": "northbridge", "user_id": "admin", "due_at": datetime.now(timezone.utc), } ) # …but NO active erasure task exists (the earlier best-effort creation failed). task_service = _RecordingErasureTaskService() deps = _build_erasure_deps( session_store, _FakeSessionAttachmentStore([]), policy_catalog=_delete_window_catalog(team_delete_grace="P30D"), team_metadata_store=_FakeTeamMetadataStore( TeamMetadata( id=TeamId("northbridge"), name="Northbridge", team_delete_grace="P30D" ) ), purge_queue_store=queue, task_service=task_service, ) await delete_or_defer_session( team_id=TeamId("northbridge"), session_id="session-1", user_id="admin", authorization="Bearer test-token", deps=deps, ) # No duplicate queue row, but the missing observable task was recreated. assert len(queue.entries) == 1 assert task_service.starts == 1 # And when a task already exists, a further no-op enqueue does NOT recreate it. already = _RecordingErasureTaskService(seeded_targets=["session-1"]) deps_existing = _build_erasure_deps( session_store, _FakeSessionAttachmentStore([]), policy_catalog=_delete_window_catalog(team_delete_grace="P30D"), team_metadata_store=_FakeTeamMetadataStore( TeamMetadata( id=TeamId("northbridge"), name="Northbridge", team_delete_grace="P30D" ) ), purge_queue_store=queue, task_service=already, ) await delete_or_defer_session( team_id=TeamId("northbridge"), session_id="session-1", user_id="admin", authorization="Bearer test-token", deps=deps_existing, ) assert already.starts == 0 @pytest.mark.asyncio async def test_personal_delete_defers_by_platform_window_not_overridable() -> None: """Personal delete → hidden + USER_DELETED entry due at `now + personal_delete_grace` (NOT immediate); the window is read straight off the platform catalog and never from a team/user override.""" from control_plane_backend.product.service import delete_or_defer_session from control_plane_backend.scheduler.policies.policy_models import ( parse_iso8601_duration, ) personal_team = personal_team_id("alice") session_store = _FakeSessionMetadataStore( [ SessionMetadataRecord( session_id="session-1", team_id=personal_team, agent_instance_id="instance-1", user_id="alice", title="Personal chat", ) ] ) queue = _FakePurgeQueueStore() deps = _build_erasure_deps( session_store, _FakeSessionAttachmentStore([]), policy_catalog=_delete_window_catalog(personal_delete_grace="P3D"), # If the personal path ever read team retention, this store would raise. team_metadata_store=_RaisingTeamMetadataStore(), purge_queue_store=queue, ) before = datetime.now(timezone.utc) await delete_or_defer_session( team_id=personal_team, session_id="session-1", user_id="alice", authorization="Bearer test-token", deps=deps, ) after = datetime.now(timezone.utc) # Deferred, NOT immediate: row hidden and survives, queue entry due at +P3D. assert len(session_store._records) == 1 assert session_store._records[0].deleted_at is not None # type: ignore[attr-defined] assert len(queue.entries) == 1 window = parse_iso8601_duration("P3D") assert before + window <= queue.entries[0]["due_at"] <= after + window # Structural guarantee: team_metadata retention cannot even express a # personal window — there is no field for a user/team to shorten it. assert "personal_delete_grace" not in TeamMetadata.model_fields @pytest.mark.asyncio async def test_delete_with_no_window_erases_immediately( monkeypatch: pytest.MonkeyPatch, ) -> None: """Both windows unset → immediate `erase_session` (back-compat): the metadata row is deleted now and nothing is deferred onto the purge queue.""" from control_plane_backend.product.service import delete_or_defer_session session_store = _FakeSessionMetadataStore( [ SessionMetadataRecord( session_id="session-1", team_id=TeamId("personal"), agent_instance_id="instance-1", user_id="admin", title="Team chat", ) ] ) queue = _FakePurgeQueueStore() runtime_calls: list[tuple[str, dict[str, str]]] = [] monkeypatch.setattr( "control_plane_backend.sessions.erasure_service.httpx.AsyncClient", _make_runtime_client(runtime_calls), ) async def _fake_cleanup(**_kwargs: Any) -> None: return None monkeypatch.setattr( "control_plane_backend.product.service._delete_knowledge_flow_attachment", _fake_cleanup, ) deps = _build_erasure_deps( session_store, _FakeSessionAttachmentStore([]), agent_instance_store=_FakeAgentInstanceStore( [ _make_record( agent_instance_id="instance-1", source_runtime_id="runtime-a" ) ] ), configuration=_runtime_config(runtime_id="runtime-a"), policy_catalog=_delete_window_catalog(), # no windows configured team_metadata_store=_FakeTeamMetadataStore(None), purge_queue_store=queue, ) await delete_or_defer_session( team_id=TeamId("personal"), session_id="session-1", user_id="admin", authorization="Bearer test-token", deps=deps, ) # Immediate erase ran: metadata row gone, nothing deferred. assert session_store._records == [] assert queue.entries == [] # The full fan-out reached the runtime (history erased, not retained). assert any("/agents/sessions/" in url for url, _ in runtime_calls) @pytest.mark.asyncio async def test_immediate_erase_incomplete_converges_via_queue( monkeypatch: pytest.MonkeyPatch, ) -> None: """CTRLP-12 (P1): an *incomplete* immediate erase must not silently return 204. When no window is configured the erase runs immediately, but if the fan-out fails (here the runtime history DELETE 502s), `erase_session` retains the metadata row (receipt not ok). The row must not be silently dropped: the conversation is hidden (`deleted_at`) and a purge-queue entry due *now* is enqueued so the lifecycle worker retries until the erasure converges — rather than leaving it visible forever with no retry. """ from control_plane_backend.product.service import delete_or_defer_session session_store = _FakeSessionMetadataStore( [ SessionMetadataRecord( session_id="session-1", team_id=TeamId("personal"), agent_instance_id="instance-1", user_id="admin", title="Team chat", ) ] ) queue = _FakePurgeQueueStore() runtime_calls: list[tuple[str, dict[str, str]]] = [] # history_error → the transcript DELETE 502s, so the fan-out is incomplete # and the session_metadata row is RETAINED (receipt.ok is False). monkeypatch.setattr( "control_plane_backend.sessions.erasure_service.httpx.AsyncClient", _make_runtime_client(runtime_calls, history_error=True), ) async def _fake_cleanup(**_kwargs: Any) -> None: return None monkeypatch.setattr( "control_plane_backend.product.service._delete_knowledge_flow_attachment", _fake_cleanup, ) deps = _build_erasure_deps( session_store, _FakeSessionAttachmentStore([]), agent_instance_store=_FakeAgentInstanceStore( [ _make_record( agent_instance_id="instance-1", source_runtime_id="runtime-a" ) ] ), configuration=_runtime_config(runtime_id="runtime-a"), policy_catalog=_delete_window_catalog(), # no windows configured team_metadata_store=_FakeTeamMetadataStore(None), purge_queue_store=queue, ) before = datetime.now(timezone.utc) # Must not raise even though the immediate erase was incomplete. await delete_or_defer_session( team_id=TeamId("personal"), session_id="session-1", user_id="admin", authorization="Bearer test-token", deps=deps, ) after = datetime.now(timezone.utc) # The metadata row is RETAINED (erase incomplete) but hidden from the sidebar. assert len(session_store._records) == 1 assert session_store._records[0].deleted_at is not None # type: ignore[attr-defined] # Convergence: exactly one retry enqueued, due *now* (not deferred by a window), # so the lifecycle worker re-runs the erase until the receipt is ok. assert len(queue.entries) == 1 entry = queue.entries[0] assert entry["session_id"] == "session-1" assert entry["user_id"] == "admin" assert before <= entry["due_at"] <= after # The incomplete fan-out really did reach the runtime (it was not skipped). assert any("/agents/sessions/" in url for url, _ in runtime_calls) @pytest.mark.asyncio async def test_team_delete_with_cap_but_unset_value_erases_immediately( monkeypatch: pytest.MonkeyPatch, ) -> None: """CTRLP-12 D1: a platform cap is a CEILING, not a default window. A team that has NOT set its own `team_delete_grace` erases immediately even when a cap is configured — it does not inherit the cap as a deferral window.""" from control_plane_backend.product.service import delete_or_defer_session session_store = _FakeSessionMetadataStore( [ SessionMetadataRecord( session_id="session-1", team_id=TeamId("northbridge"), agent_instance_id="instance-1", user_id="admin", title="Team chat", ) ] ) queue = _FakePurgeQueueStore() runtime_calls: list[tuple[str, dict[str, str]]] = [] monkeypatch.setattr( "control_plane_backend.sessions.erasure_service.httpx.AsyncClient", _make_runtime_client(runtime_calls), ) async def _fake_cleanup(**_kwargs: Any) -> None: return None monkeypatch.setattr( "control_plane_backend.product.service._delete_knowledge_flow_attachment", _fake_cleanup, ) deps = _build_erasure_deps( session_store, _FakeSessionAttachmentStore([]), agent_instance_store=_FakeAgentInstanceStore( [ _make_record( agent_instance_id="instance-1", source_runtime_id="runtime-a", team_id="northbridge", ) ] ), configuration=_runtime_config(runtime_id="runtime-a"), # A platform cap IS configured… policy_catalog=_delete_window_catalog(team_delete_grace="P30D"), # …but the team set nothing → immediate delete, not defer-for-the-cap. team_metadata_store=_FakeTeamMetadataStore(None), purge_queue_store=queue, ) await delete_or_defer_session( team_id=TeamId("northbridge"), session_id="session-1", user_id="admin", authorization="Bearer test-token", deps=deps, ) # Immediate erase ran despite the configured cap: nothing deferred. assert session_store._records == [] assert queue.entries == [] assert any("/agents/sessions/" in url for url, _ in runtime_calls) @pytest.mark.asyncio async def test_erase_session_skips_history_when_checkpoint_fails( monkeypatch: pytest.MonkeyPatch, ) -> None: """Orphan fix (A2/A5): a failed checkpoint erase SKIPS the history erase so the still-present checkpoint stays retryable (history is its ownership proof).""" from control_plane_backend.sessions.erasure_service import ( ConversationErasureService, ) session_store = _FakeSessionMetadataStore( [ SessionMetadataRecord( session_id="session-1", team_id=TeamId("personal"), agent_instance_id="instance-1", user_id="admin", title="Owned by admin", ) ] ) runtime_calls: list[tuple[str, dict[str, str]]] = [] monkeypatch.setattr( "control_plane_backend.sessions.erasure_service.httpx.AsyncClient", _make_runtime_client(runtime_calls, checkpoint_error=True), ) deps = _build_erasure_deps( session_store, _FakeSessionAttachmentStore([]), agent_instance_store=_FakeAgentInstanceStore( [ _make_record( agent_instance_id="instance-1", source_runtime_id="runtime-a" ) ] ), configuration=_runtime_config(runtime_id="runtime-a"), ) receipt = await ConversationErasureService(deps).erase_session( team_id=TeamId("personal"), session_id="session-1", user_id="admin", authorization="Bearer test-token", ) by_store = {r.store: r for r in receipt.stores} assert by_store["runtime_checkpoint"].ok is False # History was recorded as skipped, not attempted. assert by_store["runtime_history"].ok is False assert "skipped" in (by_store["runtime_history"].error or "") # The runtime only ever saw the checkpoint DELETE — history was never called. assert runtime_calls assert all("/agents/checkpoints/" in url for url, _ in runtime_calls) assert not any("/agents/sessions/" in url for url, _ in runtime_calls) @pytest.mark.asyncio async def test_session_attachment_endpoints_round_trip_for_owned_session( monkeypatch: pytest.MonkeyPatch, ) -> None: monkeypatch.setattr( "control_plane_backend.product.api.require_team_access", _fake_require_team_access, ) session_store = _FakeSessionMetadataStore( [ SessionMetadataRecord( session_id="session-1", team_id=TeamId("personal"), agent_instance_id="instance-1", user_id="admin", title="Owned by admin", ) ] ) attachment_store = _FakeSessionAttachmentStore() _patch_session_store(monkeypatch, session_store) _patch_session_attachment_store(monkeypatch, attachment_store) app = create_app() async with AsyncClient( transport=ASGITransport(app=app), base_url="http://test" ) as client: create_resp = await client.post( "/control-plane/v1/teams/personal/sessions/session-1/attachments", json={ "attachment_id": "attachment-1", "name": "notes.md", "mime": "text/markdown", "size_bytes": 321, "summary_md": "# Notes", "document_uid": "doc-1", "storage_key": "uploads/notes.md", }, ) list_resp = await client.get( "/control-plane/v1/teams/personal/sessions/session-1/attachments" ) assert create_resp.status_code == 201 assert create_resp.json()["attachment_id"] == "attachment-1" assert list_resp.status_code == 200 assert [item["name"] for item in list_resp.json()] == ["notes.md"] @pytest.mark.asyncio async def test_delete_session_attachment_calls_cleanup_and_removes_row( monkeypatch: pytest.MonkeyPatch, ) -> None: monkeypatch.setattr( "control_plane_backend.product.api.require_team_access", _fake_require_team_access, ) session_store = _FakeSessionMetadataStore( [ SessionMetadataRecord( session_id="session-1", team_id=TeamId("personal"), agent_instance_id="instance-1", user_id="admin", title="Owned by admin", ) ] ) attachment_store = _FakeSessionAttachmentStore( [ SessionAttachmentRecord( session_id="session-1", attachment_id="attachment-1", name="notes.md", summary_md="# Notes", document_uid="doc-1", storage_key="uploads/notes.md", ) ] ) cleanup_calls: list[dict[str, str | None]] = [] async def _fake_cleanup(**kwargs: Any) -> None: cleanup_calls.append( { "document_uid": kwargs["document_uid"], "storage_key": kwargs["storage_key"], "session_id": kwargs["session_id"], } ) monkeypatch.setattr( "control_plane_backend.product.service._delete_knowledge_flow_attachment", _fake_cleanup, ) _patch_session_store(monkeypatch, session_store) _patch_session_attachment_store(monkeypatch, attachment_store) app = create_app() async with AsyncClient( transport=ASGITransport(app=app), base_url="http://test" ) as client: resp = await client.delete( "/control-plane/v1/teams/personal/sessions/session-1/attachments/attachment-1", headers={"Authorization": "Bearer test-token"}, ) assert resp.status_code == 204 assert attachment_store._records == [] assert cleanup_calls == [ { "document_uid": "doc-1", "storage_key": "uploads/notes.md", "session_id": "session-1", } ] @pytest.mark.asyncio async def test_delete_knowledge_flow_attachment_uses_fast_delete_route( monkeypatch: pytest.MonkeyPatch, ) -> None: captured: dict[str, Any] = {} class _FakeAsyncClient: def __init__(self, *args: Any, **kwargs: Any) -> None: captured["timeout"] = kwargs.get("timeout") async def __aenter__(self) -> "_FakeAsyncClient": return self async def __aexit__(self, exc_type: Any, exc: Any, tb: Any) -> None: return None async def delete( self, url: str, *, params: dict[str, str], headers: dict[str, str] ) -> httpx.Response: captured["url"] = url captured["params"] = params captured["headers"] = headers request = httpx.Request("DELETE", url, params=params, headers=headers) return httpx.Response(200, request=request) monkeypatch.setattr( "control_plane_backend.product.service.httpx.AsyncClient", _FakeAsyncClient ) app = create_app() container = get_application_container_from_app(app) deps = build_product_service_dependencies(container) await _delete_knowledge_flow_attachment( authorization="Bearer test-token", document_uid="doc-1", storage_key="uploads/notes.md", session_id="session-1", deps=deps, ) assert captured["url"].endswith("/fast/delete/doc-1") assert captured["params"] == { "session_id": "session-1", "storage_key": "uploads/notes.md", } assert captured["headers"] == {"Authorization": "Bearer test-token"} def _fake_async_client_returning(status_code: int, *, detail: str) -> type: class _FakeAsyncClient: def __init__(self, *args: Any, **kwargs: Any) -> None: pass async def __aenter__(self) -> "_FakeAsyncClient": return self async def __aexit__(self, exc_type: Any, exc: Any, tb: Any) -> None: return None async def delete( self, url: str, *, params: dict[str, str], headers: dict[str, str] ) -> httpx.Response: request = httpx.Request("DELETE", url, params=params, headers=headers) return httpx.Response(status_code, json={"detail": detail}, request=request) return _FakeAsyncClient def _fake_async_client_returning_raw( status_code: int, *, content: bytes = b"", json_body: Any = None ) -> type: class _FakeAsyncClient: def __init__(self, *args: Any, **kwargs: Any) -> None: pass async def __aenter__(self) -> "_FakeAsyncClient": return self async def __aexit__(self, exc_type: Any, exc: Any, tb: Any) -> None: return None async def delete( self, url: str, *, params: dict[str, str], headers: dict[str, str] ) -> httpx.Response: request = httpx.Request("DELETE", url, params=params, headers=headers) if json_body is not None: return httpx.Response(status_code, json=json_body, request=request) return httpx.Response(status_code, content=content, request=request) return _FakeAsyncClient @pytest.mark.asyncio async def test_delete_knowledge_flow_attachment_relays_downstream_403( monkeypatch: pytest.MonkeyPatch, ) -> None: """#2223: a ReBAC denial from Knowledge Flow must surface as a 403 with the real reason, not a generic 502 that hides the failure from the frontend.""" monkeypatch.setattr( "control_plane_backend.product.service.httpx.AsyncClient", _fake_async_client_returning( 403, detail="Not authorized to delete document doc-1" ), ) app = create_app() container = get_application_container_from_app(app) deps = build_product_service_dependencies(container) with pytest.raises(SessionAttachmentRequestError) as excinfo: await _delete_knowledge_flow_attachment( authorization="Bearer test-token", document_uid="doc-1", storage_key=None, session_id="session-1", deps=deps, ) assert excinfo.value.http_status == 403 assert "Not authorized to delete document doc-1" in str(excinfo.value) @pytest.mark.asyncio async def test_delete_knowledge_flow_attachment_maps_downstream_5xx_to_502( monkeypatch: pytest.MonkeyPatch, ) -> None: monkeypatch.setattr( "control_plane_backend.product.service.httpx.AsyncClient", _fake_async_client_returning(500, detail="internal error"), ) app = create_app() container = get_application_container_from_app(app) deps = build_product_service_dependencies(container) with pytest.raises(SessionAttachmentRequestError) as excinfo: await _delete_knowledge_flow_attachment( authorization="Bearer test-token", document_uid="doc-1", storage_key=None, session_id="session-1", deps=deps, ) assert excinfo.value.http_status == 502 @pytest.mark.asyncio async def test_delete_knowledge_flow_attachment_maps_downstream_redirect_to_502( monkeypatch: pytest.MonkeyPatch, ) -> None: """A 3xx from Knowledge Flow (e.g. gateway canonicalization) must not be read as success -- this client never follows redirects, so cleanup never actually ran and control-plane must not delete its own attachment metadata.""" monkeypatch.setattr( "control_plane_backend.product.service.httpx.AsyncClient", _fake_async_client_returning_raw(307), ) app = create_app() container = get_application_container_from_app(app) deps = build_product_service_dependencies(container) with pytest.raises(SessionAttachmentRequestError) as excinfo: await _delete_knowledge_flow_attachment( authorization="Bearer test-token", document_uid="doc-1", storage_key=None, session_id="session-1", deps=deps, ) assert excinfo.value.http_status == 502 @pytest.mark.asyncio async def test_delete_knowledge_flow_attachment_relays_403_with_non_dict_json_body( monkeypatch: pytest.MonkeyPatch, ) -> None: """A non-dict JSON error body (e.g. a bare list/string) must not crash detail extraction and turn a relayable 4xx into an opaque 500.""" monkeypatch.setattr( "control_plane_backend.product.service.httpx.AsyncClient", _fake_async_client_returning_raw(403, json_body=["not", "a", "dict"]), ) app = create_app() container = get_application_container_from_app(app) deps = build_product_service_dependencies(container) with pytest.raises(SessionAttachmentRequestError) as excinfo: await _delete_knowledge_flow_attachment( authorization="Bearer test-token", document_uid="doc-1", storage_key=None, session_id="session-1", deps=deps, ) assert excinfo.value.http_status == 403 @pytest.mark.asyncio async def test_enroll_agent_instance_returns_404_for_unknown_runtime( monkeypatch: pytest.MonkeyPatch, ) -> None: monkeypatch.setattr( "control_plane_backend.product.api.require_team_access", _fake_require_team_access, ) store = _FakeAgentInstanceStore([]) app = create_app() _patch_store(monkeypatch, store) container = get_application_container_from_app(app) container.configuration.platform.runtime_catalog_sources = [] async with AsyncClient( transport=ASGITransport(app=app), base_url="http://test" ) as client: resp = await client.post( "/control-plane/v1/teams/personal/agent-instances", json={ "usage_statement": "Test usage statement covering purpose, users, data, and error impact.", "template_id": "unknown-runtime:some-agent", "display_name": "Agent", }, ) assert resp.status_code == 404 @pytest.mark.asyncio async def test_enroll_agent_instance_returns_400_for_malformed_template_id( monkeypatch: pytest.MonkeyPatch, ) -> None: monkeypatch.setattr( "control_plane_backend.product.api.require_team_access", _fake_require_team_access, ) store = _FakeAgentInstanceStore([]) app = create_app() _patch_store(monkeypatch, store) async with AsyncClient( transport=ASGITransport(app=app), base_url="http://test" ) as client: resp = await client.post( "/control-plane/v1/teams/personal/agent-instances", json={ "usage_statement": "Test usage statement covering purpose, users, data, and error impact.", "template_id": "no-colon-here", "display_name": "Agent", }, ) assert resp.status_code == 400 @pytest.mark.asyncio async def test_delete_agent_instance_removes_record( monkeypatch: pytest.MonkeyPatch, ) -> None: monkeypatch.setattr( "control_plane_backend.product.api.require_team_access", _fake_require_team_access, ) store = _FakeAgentInstanceStore([_make_record()]) app = create_app() _patch_store(monkeypatch, store) async with AsyncClient( transport=ASGITransport(app=app), base_url="http://test" ) as client: resp = await client.delete( "/control-plane/v1/teams/personal/agent-instances/instance-1" ) assert resp.status_code == 204 assert len(store._records) == 0 @pytest.mark.asyncio async def test_delete_agent_instance_returns_404_when_not_found( monkeypatch: pytest.MonkeyPatch, ) -> None: monkeypatch.setattr( "control_plane_backend.product.api.require_team_access", _fake_require_team_access, ) store = _FakeAgentInstanceStore([]) app = create_app() _patch_store(monkeypatch, store) async with AsyncClient( transport=ASGITransport(app=app), base_url="http://test" ) as client: resp = await client.delete( "/control-plane/v1/teams/personal/agent-instances/no-such" ) assert resp.status_code == 404 @pytest.mark.asyncio async def test_delete_agent_instance_enforces_team_scope( monkeypatch: pytest.MonkeyPatch, ) -> None: monkeypatch.setattr( "control_plane_backend.product.api.require_team_access", _fake_require_team_access, ) store = _FakeAgentInstanceStore([_make_record(team_id="other-team")]) app = create_app() _patch_store(monkeypatch, store) async with AsyncClient( transport=ASGITransport(app=app), base_url="http://test" ) as client: resp = await client.delete( "/control-plane/v1/teams/personal/agent-instances/instance-1" ) assert resp.status_code == 404 assert len(store._records) == 1 # record belonging to other-team is untouched @pytest.mark.asyncio async def test_teams_preflight_options_is_handled_by_cors() -> None: app = create_app() async with AsyncClient( transport=ASGITransport(app=app), base_url="http://test" ) as client: resp = await client.options( "/control-plane/v1/teams", headers={ "Origin": "http://localhost:5173", "Access-Control-Request-Method": "GET", }, ) assert resp.status_code == 200 assert resp.headers.get("access-control-allow-origin") == "http://localhost:5173" @pytest.mark.asyncio @pytest.mark.parametrize( ("relation", "expected_permission"), [ ("team_member", TeamPermission.CAN_ADMINISTER_MEMBERS), ("team_editor", TeamPermission.CAN_ADMINISTER_EDITORS), ("team_analyst", TeamPermission.CAN_ADMINISTER_ANALYSTS), ("team_admin", TeamPermission.CAN_ADMINISTER_ADMINS), ], ) async def test_add_team_member_checks_permission_for_target_relation( monkeypatch: pytest.MonkeyPatch, relation: str, expected_permission: TeamPermission, ) -> None: captured_permissions: list[list[TeamPermission]] = [] async def _fake_validate_team_and_check_permission( *_args, **_kwargs, ): permissions = _args[3] captured_permissions.append(permissions) return TeamMetadata(id=TeamId("thales"), name="Thales"), None async def _fake_add_team_member_relation(*_args, **_kwargs): return None monkeypatch.setattr( "control_plane_backend.teams.service._validate_team_and_check_permission", _fake_validate_team_and_check_permission, ) monkeypatch.setattr( "control_plane_backend.teams.service._add_team_member_relation", _fake_add_team_member_relation, ) app = create_app() async with AsyncClient( transport=ASGITransport(app=app), base_url="http://test" ) as client: resp = await client.post( "/control-plane/v1/teams/thales/members", json={"user_id": "user-001", "relation": relation}, ) assert resp.status_code == 204 assert captured_permissions == [[expected_permission]] @pytest.mark.asyncio async def test_update_team_checks_can_update_info_permission( monkeypatch: pytest.MonkeyPatch, ) -> None: class _FakeMetadataStore: def __init__(self) -> None: self.calls: list[tuple[str, dict[str, object]]] = [] async def get_by_team_id(self, team_id, session=None) -> TeamMetadata | None: return None async def upsert(self, team_id: str, patch, session=None) -> TeamMetadata: self.calls.append((team_id, patch.model_dump(exclude_unset=True))) return TeamMetadata(id=TeamId(team_id), name="Thales") fake_metadata_store = _FakeMetadataStore() captured_permissions: list[list[TeamPermission]] = [] async def _fake_validate_team_and_check_permission(*_args, **_kwargs): permissions = _args[3] captured_permissions.append(permissions) # Explicitly PUBLIC (#2433 made the metadata default PRIVATE): this # test PATCHes `joining_mode: open`, and the TEAM-10 downgrade rule # would rewrite that to `invite_only` on a private team — the # downgrade has its own test; this one covers permission gating and # the banner-field bridge. return ( TeamMetadata( id=TeamId("thales"), name="Thales", visibility=TeamVisibility.PUBLIC ), "token", ) async def _fake_get_team_permissions_for_user(*_args, **_kwargs): return [TeamPermission.CAN_UPDATE_INFO] async def _fake_enrich_teams_with_membership(*_args, **_kwargs): return [Team(id=TeamId("thales"), name="Thales")] monkeypatch.setattr( "control_plane_backend.teams.service._validate_team_and_check_permission", _fake_validate_team_and_check_permission, ) monkeypatch.setattr( "control_plane_backend.teams.service._get_team_permissions_for_user", _fake_get_team_permissions_for_user, ) monkeypatch.setattr( "control_plane_backend.teams.service._enrich_teams_with_membership", _fake_enrich_teams_with_membership, ) monkeypatch.setattr( "control_plane_backend.app.context.ApplicationContext.get_team_metadata_store", lambda _self: fake_metadata_store, ) app = create_app() async with AsyncClient( transport=ASGITransport(app=app), base_url="http://test" ) as client: resp = await client.patch( "/control-plane/v1/teams/thales", json={ "description": "Updated description", "joining_mode": "open", "avatar_image_url": "https://example.test/banner.webp", }, ) assert resp.status_code == 200 assert captured_permissions == [[TeamPermission.CAN_UPDATE_INFO]] # #2300 Option A: the public field is `avatar_image_url`, but update_team # bridges it to the storage layer's legacy `banner_image_url` before the # patch reaches the store — so the store still records `banner_image_url`. assert fake_metadata_store.calls == [ ( "thales", { "description": "Updated description", "joining_mode": "open", "banner_image_url": "https://example.test/banner.webp", }, ) ] class _FakeVisibilityRebac(NoopRebacEngine): """Records `ensure_team_public_relations`/`revoke_team_public_relations` calls so TEAM-10's immediate ReBAC sync in `update_team` is verifiable. Subclasses `NoopRebacEngine` (authorizes everything, persists nothing) for every other collaborator `update_team` touches downstream (`_get_user_roles_in_team`, `_get_team_permissions_for_user`, ...) — only the two relation-sync methods are overridden.""" def __init__(self) -> None: self.granted_team_ids: list[list[str]] = [] self.revoked_team_ids: list[list[str]] = [] async def ensure_team_public_relations( self, team_ids, *, consistency_token: str | None = None ) -> str | None: self.granted_team_ids.append(list(team_ids)) return None async def revoke_team_public_relations( self, team_ids, *, consistency_token: str | None = None ) -> str | None: self.revoked_team_ids.append(list(team_ids)) return None def _setup_update_team_test( monkeypatch: pytest.MonkeyPatch, *, starting_joining_mode: JoiningMode, starting_visibility: TeamVisibility, ): class _FakeMetadataStore: def __init__(self) -> None: self.calls: list[tuple[str, dict[str, object]]] = [] async def get_by_team_id(self, team_id, session=None) -> TeamMetadata | None: return None async def upsert(self, team_id: str, patch, session=None) -> TeamMetadata: payload = patch.model_dump(exclude_unset=True) self.calls.append((team_id, payload)) return TeamMetadata( id=TeamId(team_id), name="Thales", joining_mode=payload.get("joining_mode", starting_joining_mode), visibility=payload.get("visibility", starting_visibility), ) fake_metadata_store = _FakeMetadataStore() rebac = _FakeVisibilityRebac() async def _fake_validate_team_and_check_permission(*_args, **_kwargs): return ( TeamMetadata( id=TeamId("thales"), name="Thales", joining_mode=starting_joining_mode, visibility=starting_visibility, ), "token", ) async def _fake_get_team_permissions_for_user(*_args, **_kwargs): return [TeamPermission.CAN_UPDATE_INFO] async def _fake_enrich_teams_with_membership(*_args, **_kwargs): return [Team(id=TeamId("thales"), name="Thales")] monkeypatch.setattr( "control_plane_backend.teams.service._validate_team_and_check_permission", _fake_validate_team_and_check_permission, ) monkeypatch.setattr( "control_plane_backend.teams.service._get_team_permissions_for_user", _fake_get_team_permissions_for_user, ) monkeypatch.setattr( "control_plane_backend.teams.service._enrich_teams_with_membership", _fake_enrich_teams_with_membership, ) monkeypatch.setattr( "control_plane_backend.app.context.ApplicationContext.get_team_metadata_store", lambda _self: fake_metadata_store, ) monkeypatch.setattr( "control_plane_backend.app.context.ApplicationContext.get_rebac_engine", lambda _self: rebac, ) return fake_metadata_store, rebac @pytest.mark.asyncio async def test_update_team_downgrades_joining_mode_when_visibility_turns_private( monkeypatch: pytest.MonkeyPatch, ) -> None: """TEAM-10 (RFC §5.1.2): a PRIVATE team can never be OPEN. Setting visibility=private on a team that's currently OPEN must silently downgrade joining_mode to invite_only, not reject the request.""" fake_metadata_store, rebac = _setup_update_team_test( monkeypatch, starting_joining_mode=JoiningMode.OPEN, starting_visibility=TeamVisibility.PUBLIC, ) app = create_app() async with AsyncClient( transport=ASGITransport(app=app), base_url="http://test" ) as client: resp = await client.patch( "/control-plane/v1/teams/thales", json={"visibility": "private"} ) assert resp.status_code == 200 assert fake_metadata_store.calls == [ ("thales", {"visibility": "private", "joining_mode": "invite_only"}) ] assert rebac.revoked_team_ids == [["thales"]] assert rebac.granted_team_ids == [] @pytest.mark.asyncio async def test_update_team_downgrades_joining_mode_when_open_requested_on_private_team( monkeypatch: pytest.MonkeyPatch, ) -> None: """Same invariant, the other direction: requesting joining_mode=open on a team that's already PRIVATE must not flip it to OPEN — it silently stays (or becomes) invite_only instead.""" fake_metadata_store, rebac = _setup_update_team_test( monkeypatch, starting_joining_mode=JoiningMode.INVITE_ONLY, starting_visibility=TeamVisibility.PRIVATE, ) app = create_app() async with AsyncClient( transport=ASGITransport(app=app), base_url="http://test" ) as client: resp = await client.patch( "/control-plane/v1/teams/thales", json={"joining_mode": "open"} ) assert resp.status_code == 200 assert fake_metadata_store.calls == [("thales", {"joining_mode": "invite_only"})] # visibility wasn't part of this request, so no ReBAC sync call is expected. assert rebac.revoked_team_ids == [] assert rebac.granted_team_ids == [] @pytest.mark.asyncio async def test_update_team_syncs_rebac_public_relation_when_visibility_turns_public( monkeypatch: pytest.MonkeyPatch, ) -> None: """The reverse transition (private -> public) must grant `public` immediately rather than waiting for the next marketplace list call.""" fake_metadata_store, rebac = _setup_update_team_test( monkeypatch, starting_joining_mode=JoiningMode.INVITE_ONLY, starting_visibility=TeamVisibility.PRIVATE, ) app = create_app() async with AsyncClient( transport=ASGITransport(app=app), base_url="http://test" ) as client: resp = await client.patch( "/control-plane/v1/teams/thales", json={"visibility": "public"} ) assert resp.status_code == 200 assert fake_metadata_store.calls == [("thales", {"visibility": "public"})] assert rebac.granted_team_ids == [["thales"]] assert rebac.revoked_team_ids == [] @pytest.mark.asyncio async def test_enrich_teams_with_membership_resolves_banner_and_metadata_fields( monkeypatch: pytest.MonkeyPatch, ) -> None: """AUTHZ-05 review item 9: `_enrich_teams_with_membership` renders directly off the `TeamMetadata` rows it's handed (description/joining_mode/banner) — there is no separate Keycloak-group-summary type or admin fetch anymore.""" from control_plane_backend.teams.dependencies import TeamServiceDependencies from control_plane_backend.teams.service import _enrich_teams_with_membership class _FakeContentStore: def get_presigned_url(self, key: str, expires=None) -> str: _ = expires assert key == "teams/team-1/banner-1.png" return "https://example.test/banner.png" async def _fake_bulk_team_membership(*_args, **_kwargs): return {}, {}, {} async def _fake_get_users_by_ids(*_args, **_kwargs): return {} async def _fake_search_users(*_args, **_kwargs): return [] monkeypatch.setattr( "control_plane_backend.teams.service._bulk_team_membership", _fake_bulk_team_membership, ) from unittest.mock import MagicMock mock_config = MagicMock() mock_config.app.default_team_max_resources_storage_size = 5368709120 mock_config.app.personal_max_resources_storage_size = 5368709120 mock_config.scheduler.enabled = False fake_deps = TeamServiceDependencies( configuration=mock_config, rebac=cast(Any, object()), scheduler_backend=cast(Any, object()), get_team_metadata_store=cast(Any, object), get_prompt_store=cast(Any, object), get_prompt_category_store=cast(Any, object), get_content_store=lambda: cast(Any, _FakeContentStore()), get_session_store=cast(Any, object), get_purge_queue_store=cast(Any, object), get_policy_catalog=cast(Any, object), get_users_by_ids=_fake_get_users_by_ids, search_users=_fake_search_users, run_lifecycle_manager_once_in_memory=cast(Any, lambda _input: object()), ) teams = await _enrich_teams_with_membership( cast(Any, object()), # rebac unused due to monkeypatched _bulk_team_membership user=cast(Any, type("User", (), {"uid": "user-1"})()), teams_metadata=[ TeamMetadata( id=TeamId("team-1"), name="Team 1", description="desc", joining_mode=JoiningMode.OPEN, banner_object_storage_key="teams/team-1/banner-1.png", ) ], deps=fake_deps, ) assert len(teams) == 1 assert teams[0].description == "desc" assert teams[0].joining_mode == JoiningMode.OPEN assert teams[0].avatar_image_url == "https://example.test/banner.png" @pytest.mark.asyncio async def test_enrich_teams_dedupes_owner_alias_and_canonical_user( monkeypatch: pytest.MonkeyPatch, ) -> None: """Admin dedupe still applies: legacy relations naming a username alongside newer relations naming the canonical user id must render as one admin, even though admin ids now resolve purely through `_bulk_team_membership`.""" from control_plane_backend.teams.dependencies import TeamServiceDependencies from control_plane_backend.teams.service import _enrich_teams_with_membership class _FakeContentStore: def get_presigned_url(self, key: str, expires=None) -> str: _ = key _ = expires raise AssertionError("No banner lookup expected in this test.") async def _fake_bulk_team_membership(*_args, **_kwargs): members = {"user-1", "marc"} return {"team-1": members}, {"team-1": members}, {"team-1": set()} async def _fake_get_users_by_ids(*_args, **_kwargs): return { "user-1": UserSummary(id="user-1", username="marc"), "marc": UserSummary(id="marc"), } async def _fake_search_users(*_args, **_kwargs): return [] monkeypatch.setattr( "control_plane_backend.teams.service._bulk_team_membership", _fake_bulk_team_membership, ) from unittest.mock import MagicMock mock_config = MagicMock() mock_config.app.default_team_max_resources_storage_size = 5368709120 mock_config.app.personal_max_resources_storage_size = 5368709120 mock_config.scheduler.enabled = False fake_deps = TeamServiceDependencies( configuration=mock_config, rebac=cast(Any, object()), scheduler_backend=cast(Any, object()), get_team_metadata_store=cast(Any, object), get_prompt_store=cast(Any, object), get_prompt_category_store=cast(Any, object), get_content_store=lambda: cast(Any, _FakeContentStore()), get_session_store=cast(Any, object), get_purge_queue_store=cast(Any, object), get_policy_catalog=cast(Any, object), get_users_by_ids=_fake_get_users_by_ids, search_users=_fake_search_users, run_lifecycle_manager_once_in_memory=cast(Any, lambda _input: object()), ) teams = await _enrich_teams_with_membership( cast(Any, object()), user=cast(Any, type("User", (), {"uid": "user-1"})()), teams_metadata=[TeamMetadata(id=TeamId("team-1"), name="fredlab")], deps=fake_deps, ) assert len(teams) == 1 assert [admin.username or admin.id for admin in teams[0].admins] == ["marc"] @pytest.mark.asyncio async def test_upload_team_avatar_checks_can_update_info_permission( monkeypatch: pytest.MonkeyPatch, ) -> None: class _FakeContentStore: def __init__(self) -> None: self.calls: list[tuple[str, bytes, str]] = [] def put_object(self, key: str, stream, *, content_type: str) -> None: self.calls.append((key, stream.read(), content_type)) class _FakeMetadataStore: def __init__(self) -> None: self.calls: list[tuple[str, dict[str, object]]] = [] async def upsert(self, team_id: str, patch, session=None) -> TeamMetadata: self.calls.append((team_id, patch.model_dump(exclude_unset=True))) return TeamMetadata(id=TeamId(team_id), name="Thales") fake_content_store = _FakeContentStore() fake_metadata_store = _FakeMetadataStore() captured_permissions: list[list[TeamPermission]] = [] async def _fake_validate_team_and_check_permission(*_args, **_kwargs): permissions = _args[3] captured_permissions.append(permissions) return TeamMetadata(id=TeamId("thales"), name="Thales"), None monkeypatch.setattr( "control_plane_backend.teams.service._validate_team_and_check_permission", _fake_validate_team_and_check_permission, ) monkeypatch.setattr( "control_plane_backend.app.context.ApplicationContext.get_content_store", lambda _self: fake_content_store, ) monkeypatch.setattr( "control_plane_backend.app.context.ApplicationContext.get_team_metadata_store", lambda _self: fake_metadata_store, ) app = create_app() async with AsyncClient( transport=ASGITransport(app=app), base_url="http://test" ) as client: resp = await client.post( "/control-plane/v1/teams/thales/avatar", files={"file": ("banner.png", b"\x89PNG\r\n\x1a\nbanner", "image/png")}, ) assert resp.status_code == 204 assert captured_permissions == [[TeamPermission.CAN_UPDATE_INFO]] assert len(fake_content_store.calls) == 1 object_key, uploaded_payload, uploaded_content_type = fake_content_store.calls[0] assert object_key.startswith("teams/thales/avatar-") assert object_key.endswith(".png") assert uploaded_content_type == "image/png" assert uploaded_payload.startswith(b"\x89PNG\r\n\x1a\n") assert fake_metadata_store.calls == [ ("thales", {"banner_object_storage_key": object_key}) ] @pytest.mark.asyncio async def test_upload_team_avatar_rejects_invalid_content_type( monkeypatch: pytest.MonkeyPatch, ) -> None: async def _fake_validate_team_and_check_permission(*_args, **_kwargs): return object(), {"id": "thales", "name": "Thales"}, None monkeypatch.setattr( "control_plane_backend.teams.service._validate_team_and_check_permission", _fake_validate_team_and_check_permission, ) app = create_app() async with AsyncClient( transport=ASGITransport(app=app), base_url="http://test" ) as client: resp = await client.post( "/control-plane/v1/teams/thales/avatar", files={"file": ("banner.txt", b"not-an-image", "text/plain")}, ) assert resp.status_code == 400 assert resp.json()["detail"] == "Invalid content type: text/plain" @pytest.mark.asyncio async def test_upload_team_avatar_rejects_file_too_large( monkeypatch: pytest.MonkeyPatch, ) -> None: async def _fake_validate_team_and_check_permission(*_args, **_kwargs): return object(), {"id": "thales", "name": "Thales"}, None monkeypatch.setattr( "control_plane_backend.teams.service._validate_team_and_check_permission", _fake_validate_team_and_check_permission, ) app = create_app() too_large_payload = b"\x89PNG\r\n\x1a\n" + b"a" * (5 * 1024 * 1024) async with AsyncClient( transport=ASGITransport(app=app), base_url="http://test" ) as client: resp = await client.post( "/control-plane/v1/teams/thales/avatar", files={"file": ("banner.png", too_large_payload, "image/png")}, ) assert resp.status_code == 400 assert resp.json()["detail"].startswith("File too large:") @pytest.mark.asyncio async def test_delete_team_member_enqueues_matching_team_sessions(monkeypatch) -> None: class _FakeRebac: def __init__(self) -> None: self.delete_relations_calls = 0 async def delete_relations(self, _relations) -> None: self.delete_relations_calls += 1 class _FakeSessionStore: async def get_for_user( self, _user_id: str, team_id: Optional[str], db_session=None ) -> list[SessionSchema]: return [ SessionSchema( id="s-1", user_id=_user_id, team_id=team_id, title="", updated_at=datetime.now(), ), SessionSchema( id="s-3", user_id=_user_id, team_id=team_id, title="", updated_at=datetime.now(), ), ] class _FakeQueueStore: def __init__(self) -> None: self.enqueued: list[tuple[str, str, str, datetime]] = [] async def enqueue( self, *, session_id: str, team_id: str, user_id: str, due_at: datetime, session=None, ) -> None: self.enqueued.append((session_id, team_id, user_id, due_at)) fake_rebac = _FakeRebac() fake_queue = _FakeQueueStore() async def _fake_get_user_roles_in_team(*_args, **_kwargs): from control_plane_backend.teams.schemas import UserTeamRelation return {UserTeamRelation.TEAM_MEMBER} async def _fake_validate_team_and_check_permission(*_args, **_kwargs): return TeamMetadata(id=TeamId("swiftpost"), name="SwiftPost"), None monkeypatch.setattr( "control_plane_backend.teams.service._get_user_roles_in_team", _fake_get_user_roles_in_team, ) monkeypatch.setattr( "control_plane_backend.teams.service._validate_team_and_check_permission", _fake_validate_team_and_check_permission, ) monkeypatch.setattr( "control_plane_backend.app.context.ApplicationContext.get_rebac_engine", lambda _self: fake_rebac, ) monkeypatch.setattr( "control_plane_backend.app.context.ApplicationContext.get_session_store", lambda _self: _FakeSessionStore(), ) monkeypatch.setattr( "control_plane_backend.app.context.ApplicationContext.get_purge_queue_store", lambda _self: fake_queue, ) app = create_app() async with AsyncClient( transport=ASGITransport(app=app), base_url="http://test" ) as client: resp = await client.delete( "/control-plane/v1/teams/swiftpost/members/user-002", ) assert resp.status_code == 202 payload = resp.json() assert payload["status"] == "accepted" assert payload["team_id"] == "swiftpost" assert payload["user_id"] == "user-002" assert payload["sessions_enqueued"] == 2 assert payload["policy_mode"] == "deferred_delete" assert payload["retention_seconds"] == 60 assert payload["matched_rule_id"] == "purge.team.swiftpost" assert len(fake_queue.enqueued) == 2 assert fake_queue.enqueued[0][0] == "s-1" assert fake_queue.enqueued[1][0] == "s-3" assert fake_rebac.delete_relations_calls == 1 @pytest.mark.asyncio async def test_delete_team_member_runs_in_memory_lifecycle_pass_when_enabled( monkeypatch: pytest.MonkeyPatch, ) -> None: from control_plane_backend.scheduler.policies.policy_models import ( PolicyEvaluationResult, PurgeMode, ) from control_plane_backend.scheduler.temporal.structures import ( LifecycleManagerResult, ) from control_plane_backend.teams.dependencies import TeamServiceDependencies from fred_core.scheduler import SchedulerBackend class _FakeRebac: async def delete_relations(self, _relations) -> None: return None class _FakeSessionStore: async def get_for_user( self, _user_id: str, db_session=None ) -> list[SessionSchema]: return [ SessionSchema( id="s-1", user_id=_user_id, team_id="temp-lab", title="", updated_at=datetime.now(), ) ] class _FakeQueueStore: async def enqueue( self, *, session_id: str, team_id: str, user_id: str, due_at: datetime, session=None, ) -> None: _ = (session_id, team_id, user_id, due_at) lifecycle_calls: list[int] = [] fake_rebac = _FakeRebac() fake_session_store = _FakeSessionStore() fake_queue_store = _FakeQueueStore() async def _fake_get_user_roles_in_team(*_args, **_kwargs): from control_plane_backend.teams.schemas import UserTeamRelation return {UserTeamRelation.TEAM_MEMBER} async def _fake_validate_team_and_check_permission(*_args, **_kwargs): return TeamMetadata(id=TeamId("temp-lab"), name="Temp Lab"), None async def _fake_run_lifecycle_manager_once_in_memory(_input_data): lifecycle_calls.append(1) return LifecycleManagerResult(scanned=1, deleted=1, dry_run_actions=0) def _fake_evaluate_policy_for_request(*_args, **_kwargs): return PolicyEvaluationResult( mode=PurgeMode.IMMEDIATE_DELETE, retention="PT0S", retention_seconds=0, cancel_on_rejoin=True, matched_rule_id="purge.team.temp-lab", matched_rule_specificity=2, ) async def _fake_get_users_by_ids(_user_ids): return {} async def _fake_search_users(_query): return [] fake_scheduler = type("SchedulerCfg", (), {"enabled": True})() fake_configuration = type("Cfg", (), {"scheduler": fake_scheduler})() fake_team_deps = TeamServiceDependencies( configuration=cast(Any, fake_configuration), rebac=cast(Any, fake_rebac), scheduler_backend=SchedulerBackend.MEMORY, get_team_metadata_store=lambda: cast(Any, object()), get_prompt_store=cast(Any, object), get_prompt_category_store=cast(Any, object), get_content_store=lambda: cast(Any, object()), get_session_store=cast(Any, lambda: fake_session_store), get_purge_queue_store=cast(Any, lambda: fake_queue_store), get_policy_catalog=cast(Any, object), get_users_by_ids=_fake_get_users_by_ids, search_users=_fake_search_users, run_lifecycle_manager_once_in_memory=_fake_run_lifecycle_manager_once_in_memory, ) monkeypatch.setattr( "control_plane_backend.teams.dependencies.build_team_service_dependencies", lambda *_args, **_kwargs: fake_team_deps, ) monkeypatch.setattr( "control_plane_backend.teams.service._get_user_roles_in_team", _fake_get_user_roles_in_team, ) monkeypatch.setattr( "control_plane_backend.teams.service._validate_team_and_check_permission", _fake_validate_team_and_check_permission, ) monkeypatch.setattr( "control_plane_backend.teams.service.evaluate_policy_for_request", _fake_evaluate_policy_for_request, ) app = create_app() async with AsyncClient( transport=ASGITransport(app=app), base_url="http://test" ) as client: resp = await client.delete( "/control-plane/v1/teams/temp-lab/members/user-002", ) assert resp.status_code == 202 assert lifecycle_calls == [1] @pytest.mark.asyncio async def test_lifecycle_run_once_executes_in_memory_backend( monkeypatch: pytest.MonkeyPatch, ) -> None: from control_plane_backend.config.models import Configuration from control_plane_backend.scheduler.temporal.structures import ( LifecycleManagerResult, ) from fred_core.common import parse_yaml_mapping_file payload = parse_yaml_mapping_file("./config/configuration.yaml") payload["scheduler"]["enabled"] = True payload["scheduler"]["backend"] = "memory" config = Configuration.model_validate(payload) async def _fake_run_lifecycle_manager_once_in_memory(_input_data, *, deps=None): _ = deps return LifecycleManagerResult(scanned=2, deleted=2, dry_run_actions=0) monkeypatch.setattr( "control_plane_backend.main.load_configuration", lambda: config, ) monkeypatch.setattr( "control_plane_backend.main.run_lifecycle_manager_once_in_memory", _fake_run_lifecycle_manager_once_in_memory, ) app = create_app() async with AsyncClient( transport=ASGITransport(app=app), base_url="http://test" ) as client: resp = await client.post( "/control-plane/v1/lifecycle/run-once", json={"dry_run": False, "batch_size": 50}, ) assert resp.status_code == 200 assert resp.json() == { "status": "completed", "backend": "memory", "workflow_id": None, "run_id": None, "result": {"scanned": 2, "deleted": 2, "dry_run_actions": 0}, } @pytest.mark.asyncio async def test_revoke_team_member_role_blocks_last_admin_demotion( monkeypatch: pytest.MonkeyPatch, ) -> None: """AUTHZ-06 (RFC Part 7 §35): revoking `team_admin` from the sole admin is blocked the same way the old single-role PATCH used to be.""" from control_plane_backend.teams.schemas import UserTeamRelation async def _fake_get_user_roles_in_team(*_args, **_kwargs): return {UserTeamRelation.TEAM_ADMIN, UserTeamRelation.TEAM_EDITOR} async def _fake_get_team_users_by_relation( _rebac, _team_id: TeamId, relation: RelationType, ) -> set[str]: if relation == RelationType.TEAM_ADMIN: return {"user-001"} return set() monkeypatch.setattr( "control_plane_backend.teams.service._get_user_roles_in_team", _fake_get_user_roles_in_team, ) monkeypatch.setattr( "control_plane_backend.teams.service._get_team_users_by_relation", _fake_get_team_users_by_relation, ) app = create_app() async with AsyncClient( transport=ASGITransport(app=app), base_url="http://test" ) as client: resp = await client.delete( "/control-plane/v1/teams/thales/members/user-001/roles/team_admin", ) assert resp.status_code == 409 assert ( resp.json()["detail"] == "Operation denied: a team must keep at least one team_admin." ) @pytest.mark.asyncio async def test_remove_team_member_blocks_removing_last_admin( monkeypatch: pytest.MonkeyPatch, ) -> None: from control_plane_backend.teams.schemas import UserTeamRelation async def _fake_get_user_roles_in_team(*_args, **_kwargs): return {UserTeamRelation.TEAM_ADMIN} async def _fake_get_team_users_by_relation( _rebac, _team_id: TeamId, relation: RelationType, ) -> set[str]: if relation == RelationType.TEAM_ADMIN: return {"user-001"} return set() monkeypatch.setattr( "control_plane_backend.teams.service._get_user_roles_in_team", _fake_get_user_roles_in_team, ) monkeypatch.setattr( "control_plane_backend.teams.service._get_team_users_by_relation", _fake_get_team_users_by_relation, ) app = create_app() async with AsyncClient( transport=ASGITransport(app=app), base_url="http://test" ) as client: resp = await client.delete("/control-plane/v1/teams/thales/members/user-001") assert resp.status_code == 409 assert ( resp.json()["detail"] == "Operation denied: a team must keep at least one team_admin." ) def _make_template_with_fields() -> "_RuntimeTemplatePayload": """Return a fake template payload that declares one tunable field.""" return _RuntimeTemplatePayload( template_agent_id="rags.sample.echo", title="Echo Agent", description="Echo with fields", kind="assistant", default_tuning=ManagedAgentTuning( role="Echo Agent", description="Echo with fields", fields=[ ManagedAgentFieldSpec( key="persona", type="string", title="Persona", description="Agent persona prompt", ) ], ), ) def _make_template_with_validated_fields() -> "_RuntimeTemplatePayload": """Return a fake template payload with typed field constraints for validation tests.""" return _RuntimeTemplatePayload( template_agent_id="rags.sample.validated", title="Validated Agent", description="Echo with validated fields", kind="assistant", default_tuning=ManagedAgentTuning( role="Validated Agent", description="Echo with validated fields", fields=[ ManagedAgentFieldSpec( key="prompts.system", type="prompt", title="System prompt", pattern=r"^.{3,}$", ), ManagedAgentFieldSpec( key="settings.delay_ms", type="integer", title="Delay", min=0, max=1000, ), ManagedAgentFieldSpec( key="settings.verbose", type="boolean", title="Verbose", ), ManagedAgentFieldSpec( key="chat_options.mode", type="select", title="Mode", enum=["compact", "full"], ), ], ), ) @pytest.mark.asyncio async def test_team_agent_templates_exposes_non_empty_tuning_fields( monkeypatch: pytest.MonkeyPatch, ) -> None: async def _fake_fetch_runtime_templates( _base_url: str, include_non_public: bool = False ): return [_make_template_with_fields()] monkeypatch.setattr( "control_plane_backend.product.service._fetch_runtime_templates", _fake_fetch_runtime_templates, ) app = create_app() container = get_application_container_from_app(app) container.configuration.platform.runtime_catalog_sources = [ RuntimeCatalogSourceConfig( runtime_id="runtime-a", base_url="http://runtime-a/pod/v1", enabled=True, ) ] async with AsyncClient( transport=ASGITransport(app=app), base_url="http://test" ) as client: resp = await client.get( f"/control-plane/v1/teams/{_PERSONAL_TEAM_ID}/agent-templates" ) assert resp.status_code == 200 fields = resp.json()[0]["default_tuning_fields"] assert len(fields) == 1 assert fields[0]["key"] == "persona" assert fields[0]["type"] == "string" assert fields[0]["title"] == "Persona" @pytest.mark.asyncio async def test_enroll_agent_instance_stores_provided_field_values( monkeypatch: pytest.MonkeyPatch, ) -> None: monkeypatch.setattr( "control_plane_backend.product.api.require_team_access", _fake_require_team_access, ) async def _fake_fetch_runtime_templates( _base_url: str, include_non_public: bool = False ): return [_make_template_with_fields()] monkeypatch.setattr( "control_plane_backend.product.service._fetch_runtime_templates", _fake_fetch_runtime_templates, ) store = _FakeAgentInstanceStore([]) app = create_app() _patch_store(monkeypatch, store) container = get_application_container_from_app(app) container.configuration.platform.runtime_catalog_sources = [ RuntimeCatalogSourceConfig( runtime_id="runtime-a", base_url="http://runtime-a/pod/v1", enabled=True, ) ] async with AsyncClient( transport=ASGITransport(app=app), base_url="http://test" ) as client: resp = await client.post( "/control-plane/v1/teams/personal/agent-instances", json={ "usage_statement": "Test usage statement covering purpose, users, data, and error impact.", "template_id": "runtime-a:rags.sample.echo", "display_name": "My Echo", "tuning_field_values": {"persona": "You are a helpful assistant."}, }, ) assert resp.status_code == 201 assert resp.json()["tuning_field_values"] == { "persona": "You are a helpful assistant." } assert store._records[0].tuning.values == { "persona": "You are a helpful assistant." } @pytest.mark.asyncio async def test_enroll_agent_instance_silently_drops_unknown_field_keys( monkeypatch: pytest.MonkeyPatch, ) -> None: monkeypatch.setattr( "control_plane_backend.product.api.require_team_access", _fake_require_team_access, ) async def _fake_fetch_runtime_templates( _base_url: str, include_non_public: bool = False ): return [_make_template_with_fields()] monkeypatch.setattr( "control_plane_backend.product.service._fetch_runtime_templates", _fake_fetch_runtime_templates, ) store = _FakeAgentInstanceStore([]) app = create_app() _patch_store(monkeypatch, store) container = get_application_container_from_app(app) container.configuration.platform.runtime_catalog_sources = [ RuntimeCatalogSourceConfig( runtime_id="runtime-a", base_url="http://runtime-a/pod/v1", enabled=True, ) ] async with AsyncClient( transport=ASGITransport(app=app), base_url="http://test" ) as client: resp = await client.post( "/control-plane/v1/teams/personal/agent-instances", json={ "usage_statement": "Test usage statement covering purpose, users, data, and error impact.", "template_id": "runtime-a:rags.sample.echo", "display_name": "My Echo", "tuning_field_values": { "persona": "valid", "unknown_key": "should be dropped", }, }, ) assert resp.status_code == 201 assert resp.json()["tuning_field_values"] == {"persona": "valid"} assert "unknown_key" not in store._records[0].tuning.values @pytest.mark.asyncio async def test_enroll_agent_instance_rejects_invalid_tuning_value_type_and_range( monkeypatch: pytest.MonkeyPatch, ) -> None: monkeypatch.setattr( "control_plane_backend.product.api.require_team_access", _fake_require_team_access, ) async def _fake_fetch_runtime_templates( _base_url: str, include_non_public: bool = False ): return [_make_template_with_validated_fields()] monkeypatch.setattr( "control_plane_backend.product.service._fetch_runtime_templates", _fake_fetch_runtime_templates, ) store = _FakeAgentInstanceStore([]) app = create_app() _patch_store(monkeypatch, store) container = get_application_container_from_app(app) container.configuration.platform.runtime_catalog_sources = [ RuntimeCatalogSourceConfig( runtime_id="runtime-a", base_url="http://runtime-a/pod/v1", enabled=True, ) ] async with AsyncClient( transport=ASGITransport(app=app), base_url="http://test" ) as client: resp = await client.post( "/control-plane/v1/teams/personal/agent-instances", json={ "usage_statement": "Test usage statement covering purpose, users, data, and error impact.", "template_id": "runtime-a:rags.sample.validated", "display_name": "Validated Echo", "tuning_field_values": { "settings.delay_ms": "slow", "settings.verbose": True, }, }, ) assert resp.status_code == 422 assert "settings.delay_ms" in resp.json()["detail"] assert store._records == [] @pytest.mark.asyncio async def test_patch_agent_instance_rejects_invalid_tuning_enum_value( monkeypatch: pytest.MonkeyPatch, ) -> None: monkeypatch.setattr( "control_plane_backend.product.api.require_team_access", _fake_require_team_access, ) record = AgentInstanceRecord( agent_instance_id="instance-validated", team_id=TeamId("personal"), template_id="runtime-a:rags.sample.validated", source_runtime_id="runtime-a", source_agent_id="rags.sample.validated", display_name="Validated", description=None, enabled=True, created_by="admin", tuning=_make_template_with_validated_fields().default_tuning, ) store = _FakeAgentInstanceStore([record]) app = create_app() _patch_store(monkeypatch, store) async with AsyncClient( transport=ASGITransport(app=app), base_url="http://test" ) as client: resp = await client.patch( "/control-plane/v1/teams/personal/agent-instances/instance-validated", json={"tuning_field_values": {"chat_options.mode": "unsupported"}}, ) assert resp.status_code == 422 assert "chat_options.mode" in resp.json()["detail"] assert store._records[0].tuning.values == {} @pytest.mark.asyncio async def test_patch_agent_instance_updates_display_name( monkeypatch: pytest.MonkeyPatch, ) -> None: monkeypatch.setattr( "control_plane_backend.product.api.require_team_access", _fake_require_team_access, ) store = _FakeAgentInstanceStore([_make_record()]) app = create_app() _patch_store(monkeypatch, store) async with AsyncClient( transport=ASGITransport(app=app), base_url="http://test" ) as client: resp = await client.patch( "/control-plane/v1/teams/personal/agent-instances/instance-1", json={"display_name": "Renamed Echo Agent"}, ) assert resp.status_code == 200 payload = resp.json() assert payload["display_name"] == "Renamed Echo Agent" assert payload["agent_instance_id"] == "instance-1" assert payload["status"] == "enabled" @pytest.mark.asyncio async def test_patch_agent_instance_stamps_updated_by( monkeypatch: pytest.MonkeyPatch, ) -> None: """PATCH stamps the acting user's uid into updated_by (#1952).""" monkeypatch.setattr( "control_plane_backend.product.api.require_team_access", _fake_require_team_access, ) record = _make_record() assert record.updated_by is None store = _FakeAgentInstanceStore([record]) app = create_app() _patch_store(monkeypatch, store) async with AsyncClient( transport=ASGITransport(app=app), base_url="http://test" ) as client: resp = await client.patch( "/control-plane/v1/teams/personal/agent-instances/instance-1", json={"display_name": "Renamed Echo Agent"}, ) assert resp.status_code == 200 payload = resp.json() # No-security mode authenticates as the mock "admin" subject. assert payload["updated_by"] == "admin" assert record.updated_by == "admin" @pytest.mark.asyncio async def test_patch_agent_instance_updates_tuning_field_values( monkeypatch: pytest.MonkeyPatch, ) -> None: monkeypatch.setattr( "control_plane_backend.product.api.require_team_access", _fake_require_team_access, ) record = AgentInstanceRecord( agent_instance_id="instance-fields", team_id=TeamId("personal"), template_id="runtime-a:rags.sample.echo", source_runtime_id="runtime-a", source_agent_id="rags.sample.echo", display_name="Echo", description=None, enabled=True, created_by="admin", tuning=ManagedAgentTuning( role="Echo", description="Echo", fields=[ ManagedAgentFieldSpec(key="persona", type="string", title="Persona") ], values={"persona": "old value"}, ), ) store = _FakeAgentInstanceStore([record]) app = create_app() _patch_store(monkeypatch, store) async with AsyncClient( transport=ASGITransport(app=app), base_url="http://test" ) as client: resp = await client.patch( "/control-plane/v1/teams/personal/agent-instances/instance-fields", json={"tuning_field_values": {"persona": "new persona value"}}, ) assert resp.status_code == 200 assert resp.json()["tuning_field_values"] == {"persona": "new persona value"} assert store._records[0].tuning.values == {"persona": "new persona value"} def _fake_pod_validate_config_echo(monkeypatch: pytest.MonkeyPatch) -> None: """ Replace the capability config pod round-trip with an echo (#1978): the envelope's `config` is whatever was submitted, persisted verbatim, exactly as the real `mcp:<id>` capability's permissive `McpServerConfig` would. """ async def _fake( *, base_url: str, capability_id: str, config_values: dict[str, Any], team_id, agent_instance_id, authorization, asset_files=(), ) -> dict[str, Any]: # `asset_files` (#1903) accepted for signature parity with the # production call in `_apply_capability_selection`; these MCP-config # tests carry no uploads. return {"schema_version": "1", "config": dict(config_values)} monkeypatch.setattr( "control_plane_backend.product.service._validate_capability_config_via_pod", _fake, ) @pytest.mark.asyncio async def test_patch_agent_instance_refreshes_runtime_mcp_contract_before_validating_update( monkeypatch: pytest.MonkeyPatch, ) -> None: """An MCP server's `capability_config_values` re-validate through the same pod round-trip as any other capability (#1978), using the freshly fetched template contract rather than a stale snapshot.""" monkeypatch.setattr( "control_plane_backend.product.api.require_team_access", _fake_require_team_access, ) record = AgentInstanceRecord( agent_instance_id="instance-mcp-refresh", team_id=TeamId("personal"), template_id="runtime-a:rags.sample.mcp", source_runtime_id="runtime-a", source_agent_id="rags.sample.mcp", display_name="MCP", description=None, enabled=True, created_by="admin", tuning=ManagedAgentTuning( role="MCP", description="MCP", selected_capability_ids=[_MCP_SEARCH_ID], capability_config={ _MCP_SEARCH_ID: { "schema_version": "1", "config": {"chat_options.libraries_selection": True}, } }, ), ) store = _FakeAgentInstanceStore([record]) app = create_app() _patch_store(monkeypatch, store) container = get_application_container_from_app(app) container.configuration.platform.runtime_catalog_sources = [ RuntimeCatalogSourceConfig( runtime_id="runtime-a", base_url="http://runtime-a/pod/v1", enabled=True, ) ] async def _fake_fetch(_base_url: str, include_non_public: bool = False): return [_make_template_with_mcp_servers()] monkeypatch.setattr( "control_plane_backend.product.service._fetch_runtime_templates", _fake_fetch, ) _fake_pod_validate_config_echo(monkeypatch) async with AsyncClient( transport=ASGITransport(app=app), base_url="http://test" ) as client: resp = await client.patch( "/control-plane/v1/teams/personal/agent-instances/instance-mcp-refresh", json={ "capability_config_values": { _MCP_SEARCH_ID: { "chat_options.libraries_binding": True, "chat_options.bound_library_ids": ["lib-a", "lib-b"], "chat_options.libraries_selection": False, } } }, ) assert resp.status_code == 200 assert resp.json()["capability_config"] == { _MCP_SEARCH_ID: { "schema_version": "1", "config": { "chat_options.libraries_binding": True, "chat_options.bound_library_ids": ["lib-a", "lib-b"], "chat_options.libraries_selection": False, }, } } @pytest.mark.asyncio async def test_patch_agent_instance_returns_404_for_unknown_instance( monkeypatch: pytest.MonkeyPatch, ) -> None: monkeypatch.setattr( "control_plane_backend.product.api.require_team_access", _fake_require_team_access, ) store = _FakeAgentInstanceStore([]) app = create_app() _patch_store(monkeypatch, store) async with AsyncClient( transport=ASGITransport(app=app), base_url="http://test" ) as client: resp = await client.patch( "/control-plane/v1/teams/personal/agent-instances/no-such", json={"display_name": "Whatever"}, ) assert resp.status_code == 404 # --------------------------------------------------------------------------- # MCP server selection — MCP servers are ordinary capabilities keyed by their # plain catalog server id now (#1988, supersedes the `mcp:<server>` namespacing # of #1978; RFC AGENT-CAPABILITY-RFC.md §3.8). The generic capability-selection # contract (unknown id -> 422, pod round-trip, prune/reset semantics) is covered # by test_capability_selection_1974.py; this section covers what is specific to # MCP-backed capabilities: drift detection (`catalog_warnings`) and the # cache-aside chat-controls orchestration at prep (#1976, RFC §3.3/§3.7 — the # `chat_options.*` resolution itself now lives on the pod in # McpCapability.chat_controls, tested in fred-runtime). # --------------------------------------------------------------------------- # #1988: an MCP-backed capability's id is the plain catalog server id (no # `mcp:` prefix). These constants are the ids as advertised by the pod catalog. _MCP_SEARCH_ID = "mcp-search" _MCP_STORAGE_ID = "mcp-storage" def _make_template_with_mcp_servers( *, libraries_selection_default: bool = False, documents_selection_default: bool = False, attach_files_default: bool = False, ) -> "_RuntimeTemplatePayload": """Return a fake template payload advertising two `mcp:<id>` capabilities.""" return _RuntimeTemplatePayload( template_agent_id="rags.sample.mcp", title="MCP Agent", description="Agent with MCP servers", kind="assistant", default_tuning=ManagedAgentTuning( role="MCP Agent", description="Agent with MCP servers", ), available_capabilities=[ CapabilityCatalogEntry( id=_MCP_SEARCH_ID, version="1", name="Search", description="Search", icon="extension", config_fields=[ FieldSpec( key="chat_options.libraries_binding", type="boolean", title="Libraries binding", default=False, ), FieldSpec( key="chat_options.libraries_selection", type="boolean", title="Libraries", default=libraries_selection_default, ), FieldSpec( key="chat_options.documents_selection", type="boolean", title="Documents", default=documents_selection_default, ), FieldSpec( key="chat_options.attach_files", type="boolean", title="File attachments", default=attach_files_default, ), FieldSpec( key="chat_options.bound_library_ids", type="array", title="Bound libraries", item_type="string", default=[], ), FieldSpec( key="chat_options.search_policy_enabled", type="boolean", title="Search policy picker", default=documents_selection_default, ), FieldSpec( key="chat_options.search_policy", type="string", title="Search policy", enum=["strict", "hybrid", "semantic"], default="hybrid", ), FieldSpec( key="chat_options.search_rag_scope_enabled", type="boolean", title="RAG scope picker", default=documents_selection_default, ), FieldSpec( key="chat_options.search_rag_scope", type="string", title="RAG scope", enum=["corpus_only", "hybrid", "general_only"], default="hybrid", ), ], ), CapabilityCatalogEntry( id=_MCP_STORAGE_ID, version="1", name="Storage", description="Storage", icon="extension", ), ], ) @pytest.mark.asyncio async def test_enroll_agent_instance_stores_mcp_server_selection( monkeypatch: pytest.MonkeyPatch, ) -> None: monkeypatch.setattr( "control_plane_backend.product.api.require_team_access", _fake_require_team_access, ) async def _fake_fetch(_base_url: str, include_non_public: bool = False): return [_make_template_with_mcp_servers()] monkeypatch.setattr( "control_plane_backend.product.service._fetch_runtime_templates", _fake_fetch, ) _fake_pod_validate_config_echo(monkeypatch) store = _FakeAgentInstanceStore([]) app = create_app() _patch_store(monkeypatch, store) container = get_application_container_from_app(app) container.configuration.platform.runtime_catalog_sources = [ RuntimeCatalogSourceConfig( runtime_id="runtime-a", base_url="http://runtime-a/pod/v1", enabled=True, ) ] async with AsyncClient( transport=ASGITransport(app=app), base_url="http://test" ) as client: resp = await client.post( "/control-plane/v1/teams/personal/agent-instances", json={ "usage_statement": "Test usage statement covering purpose, users, data, and error impact.", "template_id": "runtime-a:rags.sample.mcp", "display_name": "MCP Instance", "capability_ids": [_MCP_SEARCH_ID], }, ) assert resp.status_code == 201 assert store._records[0].tuning.selected_capability_ids == [_MCP_SEARCH_ID] @pytest.mark.asyncio async def test_enrolling_internal_template_is_admin_only( monkeypatch: pytest.MonkeyPatch, ) -> None: """A non-public template (AGENT-VISIBILITY-RFC) must not be enrollable by a non-admin who guesses its id; a real OpenFGA `platform_admin` can enroll it. AUTHZ-05 review finding: this used to check the Keycloak `admin` role directly (the same anti-pattern already fixed on the read-side `get_team_agent_templates`'s `include_non_public`) — it must go through `CAN_MANAGE_PLATFORM` like everywhere else, so a bare Keycloak role with no OpenFGA `platform_admin` relation is not sufficient.""" monkeypatch.setattr( "control_plane_backend.product.api.require_team_access", _fake_require_team_access, ) async def _fake_fetch_internal(_base_url: str, include_non_public: bool = False): # Simulate an internal template: only resolvable when non-public is included. return [_make_template_with_mcp_servers()] if include_non_public else [] monkeypatch.setattr( "control_plane_backend.product.service._fetch_runtime_templates", _fake_fetch_internal, ) class _FakePlatformAdminOnlyRebac: """Grants CAN_MANAGE_PLATFORM to `alice` only — mirrors a real OpenFGA `platform_admin` relation decoupled from any Keycloak role.""" async def has_user_permission( self, user, permission, _resource_id, *, consistency_token=None ) -> bool: return ( permission == OrganizationPermission.CAN_MANAGE_PLATFORM and user.uid == "alice" ) async def has_permission( self, subject, permission, resource, *, contextual_relations=None ) -> bool: # Not what this test exercises (see CAPAB-01's template-level # `can_use` check, service.py `enroll_agent_instance`) — permissive # so the non-public-template admin-only gating above is what # actually decides the outcome. return True monkeypatch.setattr( "control_plane_backend.app.context.ApplicationContext.get_rebac_engine", lambda _self: _FakePlatformAdminOnlyRebac(), ) store = _FakeAgentInstanceStore([]) app = create_app() _patch_store(monkeypatch, store) container = get_application_container_from_app(app) container.configuration.platform.runtime_catalog_sources = [ RuntimeCatalogSourceConfig( runtime_id="runtime-a", base_url="http://runtime-a/pod/v1", enabled=True, ) ] body = { "template_id": "runtime-a:rags.sample.mcp", "display_name": "x", "usage_statement": "Test usage statement covering purpose, users, data, and error impact.", } # Keycloak `admin` role but no OpenFGA `platform_admin` relation: the hidden # template resolves to nothing -> 404 (as if it did not exist). app.dependency_overrides[get_current_user] = lambda: KeycloakUser( uid="bob", username="bob", roles=["admin"] ) async with AsyncClient( transport=ASGITransport(app=app), base_url="http://test" ) as client: denied = await client.post( "/control-plane/v1/teams/personal/agent-instances", json=body ) assert denied.status_code == 404 # Real OpenFGA `platform_admin`, no Keycloak role needed: enrollment succeeds. app.dependency_overrides[get_current_user] = lambda: KeycloakUser( uid="alice", username="alice", roles=[] ) async with AsyncClient( transport=ASGITransport(app=app), base_url="http://test" ) as client: allowed = await client.post( "/control-plane/v1/teams/personal/agent-instances", json=body ) assert allowed.status_code == 201 app.dependency_overrides.clear() @pytest.mark.asyncio async def test_direct_execution_of_internal_agent_is_refused_for_everyone( monkeypatch: pytest.MonkeyPatch, ) -> None: """The direct (evaluation) prepare-execution route must NOT mint a grant for a non-public agent for ANYONE — not even admins. The runtime refuses direct execution of a non-public agent_id (agent_app._resolve_agent_instance), so a direct grant would be unusable; control-plane stays consistent by resolving with include_non_public=False unconditionally. Internal agents are reachable only via the managed (enrollment) path. See AGENT-VISIBILITY-RFC §3.1.""" monkeypatch.setattr( "control_plane_backend.product.api.require_team_access", _fake_require_team_access, ) # The hidden agent is only ever returned when include_non_public=True; the # service must never request that on this route, so the agent stays invisible. async def _fake_fetch_internal(_base_url: str, include_non_public: bool = False): return [_make_template_with_mcp_servers()] if include_non_public else [] monkeypatch.setattr( "control_plane_backend.product.service._fetch_runtime_templates", _fake_fetch_internal, ) app = create_app() container = get_application_container_from_app(app) container.configuration.platform.runtime_catalog_sources = [ RuntimeCatalogSourceConfig( runtime_id="runtime-a", base_url="http://runtime-a/pod/v1", enabled=True, ingress_prefix="/runtime/runtime-a", ) ] url = "/control-plane/v1/teams/personal/runtimes/runtime-a/agents/rags.sample.mcp/prepare-execution" # Both a non-admin AND an admin get 404 — the direct path never serves a # non-public agent (no unusable grant is ever minted). for roles in ([], ["admin"]): app.dependency_overrides[get_current_user] = lambda roles=roles: KeycloakUser( uid="u", username="u", roles=roles ) async with AsyncClient( transport=ASGITransport(app=app), base_url="http://test" ) as client: resp = await client.post(url) assert resp.status_code == 404, f"roles={roles} should be refused" app.dependency_overrides.clear() # --------------------------------------------------------------------------- # RUNTIME-07 Phase 0 — characterization of CURRENT (pre-hardening) behavior. # # The runtime calls GET /agent-instances/{id}/runtime to resolve a managed # instance, forwarding the END USER's token. That endpoint today gates on the # GLOBAL `admin` role (require_admin) and resolves via an UNSCOPED store.get — # the wrong check (F2). This test PINS that behavior so Phase 2 (per-user team # ReBAC + store.get_for_team) has a red->green signal. Update in place when # Phase 2 lands; do not delete. # See docs/swift/rfc/EXECUTION-GRANT-SECURITY-HARDENING-RFC.md (F2). # --------------------------------------------------------------------------- @pytest.mark.asyncio async def test_f2_team_scoped_resolution_is_tenant_isolated( monkeypatch: pytest.MonkeyPatch, ) -> None: """F2 fixed (RUNTIME-07 rev. 2): resolution is team-scoped + ReBAC-gated. (a) a team member resolves their own team's instance (200) — no admin gate; (b) the same instance is NOT reachable through a different team's path (404 via store.get_for_team), so no cross-tenant binding leaks.""" monkeypatch.setattr( "control_plane_backend.product.api.require_team_access", _fake_require_team_access, ) record = _make_record(agent_instance_id="instance-1", team_id="team-x") store = _FakeAgentInstanceStore([record]) app = create_app() _patch_store(monkeypatch, store) app.dependency_overrides[get_current_user] = lambda: KeycloakUser( uid="member-bob", username="member-bob", roles=[] ) async with AsyncClient( transport=ASGITransport(app=app), base_url="http://test" ) as client: # (a) resolved within the owning team. allowed = await client.get( "/control-plane/v1/teams/team-x/agent-instances/instance-1/runtime" ) # (b) not reachable through another team's path (team-scoped lookup). cross = await client.get( "/control-plane/v1/teams/team-y/agent-instances/instance-1/runtime" ) assert allowed.status_code == 200 assert allowed.json()["owner_team_id"] == "team-x" assert cross.status_code == 404 app.dependency_overrides.clear() @pytest.mark.asyncio async def test_enroll_agent_instance_stores_mcp_config_values( monkeypatch: pytest.MonkeyPatch, ) -> None: monkeypatch.setattr( "control_plane_backend.product.api.require_team_access", _fake_require_team_access, ) async def _fake_fetch(_base_url: str, include_non_public: bool = False): return [_make_template_with_mcp_servers()] monkeypatch.setattr( "control_plane_backend.product.service._fetch_runtime_templates", _fake_fetch, ) _fake_pod_validate_config_echo(monkeypatch) store = _FakeAgentInstanceStore([]) app = create_app() _patch_store(monkeypatch, store) container = get_application_container_from_app(app) container.configuration.platform.runtime_catalog_sources = [ RuntimeCatalogSourceConfig( runtime_id="runtime-a", base_url="http://runtime-a/pod/v1", enabled=True, ) ] async with AsyncClient( transport=ASGITransport(app=app), base_url="http://test" ) as client: resp = await client.post( "/control-plane/v1/teams/personal/agent-instances", json={ "usage_statement": "Test usage statement covering purpose, users, data, and error impact.", "template_id": "runtime-a:rags.sample.mcp", "display_name": "MCP Instance", "capability_ids": [_MCP_SEARCH_ID], "capability_config_values": { _MCP_SEARCH_ID: { "chat_options.libraries_binding": True, "chat_options.bound_library_ids": ["lib-a", "lib-b"], "chat_options.libraries_selection": False, "chat_options.search_policy_enabled": True, "chat_options.search_policy": "semantic", } }, }, ) assert resp.status_code == 201 expected_config = { "chat_options.libraries_binding": True, "chat_options.bound_library_ids": ["lib-a", "lib-b"], "chat_options.libraries_selection": False, "chat_options.search_policy_enabled": True, "chat_options.search_policy": "semantic", } assert resp.json()["capability_config"] == { _MCP_SEARCH_ID: {"schema_version": "1", "config": expected_config} } assert ( store._records[0].tuning.capability_config[_MCP_SEARCH_ID]["config"] == expected_config ) @pytest.mark.asyncio async def test_enroll_agent_instance_rejects_unknown_mcp_server_id( monkeypatch: pytest.MonkeyPatch, ) -> None: """An unknown MCP-backed capability id (plain catalog server id, #1988) goes through the SAME save-time availability check as any other capability id — see test_capability_selection_1974.py for the generic version.""" monkeypatch.setattr( "control_plane_backend.product.api.require_team_access", _fake_require_team_access, ) async def _fake_fetch(_base_url: str, include_non_public: bool = False): return [_make_template_with_mcp_servers()] monkeypatch.setattr( "control_plane_backend.product.service._fetch_runtime_templates", _fake_fetch, ) store = _FakeAgentInstanceStore([]) app = create_app() _patch_store(monkeypatch, store) container = get_application_container_from_app(app) container.configuration.platform.runtime_catalog_sources = [ RuntimeCatalogSourceConfig( runtime_id="runtime-a", base_url="http://runtime-a/pod/v1", enabled=True, ) ] async with AsyncClient( transport=ASGITransport(app=app), base_url="http://test" ) as client: resp = await client.post( "/control-plane/v1/teams/personal/agent-instances", json={ "usage_statement": "Test usage statement covering purpose, users, data, and error impact.", "template_id": "runtime-a:rags.sample.mcp", "display_name": "MCP Instance", "capability_ids": ["mcp-unknown"], }, ) assert resp.status_code == 422 assert "mcp-unknown" in resp.json()["detail"] assert store._records == [] # Note (#1978): the pre-migration `_validate_mcp_config_values` locally # rejected an unsupported dotted config key (e.g. "chat_options.unsupported") # with a 422. That local field-name check is retired by design: an MCP # server's stored config is now the pod-validated capability envelope, and # `McpServerConfig` (fred_runtime.capabilities.mcp) declares # `model_config = ConfigDict(extra="allow")` — a permissive bag, because # dotted keys cannot be declared as real Pydantic fields. Rejecting an unknown # key is the POD's call to make (if it chooses to), not control-plane's; # `test_enroll_agent_instance_rejects_unknown_mcp_server_id` above and # test_capability_selection_1974.py cover the ids/shape that ARE still # validated at this layer, and `test_enroll_propagates_pod_422_wording` # (test_capability_selection_1974.py) covers a pod-side rejection propagating. # There is deliberately no equivalent "unknown mcp config key -> 422" test. def _record_with_mcp_search_selected( *, agent_instance_id: str, selected_capability_ids: list[str] | None ) -> AgentInstanceRecord: return AgentInstanceRecord( agent_instance_id=agent_instance_id, team_id=TeamId("personal"), template_id="runtime-a:rags.sample.mcp", source_runtime_id="runtime-a", source_agent_id="rags.sample.mcp", display_name="MCP", description=None, enabled=True, created_by="admin", tuning=ManagedAgentTuning( role="MCP", description="MCP", selected_capability_ids=selected_capability_ids, capability_config={ _MCP_SEARCH_ID: { "schema_version": "1", "config": {"chat_options.search_policy": "semantic"}, } }, ), ) @pytest.mark.asyncio async def test_patch_agent_instance_can_clear_mcp_config_values( monkeypatch: pytest.MonkeyPatch, ) -> None: monkeypatch.setattr( "control_plane_backend.product.api.require_team_access", _fake_require_team_access, ) record = _record_with_mcp_search_selected( agent_instance_id="instance-mcp-config", selected_capability_ids=[_MCP_SEARCH_ID], ) store = _FakeAgentInstanceStore([record]) app = create_app() _patch_store(monkeypatch, store) container = get_application_container_from_app(app) container.configuration.platform.runtime_catalog_sources = [ RuntimeCatalogSourceConfig( runtime_id="runtime-a", base_url="http://runtime-a/pod/v1", enabled=True, ) ] async def _fake_fetch(_base_url: str, include_non_public: bool = False): return [_make_template_with_mcp_servers()] monkeypatch.setattr( "control_plane_backend.product.service._fetch_runtime_templates", _fake_fetch, ) _fake_pod_validate_config_echo(monkeypatch) async with AsyncClient( transport=ASGITransport(app=app), base_url="http://test" ) as client: resp = await client.patch( "/control-plane/v1/teams/personal/agent-instances/instance-mcp-config", json={"capability_config_values": None}, ) assert resp.status_code == 200 assert resp.json()["capability_config"] == { _MCP_SEARCH_ID: {"schema_version": "1", "config": {}} } assert store._records[0].tuning.capability_config[_MCP_SEARCH_ID]["config"] == {} @pytest.mark.asyncio async def test_patch_agent_instance_can_activate_no_mcp_servers_and_prunes_config( monkeypatch: pytest.MonkeyPatch, ) -> None: monkeypatch.setattr( "control_plane_backend.product.api.require_team_access", _fake_require_team_access, ) record = _record_with_mcp_search_selected( agent_instance_id="instance-mcp-none", selected_capability_ids=None, ) store = _FakeAgentInstanceStore([record]) app = create_app() _patch_store(monkeypatch, store) container = get_application_container_from_app(app) container.configuration.platform.runtime_catalog_sources = [ RuntimeCatalogSourceConfig( runtime_id="runtime-a", base_url="http://runtime-a/pod/v1", enabled=True, ) ] async def _fake_fetch(_base_url: str, include_non_public: bool = False): return [_make_template_with_mcp_servers()] monkeypatch.setattr( "control_plane_backend.product.service._fetch_runtime_templates", _fake_fetch, ) _fake_pod_validate_config_echo(monkeypatch) async with AsyncClient( transport=ASGITransport(app=app), base_url="http://test" ) as client: resp = await client.patch( "/control-plane/v1/teams/personal/agent-instances/instance-mcp-none", json={"capability_ids": []}, ) assert resp.status_code == 200 assert resp.json()["selected_capability_ids"] == [] assert resp.json()["capability_config"] == {} assert store._records[0].tuning.selected_capability_ids == [] assert store._records[0].tuning.capability_config == {} def _wire_capability_catalog( monkeypatch: pytest.MonkeyPatch, template: "_RuntimeTemplatePayload" ) -> None: """Provide the pod capability catalog `_available_capabilities_for_source` reads at prep (#1976, RFC §3.7): the authoritative source of each capability's `version`, which keys the chat-controls cache. Fetched through the same `_fetch_runtime_templates` seam used everywhere else.""" async def _fake_fetch(_base_url: str, include_non_public: bool = False): return [template] monkeypatch.setattr( "control_plane_backend.product.service._fetch_runtime_templates", _fake_fetch, ) def _stub_chat_controls( monkeypatch: pytest.MonkeyPatch, response: ChatControlsResponse | None, captured_authorization: list | None = None, ) -> list[int]: """Stub the control-plane→pod chat-controls call (#1976). Returns a one-element counter of how many times the pod was asked — misses only, so a cache hit leaves it unchanged. Pass `captured_authorization` to record the bearer forwarded on each pod call.""" calls = [0] async def _fake_fetch_chat_controls(_base_url, _request, authorization=None): calls[0] += 1 if captured_authorization is not None: captured_authorization.append(authorization) return response monkeypatch.setattr( "control_plane_backend.product.service._fetch_chat_controls", _fake_fetch_chat_controls, ) return calls def _mcp_chat_instance( agent_instance_id: str, config: dict[str, Any] | None = None ) -> AgentInstanceRecord: return AgentInstanceRecord( agent_instance_id=agent_instance_id, team_id=TeamId("personal"), template_id="agents-v2:rags.sample.mcp", source_runtime_id="agents-v2", source_agent_id="rags.sample.mcp", display_name="MCP Chat Agent", description="Chat options", enabled=True, created_by="admin", tuning=ManagedAgentTuning( role="MCP Chat Agent", description="Chat options", selected_capability_ids=[_MCP_SEARCH_ID], capability_config=( {_MCP_SEARCH_ID: {"schema_version": "1", "config": config}} if config is not None else {} ), ), ) def _prep_app_for_mcp_instance( monkeypatch: pytest.MonkeyPatch, store: "_FakeAgentInstanceStore" ): monkeypatch.setattr( "control_plane_backend.product.api.require_team_access", _fake_require_team_access, ) app = create_app() _patch_store(monkeypatch, store) container = get_application_container_from_app(app) container.configuration.platform.runtime_catalog_sources = [ RuntimeCatalogSourceConfig( runtime_id="agents-v2", base_url="http://agents-v2-svc.fred.svc.cluster.local/api/v1", enabled=True, ingress_prefix="/runtime/agents-v2", ) ] return app @pytest.mark.asyncio async def test_prepare_execution_attaches_computed_chat_controls( monkeypatch: pytest.MonkeyPatch, ) -> None: """#1976 (RFC §3.3/§3.7): prep flattens the pod's per-capability chat-controls onto `ExecutionPreparation.chat_controls`, tagged with the owning capability id and in returned-list order. The old control-plane `chat_options.*` resolution is retired — the computation lives on the pod (McpCapability.chat_controls), tested in fred-runtime.""" product_service._chat_controls_cache.clear() store = _FakeAgentInstanceStore([_mcp_chat_instance("inst-cc")]) app = _prep_app_for_mcp_instance(monkeypatch, store) _wire_capability_catalog(monkeypatch, _make_template_with_mcp_servers()) _stub_chat_controls( monkeypatch, ChatControlsResponse( results=[ ChatControlsResult( capability_id=_MCP_SEARCH_ID, manifest_version="1", controls=[ ChatControlItem( widget="search_policy", params={"default": "semantic"} ), ChatControlItem(widget="rag_scope"), ], ) ] ), ) async with AsyncClient( transport=ASGITransport(app=app), base_url="http://test" ) as client: resp = await client.post( "/control-plane/v1/teams/personal/agent-instances/inst-cc/prepare-execution" ) assert resp.status_code == 200 # Prepare-execution serializes with exclude_none, so a null `params` is # simply absent (the generated frontend type marks it optional). assert resp.json()["chat_controls"] == [ { "capability_id": _MCP_SEARCH_ID, "widget": "search_policy", "params": {"default": "semantic"}, }, {"capability_id": _MCP_SEARCH_ID, "widget": "rag_scope"}, ] @pytest.mark.asyncio async def test_prepare_execution_forwards_bearer_to_chat_controls( monkeypatch: pytest.MonkeyPatch, ) -> None: """The pod's chat-controls route authenticates the caller, so prep must forward the acting user's Authorization header — a bearer-less call 401s on auth-enabled deployments and silently empties the composer.""" product_service._chat_controls_cache.clear() store = _FakeAgentInstanceStore([_mcp_chat_instance("inst-cc-auth")]) app = _prep_app_for_mcp_instance(monkeypatch, store) _wire_capability_catalog(monkeypatch, _make_template_with_mcp_servers()) captured_auth: list = [] _stub_chat_controls( monkeypatch, ChatControlsResponse( results=[ ChatControlsResult( capability_id=_MCP_SEARCH_ID, manifest_version="1", controls=[ChatControlItem(widget="rag_scope")], ) ] ), captured_authorization=captured_auth, ) async with AsyncClient( transport=ASGITransport(app=app), base_url="http://test" ) as client: resp = await client.post( "/control-plane/v1/teams/personal/agent-instances/inst-cc-auth/prepare-execution", headers={"Authorization": "Bearer test-token"}, ) assert resp.status_code == 200 assert captured_auth == ["Bearer test-token"] @pytest.mark.asyncio async def test_prepare_execution_chat_controls_are_cache_aside( monkeypatch: pytest.MonkeyPatch, ) -> None: """#1976 (RFC §3.7): the pod is asked once per `(capability, version, config_hash)`; a second prep with an unchanged instance serves from the in-process cache without another pod round-trip.""" product_service._chat_controls_cache.clear() store = _FakeAgentInstanceStore([_mcp_chat_instance("inst-cache")]) app = _prep_app_for_mcp_instance(monkeypatch, store) _wire_capability_catalog(monkeypatch, _make_template_with_mcp_servers()) calls = _stub_chat_controls( monkeypatch, ChatControlsResponse( results=[ ChatControlsResult( capability_id=_MCP_SEARCH_ID, manifest_version="1", controls=[ChatControlItem(widget="attach_files")], ) ] ), ) async with AsyncClient( transport=ASGITransport(app=app), base_url="http://test" ) as client: first = await client.post( "/control-plane/v1/teams/personal/agent-instances/inst-cache/prepare-execution" ) second = await client.post( "/control-plane/v1/teams/personal/agent-instances/inst-cache/prepare-execution" ) assert first.status_code == 200 assert second.status_code == 200 assert first.json()["chat_controls"] == second.json()["chat_controls"] assert [c["widget"] for c in first.json()["chat_controls"]] == ["attach_files"] assert calls[0] == 1 # second prep hit the cache @pytest.mark.asyncio async def test_prepare_execution_skips_capability_chat_controls_on_error( monkeypatch: pytest.MonkeyPatch, ) -> None: """#1976 (RFC §3.9): a per-capability pod error skips ONLY that capability's controls (with a warning) — never failing the whole prep, and never cached.""" product_service._chat_controls_cache.clear() store = _FakeAgentInstanceStore([_mcp_chat_instance("inst-err")]) app = _prep_app_for_mcp_instance(monkeypatch, store) _wire_capability_catalog(monkeypatch, _make_template_with_mcp_servers()) _stub_chat_controls( monkeypatch, ChatControlsResponse( results=[ ChatControlsResult( capability_id=_MCP_SEARCH_ID, manifest_version="1", controls=[], error="capability_config_invalid", ) ] ), ) async with AsyncClient( transport=ASGITransport(app=app), base_url="http://test" ) as client: resp = await client.post( "/control-plane/v1/teams/personal/agent-instances/inst-err/prepare-execution" ) assert resp.status_code == 200 assert resp.json()["chat_controls"] == [] @pytest.mark.asyncio async def test_prepare_execution_chat_controls_empty_when_pod_unreachable( monkeypatch: pytest.MonkeyPatch, ) -> None: """#1976 (RFC §3.7): an unreachable pod yields no controls this prep (best-effort, logged) rather than a failed prep — a cache MISS has no stale entry to fall back to.""" product_service._chat_controls_cache.clear() store = _FakeAgentInstanceStore([_mcp_chat_instance("inst-down")]) app = _prep_app_for_mcp_instance(monkeypatch, store) _wire_capability_catalog(monkeypatch, _make_template_with_mcp_servers()) _stub_chat_controls(monkeypatch, None) async with AsyncClient( transport=ASGITransport(app=app), base_url="http://test" ) as client: resp = await client.post( "/control-plane/v1/teams/personal/agent-instances/inst-down/prepare-execution" ) assert resp.status_code == 200 assert resp.json()["chat_controls"] == [] @pytest.mark.asyncio async def test_list_agent_instances_sets_unavailable_when_pod_unreachable( monkeypatch: pytest.MonkeyPatch, ) -> None: base = _make_record(team_id=_PERSONAL_TEAM_ID) record = AgentInstanceRecord( agent_instance_id=base.agent_instance_id, team_id=base.team_id, template_id=base.template_id, source_runtime_id=base.source_runtime_id, source_agent_id=base.source_agent_id, display_name=base.display_name, description=base.description, enabled=base.enabled, created_by=base.created_by, tuning=ManagedAgentTuning( role=base.tuning.role, description=base.tuning.description, selected_capability_ids=[_MCP_SEARCH_ID], ), ) store = _FakeAgentInstanceStore([record]) app = create_app() _patch_store(monkeypatch, store) container = get_application_container_from_app(app) container.configuration.platform.runtime_catalog_sources = [ RuntimeCatalogSourceConfig( runtime_id="runtime-a", base_url="http://runtime-a/pod/v1", enabled=True, ) ] async with AsyncClient( transport=ASGITransport(app=app), base_url="http://test" ) as client: resp = await client.get( f"/control-plane/v1/teams/{_PERSONAL_TEAM_ID}/agent-instances" ) assert resp.status_code == 200 item = resp.json()[0] assert item["runtime_status"] == "unavailable" assert item["catalog_warnings"] == [] assert item["selected_capability_ids"] == [_MCP_SEARCH_ID] assert item["capability_config"] == {} # --------------------------------------------------------------------------- # Prompt library CRUD # --------------------------------------------------------------------------- @pytest.mark.asyncio async def test_list_prompts_returns_team_scoped_summaries( monkeypatch: pytest.MonkeyPatch, ) -> None: """Prompt list returns team-scoped summaries without the prompt text body.""" monkeypatch.setattr( "control_plane_backend.product.api.require_team_access", _fake_require_team_access, ) store = _FakePromptStore( [ _make_prompt_record(prompt_id="prompt-1", team_id="personal"), _make_prompt_record(prompt_id="prompt-2", team_id="other-team"), ] ) app = create_app() _patch_prompt_store(monkeypatch, store) async with AsyncClient( transport=ASGITransport(app=app), base_url="http://test" ) as client: resp = await client.get("/control-plane/v1/teams/personal/prompts") assert resp.status_code == 200 body = resp.json() assert len(body) == 1 item = body[0] assert item["id"] == "prompt-1" assert item["name"] == "Daily brief" assert item["description"] == "Ops baseline" assert item["created_by"] == "internal-admin" assert item["version"] == 1 assert item["import_count"] == 0 assert item["session_count"] == 0 # score is null and response_model_exclude_none=True strips null fields assert item.get("score") is None @pytest.mark.asyncio async def test_create_prompt_persists_summary_and_rejects_duplicate_name( monkeypatch: pytest.MonkeyPatch, ) -> None: """Prompt create stores one team-scoped record and later rejects duplicates.""" monkeypatch.setattr( "control_plane_backend.product.api.require_team_access", _fake_require_team_access, ) store = _FakePromptStore([]) app = create_app() _patch_prompt_store(monkeypatch, store) async with AsyncClient( transport=ASGITransport(app=app), base_url="http://test" ) as client: created = await client.post( "/control-plane/v1/teams/personal/prompts", json={ "name": "Daily brief", "description": "Ops baseline", "text": "Today is {today}.", }, ) duplicate = await client.post( "/control-plane/v1/teams/personal/prompts", json={ "name": "Daily brief", "description": "Duplicate", "text": "Respond in {response_language}.", }, ) assert created.status_code == 201 created_body = created.json() assert created_body["name"] == "Daily brief" assert created_body["description"] == "Ops baseline" assert "id" in created_body assert len(store._records) == 1 assert store._records[0].text == "Today is {today}." assert duplicate.status_code == 409 assert "already exists" in duplicate.json()["detail"] @pytest.mark.asyncio async def test_get_update_and_delete_prompt_use_team_scope( monkeypatch: pytest.MonkeyPatch, ) -> None: """Prompt detail, replace, and delete operate strictly inside one team scope.""" monkeypatch.setattr( "control_plane_backend.product.api.require_team_access", _fake_require_team_access, ) store = _FakePromptStore([_make_prompt_record()]) app = create_app() _patch_prompt_store(monkeypatch, store) async with AsyncClient( transport=ASGITransport(app=app), base_url="http://test" ) as client: detail = await client.get("/control-plane/v1/teams/personal/prompts/prompt-1") updated = await client.put( "/control-plane/v1/teams/personal/prompts/prompt-1", json={ "name": "Daily brief v2", "description": "Refined", "text": "Session is {session_id}.", }, ) deleted = await client.delete( "/control-plane/v1/teams/personal/prompts/prompt-1" ) missing = await client.get("/control-plane/v1/teams/personal/prompts/prompt-1") assert detail.status_code == 200 assert detail.json()["text"] == "Today is {today}." assert updated.status_code == 200 assert updated.json()["name"] == "Daily brief v2" assert store._records == [] assert deleted.status_code == 204 assert missing.status_code == 404 @pytest.mark.asyncio async def test_get_prompt_detail_includes_category_id_emoji_and_tags( monkeypatch: pytest.MonkeyPatch, ) -> None: """ Regression test: `_prompt_record_to_detail` used to omit `category_id`, `emoji`, and `tags` entirely, so the single-prompt GET endpoint always returned `category_id: null` and `tags: []` regardless of what was actually stored — surfacing as "always shows no category" in the frontend's read-only prompt view, and silently wiping category/tags on any edit-form save (the edit form seeds itself from this same endpoint). """ monkeypatch.setattr( "control_plane_backend.product.api.require_team_access", _fake_require_team_access, ) record = PromptRecord( prompt_id="prompt-1", team_id=TeamId("personal"), name="Daily brief", description="Ops baseline", category_id="cat-writing", emoji="✍️", tags=["daily", "ops"], text="Today is {today}.", created_by="internal-admin", ) store = _FakePromptStore([record]) app = create_app() _patch_prompt_store(monkeypatch, store) async with AsyncClient( transport=ASGITransport(app=app), base_url="http://test" ) as client: detail = await client.get("/control-plane/v1/teams/personal/prompts/prompt-1") assert detail.status_code == 200 body = detail.json() assert body["category_id"] == "cat-writing" assert body["emoji"] == "✍️" assert body["tags"] == ["daily", "ops"] @pytest.mark.asyncio async def test_prompt_library_accepts_unknown_prompt_template_token( monkeypatch: pytest.MonkeyPatch, ) -> None: """Prompt CRUD stores unknown {tokens} verbatim rather than rejecting (#2277).""" monkeypatch.setattr( "control_plane_backend.product.api.require_team_access", _fake_require_team_access, ) store = _FakePromptStore([]) app = create_app() _patch_prompt_store(monkeypatch, store) async with AsyncClient( transport=ASGITransport(app=app), base_url="http://test" ) as client: resp = await client.post( "/control-plane/v1/teams/personal/prompts", json={ "name": "Unknown token prompt", "description": None, "text": "Hello {unknown_token}.", }, ) assert resp.status_code == 201 assert len(store._records) == 1 assert store._records[0].text == "Hello {unknown_token}." # --------------------------------------------------------------------------- # Prompt categories (PROMPT-09) — team-owned, no global taxonomy # --------------------------------------------------------------------------- @pytest.mark.asyncio async def test_list_and_create_prompt_categories( monkeypatch: pytest.MonkeyPatch, ) -> None: """Categories list alphabetically and create rejects a duplicate name.""" monkeypatch.setattr( "control_plane_backend.product.api.require_team_access", _fake_require_team_access, ) category_store = _FakePromptCategoryStore( [ PromptCategoryRecord( category_id="cat-2", team_id=TeamId("personal"), name="Stratégie" ), PromptCategoryRecord( category_id="cat-1", team_id=TeamId("personal"), name="Analyse" ), ] ) app = create_app() _patch_prompt_category_store(monkeypatch, category_store) async with AsyncClient( transport=ASGITransport(app=app), base_url="http://test" ) as client: listed = await client.get("/control-plane/v1/teams/personal/prompt-categories") created = await client.post( "/control-plane/v1/teams/personal/prompt-categories", json={"name": "Communication"}, ) duplicate = await client.post( "/control-plane/v1/teams/personal/prompt-categories", json={"name": "Analyse"}, ) assert listed.status_code == 200 assert [c["name"] for c in listed.json()] == ["Analyse", "Stratégie"] assert created.status_code == 201 assert created.json()["name"] == "Communication" assert duplicate.status_code == 409 assert "already exists" in duplicate.json()["detail"] @pytest.mark.asyncio async def test_rename_and_delete_prompt_category( monkeypatch: pytest.MonkeyPatch, ) -> None: """A category can be renamed and, once unused, deleted.""" monkeypatch.setattr( "control_plane_backend.product.api.require_team_access", _fake_require_team_access, ) category_store = _FakePromptCategoryStore( [ PromptCategoryRecord( category_id="cat-1", team_id=TeamId("personal"), name="Analyse" ) ] ) prompt_store = _FakePromptStore([]) app = create_app() _patch_prompt_category_store(monkeypatch, category_store) _patch_prompt_store(monkeypatch, prompt_store) async with AsyncClient( transport=ASGITransport(app=app), base_url="http://test" ) as client: renamed = await client.put( "/control-plane/v1/teams/personal/prompt-categories/cat-1", json={"name": "Analyse & synthèse"}, ) deleted = await client.delete( "/control-plane/v1/teams/personal/prompt-categories/cat-1" ) missing = await client.put( "/control-plane/v1/teams/personal/prompt-categories/cat-1", json={"name": "Nope"}, ) assert renamed.status_code == 200 assert renamed.json()["name"] == "Analyse & synthèse" assert deleted.status_code == 204 assert missing.status_code == 404 @pytest.mark.asyncio async def test_delete_prompt_category_blocked_while_in_use( monkeypatch: pytest.MonkeyPatch, ) -> None: """Deleting a category still referenced by a prompt is a hard 409 block — never an automatic reassignment of the orphaned prompt(s).""" monkeypatch.setattr( "control_plane_backend.product.api.require_team_access", _fake_require_team_access, ) category_store = _FakePromptCategoryStore( [ PromptCategoryRecord( category_id="cat-1", team_id=TeamId("personal"), name="Analyse" ) ] ) record = _make_prompt_record(prompt_id="prompt-1", team_id="personal") record.category_id = "cat-1" prompt_store = _FakePromptStore([record]) app = create_app() _patch_prompt_category_store(monkeypatch, category_store) _patch_prompt_store(monkeypatch, prompt_store) async with AsyncClient( transport=ASGITransport(app=app), base_url="http://test" ) as client: resp = await client.delete( "/control-plane/v1/teams/personal/prompt-categories/cat-1" ) assert resp.status_code == 409 assert "still used by 1 prompt" in resp.json()["detail"] # The category row itself must survive the blocked delete. assert await category_store.get_for_team("cat-1", TeamId("personal")) is not None # --------------------------------------------------------------------------- # Prompt template tokens — enroll (unknown tokens are accepted, #2277) # --------------------------------------------------------------------------- @pytest.mark.asyncio async def test_enroll_agent_instance_accepts_unknown_prompt_token( monkeypatch: pytest.MonkeyPatch, ) -> None: """Unknown {token} in prompts.system → 201; the renderer leaves it verbatim.""" monkeypatch.setattr( "control_plane_backend.product.api.require_team_access", _fake_require_team_access, ) async def _fake_fetch_runtime_templates( _base_url: str, include_non_public: bool = False ): return [_make_template_with_validated_fields()] monkeypatch.setattr( "control_plane_backend.product.service._fetch_runtime_templates", _fake_fetch_runtime_templates, ) store = _FakeAgentInstanceStore([]) app = create_app() _patch_store(monkeypatch, store) container = get_application_container_from_app(app) container.configuration.platform.runtime_catalog_sources = [ RuntimeCatalogSourceConfig( runtime_id="runtime-a", base_url="http://runtime-a/pod/v1", enabled=True, ) ] async with AsyncClient( transport=ASGITransport(app=app), base_url="http://test" ) as client: resp = await client.post( "/control-plane/v1/teams/personal/agent-instances", json={ "usage_statement": "Test usage statement covering purpose, users, data, and error impact.", "template_id": "runtime-a:rags.sample.validated", "display_name": "Unknown Token Agent", "tuning_field_values": { "prompts.system": "Hello {name}, today is {today}.", }, }, ) assert resp.status_code == 201 assert len(store._records) == 1 # Text is stored verbatim — {name} survives to be rendered as a literal assert ( store._records[0].tuning.values["prompts.system"] == "Hello {name}, today is {today}." ) @pytest.mark.asyncio async def test_enroll_agent_instance_accepts_valid_prompt_tokens( monkeypatch: pytest.MonkeyPatch, ) -> None: """All canonical {tokens} in prompts.system → 201, agent created.""" monkeypatch.setattr( "control_plane_backend.product.api.require_team_access", _fake_require_team_access, ) async def _fake_fetch_runtime_templates( _base_url: str, include_non_public: bool = False ): return [_make_template_with_validated_fields()] monkeypatch.setattr( "control_plane_backend.product.service._fetch_runtime_templates", _fake_fetch_runtime_templates, ) store = _FakeAgentInstanceStore([]) app = create_app() _patch_store(monkeypatch, store) container = get_application_container_from_app(app) container.configuration.platform.runtime_catalog_sources = [ RuntimeCatalogSourceConfig( runtime_id="runtime-a", base_url="http://runtime-a/pod/v1", enabled=True, ) ] async with AsyncClient( transport=ASGITransport(app=app), base_url="http://test" ) as client: resp = await client.post( "/control-plane/v1/teams/personal/agent-instances", json={ "usage_statement": "Test usage statement covering purpose, users, data, and error impact.", "template_id": "runtime-a:rags.sample.validated", "display_name": "Good Prompt Agent", "tuning_field_values": { "prompts.system": ( "You are a helpful assistant. Today is {today}. " "Respond in {response_language}." ), }, }, ) assert resp.status_code == 201 assert len(store._records) == 1 @pytest.mark.asyncio async def test_enroll_agent_instance_accepts_prompt_with_code_braces( monkeypatch: pytest.MonkeyPatch, ) -> None: """Curly braces from code snippets (non-simple patterns) are not flagged.""" monkeypatch.setattr( "control_plane_backend.product.api.require_team_access", _fake_require_team_access, ) async def _fake_fetch_runtime_templates( _base_url: str, include_non_public: bool = False ): return [_make_template_with_validated_fields()] monkeypatch.setattr( "control_plane_backend.product.service._fetch_runtime_templates", _fake_fetch_runtime_templates, ) store = _FakeAgentInstanceStore([]) app = create_app() _patch_store(monkeypatch, store) container = get_application_container_from_app(app) container.configuration.platform.runtime_catalog_sources = [ RuntimeCatalogSourceConfig( runtime_id="runtime-a", base_url="http://runtime-a/pod/v1", enabled=True, ) ] async with AsyncClient( transport=ASGITransport(app=app), base_url="http://test" ) as client: resp = await client.post( "/control-plane/v1/teams/personal/agent-instances", json={ "usage_statement": "Test usage statement covering purpose, users, data, and error impact.", "template_id": "runtime-a:rags.sample.validated", "display_name": "Code Prompt Agent", "tuning_field_values": { "prompts.system": ( "Help write code like: if (x > 0) { return x; } else { return 0; }" ), }, }, ) assert resp.status_code == 201 assert len(store._records) == 1 @pytest.mark.asyncio async def test_patch_agent_instance_accepts_unknown_prompt_token( monkeypatch: pytest.MonkeyPatch, ) -> None: """Updating prompts.system with an unknown {token} → 200, value persisted.""" monkeypatch.setattr( "control_plane_backend.product.api.require_team_access", _fake_require_team_access, ) record = AgentInstanceRecord( agent_instance_id="instance-validated", team_id=TeamId("personal"), template_id="runtime-a:rags.sample.validated", source_runtime_id="runtime-a", source_agent_id="rags.sample.validated", display_name="Validated", description=None, enabled=True, created_by="admin", tuning=_make_template_with_validated_fields().default_tuning, ) store = _FakeAgentInstanceStore([record]) app = create_app() _patch_store(monkeypatch, store) async with AsyncClient( transport=ASGITransport(app=app), base_url="http://test" ) as client: resp = await client.patch( "/control-plane/v1/teams/personal/agent-instances/instance-validated", json={ "tuning_field_values": { "prompts.system": "Hi {unknown_var}, today is {today}.", } }, ) assert resp.status_code == 200 assert ( store._records[0].tuning.values["prompts.system"] == "Hi {unknown_var}, today is {today}." ) # --------------------------------------------------------------------------- # P1-D1b — versioning, analytics, context integration # --------------------------------------------------------------------------- @pytest.mark.asyncio async def test_prompt_update_increments_version( monkeypatch: pytest.MonkeyPatch, ) -> None: """PUT on an existing prompt auto-increments version in the summary response.""" monkeypatch.setattr( "control_plane_backend.product.api.require_team_access", _fake_require_team_access, ) record = _make_prompt_record() record.version = 1 store = _FakePromptStore([record]) app = create_app() _patch_prompt_store(monkeypatch, store) async with AsyncClient( transport=ASGITransport(app=app), base_url="http://test" ) as client: resp = await client.put( "/control-plane/v1/teams/personal/prompts/prompt-1", json={ "name": "Daily brief v2", "description": "Refined", "text": "New {today}.", }, ) assert resp.status_code == 200 body = resp.json() assert body["version"] == 2 @pytest.mark.asyncio async def test_get_context_prompts_excludes_personal_in_team_space( monkeypatch: pytest.MonkeyPatch, ) -> None: """GET /prompts/context on a team never exposes the caller's personal prompts.""" monkeypatch.setattr( "control_plane_backend.product.api.require_team_access", _fake_require_team_access, ) personal = _make_prompt_record( prompt_id="p-personal", team_id=_PERSONAL_TEAM_ID, name="My prompt" ) team_p = _make_prompt_record( prompt_id="p-team", team_id="bid-team", name="Team prompt" ) team_p.session_count = 5 store = _FakePromptStore([personal, team_p]) app = create_app() _patch_prompt_store(monkeypatch, store) async with AsyncClient( transport=ASGITransport(app=app), base_url="http://test" ) as client: resp = await client.get("/control-plane/v1/teams/bid-team/prompts/context") assert resp.status_code == 200 body = resp.json() ids = [item["id"] for item in body] assert "p-personal" not in ids assert "p-team" in ids assert body[0]["id"] == "p-team" assert body[0]["scope"] == "team" @pytest.mark.asyncio async def test_get_context_prompts_personal_space_returns_personal_scope( monkeypatch: pytest.MonkeyPatch, ) -> None: """GET /prompts/context on the personal team returns the user's prompts as scope=personal.""" monkeypatch.setattr( "control_plane_backend.product.api.require_team_access", _fake_require_team_access, ) personal = _make_prompt_record( prompt_id="p-personal", team_id=_PERSONAL_TEAM_ID, name="My prompt" ) team_p = _make_prompt_record( prompt_id="p-team", team_id="bid-team", name="Team prompt" ) store = _FakePromptStore([personal, team_p]) app = create_app() _patch_prompt_store(monkeypatch, store) async with AsyncClient( transport=ASGITransport(app=app), base_url="http://test" ) as client: resp = await client.get( f"/control-plane/v1/teams/{_PERSONAL_TEAM_ID}/prompts/context" ) assert resp.status_code == 200 body = resp.json() ids = [item["id"] for item in body] assert "p-personal" in ids assert "p-team" not in ids assert body[0]["scope"] == "personal" @pytest.mark.asyncio async def test_promote_prompt_copies_to_target_team( monkeypatch: pytest.MonkeyPatch, ) -> None: """POST /prompts/{id}/promote creates a copy in the target team.""" monkeypatch.setattr( "control_plane_backend.product.api.require_team_access", _fake_require_team_access, ) store = _FakePromptStore([_make_prompt_record()]) app = create_app() _patch_prompt_store(monkeypatch, store) async with AsyncClient( transport=ASGITransport(app=app), base_url="http://test" ) as client: resp = await client.post( "/control-plane/v1/teams/personal/prompts/prompt-1/promote", json={"target_team_id": "bid-team"}, ) assert resp.status_code == 201 body = resp.json() assert body["name"] == "Daily brief" assert body["version"] == 1 assert body["import_count"] == 0 assert body["session_count"] == 0 assert body["score"] is None # Two records now: original in personal, copy in bid-team assert len(store._records) == 2 copy = next(r for r in store._records if str(r.team_id) == "bid-team") assert copy.text == "Today is {today}." @pytest.mark.asyncio async def test_promote_prompt_copies_emoji_and_tags_but_not_category_id( monkeypatch: pytest.MonkeyPatch, ) -> None: """Regression test: `promote_prompt` used to drop `emoji`/`tags` when copying a prompt to another team (same bug class already fixed once on `_prompt_record_to_detail`). `category_id` is deliberately excluded from the copy instead — prompt categories are team-scoped (PROMPT-09), so the source category_id would not resolve to anything in the target team.""" monkeypatch.setattr( "control_plane_backend.product.api.require_team_access", _fake_require_team_access, ) source = _make_prompt_record( category_id="cat-writing", emoji="✍️", tags=["daily", "ops"] ) store = _FakePromptStore([source]) app = create_app() _patch_prompt_store(monkeypatch, store) async with AsyncClient( transport=ASGITransport(app=app), base_url="http://test" ) as client: resp = await client.post( "/control-plane/v1/teams/personal/prompts/prompt-1/promote", json={"target_team_id": "bid-team"}, ) assert resp.status_code == 201 body = resp.json() assert body["emoji"] == "✍️" assert body["tags"] == ["daily", "ops"] assert body["category_id"] is None copy = next(r for r in store._records if str(r.team_id) == "bid-team") assert copy.emoji == "✍️" assert copy.tags == ["daily", "ops"] assert copy.category_id is None @pytest.mark.asyncio async def test_promote_prompt_returns_409_on_name_conflict( monkeypatch: pytest.MonkeyPatch, ) -> None: """POST /prompts/{id}/promote → 409 when a same-name prompt already exists in target.""" monkeypatch.setattr( "control_plane_backend.product.api.require_team_access", _fake_require_team_access, ) source = _make_prompt_record( prompt_id="p-src", team_id="personal", name="Shared name" ) conflict = _make_prompt_record( prompt_id="p-conflict", team_id="bid-team", name="Shared name" ) store = _FakePromptStore([source, conflict]) app = create_app() _patch_prompt_store(monkeypatch, store) async with AsyncClient( transport=ASGITransport(app=app), base_url="http://test" ) as client: resp = await client.post( "/control-plane/v1/teams/personal/prompts/p-src/promote", json={"target_team_id": "bid-team"}, ) assert resp.status_code == 409 @pytest.mark.asyncio async def test_patch_prompt_score_updates_and_returns_summary( monkeypatch: pytest.MonkeyPatch, ) -> None: """PATCH /prompts/{id} sets the quality score and returns the updated summary.""" monkeypatch.setattr( "control_plane_backend.product.api.require_team_access", _fake_require_team_access, ) store = _FakePromptStore([_make_prompt_record()]) app = create_app() _patch_prompt_store(monkeypatch, store) async with AsyncClient( transport=ASGITransport(app=app), base_url="http://test" ) as client: resp = await client.patch( "/control-plane/v1/teams/personal/prompts/prompt-1", json={"score": 4.5}, ) assert resp.status_code == 200 assert resp.json()["score"] == 4.5 assert store._records[0].score == 4.5 def _make_context_session( monkeypatch: pytest.MonkeyPatch, *, prompt_ids: list[str], ) -> tuple[Any, _FakeSessionMetadataStore, _FakePromptStore]: """Build an app + fakes for one owned session and the given library prompts.""" monkeypatch.setattr( "control_plane_backend.product.api.require_team_access", _fake_require_team_access, ) session_record = SessionMetadataRecord( session_id="sess-1", team_id=TeamId("personal"), agent_instance_id=None, user_id="admin", title=None, context_prompt_ids=[], ) session_store = _FakeSessionMetadataStore([session_record]) prompt_store = _FakePromptStore( [_make_prompt_record(prompt_id=pid, team_id="personal") for pid in prompt_ids] ) app = create_app() _patch_session_store(monkeypatch, session_store) _patch_prompt_store(monkeypatch, prompt_store) return app, session_store, prompt_store @pytest.mark.asyncio async def test_patch_session_sets_ordered_context_prompts( monkeypatch: pytest.MonkeyPatch, ) -> None: """PATCH with context_prompt_ids stores the ordered set and counts first attach.""" app, _session_store, prompt_store = _make_context_session( monkeypatch, prompt_ids=["p1", "p2"] ) async with AsyncClient( transport=ASGITransport(app=app), base_url="http://test" ) as client: resp = await client.patch( "/control-plane/v1/teams/personal/sessions/sess-1", json={"context_prompt_ids": ["p2", "p1"]}, ) assert resp.status_code == 200 assert resp.json()["context_prompt_ids"] == ["p2", "p1"] # session_count incremented once per newly-attached prompt. counts = {r.prompt_id: r.session_count for r in prompt_store._records} assert counts == {"p1": 1, "p2": 1} @pytest.mark.asyncio async def test_patch_session_context_prompts_increment_first_attach_only( monkeypatch: pytest.MonkeyPatch, ) -> None: """Re-sending an already-attached id does not double-count; new ids do count.""" app, _session_store, prompt_store = _make_context_session( monkeypatch, prompt_ids=["p1", "p2"] ) async with AsyncClient( transport=ASGITransport(app=app), base_url="http://test" ) as client: await client.patch( "/control-plane/v1/teams/personal/sessions/sess-1", json={"context_prompt_ids": ["p1"]}, ) resp = await client.patch( "/control-plane/v1/teams/personal/sessions/sess-1", json={"context_prompt_ids": ["p1", "p2"]}, ) assert resp.status_code == 200 assert resp.json()["context_prompt_ids"] == ["p1", "p2"] counts = {r.prompt_id: r.session_count for r in prompt_store._records} # p1 counted once (first PATCH), p2 once (second PATCH) — p1 not re-counted. assert counts == {"p1": 1, "p2": 1} @pytest.mark.asyncio async def test_patch_session_empty_list_clears_context_prompts( monkeypatch: pytest.MonkeyPatch, ) -> None: """An empty context_prompt_ids list clears the attached set.""" app, session_store, _prompt_store = _make_context_session( monkeypatch, prompt_ids=["p1"] ) session_store._records[0].context_prompt_ids = ["p1"] async with AsyncClient( transport=ASGITransport(app=app), base_url="http://test" ) as client: resp = await client.patch( "/control-plane/v1/teams/personal/sessions/sess-1", json={"context_prompt_ids": []}, ) assert resp.status_code == 200 assert resp.json()["context_prompt_ids"] == [] assert session_store._records[0].context_prompt_ids == [] @pytest.mark.asyncio async def test_patch_session_freshness_only_keeps_context_prompts( monkeypatch: pytest.MonkeyPatch, ) -> None: """A freshness-only PATCH (no context field) must not wipe attached prompts.""" app, session_store, _prompt_store = _make_context_session( monkeypatch, prompt_ids=["p1"] ) session_store._records[0].context_prompt_ids = ["p1"] async with AsyncClient( transport=ASGITransport(app=app), base_url="http://test" ) as client: resp = await client.patch( "/control-plane/v1/teams/personal/sessions/sess-1", json={"updated_at": "2026-06-19T10:00:00Z"}, ) assert resp.status_code == 200 assert resp.json()["context_prompt_ids"] == ["p1"] assert session_store._records[0].context_prompt_ids == ["p1"] # --- CTRLP-12 (rev. 2 / Phase R): retention on GET/PATCH /teams/{id} ---------- # # Retention folded from the removed `team_policy_override` table + `/retention` # endpoints into `team_metadata`, surfaced through the existing team API: GET # embeds the resolved `retention` view; PATCH accepts the two governed fields # (owner-only, clamped to the platform cap server-side). def _retention_catalog() -> Any: """Policy catalog with platform caps for both governed retention fields.""" from control_plane_backend.scheduler.policies.policy_models import ( ConversationPolicyCatalog, ) return ConversationPolicyCatalog.model_validate( { "conversation_policies": { "purge": { "default": { "team_delete_grace": "P30D", "max_idle": "P60D", } } } } ) class _FakeRetentionMetadataStore: """Stateful team_metadata stand-in: get_by_team_id + partial upsert. Mirrors the real store's partial semantics (``TeamMetadataPatch.to_store_values``) so retention resolution and PATCH overlay behave exactly like production. """ def __init__(self, record: TeamMetadata | None = None) -> None: self.record = record async def get_by_team_id( self, team_id: Any, session: Any | None = None ) -> TeamMetadata | None: return self.record async def upsert(self, team_id: Any, patch: Any, session: Any | None = None) -> Any: values = patch.to_store_values() base = self.record.model_dump() if self.record is not None else {} base.update(values) base["id"] = TeamId(str(team_id)) base.setdefault("name", "Northbridge") self.record = TeamMetadata(**base) return self.record def _patch_team_retention( monkeypatch: pytest.MonkeyPatch, *, metadata_store: Any, permissions: list[TeamPermission], deny_permission: TeamPermission | None = None, ) -> list[list[TeamPermission]]: """Wire the team GET/PATCH path with fakes; return the captured permissions. Bypasses ReBAC exactly like the existing team-update test, but keeps the real retention resolution (metadata store + policy catalog) under test. """ from fred_core import AuthorizationError from fred_core.security.models import Resource captured: list[list[TeamPermission]] = [] async def _fake_validate(*_args: Any, **_kwargs: Any) -> Any: required = _args[3] captured.append(required) if deny_permission is not None and deny_permission in required: raise AuthorizationError( user_id="member-1", action=str(deny_permission.value), resource=Resource.TEAM, ) return TeamMetadata(id=TeamId("northbridge"), name="Northbridge"), "tok" async def _fake_permissions(*_args: Any, **_kwargs: Any) -> list[TeamPermission]: return permissions async def _fake_enrich(*_args: Any, **_kwargs: Any) -> list[Team]: return [Team(id=TeamId("northbridge"), name="Northbridge")] monkeypatch.setattr( "control_plane_backend.teams.service._validate_team_and_check_permission", _fake_validate, ) monkeypatch.setattr( "control_plane_backend.teams.service._get_team_permissions_for_user", _fake_permissions, ) monkeypatch.setattr( "control_plane_backend.teams.service._enrich_teams_with_membership", _fake_enrich, ) monkeypatch.setattr( "control_plane_backend.app.context.ApplicationContext.get_policy_catalog", lambda _self, **_kwargs: _retention_catalog(), ) monkeypatch.setattr( "control_plane_backend.app.context.ApplicationContext.get_team_metadata_store", lambda _self: metadata_store, ) return captured @pytest.mark.asyncio async def test_get_team_embeds_retention_without_value_uses_platform( monkeypatch: pytest.MonkeyPatch, ) -> None: """GET /teams/{id}: with no team value the embedded view inherits the cap.""" _patch_team_retention( monkeypatch, metadata_store=_FakeRetentionMetadataStore(None), permissions=[TeamPermission.CAN_READ], ) app = create_app() async with AsyncClient( transport=ASGITransport(app=app), base_url="http://test" ) as client: resp = await client.get("/control-plane/v1/teams/northbridge") assert resp.status_code == 200 retention = resp.json()["retention"] # The team endpoint serializes with exclude_none, so None/False subfields are # omitted rather than emitted; assert the present fields. grace = retention["team_delete_grace"] assert grace["platform_max"] == "P30D" assert grace["effective"] == "P30D" assert grace["source"] == "platform" assert grace.get("team_value") is None assert grace.get("would_exceed", False) is False assert retention["max_idle"]["effective"] == "P60D" assert retention["max_idle"]["source"] == "platform" @pytest.mark.asyncio async def test_get_team_embeds_retention_with_value_flips_to_team( monkeypatch: pytest.MonkeyPatch, ) -> None: """GET /teams/{id}: a team value below the cap flips source to team; a value above the cap is clamped back to platform (would_exceed).""" from control_plane_backend.scheduler.policies.retention_resolver import ( resolve_team_retention_view, ) record = TeamMetadata( id=TeamId("northbridge"), name="Northbridge", team_delete_grace="P7D", max_idle="P90D", # above the P60D cap -> clamped retention_updated_by="owner-1", ) _patch_team_retention( monkeypatch, metadata_store=_FakeRetentionMetadataStore(record), permissions=[TeamPermission.CAN_READ], ) app = create_app() async with AsyncClient( transport=ASGITransport(app=app), base_url="http://test" ) as client: resp = await client.get("/control-plane/v1/teams/northbridge") assert resp.status_code == 200 retention = resp.json()["retention"] # Endpoint output must match the pure resolver for the same inputs. expected = resolve_team_retention_view( policy=_retention_catalog().conversation_policies.purge, team_id="northbridge", team_delete_grace_override="P7D", max_idle_override="P90D", ) assert ( retention["team_delete_grace"]["effective"] == expected.team_delete_grace.effective ) assert retention["team_delete_grace"]["source"] == "team" assert retention["team_delete_grace"]["team_value"] == "P7D" assert retention["max_idle"]["effective"] == "P60D" assert retention["max_idle"]["source"] == "platform" assert retention["max_idle"]["would_exceed"] is True @pytest.mark.asyncio async def test_patch_team_retention_owner_below_cap_persists( monkeypatch: pytest.MonkeyPatch, ) -> None: """Owner PATCHes a value < cap -> 200, persisted, source=team, audit stamped.""" store = _FakeRetentionMetadataStore(None) captured = _patch_team_retention( monkeypatch, metadata_store=store, permissions=[TeamPermission.CAN_UPDATE_INFO], ) app = create_app() async with AsyncClient( transport=ASGITransport(app=app), base_url="http://test" ) as client: resp = await client.patch( "/control-plane/v1/teams/northbridge", json={"team_delete_grace": "P7D"}, # < P30D cap ) assert resp.status_code == 200 # The team update surface authorized with CAN_UPDATE_INFO (owner-only). assert [TeamPermission.CAN_UPDATE_INFO] in captured retention = resp.json()["retention"] assert retention["team_delete_grace"]["team_value"] == "P7D" assert retention["team_delete_grace"]["effective"] == "P7D" assert retention["team_delete_grace"]["source"] == "team" # Omitted field inherits the platform cap. assert retention["max_idle"]["source"] == "platform" # Persisted with the caller stamped as the retention auditor. assert store.record is not None assert store.record.team_delete_grace == "P7D" assert store.record.retention_updated_by # caller uid recorded @pytest.mark.asyncio async def test_patch_team_retention_partial_overlay( monkeypatch: pytest.MonkeyPatch, ) -> None: """PATCH overlay over an existing record: an omitted field keeps its stored value; an explicit null clears it (partial semantics).""" existing = TeamMetadata( id=TeamId("northbridge"), name="Northbridge", team_delete_grace="P7D", max_idle="P30D", retention_updated_by="prior", ) store = _FakeRetentionMetadataStore(existing) _patch_team_retention( monkeypatch, metadata_store=store, permissions=[TeamPermission.CAN_UPDATE_INFO], ) app = create_app() async with AsyncClient( transport=ASGITransport(app=app), base_url="http://test" ) as client: # Omit team_delete_grace (keep P7D); explicit null clears max_idle. resp = await client.patch( "/control-plane/v1/teams/northbridge", json={"max_idle": None}, ) assert resp.status_code == 200 assert store.record is not None assert store.record.team_delete_grace == "P7D" # omitted -> preserved assert store.record.max_idle is None # explicit null -> cleared assert store.record.retention_updated_by # re-stamped on the retention edit retention = resp.json()["retention"] assert retention["team_delete_grace"]["team_value"] == "P7D" assert retention["team_delete_grace"]["source"] == "team" # Cleared field falls back to the platform cap (None team_value stripped by # exclude_none serialization). assert retention["max_idle"].get("team_value") is None assert retention["max_idle"]["source"] == "platform" @pytest.mark.asyncio async def test_patch_team_retention_above_cap_returns_422( monkeypatch: pytest.MonkeyPatch, ) -> None: """Owner PATCHes a value > cap -> 422; nothing is persisted.""" store = _FakeRetentionMetadataStore(None) _patch_team_retention( monkeypatch, metadata_store=store, permissions=[TeamPermission.CAN_UPDATE_INFO], ) app = create_app() async with AsyncClient( transport=ASGITransport(app=app), base_url="http://test" ) as client: resp = await client.patch( "/control-plane/v1/teams/northbridge", json={"max_idle": "P90D"}, # > P60D cap ) assert resp.status_code == 422 assert "max_idle" in resp.json()["detail"] # Rejected before persistence. assert store.record is None @pytest.mark.asyncio async def test_patch_team_retention_non_owner_forbidden( monkeypatch: pytest.MonkeyPatch, ) -> None: """A non-owner (no CAN_UPDATE_INFO) is refused with 403; nothing persisted.""" store = _FakeRetentionMetadataStore(None) _patch_team_retention( monkeypatch, metadata_store=store, permissions=[TeamPermission.CAN_READ], deny_permission=TeamPermission.CAN_UPDATE_INFO, ) app = create_app() async with AsyncClient( transport=ASGITransport(app=app), base_url="http://test" ) as client: resp = await client.patch( "/control-plane/v1/teams/northbridge", json={"team_delete_grace": "P1D"}, ) assert resp.status_code == 403 assert store.record is None # --- CTRLP-12 DoD §6: evaluation campaign authorization ------------------------ @pytest.mark.asyncio async def test_create_evaluation_campaign_requires_can_update_agents( monkeypatch: pytest.MonkeyPatch, ) -> None: """Creating an evaluation campaign is an agent-management action: it must require CAN_UPDATE_AGENTS (not CAN_UPDATE_RESOURCES), so a plain member who can only read is refused (403). Pins the DoD §6 create permission.""" from fred_core import AuthorizationError, TeamPermission from fred_core.security.models import Resource checked: list[tuple[TeamPermission, str]] = [] class _FakeRebac: async def check_user_team_permission_or_raise( self, user: Any, permission: TeamPermission, team_id: str ) -> None: checked.append((permission, team_id)) raise AuthorizationError( getattr(user, "uid", "u"), str(permission.value), Resource.TEAM ) monkeypatch.setattr( "control_plane_backend.app.context.ApplicationContext.get_rebac_engine", lambda _self: _FakeRebac(), ) app = create_app() async with AsyncClient( transport=ASGITransport(app=app), base_url="http://test" ) as client: resp = await client.post( "/control-plane/v1/evaluation-campaigns", json={ "name": "campaign-1", "team_id": "northbridge", "target": { "kind": "managed_instance", "agent_instance_id": "instance-1", }, "dataset": {"name": "ds", "cases": [{"input": "hi"}]}, "judge_profile_id": "judge-1", }, ) assert resp.status_code == 403 # The endpoint gated on CAN_UPDATE_AGENTS for the target team before any work. assert checked == [(TeamPermission.CAN_UPDATE_AGENTS, "northbridge")] @pytest.mark.asyncio async def test_deferred_delete_creates_scheduled_erasure_task(tmp_path) -> None: """CTRLP-12: a deferred delete creates a future-dated `erasure` task, so a platform/team admin sees the scheduled erasure — with its due date, target and team — immediately via GET /tasks, before any worker runs.""" from control_plane_backend.models.base import Base as CPBase from control_plane_backend.models.task_models import TASK_TABLES from control_plane_backend.product.service import delete_or_defer_session from fred_core.common import PostgresStoreConfig from fred_core.models.base import Base as CoreBase from fred_core.sql import create_async_engine_from_config from fred_core.tasks.bus import MemoryEventBus from fred_core.tasks.service import TaskService from fred_core.tasks.store import TaskStore from fred_core.tasks.workflow_control import NoopWorkflowControl engine = create_async_engine_from_config( PostgresStoreConfig(sqlite_path=str(tmp_path / "tasks.sqlite3")) ) async with engine.begin() as conn: await conn.run_sync(CoreBase.metadata.create_all) await conn.run_sync(CPBase.metadata.create_all) task_service = TaskService( store=TaskStore(engine, TASK_TABLES), bus=MemoryEventBus(), control=NoopWorkflowControl(), ) session_store = _FakeSessionMetadataStore( [ SessionMetadataRecord( session_id="session-1", team_id=TeamId("northbridge"), agent_instance_id="instance-1", user_id="admin", title="Q3 pricing", ) ] ) deps = _build_erasure_deps( session_store, _FakeSessionAttachmentStore([]), policy_catalog=_delete_window_catalog(team_delete_grace="P30D"), team_metadata_store=_FakeTeamMetadataStore( TeamMetadata( id=TeamId("northbridge"), name="Northbridge", team_delete_grace="P30D" ) ), purge_queue_store=_FakePurgeQueueStore(), task_service=task_service, ) await delete_or_defer_session( team_id=TeamId("northbridge"), session_id="session-1", user_id="admin", authorization="Bearer test-token", deps=deps, ) tasks = (await task_service.list_tasks(kind="erasure", team_id="northbridge")).tasks assert len(tasks) == 1 task = tasks[0] assert task.state.value == "pending" # scheduled, not yet run assert task.scheduled_for is not None # the schedule is visible with its date assert task.team_id == "northbridge" assert task.target is not None assert task.target.id == "session-1" assert task.target.label == "Q3 pricing" @pytest.mark.asyncio async def test_compute_platform_stats_lists_all_teams_for_admin_without_personal_membership( monkeypatch: pytest.MonkeyPatch, ) -> None: """AUTHZ-05 item 3: `platform_stats` already checked CAN_MANAGE_PLATFORM, so `compute_platform_stats` must show every real team's row — even for a platform_admin who personally belongs to none of them, i.e. whose CAN_READ (`list_teams`) view of the world would be empty.""" from control_plane_backend.import_export.stats import compute_platform_stats from control_plane_backend.teams.schemas import TeamMember, UserTeamRelation real_teams = [ Team( id=TeamId("thales"), name="Thales", member_count=1, is_member=False, joining_mode=JoiningMode.INVITE_ONLY, max_resources_storage_size=5368709120, current_resources_storage_size=0, ), Team( id=TeamId("fredlab"), name="Fredlab", member_count=1, is_member=False, joining_mode=JoiningMode.OPEN, max_resources_storage_size=5368709120, current_resources_storage_size=0, ), ] async def _fake_list_all_teams_unfiltered(_user: Any, _deps: Any) -> list[Team]: # Real Keycloak root groups exist regardless of the caller's CAN_READ view. return real_teams async def _fake_list_teams_can_read_filtered(_user: Any, _deps: Any) -> list[Team]: # A platform_admin with zero personal team membership: CAN_READ surfaces # nothing. If `compute_platform_stats` regressed to calling `list_teams` # (the filtered function) instead of the unfiltered one, this empty # result would make the assertions below fail. return [] async def _fake_list_team_members( _user: Any, team_id: TeamId, _deps: Any ) -> list[TeamMember]: return [ TeamMember( user=UserSummary(id=f"admin-of-{team_id}"), relations=[UserTeamRelation.TEAM_ADMIN], ) ] async def _fake_counts_by_team( _engine: Any, ) -> tuple[dict[str, int], dict[str, int]]: return {"thales": 2, "fredlab": 1}, {"thales": 3, "fredlab": 0} monkeypatch.setattr( "control_plane_backend.import_export.stats.list_all_teams_unfiltered", _fake_list_all_teams_unfiltered, ) monkeypatch.setattr( "control_plane_backend.teams.service.list_teams", _fake_list_teams_can_read_filtered, ) monkeypatch.setattr( "control_plane_backend.import_export.stats.list_team_members_unfiltered", _fake_list_team_members, ) monkeypatch.setattr( "control_plane_backend.import_export.stats._counts_by_team", _fake_counts_by_team, ) stats = await compute_platform_stats( user=cast(Any, type("User", (), {"uid": "platform-admin-no-team"})()), team_deps=cast(Any, object()), engine=cast(Any, object()), ) assert stats.teams == 2 assert {team.team_id for team in stats.per_team} == {"thales", "fredlab"} assert stats.total_agents == 3 assert stats.total_prompts == 3 thales_row = next(t for t in stats.per_team if t.team_id == "thales") assert thales_row.admins == 1 assert thales_row.agents == 2 assert thales_row.prompts == 3
"""
Offline integration tests for the control-plane-backend product API.
Ref: docs/backlog/BACKLOG.md §3d — managed agent CRUD, enrollment, update, tuning
field validation (type/enum/min-max/pattern), MCP server selection as
`mcp:<server>` capabilities (#1978, RFC AGENT-CAPABILITY-RFC.md §3.8) —
see test_capability_selection_1974.py for the generic capability-selection
contract (unknown id -> 422, pod round-trip, prune/reset semantics);
§3d.9 (P1) — prompt template validation at persistence boundary (unknown tokens → 422);
§6.4.D — PATCH session endpoint (updated_at, title).
"""
from __future__ import annotations
from datetime import datetime, timezone
from pathlib import Path
from types import SimpleNamespace
from typing import Any, Optional, cast
import httpx
import pytest
from control_plane_backend.agent_instances.store import (
AgentInstanceRecord,
AgentInstanceStore,
)
from control_plane_backend.app.dependencies import get_application_container_from_app
from control_plane_backend.bootstrap.store import PlatformBootstrapStore
from control_plane_backend.config.models import (
InfoBanner,
InfoBannerLink,
ManagedAgentFieldSpec,
ManagedAgentTuning,
RuntimeCatalogSourceConfig,
)
from control_plane_backend.main import create_app
from control_plane_backend.models.base import Base as CPBase
from control_plane_backend.product import service as product_service
from control_plane_backend.product.dependencies import (
ProductServiceDependencies,
build_product_service_dependencies,
)
from control_plane_backend.product.schemas import CreateSessionRequest
from control_plane_backend.product.service import (
SessionAttachmentRequestError,
_delete_knowledge_flow_attachment,
_RuntimeTemplatePayload,
)
from control_plane_backend.prompts.category_store import PromptCategoryRecord
from control_plane_backend.prompts.store import PromptRecord
from control_plane_backend.sessions.attachment_store import SessionAttachmentRecord
from control_plane_backend.sessions.store import SessionMetadataRecord
from control_plane_backend.teams.schemas import Team
from control_plane_backend.users.schemas import UserSummary
from fred_core import (
JoiningMode,
KeycloakUser,
OrganizationPermission,
RelationType,
SessionSchema,
TeamPermission,
TeamVisibility,
get_current_user,
)
from fred_core.common import TeamId, personal_team_id
from fred_core.security import oidc
from fred_core.security.rebac.noop_engine import NoopRebacEngine
from fred_core.teams.metadata_store import TeamMetadata
from fred_sdk.contracts.capability import (
CapabilityCatalogEntry,
ChatControlItem,
ChatControlsResponse,
ChatControlsResult,
)
from fred_sdk.contracts.models import FieldSpec
from httpx import ASGITransport, AsyncClient
from sqlalchemy import text
from sqlalchemy.ext.asyncio import create_async_engine
@pytest.fixture(autouse=True)
def _use_test_configuration(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setenv("CONFIG_FILE", "./config/configuration_test.yaml")
_PERSONAL_TEAM_ID = personal_team_id("admin")
def _make_record(
*,
agent_instance_id: str = "instance-1",
team_id: str = "personal",
template_id: str = "runtime-a:rags.sample.echo",
source_runtime_id: str = "runtime-a",
source_agent_id: str = "rags.sample.echo",
display_name: str = "Echo Team Agent",
description: str | None = "Managed echo agent",
enabled: bool = True,
created_by: str | None = "internal-admin",
) -> AgentInstanceRecord:
return AgentInstanceRecord(

Xet Storage Details

Size:
324 kB
·
Xet hash:
f9fa784f62d43677d6e68d9b124ead1f4d98712ca682d8c0d0ab9fc7c298d3ba

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.