diff --git a/models/src/agent_control_models/__init__.py b/models/src/agent_control_models/__init__.py index 148cdd7a..6b5562a7 100644 --- a/models/src/agent_control_models/__init__.py +++ b/models/src/agent_control_models/__init__.py @@ -83,7 +83,11 @@ from .server import ( AgentRef, AgentSummary, + CloneAndBindControlRequest, + CloneAndBindControlResponse, + CloneAndBindTargetBinding, ConflictMode, + ControlAttachments, ControlSummary, ControlVersionSummary, CreateControlBindingRequest, @@ -107,9 +111,11 @@ PatchControlBindingResponse, PatchControlRequest, PatchControlResponse, + PolicyRef, RenderControlTemplateRequest, RenderControlTemplateResponse, StepKey, + TargetAttachmentRef, UpsertControlBindingRequest, UpsertControlBindingResponse, ValidateControlDataRequest, @@ -176,7 +182,11 @@ # Server models "AgentRef", "AgentSummary", + "CloneAndBindControlRequest", + "CloneAndBindControlResponse", + "CloneAndBindTargetBinding", "ConflictMode", + "ControlAttachments", "ControlVersionSummary", "ControlSummary", "CreateControlBindingRequest", @@ -200,9 +210,11 @@ "PatchControlBindingResponse", "PatchControlRequest", "PatchControlResponse", + "PolicyRef", "RenderControlTemplateRequest", "RenderControlTemplateResponse", "StepKey", + "TargetAttachmentRef", "UpsertControlBindingRequest", "UpsertControlBindingResponse", "ValidateControlDataRequest", diff --git a/models/src/agent_control_models/errors.py b/models/src/agent_control_models/errors.py index 0bf644d4..0db04134 100644 --- a/models/src/agent_control_models/errors.py +++ b/models/src/agent_control_models/errors.py @@ -54,6 +54,7 @@ class ErrorCode(StrEnum): AUTH_INVALID_KEY = "AUTH_INVALID_KEY" AUTH_INSUFFICIENT_PRIVILEGES = "AUTH_INSUFFICIENT_PRIVILEGES" AUTH_MISCONFIGURED = "AUTH_MISCONFIGURED" + AUTH_UPSTREAM_REJECTED = "AUTH_UPSTREAM_REJECTED" # Resource Not Found (2xx pattern) RESOURCE_NOT_FOUND = "RESOURCE_NOT_FOUND" # Generic fallback @@ -363,6 +364,7 @@ def make_error_type(error_code: ErrorCode) -> str: ErrorCode.AUTH_INVALID_KEY: "Invalid API Key", ErrorCode.AUTH_INSUFFICIENT_PRIVILEGES: "Insufficient Privileges", ErrorCode.AUTH_MISCONFIGURED: "Authentication Misconfigured", + ErrorCode.AUTH_UPSTREAM_REJECTED: "Authorization Upstream Rejected Request", # Not found errors ErrorCode.RESOURCE_NOT_FOUND: "Resource Not Found", ErrorCode.AGENT_NOT_FOUND: "Agent Not Found", diff --git a/models/src/agent_control_models/server.py b/models/src/agent_control_models/server.py index 3529a5d4..a96b0410 100644 --- a/models/src/agent_control_models/server.py +++ b/models/src/agent_control_models/server.py @@ -14,6 +14,7 @@ from .agent import Agent, StepSchema from .base import BaseModel from .controls import ( + ControlAction, ControlDefinition, TemplateControlInput, TemplateDefinition, @@ -347,6 +348,9 @@ class GetControlResponse(BaseModel): id: int = Field(..., description="Control ID") name: str = Field(..., description="Control name") + cloned_from_control_id: int | None = Field( + None, description="Source control ID when this control is a clone." + ) data: ControlDefinition | UnrenderedTemplateControl = Field( description=( "Control configuration data. A ControlDefinition for raw/rendered " @@ -514,14 +518,60 @@ class AgentRef(BaseModel): agent_name: str = Field(..., description="Agent name") +class PolicyRef(BaseModel): + """Reference to a policy attached to a control.""" + + policy_id: int = Field(..., description="Policy ID") + + +class TargetAttachmentRef(BaseModel): + """Reference to a target binding attached to a control.""" + + binding_id: int = Field(..., description="Control binding ID") + target_type: str = Field(..., description="Opaque target kind") + target_id: str = Field(..., description="Opaque target identifier") + enabled: bool = Field(..., description="Whether this target binding is enabled") + + +class ControlAttachments(BaseModel): + """Attachments for a listed control.""" + + agents: list[AgentRef] = Field( + default_factory=list, + description="Direct agent associations for this control", + ) + policies: list[PolicyRef] = Field( + default_factory=list, + description="Policy associations for this control", + ) + targets: list[TargetAttachmentRef] = Field( + default_factory=list, + description="Target bindings for this control", + ) + targets_total: int = Field( + default=0, + description="Total target bindings matching the attachment filters", + ) + targets_truncated: bool = Field( + default=False, + description="Whether the target bindings list was capped", + ) + + class ControlSummary(BaseModel): """Summary of a control for list responses.""" id: int = Field(..., description="Control ID") name: str = Field(..., description="Control name") + cloned_from_control_id: int | None = Field( + None, description="Source control ID when this control is a clone." + ) description: str | None = Field(None, description="Control description") enabled: bool = Field(True, description="Whether control is enabled") execution: str | None = Field(None, description="'server' or 'sdk'") + action: ControlAction | None = Field( + None, description="Action applied when the control matches." + ) step_types: list[str] | None = Field(None, description="Step types in scope") stages: list[str] | None = Field(None, description="Evaluation stages in scope") tags: list[str] = Field(default_factory=list, description="Control tags") @@ -542,6 +592,13 @@ class ControlSummary(BaseModel): used_by_agents_count: int = Field( 0, description="Number of unique agents using this control" ) + attachments: ControlAttachments | None = Field( + None, + description=( + "Expanded attachment details. Present when list controls is called " + "with include_attachments=true." + ), + ) class ListControlsResponse(BaseModel): @@ -580,7 +637,7 @@ class GetControlVersionResponse(BaseModel): ..., description=( "Raw persisted snapshot of the control state at this version, including " - "metadata such as name, deleted_at, and cloned_control_id." + "metadata such as name, deleted_at, and cloned_from_control_id." ), ) @@ -635,6 +692,50 @@ class PatchControlResponse(BaseModel): ] +class CloneAndBindTargetBinding(BaseModel): + """Target binding to create for a cloned control.""" + + model_config = ConfigDict(extra="forbid") + + target_type: ControlBindingTargetField = Field( + ..., + description="Opaque attachment kind (caller-defined; e.g. 'environment', 'session').", + ) + target_id: ControlBindingTargetField = Field( + ..., description="Opaque external identifier within the target_type." + ) + enabled: bool = Field( + default=True, + description="Whether the created binding is active.", + ) + + +class CloneAndBindControlRequest(BaseModel): + """Request to clone a control and attach the clone to one target.""" + + model_config = ConfigDict(extra="forbid") + + name: SlugName | None = Field( + None, + description=( + "Optional unique name for the cloned control. If omitted, the server " + "generates a name from the source control name." + ), + ) + target_binding: CloneAndBindTargetBinding = Field( + ..., description="Target binding to create for the cloned control." + ) + + +class CloneAndBindControlResponse(BaseModel): + """Response from cloning and binding a control.""" + + id: int = Field(..., description="Identifier of the cloned control.") + name: str = Field(..., description="Name of the cloned control.") + cloned_from_control_id: int = Field(..., description="Source control ID.") + binding_id: int = Field(..., description="Identifier of the created binding.") + + class CreateControlBindingRequest(BaseModel): """Request to attach a control to an opaque external target.""" @@ -741,6 +842,21 @@ class UpsertControlBindingResponse(BaseModel): enabled: bool = Field(..., description="Current enabled value.") +class PatchControlBindingByKeyRequest(BaseModel): + """Request to update an existing control binding by natural key.""" + + target_type: ControlBindingTargetField = Field( + ..., description="Opaque attachment kind." + ) + target_id: ControlBindingTargetField = Field( + ..., description="Opaque external identifier within the target_type." + ) + control_id: int = Field( + ..., gt=0, description="ID of the bound control." + ) + enabled: bool = Field(..., description="New enabled value for the binding.") + + class DeleteControlBindingByKeyRequest(BaseModel): """Request to detach a control binding by natural key (idempotent).""" @@ -759,4 +875,3 @@ class DeleteControlBindingByKeyResponse(BaseModel): "binding existed." ), ) - diff --git a/sdks/python/src/agent_control/__init__.py b/sdks/python/src/agent_control/__init__.py index 0a1dc1ea..f0d07520 100644 --- a/sdks/python/src/agent_control/__init__.py +++ b/sdks/python/src/agent_control/__init__.py @@ -79,7 +79,7 @@ async def handle_input(user_message: str) -> str: set_trace_context_provider, ) -from . import agents, controls, evaluation, evaluators, policies +from . import agents, control_bindings, controls, evaluation, evaluators, policies from ._control_registry import ( StepSchemaDict, get_registered_steps, @@ -1019,10 +1019,14 @@ async def list_controls( name: str | None = None, enabled: bool | None = None, template_backed: bool | None = None, + cloned: bool | None = None, step_type: str | None = None, stage: Literal["pre", "post"] | None = None, execution: Literal["server", "sdk"] | None = None, tag: str | None = None, + include_attachments: bool = False, + attachment_target_type: str | None = None, + attachment_target_id: str | None = None, ) -> dict[str, Any]: """ List all controls from the server with optional filtering. @@ -1035,10 +1039,14 @@ async def list_controls( name: Optional filter by name (partial, case-insensitive) enabled: Optional filter by enabled status template_backed: Optional filter by whether the control is template-backed + cloned: Optional filter by whether the control was cloned from another control step_type: Optional filter by step type (built-ins: 'tool', 'llm') stage: Optional filter by stage ('pre' or 'post') execution: Optional filter by execution ('server' or 'sdk') tag: Optional filter by tag + include_attachments: Whether to include attachment details + attachment_target_type: Optional target binding type filter for attachments + attachment_target_id: Optional target binding ID filter for attachments Returns: Dictionary containing: @@ -1079,10 +1087,14 @@ async def main(): name=name, enabled=enabled, template_backed=template_backed, + cloned=cloned, step_type=step_type, stage=stage, execution=execution, tag=tag, + include_attachments=include_attachments, + attachment_target_type=attachment_target_type, + attachment_target_id=attachment_target_id, ) @@ -1147,6 +1159,49 @@ async def main(): return await controls.create_control(client, name, data=data) +async def clone_and_bind_control( + control_id: int, + *, + target_type: str, + target_id: str, + name: str | None = None, + enabled: bool = True, + server_url: str | None = None, + api_key: str | None = None, + api_key_header: str | None = None, +) -> dict[str, Any]: + """ + Clone an existing control and bind the clone to a target. + + Args: + control_id: Source control ID to clone + target_type: Opaque attachment kind + target_id: Opaque external target identifier + name: Optional unique name for the cloned control + enabled: Whether the created binding is active + server_url: Optional server URL (defaults to AGENT_CONTROL_URL env var) + api_key: Optional API key for authentication (defaults to AGENT_CONTROL_API_KEY env var) + + Returns: + Dictionary containing id, name, cloned_from_control_id, and binding_id. + """ + _final_server_url = server_url or os.getenv('AGENT_CONTROL_URL') or 'http://localhost:8000' + + async with _ad_hoc_client( + server_url=_final_server_url, + api_key=api_key, + api_key_header=api_key_header, + ) as client: + return await controls.clone_and_bind_control( + client, + control_id, + target_type=target_type, + target_id=target_id, + name=name, + enabled=enabled, + ) + + async def validate_control_data( data: dict[str, Any] | ControlDefinition | TemplateControlInput, server_url: str | None = None, @@ -1502,6 +1557,7 @@ async def main(): "add_agent_control", "remove_agent_control", # Control management + "clone_and_bind_control", "create_control", "list_controls", "get_control", @@ -1520,6 +1576,7 @@ async def main(): "agents", "policies", "controls", + "control_bindings", "evaluation", "evaluators", # Policy-Control management diff --git a/sdks/python/src/agent_control/control_bindings.py b/sdks/python/src/agent_control/control_bindings.py new file mode 100644 index 00000000..ca96a90e --- /dev/null +++ b/sdks/python/src/agent_control/control_bindings.py @@ -0,0 +1,69 @@ +"""Control binding management operations for Agent Control SDK.""" + +from typing import Any, cast + +from .client import AgentControlClient + + +async def upsert_control_binding_by_key( + client: AgentControlClient, + *, + target_type: str, + target_id: str, + control_id: int, + enabled: bool = True, +) -> dict[str, Any]: + """Attach a control to a target, or update the existing binding.""" + response = await client.http_client.put( + "/api/v1/control-bindings/by-key", + json={ + "target_type": target_type, + "target_id": target_id, + "control_id": control_id, + "enabled": enabled, + }, + ) + response.raise_for_status() + return cast(dict[str, Any], response.json()) + + +async def update_control_binding_by_key( + client: AgentControlClient, + *, + target_type: str, + target_id: str, + control_id: int, + enabled: bool, +) -> dict[str, Any]: + """Update an existing target binding without creating a missing binding.""" + response = await client.http_client.patch( + "/api/v1/control-bindings/by-key", + json={ + "target_type": target_type, + "target_id": target_id, + "control_id": control_id, + "enabled": enabled, + }, + ) + response.raise_for_status() + return cast(dict[str, Any], response.json()) + + +async def delete_control_binding_by_key( + client: AgentControlClient, + *, + target_type: str, + target_id: str, + control_id: int, +) -> dict[str, Any]: + """Detach a control from a target by natural key.""" + response = await client.http_client.post( + "/api/v1/control-bindings/by-key:delete", + json={ + "target_type": target_type, + "target_id": target_id, + "control_id": control_id, + }, + ) + response.raise_for_status() + return cast(dict[str, Any], response.json()) diff --git a/sdks/python/src/agent_control/controls.py b/sdks/python/src/agent_control/controls.py index 99fc6265..8478c357 100644 --- a/sdks/python/src/agent_control/controls.py +++ b/sdks/python/src/agent_control/controls.py @@ -20,10 +20,14 @@ async def list_controls( name: str | None = None, enabled: bool | None = None, template_backed: bool | None = None, + cloned: bool | None = None, step_type: str | None = None, stage: Literal["pre", "post"] | None = None, execution: Literal["server", "sdk"] | None = None, tag: str | None = None, + include_attachments: bool = False, + attachment_target_type: str | None = None, + attachment_target_id: str | None = None, ) -> dict[str, Any]: """ List all controls with optional filtering and pagination. @@ -37,10 +41,14 @@ async def list_controls( name: Optional filter by name (partial, case-insensitive match) enabled: Optional filter by enabled status template_backed: Optional filter by whether the control is template-backed + cloned: Optional filter by whether the control was cloned from another control step_type: Optional filter by step type (built-ins: 'tool', 'llm') stage: Optional filter by stage ('pre' or 'post') execution: Optional filter by execution ('server' or 'sdk') tag: Optional filter by tag + include_attachments: Whether to include attachment details + attachment_target_type: Optional target binding type filter for attachments + attachment_target_id: Optional target binding ID filter for attachments Returns: Dictionary containing: @@ -78,6 +86,8 @@ async def list_controls( params["enabled"] = enabled if template_backed is not None: params["template_backed"] = template_backed + if cloned is not None: + params["cloned"] = cloned if step_type is not None: params["step_type"] = step_type if stage is not None: @@ -86,6 +96,12 @@ async def list_controls( params["execution"] = execution if tag is not None: params["tag"] = tag + if include_attachments: + params["include_attachments"] = include_attachments + if attachment_target_type is not None: + params["attachment_target_type"] = attachment_target_type + if attachment_target_id is not None: + params["attachment_target_id"] = attachment_target_id response = await client.http_client.get("/api/v1/controls", params=params) response.raise_for_status() @@ -243,6 +259,47 @@ async def create_control( return result +async def clone_and_bind_control( + client: AgentControlClient, + control_id: int, + *, + target_type: str, + target_id: str, + name: str | None = None, + enabled: bool = True, +) -> dict[str, Any]: + """ + Clone an existing control and bind the clone to a target in one API call. + + Args: + client: AgentControlClient instance + control_id: Source control ID to clone + target_type: Opaque attachment kind + target_id: Opaque external target identifier + name: Optional unique name for the cloned control + enabled: Whether the created binding is active + + Returns: + Dictionary containing id, name, cloned_from_control_id, and binding_id. + """ + payload: dict[str, Any] = { + "target_binding": { + "target_type": target_type, + "target_id": target_id, + "enabled": enabled, + } + } + if name is not None: + payload["name"] = name + + response = await client.http_client.post( + f"/api/v1/controls/{control_id}/clone-and-bind", + json=payload, + ) + response.raise_for_status() + return cast(dict[str, Any], response.json()) + + async def set_control_data( client: AgentControlClient, control_id: int, diff --git a/sdks/python/tests/test_control_bindings_api.py b/sdks/python/tests/test_control_bindings_api.py new file mode 100644 index 00000000..d21d85fe --- /dev/null +++ b/sdks/python/tests/test_control_bindings_api.py @@ -0,0 +1,87 @@ +"""Unit tests for agent_control.control_bindings API wrappers.""" + +from __future__ import annotations + +from types import SimpleNamespace +from unittest.mock import AsyncMock, Mock + +import agent_control +import pytest + + +@pytest.mark.asyncio +async def test_upsert_control_binding_by_key_calls_endpoint() -> None: + response = Mock() + response.raise_for_status = Mock() + response.json = Mock(return_value={"binding_id": 123, "created": True, "enabled": True}) + client = SimpleNamespace(http_client=SimpleNamespace(put=AsyncMock(return_value=response))) + + result = await agent_control.control_bindings.upsert_control_binding_by_key( + client, + target_type="log_stream", + target_id="ls-prod", + control_id=456, + ) + + assert result["binding_id"] == 123 + client.http_client.put.assert_awaited_once_with( + "/api/v1/control-bindings/by-key", + json={ + "target_type": "log_stream", + "target_id": "ls-prod", + "control_id": 456, + "enabled": True, + }, + ) + + +@pytest.mark.asyncio +async def test_update_control_binding_by_key_calls_endpoint() -> None: + response = Mock() + response.raise_for_status = Mock() + response.json = Mock(return_value={"success": True, "enabled": False}) + client = SimpleNamespace(http_client=SimpleNamespace(patch=AsyncMock(return_value=response))) + + result = await agent_control.control_bindings.update_control_binding_by_key( + client, + target_type="log_stream", + target_id="ls-prod", + control_id=456, + enabled=False, + ) + + assert result["enabled"] is False + client.http_client.patch.assert_awaited_once_with( + "/api/v1/control-bindings/by-key", + json={ + "target_type": "log_stream", + "target_id": "ls-prod", + "control_id": 456, + "enabled": False, + }, + ) + + +@pytest.mark.asyncio +async def test_delete_control_binding_by_key_calls_endpoint() -> None: + response = Mock() + response.raise_for_status = Mock() + response.json = Mock(return_value={"deleted": True}) + client = SimpleNamespace(http_client=SimpleNamespace(post=AsyncMock(return_value=response))) + + result = await agent_control.control_bindings.delete_control_binding_by_key( + client, + target_type="log_stream", + target_id="ls-prod", + control_id=456, + ) + + assert result["deleted"] is True + client.http_client.post.assert_awaited_once_with( + "/api/v1/control-bindings/by-key:delete", + json={ + "target_type": "log_stream", + "target_id": "ls-prod", + "control_id": 456, + }, + ) diff --git a/sdks/python/tests/test_controls_api.py b/sdks/python/tests/test_controls_api.py index ed505451..78a01c4e 100644 --- a/sdks/python/tests/test_controls_api.py +++ b/sdks/python/tests/test_controls_api.py @@ -2,7 +2,10 @@ from __future__ import annotations +from collections.abc import AsyncGenerator +from contextlib import asynccontextmanager from types import SimpleNamespace +from typing import Any from unittest.mock import AsyncMock, Mock import pytest @@ -29,6 +32,49 @@ async def test_list_controls_passes_template_backed_filter() -> None: ) +@pytest.mark.asyncio +async def test_list_controls_passes_cloned_filter() -> None: + # Given: an SDK client stub and a cloned list filter + response = Mock() + response.raise_for_status = Mock() + response.json = Mock(return_value={"controls": [], "pagination": {}}) + client = SimpleNamespace(http_client=SimpleNamespace(get=AsyncMock(return_value=response))) + + # When: listing controls through the SDK wrapper + await agent_control.controls.list_controls(client, cloned=False) + + # Then: the filter is forwarded to the API request + client.http_client.get.assert_awaited_once_with( + "/api/v1/controls", + params={"limit": 20, "cloned": False}, + ) + + +@pytest.mark.asyncio +async def test_list_controls_passes_attachment_filters() -> None: + response = Mock() + response.raise_for_status = Mock() + response.json = Mock(return_value={"controls": [], "pagination": {}}) + client = SimpleNamespace(http_client=SimpleNamespace(get=AsyncMock(return_value=response))) + + await agent_control.controls.list_controls( + client, + include_attachments=True, + attachment_target_type="log_stream", + attachment_target_id="ls-prod", + ) + + client.http_client.get.assert_awaited_once_with( + "/api/v1/controls", + params={ + "limit": 20, + "include_attachments": True, + "attachment_target_type": "log_stream", + "attachment_target_id": "ls-prod", + }, + ) + + @pytest.mark.asyncio async def test_create_control_accepts_template_control_input() -> None: # Given: an SDK client stub and template-backed control input @@ -71,6 +117,133 @@ async def test_create_control_accepts_template_control_input() -> None: assert kwargs["json"]["data"]["template_values"]["pattern"] == "hello" +@pytest.mark.asyncio +async def test_clone_and_bind_control_calls_clone_endpoint() -> None: + # Given: an SDK client stub for clone-and-bind + response = Mock() + response.raise_for_status = Mock() + response.json = Mock( + return_value={ + "id": 456, + "name": "clone-name", + "cloned_from_control_id": 123, + "binding_id": 789, + } + ) + client = SimpleNamespace(http_client=SimpleNamespace(post=AsyncMock(return_value=response))) + + # When: cloning and binding through the SDK wrapper + result = await agent_control.controls.clone_and_bind_control( + client, + 123, + target_type="log_stream", + target_id="logstream-123", + name="clone-name", + enabled=False, + ) + + # Then: the SDK posts the expected payload + assert result["id"] == 456 + client.http_client.post.assert_awaited_once_with( + "/api/v1/controls/123/clone-and-bind", + json={ + "target_binding": { + "target_type": "log_stream", + "target_id": "logstream-123", + "enabled": False, + }, + "name": "clone-name", + }, + ) + + +@pytest.mark.asyncio +async def test_top_level_list_controls_passes_cloned_filter( + monkeypatch: pytest.MonkeyPatch, +) -> None: + captured: dict[str, Any] = {} + stub_client = object() + + @asynccontextmanager + async def fake_ad_hoc_client(**kwargs: Any) -> AsyncGenerator[object, None]: + captured["client_kwargs"] = kwargs + yield stub_client + + async def fake_list_controls(client: object, **kwargs: Any) -> dict[str, Any]: + captured["client"] = client + captured["list_kwargs"] = kwargs + return {"controls": [], "pagination": {}} + + monkeypatch.setattr(agent_control, "_ad_hoc_client", fake_ad_hoc_client) + monkeypatch.setattr(agent_control.controls, "list_controls", fake_list_controls) + + result = await agent_control.list_controls( + cloned=False, + include_attachments=True, + attachment_target_type="log_stream", + attachment_target_id="ls-prod", + server_url="http://server", + ) + + assert result["controls"] == [] + assert captured["client"] is stub_client + assert captured["client_kwargs"]["server_url"] == "http://server" + assert captured["list_kwargs"]["cloned"] is False + assert captured["list_kwargs"]["include_attachments"] is True + assert captured["list_kwargs"]["attachment_target_type"] == "log_stream" + assert captured["list_kwargs"]["attachment_target_id"] == "ls-prod" + + +@pytest.mark.asyncio +async def test_top_level_clone_and_bind_control_uses_ad_hoc_client( + monkeypatch: pytest.MonkeyPatch, +) -> None: + captured: dict[str, Any] = {} + stub_client = object() + + @asynccontextmanager + async def fake_ad_hoc_client(**kwargs: Any) -> AsyncGenerator[object, None]: + captured["client_kwargs"] = kwargs + yield stub_client + + async def fake_clone_and_bind_control( + client: object, + control_id: int, + **kwargs: Any, + ) -> dict[str, Any]: + captured["client"] = client + captured["control_id"] = control_id + captured["clone_kwargs"] = kwargs + return {"id": 456, "binding_id": 789} + + monkeypatch.setattr(agent_control, "_ad_hoc_client", fake_ad_hoc_client) + monkeypatch.setattr( + agent_control.controls, + "clone_and_bind_control", + fake_clone_and_bind_control, + ) + + result = await agent_control.clone_and_bind_control( + 123, + target_type="log_stream", + target_id="logstream-123", + name="clone-name", + enabled=False, + server_url="http://server", + ) + + assert result["binding_id"] == 789 + assert captured["client"] is stub_client + assert captured["client_kwargs"]["server_url"] == "http://server" + assert captured["control_id"] == 123 + assert captured["clone_kwargs"] == { + "target_type": "log_stream", + "target_id": "logstream-123", + "name": "clone-name", + "enabled": False, + } + + @pytest.mark.asyncio async def test_list_control_versions_forwards_cursor_and_limit() -> None: # Given: an SDK client stub and version-history pagination params diff --git a/sdks/typescript/overlays/method-names.overlay.yaml b/sdks/typescript/overlays/method-names.overlay.yaml index ce36006c..967847c6 100644 --- a/sdks/typescript/overlays/method-names.overlay.yaml +++ b/sdks/typescript/overlays/method-names.overlay.yaml @@ -120,6 +120,11 @@ actions: x-speakeasy-group: controlBindings x-speakeasy-name-override: upsertByKey + - target: $["paths"]["/api/v1/control-bindings/by-key"]["patch"] + update: + x-speakeasy-group: controlBindings + x-speakeasy-name-override: updateByKey + - target: $["paths"]["/api/v1/control-bindings/by-key:delete"]["post"] update: x-speakeasy-group: controlBindings @@ -180,6 +185,11 @@ actions: x-speakeasy-group: controls x-speakeasy-name-override: delete + - target: $["paths"]["/api/v1/controls/{control_id}/clone-and-bind"]["post"] + update: + x-speakeasy-group: controls + x-speakeasy-name-override: cloneAndBindControl + - target: $["paths"]["/api/v1/controls/{control_id}/data"]["get"] update: x-speakeasy-group: controls diff --git a/sdks/typescript/src/generated/funcs/control-bindings-update-by-key.ts b/sdks/typescript/src/generated/funcs/control-bindings-update-by-key.ts new file mode 100644 index 00000000..f34d5ff1 --- /dev/null +++ b/sdks/typescript/src/generated/funcs/control-bindings-update-by-key.ts @@ -0,0 +1,176 @@ +/* + * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. + */ + +import * as z from "zod/v4-mini"; +import { AgentControlSDKCore } from "../core.js"; +import { encodeJSON } from "../lib/encodings.js"; +import * as M from "../lib/matchers.js"; +import { compactMap } from "../lib/primitives.js"; +import { safeParse } from "../lib/schemas.js"; +import { RequestOptions } from "../lib/sdks.js"; +import { extractSecurity, resolveGlobalSecurity } from "../lib/security.js"; +import { pathToFunc } from "../lib/url.js"; +import { AgentControlSDKError } from "../models/errors/agent-control-sdk-error.js"; +import { + ConnectionError, + InvalidRequestError, + RequestAbortedError, + RequestTimeoutError, + UnexpectedClientError, +} from "../models/errors/http-client-errors.js"; +import * as errors from "../models/errors/index.js"; +import { ResponseValidationError } from "../models/errors/response-validation-error.js"; +import { SDKValidationError } from "../models/errors/sdk-validation-error.js"; +import * as models from "../models/index.js"; +import { APICall, APIPromise } from "../types/async.js"; +import { Result } from "../types/fp.js"; + +/** + * Update a control binding by natural key + * + * @remarks + * Update an existing binding using ``(target_type, target_id, control_id)``. + * + * This route is target-scoped because the request body includes the target + * identifiers before authorization runs. Unlike ``PUT /by-key``, it never + * creates a missing binding. + */ +export function controlBindingsUpdateByKey( + client: AgentControlSDKCore, + request: models.PatchControlBindingByKeyRequest, + options?: RequestOptions, +): APIPromise< + Result< + models.PatchControlBindingResponse, + | errors.HTTPValidationError + | AgentControlSDKError + | ResponseValidationError + | ConnectionError + | RequestAbortedError + | RequestTimeoutError + | InvalidRequestError + | UnexpectedClientError + | SDKValidationError + > +> { + return new APIPromise($do( + client, + request, + options, + )); +} + +async function $do( + client: AgentControlSDKCore, + request: models.PatchControlBindingByKeyRequest, + options?: RequestOptions, +): Promise< + [ + Result< + models.PatchControlBindingResponse, + | errors.HTTPValidationError + | AgentControlSDKError + | ResponseValidationError + | ConnectionError + | RequestAbortedError + | RequestTimeoutError + | InvalidRequestError + | UnexpectedClientError + | SDKValidationError + >, + APICall, + ] +> { + const parsed = safeParse( + request, + (value) => + z.parse(models.PatchControlBindingByKeyRequest$outboundSchema, value), + "Input validation failed", + ); + if (!parsed.ok) { + return [parsed, { status: "invalid" }]; + } + const payload = parsed.value; + const body = encodeJSON("body", payload, { explode: true }); + + const path = pathToFunc("/api/v1/control-bindings/by-key")(); + + const headers = new Headers(compactMap({ + "Content-Type": "application/json", + Accept: "application/json", + })); + + const secConfig = await extractSecurity(client._options.apiKeyHeader); + const securityInput = secConfig == null ? {} : { apiKeyHeader: secConfig }; + const requestSecurity = resolveGlobalSecurity(securityInput); + + const context = { + options: client._options, + baseURL: options?.serverURL ?? client._baseURL ?? "", + operationID: + "patch_control_binding_by_key_api_v1_control_bindings_by_key_patch", + oAuth2Scopes: null, + + resolvedSecurity: requestSecurity, + + securitySource: client._options.apiKeyHeader, + retryConfig: options?.retries + || client._options.retryConfig + || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"], + }; + + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "PATCH", + baseURL: options?.serverURL, + path: path, + headers: headers, + body: body, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1, + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + + const doResult = await client._do(req, { + context, + errorCodes: ["422", "4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes, + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + + const responseFields = { + HttpMeta: { Response: response, Request: req }, + }; + + const [result] = await M.match< + models.PatchControlBindingResponse, + | errors.HTTPValidationError + | AgentControlSDKError + | ResponseValidationError + | ConnectionError + | RequestAbortedError + | RequestTimeoutError + | InvalidRequestError + | UnexpectedClientError + | SDKValidationError + >( + M.json(200, models.PatchControlBindingResponse$inboundSchema), + M.jsonErr(422, errors.HTTPValidationError$inboundSchema), + M.fail("4XX"), + M.fail("5XX"), + )(response, req, { extraFields: responseFields }); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + + return [result, { status: "complete", request: req, response }]; +} diff --git a/sdks/typescript/src/generated/funcs/controls-clone-and-bind-control.ts b/sdks/typescript/src/generated/funcs/controls-clone-and-bind-control.ts new file mode 100644 index 00000000..559c3848 --- /dev/null +++ b/sdks/typescript/src/generated/funcs/controls-clone-and-bind-control.ts @@ -0,0 +1,188 @@ +/* + * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. + */ + +import * as z from "zod/v4-mini"; +import { AgentControlSDKCore } from "../core.js"; +import { encodeJSON, encodeSimple } from "../lib/encodings.js"; +import * as M from "../lib/matchers.js"; +import { compactMap } from "../lib/primitives.js"; +import { safeParse } from "../lib/schemas.js"; +import { RequestOptions } from "../lib/sdks.js"; +import { extractSecurity, resolveGlobalSecurity } from "../lib/security.js"; +import { pathToFunc } from "../lib/url.js"; +import { AgentControlSDKError } from "../models/errors/agent-control-sdk-error.js"; +import { + ConnectionError, + InvalidRequestError, + RequestAbortedError, + RequestTimeoutError, + UnexpectedClientError, +} from "../models/errors/http-client-errors.js"; +import * as errors from "../models/errors/index.js"; +import { ResponseValidationError } from "../models/errors/response-validation-error.js"; +import { SDKValidationError } from "../models/errors/sdk-validation-error.js"; +import * as models from "../models/index.js"; +import * as operations from "../models/operations/index.js"; +import { APICall, APIPromise } from "../types/async.js"; +import { Result } from "../types/fp.js"; + +/** + * Clone a control and bind the clone to a target + * + * @remarks + * Clone an active control and attach the clone to an opaque target. + */ +export function controlsCloneAndBindControl( + client: AgentControlSDKCore, + request: + operations.CloneAndBindControlApiV1ControlsControlIdCloneAndBindPostRequest, + options?: RequestOptions, +): APIPromise< + Result< + models.CloneAndBindControlResponse, + | errors.HTTPValidationError + | AgentControlSDKError + | ResponseValidationError + | ConnectionError + | RequestAbortedError + | RequestTimeoutError + | InvalidRequestError + | UnexpectedClientError + | SDKValidationError + > +> { + return new APIPromise($do( + client, + request, + options, + )); +} + +async function $do( + client: AgentControlSDKCore, + request: + operations.CloneAndBindControlApiV1ControlsControlIdCloneAndBindPostRequest, + options?: RequestOptions, +): Promise< + [ + Result< + models.CloneAndBindControlResponse, + | errors.HTTPValidationError + | AgentControlSDKError + | ResponseValidationError + | ConnectionError + | RequestAbortedError + | RequestTimeoutError + | InvalidRequestError + | UnexpectedClientError + | SDKValidationError + >, + APICall, + ] +> { + const parsed = safeParse( + request, + (value) => + z.parse( + operations + .CloneAndBindControlApiV1ControlsControlIdCloneAndBindPostRequest$outboundSchema, + value, + ), + "Input validation failed", + ); + if (!parsed.ok) { + return [parsed, { status: "invalid" }]; + } + const payload = parsed.value; + const body = encodeJSON("body", payload.body, { explode: true }); + + const pathParams = { + control_id: encodeSimple("control_id", payload.control_id, { + explode: false, + charEncoding: "percent", + }), + }; + + const path = pathToFunc("/api/v1/controls/{control_id}/clone-and-bind")( + pathParams, + ); + + const headers = new Headers(compactMap({ + "Content-Type": "application/json", + Accept: "application/json", + })); + + const secConfig = await extractSecurity(client._options.apiKeyHeader); + const securityInput = secConfig == null ? {} : { apiKeyHeader: secConfig }; + const requestSecurity = resolveGlobalSecurity(securityInput); + + const context = { + options: client._options, + baseURL: options?.serverURL ?? client._baseURL ?? "", + operationID: + "clone_and_bind_control_api_v1_controls__control_id__clone_and_bind_post", + oAuth2Scopes: null, + + resolvedSecurity: requestSecurity, + + securitySource: client._options.apiKeyHeader, + retryConfig: options?.retries + || client._options.retryConfig + || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"], + }; + + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "POST", + baseURL: options?.serverURL, + path: path, + headers: headers, + body: body, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1, + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + + const doResult = await client._do(req, { + context, + errorCodes: ["422", "4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes, + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + + const responseFields = { + HttpMeta: { Response: response, Request: req }, + }; + + const [result] = await M.match< + models.CloneAndBindControlResponse, + | errors.HTTPValidationError + | AgentControlSDKError + | ResponseValidationError + | ConnectionError + | RequestAbortedError + | RequestTimeoutError + | InvalidRequestError + | UnexpectedClientError + | SDKValidationError + >( + M.json(200, models.CloneAndBindControlResponse$inboundSchema), + M.jsonErr(422, errors.HTTPValidationError$inboundSchema), + M.fail("4XX"), + M.fail("5XX"), + )(response, req, { extraFields: responseFields }); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + + return [result, { status: "complete", request: req, response }]; +} diff --git a/sdks/typescript/src/generated/funcs/controls-list.ts b/sdks/typescript/src/generated/funcs/controls-list.ts index 2fd69073..4b1aadd7 100644 --- a/sdks/typescript/src/generated/funcs/controls-list.ts +++ b/sdks/typescript/src/generated/funcs/controls-list.ts @@ -41,10 +41,16 @@ import { Result } from "../types/fp.js"; * name: Optional filter by name (partial, case-insensitive match) * enabled: Optional filter by enabled status * template_backed: Optional filter by whether the control is template-backed + * cloned: Optional filter by whether the control was cloned from another control * step_type: Optional filter by step type (built-ins: 'tool', 'llm') * stage: Optional filter by stage ('pre' or 'post') * execution: Optional filter by execution ('server' or 'sdk') * tag: Optional filter by tag + * include_attachments: Whether to include attachment details for listed controls + * attachment_target_type: Optional target binding type filter for controls and + * attachments + * attachment_target_id: Optional target binding ID filter for controls and + * attachments * db: Database session (injected) * * Returns: @@ -119,9 +125,13 @@ async function $do( const path = pathToFunc("/api/v1/controls")(); const query = encodeFormQuery({ + "attachment_target_id": payload?.attachment_target_id, + "attachment_target_type": payload?.attachment_target_type, + "cloned": payload?.cloned, "cursor": payload?.cursor, "enabled": payload?.enabled, "execution": payload?.execution, + "include_attachments": payload?.include_attachments, "limit": payload?.limit, "name": payload?.name, "stage": payload?.stage, diff --git a/sdks/typescript/src/generated/models/clone-and-bind-control-request.ts b/sdks/typescript/src/generated/models/clone-and-bind-control-request.ts new file mode 100644 index 00000000..90d4a54b --- /dev/null +++ b/sdks/typescript/src/generated/models/clone-and-bind-control-request.ts @@ -0,0 +1,55 @@ +/* + * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. + */ + +import * as z from "zod/v4-mini"; +import { remap as remap$ } from "../lib/primitives.js"; +import { + CloneAndBindTargetBinding, + CloneAndBindTargetBinding$Outbound, + CloneAndBindTargetBinding$outboundSchema, +} from "./clone-and-bind-target-binding.js"; + +/** + * Request to clone a control and attach the clone to one target. + */ +export type CloneAndBindControlRequest = { + /** + * Optional unique name for the cloned control. If omitted, the server generates a name from the source control name. + */ + name?: string | null | undefined; + /** + * Target binding to create for a cloned control. + */ + targetBinding: CloneAndBindTargetBinding; +}; + +/** @internal */ +export type CloneAndBindControlRequest$Outbound = { + name?: string | null | undefined; + target_binding: CloneAndBindTargetBinding$Outbound; +}; + +/** @internal */ +export const CloneAndBindControlRequest$outboundSchema: z.ZodMiniType< + CloneAndBindControlRequest$Outbound, + CloneAndBindControlRequest +> = z.pipe( + z.object({ + name: z.optional(z.nullable(z.string())), + targetBinding: CloneAndBindTargetBinding$outboundSchema, + }), + z.transform((v) => { + return remap$(v, { + targetBinding: "target_binding", + }); + }), +); + +export function cloneAndBindControlRequestToJSON( + cloneAndBindControlRequest: CloneAndBindControlRequest, +): string { + return JSON.stringify( + CloneAndBindControlRequest$outboundSchema.parse(cloneAndBindControlRequest), + ); +} diff --git a/sdks/typescript/src/generated/models/clone-and-bind-control-response.ts b/sdks/typescript/src/generated/models/clone-and-bind-control-response.ts new file mode 100644 index 00000000..f65e09f0 --- /dev/null +++ b/sdks/typescript/src/generated/models/clone-and-bind-control-response.ts @@ -0,0 +1,61 @@ +/* + * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. + */ + +import * as z from "zod/v4-mini"; +import { remap as remap$ } from "../lib/primitives.js"; +import { safeParse } from "../lib/schemas.js"; +import { Result as SafeParseResult } from "../types/fp.js"; +import * as types from "../types/primitives.js"; +import { SDKValidationError } from "./errors/sdk-validation-error.js"; + +/** + * Response from cloning and binding a control. + */ +export type CloneAndBindControlResponse = { + /** + * Identifier of the created binding. + */ + bindingId: number; + /** + * Source control ID. + */ + clonedFromControlId: number; + /** + * Identifier of the cloned control. + */ + id: number; + /** + * Name of the cloned control. + */ + name: string; +}; + +/** @internal */ +export const CloneAndBindControlResponse$inboundSchema: z.ZodMiniType< + CloneAndBindControlResponse, + unknown +> = z.pipe( + z.object({ + binding_id: types.number(), + cloned_from_control_id: types.number(), + id: types.number(), + name: types.string(), + }), + z.transform((v) => { + return remap$(v, { + "binding_id": "bindingId", + "cloned_from_control_id": "clonedFromControlId", + }); + }), +); + +export function cloneAndBindControlResponseFromJSON( + jsonString: string, +): SafeParseResult { + return safeParse( + jsonString, + (x) => CloneAndBindControlResponse$inboundSchema.parse(JSON.parse(x)), + `Failed to parse 'CloneAndBindControlResponse' from JSON`, + ); +} diff --git a/sdks/typescript/src/generated/models/clone-and-bind-target-binding.ts b/sdks/typescript/src/generated/models/clone-and-bind-target-binding.ts new file mode 100644 index 00000000..26fb57fc --- /dev/null +++ b/sdks/typescript/src/generated/models/clone-and-bind-target-binding.ts @@ -0,0 +1,57 @@ +/* + * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. + */ + +import * as z from "zod/v4-mini"; +import { remap as remap$ } from "../lib/primitives.js"; + +/** + * Target binding to create for a cloned control. + */ +export type CloneAndBindTargetBinding = { + /** + * Whether the created binding is active. + */ + enabled?: boolean | undefined; + /** + * Opaque external identifier within the target_type. + */ + targetId: string; + /** + * Opaque attachment kind (caller-defined; e.g. 'environment', 'session'). + */ + targetType: string; +}; + +/** @internal */ +export type CloneAndBindTargetBinding$Outbound = { + enabled: boolean; + target_id: string; + target_type: string; +}; + +/** @internal */ +export const CloneAndBindTargetBinding$outboundSchema: z.ZodMiniType< + CloneAndBindTargetBinding$Outbound, + CloneAndBindTargetBinding +> = z.pipe( + z.object({ + enabled: z._default(z.boolean(), true), + targetId: z.string(), + targetType: z.string(), + }), + z.transform((v) => { + return remap$(v, { + targetId: "target_id", + targetType: "target_type", + }); + }), +); + +export function cloneAndBindTargetBindingToJSON( + cloneAndBindTargetBinding: CloneAndBindTargetBinding, +): string { + return JSON.stringify( + CloneAndBindTargetBinding$outboundSchema.parse(cloneAndBindTargetBinding), + ); +} diff --git a/sdks/typescript/src/generated/models/control-attachments.ts b/sdks/typescript/src/generated/models/control-attachments.ts new file mode 100644 index 00000000..31e901f5 --- /dev/null +++ b/sdks/typescript/src/generated/models/control-attachments.ts @@ -0,0 +1,72 @@ +/* + * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. + */ + +import * as z from "zod/v4-mini"; +import { remap as remap$ } from "../lib/primitives.js"; +import { safeParse } from "../lib/schemas.js"; +import { Result as SafeParseResult } from "../types/fp.js"; +import * as types from "../types/primitives.js"; +import { AgentRef, AgentRef$inboundSchema } from "./agent-ref.js"; +import { SDKValidationError } from "./errors/sdk-validation-error.js"; +import { PolicyRef, PolicyRef$inboundSchema } from "./policy-ref.js"; +import { + TargetAttachmentRef, + TargetAttachmentRef$inboundSchema, +} from "./target-attachment-ref.js"; + +/** + * Attachments for a listed control. + */ +export type ControlAttachments = { + /** + * Direct agent associations for this control + */ + agents?: Array | undefined; + /** + * Policy associations for this control + */ + policies?: Array | undefined; + /** + * Target bindings for this control + */ + targets?: Array | undefined; + /** + * Total target bindings matching the attachment filters + */ + targetsTotal: number; + /** + * Whether the target bindings list was capped + */ + targetsTruncated: boolean; +}; + +/** @internal */ +export const ControlAttachments$inboundSchema: z.ZodMiniType< + ControlAttachments, + unknown +> = z.pipe( + z.object({ + agents: types.optional(z.array(AgentRef$inboundSchema)), + policies: types.optional(z.array(PolicyRef$inboundSchema)), + targets: types.optional(z.array(TargetAttachmentRef$inboundSchema)), + targets_total: z._default(types.number(), 0), + targets_truncated: z._default(types.boolean(), false), + }), + z.transform((v) => { + return remap$(v, { + "targets_total": "targetsTotal", + "targets_truncated": "targetsTruncated", + }); + }), +); + +export function controlAttachmentsFromJSON( + jsonString: string, +): SafeParseResult { + return safeParse( + jsonString, + (x) => ControlAttachments$inboundSchema.parse(JSON.parse(x)), + `Failed to parse 'ControlAttachments' from JSON`, + ); +} diff --git a/sdks/typescript/src/generated/models/control-summary.ts b/sdks/typescript/src/generated/models/control-summary.ts index 4c0b0fb3..5b439c9d 100644 --- a/sdks/typescript/src/generated/models/control-summary.ts +++ b/sdks/typescript/src/generated/models/control-summary.ts @@ -8,12 +8,32 @@ import { safeParse } from "../lib/schemas.js"; import { Result as SafeParseResult } from "../types/fp.js"; import * as types from "../types/primitives.js"; import { AgentRef, AgentRef$inboundSchema } from "./agent-ref.js"; +import { + ControlAction, + ControlAction$inboundSchema, +} from "./control-action.js"; +import { + ControlAttachments, + ControlAttachments$inboundSchema, +} from "./control-attachments.js"; import { SDKValidationError } from "./errors/sdk-validation-error.js"; /** * Summary of a control for list responses. */ export type ControlSummary = { + /** + * Action applied when the control matches. + */ + action?: ControlAction | null | undefined; + /** + * Expanded attachment details. Present when list controls is called with include_attachments=true. + */ + attachments?: ControlAttachments | null | undefined; + /** + * Source control ID when this control is a clone. + */ + clonedFromControlId?: number | null | undefined; /** * Control description */ @@ -70,6 +90,9 @@ export const ControlSummary$inboundSchema: z.ZodMiniType< unknown > = z.pipe( z.object({ + action: z.optional(z.nullable(ControlAction$inboundSchema)), + attachments: z.optional(z.nullable(ControlAttachments$inboundSchema)), + cloned_from_control_id: z.optional(z.nullable(types.number())), description: z.optional(z.nullable(types.string())), enabled: z._default(types.boolean(), true), execution: z.optional(z.nullable(types.string())), @@ -85,6 +108,7 @@ export const ControlSummary$inboundSchema: z.ZodMiniType< }), z.transform((v) => { return remap$(v, { + "cloned_from_control_id": "clonedFromControlId", "step_types": "stepTypes", "template_backed": "templateBacked", "template_rendered": "templateRendered", diff --git a/sdks/typescript/src/generated/models/get-control-response.ts b/sdks/typescript/src/generated/models/get-control-response.ts index 8e65e936..58bcfcc9 100644 --- a/sdks/typescript/src/generated/models/get-control-response.ts +++ b/sdks/typescript/src/generated/models/get-control-response.ts @@ -3,6 +3,7 @@ */ import * as z from "zod/v4-mini"; +import { remap as remap$ } from "../lib/primitives.js"; import { safeParse } from "../lib/schemas.js"; import { Result as SafeParseResult } from "../types/fp.js"; import * as types from "../types/primitives.js"; @@ -28,6 +29,10 @@ export type GetControlResponseData = * Response containing control details. */ export type GetControlResponse = { + /** + * Source control ID when this control is a clone. + */ + clonedFromControlId?: number | null | undefined; /** * Control configuration data. A ControlDefinition for raw/rendered controls or an UnrenderedTemplateControl for unrendered templates. */ @@ -65,14 +70,22 @@ export function getControlResponseDataFromJSON( export const GetControlResponse$inboundSchema: z.ZodMiniType< GetControlResponse, unknown -> = z.object({ - data: smartUnion([ - ControlDefinitionOutput$inboundSchema, - UnrenderedTemplateControl$inboundSchema, - ]), - id: types.number(), - name: types.string(), -}); +> = z.pipe( + z.object({ + cloned_from_control_id: z.optional(z.nullable(types.number())), + data: smartUnion([ + ControlDefinitionOutput$inboundSchema, + UnrenderedTemplateControl$inboundSchema, + ]), + id: types.number(), + name: types.string(), + }), + z.transform((v) => { + return remap$(v, { + "cloned_from_control_id": "clonedFromControlId", + }); + }), +); export function getControlResponseFromJSON( jsonString: string, diff --git a/sdks/typescript/src/generated/models/get-control-version-response.ts b/sdks/typescript/src/generated/models/get-control-version-response.ts index d502371c..1c9871b6 100644 --- a/sdks/typescript/src/generated/models/get-control-version-response.ts +++ b/sdks/typescript/src/generated/models/get-control-version-response.ts @@ -26,7 +26,7 @@ export type GetControlVersionResponse = { */ note?: string | null | undefined; /** - * Raw persisted snapshot of the control state at this version, including metadata such as name, deleted_at, and cloned_control_id. + * Raw persisted snapshot of the control state at this version, including metadata such as name, deleted_at, and cloned_from_control_id. */ snapshot: { [k: string]: any }; /** diff --git a/sdks/typescript/src/generated/models/index.ts b/sdks/typescript/src/generated/models/index.ts index 595a9501..8043233b 100644 --- a/sdks/typescript/src/generated/models/index.ts +++ b/sdks/typescript/src/generated/models/index.ts @@ -12,11 +12,15 @@ export * from "./auth-mode.js"; export * from "./batch-events-request.js"; export * from "./batch-events-response.js"; export * from "./boolean-template-parameter.js"; +export * from "./clone-and-bind-control-request.js"; +export * from "./clone-and-bind-control-response.js"; +export * from "./clone-and-bind-target-binding.js"; export * from "./condition-node-input.js"; export * from "./condition-node-output.js"; export * from "./config-response.js"; export * from "./conflict-mode.js"; export * from "./control-action.js"; +export * from "./control-attachments.js"; export * from "./control-definition-input.js"; export * from "./control-definition-output.js"; export * from "./control-execution-event.js"; @@ -73,10 +77,12 @@ export * from "./login-response.js"; export * from "./pagination-info.js"; export * from "./patch-agent-request.js"; export * from "./patch-agent-response.js"; +export * from "./patch-control-binding-by-key-request.js"; export * from "./patch-control-binding-request.js"; export * from "./patch-control-binding-response.js"; export * from "./patch-control-request.js"; export * from "./patch-control-response.js"; +export * from "./policy-ref.js"; export * from "./regex-template-parameter.js"; export * from "./remove-agent-control-response.js"; export * from "./render-control-template-request.js"; @@ -95,6 +101,7 @@ export * from "./step-schema.js"; export * from "./step.js"; export * from "./string-list-template-parameter.js"; export * from "./string-template-parameter.js"; +export * from "./target-attachment-ref.js"; export * from "./template-control-input.js"; export * from "./template-definition-input.js"; export * from "./template-definition-output.js"; diff --git a/sdks/typescript/src/generated/models/operations/clone-and-bind-control-api-v1-controls-control-id-clone-and-bind-post.ts b/sdks/typescript/src/generated/models/operations/clone-and-bind-control-api-v1-controls-control-id-clone-and-bind-post.ts new file mode 100644 index 00000000..888f3adc --- /dev/null +++ b/sdks/typescript/src/generated/models/operations/clone-and-bind-control-api-v1-controls-control-id-clone-and-bind-post.ts @@ -0,0 +1,46 @@ +/* + * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. + */ + +import * as z from "zod/v4-mini"; +import { remap as remap$ } from "../../lib/primitives.js"; +import * as models from "../index.js"; + +export type CloneAndBindControlApiV1ControlsControlIdCloneAndBindPostRequest = { + controlId: number; + body: models.CloneAndBindControlRequest; +}; + +/** @internal */ +export type CloneAndBindControlApiV1ControlsControlIdCloneAndBindPostRequest$Outbound = + { + control_id: number; + body: models.CloneAndBindControlRequest$Outbound; + }; + +/** @internal */ +export const CloneAndBindControlApiV1ControlsControlIdCloneAndBindPostRequest$outboundSchema: + z.ZodMiniType< + CloneAndBindControlApiV1ControlsControlIdCloneAndBindPostRequest$Outbound, + CloneAndBindControlApiV1ControlsControlIdCloneAndBindPostRequest + > = z.pipe( + z.object({ + controlId: z.int(), + body: models.CloneAndBindControlRequest$outboundSchema, + }), + z.transform((v) => { + return remap$(v, { + controlId: "control_id", + }); + }), + ); + +export function cloneAndBindControlApiV1ControlsControlIdCloneAndBindPostRequestToJSON( + cloneAndBindControlApiV1ControlsControlIdCloneAndBindPostRequest: + CloneAndBindControlApiV1ControlsControlIdCloneAndBindPostRequest, +): string { + return JSON.stringify( + CloneAndBindControlApiV1ControlsControlIdCloneAndBindPostRequest$outboundSchema + .parse(cloneAndBindControlApiV1ControlsControlIdCloneAndBindPostRequest), + ); +} diff --git a/sdks/typescript/src/generated/models/operations/index.ts b/sdks/typescript/src/generated/models/operations/index.ts index 819659f8..b031df32 100644 --- a/sdks/typescript/src/generated/models/operations/index.ts +++ b/sdks/typescript/src/generated/models/operations/index.ts @@ -5,6 +5,7 @@ export * from "./add-agent-control-api-v1-agents-agent-name-controls-control-id-post.js"; export * from "./add-agent-policy-api-v1-agents-agent-name-policies-policy-id-post.js"; export * from "./add-control-to-policy-api-v1-policies-policy-id-controls-control-id-post.js"; +export * from "./clone-and-bind-control-api-v1-controls-control-id-clone-and-bind-post.js"; export * from "./delete-agent-policy-api-v1-agents-agent-name-policy-delete.js"; export * from "./delete-control-api-v1-controls-control-id-delete.js"; export * from "./delete-control-binding-api-v1-control-bindings-binding-id-delete.js"; diff --git a/sdks/typescript/src/generated/models/operations/list-controls-api-v1-controls-get.ts b/sdks/typescript/src/generated/models/operations/list-controls-api-v1-controls-get.ts index 7f19162e..dac0a4fd 100644 --- a/sdks/typescript/src/generated/models/operations/list-controls-api-v1-controls-get.ts +++ b/sdks/typescript/src/generated/models/operations/list-controls-api-v1-controls-get.ts @@ -23,6 +23,10 @@ export type ListControlsApiV1ControlsGetRequest = { * Filter by whether the control is template-backed */ templateBacked?: boolean | null | undefined; + /** + * Filter by whether the control was cloned from another control + */ + cloned?: boolean | null | undefined; /** * Filter by step type (built-ins: 'tool', 'llm') */ @@ -39,6 +43,18 @@ export type ListControlsApiV1ControlsGetRequest = { * Filter by tag */ tag?: string | null | undefined; + /** + * When true, include direct agent associations, policy associations, and target bindings for each listed control. + */ + includeAttachments?: boolean | undefined; + /** + * Optional target_type filter applied to the returned controls and expanded target bindings. Only used when include_attachments=true. + */ + attachmentTargetType?: string | null | undefined; + /** + * Optional target_id filter applied to the returned controls and expanded target bindings. Only used when include_attachments=true. + */ + attachmentTargetId?: string | null | undefined; }; /** @internal */ @@ -48,10 +64,14 @@ export type ListControlsApiV1ControlsGetRequest$Outbound = { name?: string | null | undefined; enabled?: boolean | null | undefined; template_backed?: boolean | null | undefined; + cloned?: boolean | null | undefined; step_type?: string | null | undefined; stage?: string | null | undefined; execution?: string | null | undefined; tag?: string | null | undefined; + include_attachments: boolean; + attachment_target_type?: string | null | undefined; + attachment_target_id?: string | null | undefined; }; /** @internal */ @@ -65,15 +85,22 @@ export const ListControlsApiV1ControlsGetRequest$outboundSchema: z.ZodMiniType< name: z.optional(z.nullable(z.string())), enabled: z.optional(z.nullable(z.boolean())), templateBacked: z.optional(z.nullable(z.boolean())), + cloned: z.optional(z.nullable(z.boolean())), stepType: z.optional(z.nullable(z.string())), stage: z.optional(z.nullable(z.string())), execution: z.optional(z.nullable(z.string())), tag: z.optional(z.nullable(z.string())), + includeAttachments: z._default(z.boolean(), false), + attachmentTargetType: z.optional(z.nullable(z.string())), + attachmentTargetId: z.optional(z.nullable(z.string())), }), z.transform((v) => { return remap$(v, { templateBacked: "template_backed", stepType: "step_type", + includeAttachments: "include_attachments", + attachmentTargetType: "attachment_target_type", + attachmentTargetId: "attachment_target_id", }); }), ); diff --git a/sdks/typescript/src/generated/models/patch-control-binding-by-key-request.ts b/sdks/typescript/src/generated/models/patch-control-binding-by-key-request.ts new file mode 100644 index 00000000..c66588d9 --- /dev/null +++ b/sdks/typescript/src/generated/models/patch-control-binding-by-key-request.ts @@ -0,0 +1,66 @@ +/* + * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. + */ + +import * as z from "zod/v4-mini"; +import { remap as remap$ } from "../lib/primitives.js"; + +/** + * Request to update an existing control binding by natural key. + */ +export type PatchControlBindingByKeyRequest = { + /** + * ID of the bound control. + */ + controlId: number; + /** + * New enabled value for the binding. + */ + enabled: boolean; + /** + * Opaque external identifier within the target_type. + */ + targetId: string; + /** + * Opaque attachment kind. + */ + targetType: string; +}; + +/** @internal */ +export type PatchControlBindingByKeyRequest$Outbound = { + control_id: number; + enabled: boolean; + target_id: string; + target_type: string; +}; + +/** @internal */ +export const PatchControlBindingByKeyRequest$outboundSchema: z.ZodMiniType< + PatchControlBindingByKeyRequest$Outbound, + PatchControlBindingByKeyRequest +> = z.pipe( + z.object({ + controlId: z.int(), + enabled: z.boolean(), + targetId: z.string(), + targetType: z.string(), + }), + z.transform((v) => { + return remap$(v, { + controlId: "control_id", + targetId: "target_id", + targetType: "target_type", + }); + }), +); + +export function patchControlBindingByKeyRequestToJSON( + patchControlBindingByKeyRequest: PatchControlBindingByKeyRequest, +): string { + return JSON.stringify( + PatchControlBindingByKeyRequest$outboundSchema.parse( + patchControlBindingByKeyRequest, + ), + ); +} diff --git a/sdks/typescript/src/generated/models/policy-ref.ts b/sdks/typescript/src/generated/models/policy-ref.ts new file mode 100644 index 00000000..ab6f9fbc --- /dev/null +++ b/sdks/typescript/src/generated/models/policy-ref.ts @@ -0,0 +1,43 @@ +/* + * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. + */ + +import * as z from "zod/v4-mini"; +import { remap as remap$ } from "../lib/primitives.js"; +import { safeParse } from "../lib/schemas.js"; +import { Result as SafeParseResult } from "../types/fp.js"; +import * as types from "../types/primitives.js"; +import { SDKValidationError } from "./errors/sdk-validation-error.js"; + +/** + * Reference to a policy attached to a control. + */ +export type PolicyRef = { + /** + * Policy ID + */ + policyId: number; +}; + +/** @internal */ +export const PolicyRef$inboundSchema: z.ZodMiniType = z + .pipe( + z.object({ + policy_id: types.number(), + }), + z.transform((v) => { + return remap$(v, { + "policy_id": "policyId", + }); + }), + ); + +export function policyRefFromJSON( + jsonString: string, +): SafeParseResult { + return safeParse( + jsonString, + (x) => PolicyRef$inboundSchema.parse(JSON.parse(x)), + `Failed to parse 'PolicyRef' from JSON`, + ); +} diff --git a/sdks/typescript/src/generated/models/target-attachment-ref.ts b/sdks/typescript/src/generated/models/target-attachment-ref.ts new file mode 100644 index 00000000..c1393dc5 --- /dev/null +++ b/sdks/typescript/src/generated/models/target-attachment-ref.ts @@ -0,0 +1,62 @@ +/* + * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. + */ + +import * as z from "zod/v4-mini"; +import { remap as remap$ } from "../lib/primitives.js"; +import { safeParse } from "../lib/schemas.js"; +import { Result as SafeParseResult } from "../types/fp.js"; +import * as types from "../types/primitives.js"; +import { SDKValidationError } from "./errors/sdk-validation-error.js"; + +/** + * Reference to a target binding attached to a control. + */ +export type TargetAttachmentRef = { + /** + * Control binding ID + */ + bindingId: number; + /** + * Whether this target binding is enabled + */ + enabled: boolean; + /** + * Opaque target identifier + */ + targetId: string; + /** + * Opaque target kind + */ + targetType: string; +}; + +/** @internal */ +export const TargetAttachmentRef$inboundSchema: z.ZodMiniType< + TargetAttachmentRef, + unknown +> = z.pipe( + z.object({ + binding_id: types.number(), + enabled: types.boolean(), + target_id: types.string(), + target_type: types.string(), + }), + z.transform((v) => { + return remap$(v, { + "binding_id": "bindingId", + "target_id": "targetId", + "target_type": "targetType", + }); + }), +); + +export function targetAttachmentRefFromJSON( + jsonString: string, +): SafeParseResult { + return safeParse( + jsonString, + (x) => TargetAttachmentRef$inboundSchema.parse(JSON.parse(x)), + `Failed to parse 'TargetAttachmentRef' from JSON`, + ); +} diff --git a/sdks/typescript/src/generated/sdk/control-bindings.ts b/sdks/typescript/src/generated/sdk/control-bindings.ts index 5a5bcf2b..a8708986 100644 --- a/sdks/typescript/src/generated/sdk/control-bindings.ts +++ b/sdks/typescript/src/generated/sdk/control-bindings.ts @@ -7,6 +7,7 @@ import { controlBindingsDeleteByKey } from "../funcs/control-bindings-delete-by- import { controlBindingsDelete } from "../funcs/control-bindings-delete.js"; import { controlBindingsGet } from "../funcs/control-bindings-get.js"; import { controlBindingsList } from "../funcs/control-bindings-list.js"; +import { controlBindingsUpdateByKey } from "../funcs/control-bindings-update-by-key.js"; import { controlBindingsUpdate } from "../funcs/control-bindings-update.js"; import { controlBindingsUpsertByKey } from "../funcs/control-bindings-upsert-by-key.js"; import { ClientSDK, RequestOptions } from "../lib/sdks.js"; @@ -58,6 +59,27 @@ export class ControlBindings extends ClientSDK { )); } + /** + * Update a control binding by natural key + * + * @remarks + * Update an existing binding using ``(target_type, target_id, control_id)``. + * + * This route is target-scoped because the request body includes the target + * identifiers before authorization runs. Unlike ``PUT /by-key``, it never + * creates a missing binding. + */ + async updateByKey( + request: models.PatchControlBindingByKeyRequest, + options?: RequestOptions, + ): Promise { + return unwrapAsync(controlBindingsUpdateByKey( + this, + request, + options, + )); + } + /** * Attach a control to a target by natural key (idempotent) * diff --git a/sdks/typescript/src/generated/sdk/controls.ts b/sdks/typescript/src/generated/sdk/controls.ts index ed3cf8db..1168463a 100644 --- a/sdks/typescript/src/generated/sdk/controls.ts +++ b/sdks/typescript/src/generated/sdk/controls.ts @@ -2,6 +2,7 @@ * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. */ +import { controlsCloneAndBindControl } from "../funcs/controls-clone-and-bind-control.js"; import { controlsCreate } from "../funcs/controls-create.js"; import { controlsDelete } from "../funcs/controls-delete.js"; import { controlsGetData } from "../funcs/controls-get-data.js"; @@ -51,10 +52,16 @@ export class Controls extends ClientSDK { * name: Optional filter by name (partial, case-insensitive match) * enabled: Optional filter by enabled status * template_backed: Optional filter by whether the control is template-backed + * cloned: Optional filter by whether the control was cloned from another control * step_type: Optional filter by step type (built-ins: 'tool', 'llm') * stage: Optional filter by stage ('pre' or 'post') * execution: Optional filter by execution ('server' or 'sdk') * tag: Optional filter by tag + * include_attachments: Whether to include attachment details for listed controls + * attachment_target_type: Optional target binding type filter for controls and + * attachments + * attachment_target_id: Optional target binding ID filter for controls and + * attachments * db: Database session (injected) * * Returns: @@ -239,6 +246,24 @@ export class Controls extends ClientSDK { )); } + /** + * Clone a control and bind the clone to a target + * + * @remarks + * Clone an active control and attach the clone to an opaque target. + */ + async cloneAndBindControl( + request: + operations.CloneAndBindControlApiV1ControlsControlIdCloneAndBindPostRequest, + options?: RequestOptions, + ): Promise { + return unwrapAsync(controlsCloneAndBindControl( + this, + request, + options, + )); + } + /** * Get control configuration data * diff --git a/server/alembic/versions/e2b7f4a9c6d1_control_clone_lineage.py b/server/alembic/versions/e2b7f4a9c6d1_control_clone_lineage.py new file mode 100644 index 00000000..c0a242b2 --- /dev/null +++ b/server/alembic/versions/e2b7f4a9c6d1_control_clone_lineage.py @@ -0,0 +1,53 @@ +"""control clone lineage + +Revision ID: e2b7f4a9c6d1 +Revises: b6f4c2d8e9a1 +Create Date: 2026-05-19 00:00:00.000000 + +""" + +from __future__ import annotations + +import sqlalchemy as sa +from alembic import op + +# revision identifiers, used by Alembic. +revision = "e2b7f4a9c6d1" +down_revision = "b6f4c2d8e9a1" +branch_labels = None +depends_on = None + + +def upgrade() -> None: + op.add_column( + "controls", + sa.Column("cloned_from_control_id", sa.Integer(), nullable=True), + ) + # No ON DELETE action: hard deletes of clone sources are restricted. + # The API soft-deletes controls so clone lineage remains intact. + op.create_foreign_key( + "controls_cloned_from_control_fkey", + "controls", + "controls", + ["namespace_key", "cloned_from_control_id"], + ["namespace_key", "id"], + ) + with op.get_context().autocommit_block(): + op.execute( + """ + CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_controls_cloned_from + ON controls (namespace_key, cloned_from_control_id) + WHERE cloned_from_control_id IS NOT NULL + """ + ) + + +def downgrade() -> None: + with op.get_context().autocommit_block(): + op.execute("DROP INDEX CONCURRENTLY IF EXISTS idx_controls_cloned_from") + op.drop_constraint( + "controls_cloned_from_control_fkey", + "controls", + type_="foreignkey", + ) + op.drop_column("controls", "cloned_from_control_id") diff --git a/server/src/agent_control_server/auth_framework/providers/http_upstream.py b/server/src/agent_control_server/auth_framework/providers/http_upstream.py index b68972ed..f6ce3b5f 100644 --- a/server/src/agent_control_server/auth_framework/providers/http_upstream.py +++ b/server/src/agent_control_server/auth_framework/providers/http_upstream.py @@ -33,7 +33,10 @@ "caller_id": "..." } -Statuses other than 200 / 401 / 403 / 404 / 5xx fail closed (503). +Statuses other than 200 / 401 / 403 / 404 / 429 fail closed. Unexpected +upstream 4xx responses are reported separately from Agent Control +misconfiguration so operators can distinguish upstream request rejection +from local auth setup failures. """ from __future__ import annotations @@ -280,6 +283,25 @@ def _handle_response( detail="Authorization service is rate-limiting requests.", hint=hint, ) + if 400 <= status < 500: + _logger.warning( + "Authorization upstream rejected operation %s with status %d", + operation.value, + status, + ) + raise APIError( + status_code=502, + error_code=ErrorCode.AUTH_UPSTREAM_REJECTED, + reason=ErrorReason.INTERNAL_ERROR, + detail=( + "Authorization service rejected the authorization check " + f"(status {status})." + ), + hint=( + "Check that the Agent Control authorization request shape " + "matches the upstream authorization service contract." + ), + ) # Fail closed on 5xx and unexpected statuses. _logger.warning( "Unexpected upstream status %d for operation %s", diff --git a/server/src/agent_control_server/endpoints/control_bindings.py b/server/src/agent_control_server/endpoints/control_bindings.py index 87386723..279328c4 100644 --- a/server/src/agent_control_server/endpoints/control_bindings.py +++ b/server/src/agent_control_server/endpoints/control_bindings.py @@ -14,6 +14,7 @@ GetControlBindingResponse, ListControlBindingsResponse, PaginationInfo, + PatchControlBindingByKeyRequest, PatchControlBindingRequest, PatchControlBindingResponse, UpsertControlBindingRequest, @@ -214,6 +215,40 @@ async def get_control_binding( return _to_response(binding) +@router.patch( + "/by-key", + response_model=PatchControlBindingResponse, + summary="Update a control binding by natural key", + response_description="Updated enabled flag", +) +async def patch_control_binding_by_key( + request: PatchControlBindingByKeyRequest, + db: AsyncSession = Depends(get_async_db), + principal: Principal = Depends( + require_operation( + Operation.CONTROL_BINDINGS_WRITE, + context_builder=_binding_body_context, + ) + ), +) -> PatchControlBindingResponse: + """Update an existing binding using ``(target_type, target_id, control_id)``. + + This route is target-scoped because the request body includes the target + identifiers before authorization runs. Unlike ``PUT /by-key``, it never + creates a missing binding. + """ + service = ControlBindingsService(db) + binding = await service.set_enabled_by_natural_key( + namespace_key=principal.namespace_key, + target_type=request.target_type, + target_id=request.target_id, + control_id=request.control_id, + enabled=request.enabled, + ) + await db.commit() + return PatchControlBindingResponse(success=True, enabled=binding.enabled) + + @router.patch( "/{binding_id}", response_model=PatchControlBindingResponse, diff --git a/server/src/agent_control_server/endpoints/controls.py b/server/src/agent_control_server/endpoints/controls.py index 6e6441e9..607fcd08 100644 --- a/server/src/agent_control_server/endpoints/controls.py +++ b/server/src/agent_control_server/endpoints/controls.py @@ -1,10 +1,16 @@ import datetime as dt +import uuid +from copy import deepcopy +from typing import Any from agent_control_engine import list_evaluators from agent_control_models import ControlDefinition, TemplateControlInput, UnrenderedTemplateControl from agent_control_models.errors import ErrorCode, ValidationErrorItem from agent_control_models.server import ( AgentRef, + CloneAndBindControlRequest, + CloneAndBindControlResponse, + ControlAttachments, ControlSummary, ControlVersionSummary, CreateControlRequest, @@ -19,26 +25,32 @@ PaginationInfo, PatchControlRequest, PatchControlResponse, + PolicyRef, RenderControlTemplateRequest, RenderControlTemplateResponse, SetControlDataRequest, SetControlDataResponse, + SlugName, + TargetAttachmentRef, ValidateControlDataRequest, ValidateControlDataResponse, ) -from fastapi import APIRouter, Depends, Query +from fastapi import APIRouter, Depends, Query, Request from jsonschema_rs import ValidationError as JSONSchemaValidationError -from pydantic import ValidationError +from pydantic import TypeAdapter, ValidationError from sqlalchemy import select from sqlalchemy.exc import IntegrityError from sqlalchemy.ext.asyncio import AsyncSession -from ..auth_framework import Operation, Principal, require_operation +from ..auth_framework import Operation, Principal, get_authorizer, require_operation from ..db import get_async_db from ..errors import ( + APIError, APIValidationError, + AuthenticationError, ConflictError, DatabaseError, + ForbiddenError, NotFoundError, ) from ..logging_utils import get_logger @@ -77,6 +89,168 @@ "idx_controls_name_active", "idx_controls_namespace_name_active", } +_MAX_TARGET_CONTEXT_VALUE_LENGTH = 255 +_CLONE_NAME_SUFFIX_HEX_LENGTH = 16 +_GENERATED_CLONE_NAME_ATTEMPTS = 5 +_TRUE_QUERY_VALUES = {"1", "true", "t", "yes", "y", "on"} +_SLUG_NAME_ADAPTER = TypeAdapter(SlugName) + + +def _is_target_context_value(value: object) -> bool: + return ( + isinstance(value, str) + and bool(value) + and len(value) <= _MAX_TARGET_CONTEXT_VALUE_LENGTH + ) + + +def _ensure_same_namespace_authorization( + *principals: Principal, + detail: str = "Authorization resolved to different namespaces.", + hint: str = "Use credentials that grant the required operations in the same namespace.", +) -> None: + namespace_keys = {principal.namespace_key for principal in principals} + if len(namespace_keys) == 1: + return + raise ForbiddenError( + error_code=ErrorCode.AUTH_INSUFFICIENT_PRIVILEGES, + detail=detail, + resource="ControlBinding", + hint=hint, + ) + + +async def _clone_and_bind_context(request: Request) -> dict[str, Any]: + """Surface clone target identifiers to the authorization context.""" + try: + body = await request.json() + except Exception: # noqa: BLE001 malformed JSON falls through to endpoint validation + return {} + if not isinstance(body, dict): + return {} + target_binding = body.get("target_binding") + if not isinstance(target_binding, dict): + return {} + target_type = target_binding.get("target_type") + target_id = target_binding.get("target_id") + if not _is_target_context_value(target_type): + return {} + if not _is_target_context_value(target_id): + return {} + return { + "target_type": target_type, + "target_id": target_id, + } + + +def _attachment_target_context(request: Request) -> dict[str, str]: + context: dict[str, str] = {} + target_type = request.query_params.get("attachment_target_type") + target_id = request.query_params.get("attachment_target_id") + if target_type is not None: + if not _is_target_context_value(target_type): + return {} + context["target_type"] = target_type + if target_id is not None: + if not _is_target_context_value(target_id): + return {} + context["target_id"] = target_id + return context + + +async def _optional_attachment_target_principal(request: Request) -> Principal | None: + include_attachments = request.query_params.get("include_attachments") + if include_attachments is None: + return None + if include_attachments.lower() not in _TRUE_QUERY_VALUES: + return None + target_context = _attachment_target_context(request) + try: + return await get_authorizer(Operation.CONTROL_BINDINGS_READ).authorize( + request, + Operation.CONTROL_BINDINGS_READ, + target_context, + ) + except (AuthenticationError, ForbiddenError, NotFoundError): + if target_context: + raise + return None + + +def _generated_clone_name(source_id: int, source_name: str) -> str: + """Return a slug-safe default name for a cloned control.""" + suffix = f"-clone-{uuid.uuid4().hex[:_CLONE_NAME_SUFFIX_HEX_LENGTH]}" + candidate = f"{source_name[: 255 - len(suffix)]}{suffix}" + try: + return _SLUG_NAME_ADAPTER.validate_python(candidate) + except ValidationError: + return _SLUG_NAME_ADAPTER.validate_python(f"control-{source_id}{suffix}") + + +async def _resolve_clone_name( + control_service: ControlService, + *, + namespace_key: str, + source_id: int, + source_name: str, + requested_name: str | None, +) -> str: + if requested_name is not None: + if await control_service.active_control_name_exists( + requested_name, namespace_key=namespace_key + ): + raise ConflictError( + error_code=ErrorCode.CONTROL_NAME_CONFLICT, + detail=f"Control with name '{requested_name}' already exists", + resource="Control", + resource_id=requested_name, + hint="Choose a different clone name.", + ) + return requested_name + + for _ in range(_GENERATED_CLONE_NAME_ATTEMPTS): + clone_name = _generated_clone_name(source_id, source_name) + if not await control_service.active_control_name_exists( + clone_name, namespace_key=namespace_key + ): + return clone_name + + raise ConflictError( + error_code=ErrorCode.CONTROL_NAME_CONFLICT, + detail="Could not generate a unique clone name.", + resource="Control", + resource_id=source_name, + hint="Retry the request or provide an explicit clone name.", + ) + + +def _validate_attachment_filters( + *, + include_attachments: bool, + attachment_target_type: str | None, + attachment_target_id: str | None, +) -> None: + if include_attachments: + return + if attachment_target_type is None and attachment_target_id is None: + return + raise APIValidationError( + error_code=ErrorCode.VALIDATION_ERROR, + detail="Attachment target filters require include_attachments=true.", + resource="Control", + hint="Set include_attachments=true or remove attachment target filters.", + errors=[ + ValidationErrorItem( + resource="Control", + field="include_attachments", + code="missing_required_parameter", + message=( + "Set include_attachments=true when using attachment_target_type " + "or attachment_target_id." + ), + ) + ], + ) def _serialize_control_data( @@ -576,6 +750,118 @@ async def create_control( return CreateControlResponse(control_id=control.id) +@router.post( + "/{control_id}/clone-and-bind", + response_model=CloneAndBindControlResponse, + summary="Clone a control and bind the clone to a target", + response_description="Created clone and binding identifiers", +) +async def clone_and_bind_control( + control_id: int, + request: CloneAndBindControlRequest, + db: AsyncSession = Depends(get_async_db), + principal: Principal = Depends(require_operation(Operation.CONTROLS_CREATE)), + read_principal: Principal = Depends(require_operation(Operation.CONTROLS_READ)), + binding_principal: Principal = Depends( + require_operation( + Operation.CONTROL_BINDINGS_WRITE, + context_builder=_clone_and_bind_context, + ) + ), +) -> CloneAndBindControlResponse: + """Clone an active control and attach the clone to an opaque target.""" + _ensure_same_namespace_authorization( + principal, + read_principal, + binding_principal, + detail="Clone authorization resolved to different namespaces.", + hint=( + "Use credentials that grant source read, control creation, and target " + "binding in the same namespace." + ), + ) + + namespace_key = principal.namespace_key + control_service = ControlService(db) + bindings_service = ControlBindingsService(db) + + source = await control_service.get_active_control_or_404( + control_id, + namespace_key=namespace_key, + for_update=True, + ) + clone_name = await _resolve_clone_name( + control_service, + namespace_key=namespace_key, + source_id=source.id, + source_name=source.name, + requested_name=request.name, + ) + + clone = control_service.create_control( + namespace_key=namespace_key, + name=clone_name, + data=deepcopy(source.data), + cloned_from_control_id=source.id, + ) + try: + await control_service.create_version( + clone, + event_type="cloned", + note=f"Cloned from control {source.id}", + ) + binding = await bindings_service.create_binding( + namespace_key=namespace_key, + target_type=request.target_binding.target_type, + target_id=request.target_binding.target_id, + control_id=clone.id, + enabled=request.target_binding.enabled, + ) + await db.commit() + except APIError: + await db.rollback() + raise + except IntegrityError as exc: + await db.rollback() + if _is_control_name_conflict(exc): + raise ConflictError( + error_code=ErrorCode.CONTROL_NAME_CONFLICT, + detail=f"Control with name '{clone_name}' already exists", + resource="Control", + resource_id=clone_name, + hint="Choose a different clone name.", + ) + _logger.error( + "Failed to clone control '%s' due to integrity error", + source.name, + exc_info=True, + ) + raise DatabaseError( + detail=f"Failed to clone control '{source.id}': database error", + resource="Control", + operation="clone_and_bind", + ) + except Exception: + await db.rollback() + _logger.error( + "Failed to clone and bind control '%s'", + source.name, + exc_info=True, + ) + raise DatabaseError( + detail=f"Failed to clone control '{source.id}': database error", + resource="Control", + operation="clone_and_bind", + ) + + return CloneAndBindControlResponse( + id=clone.id, + name=clone.name, + cloned_from_control_id=source.id, + binding_id=binding.id, + ) + + @router.get( "/schema", response_model=GetControlSchemaResponse, @@ -626,6 +912,7 @@ async def get_control( return GetControlResponse( id=control.id, name=control.name, + cloned_from_control_id=control.cloned_from_control_id, data=control_data, ) @@ -852,14 +1139,46 @@ async def list_controls( None, description="Filter by whether the control is template-backed", ), + cloned: bool | None = Query( + None, + description="Filter by whether the control was cloned from another control", + ), step_type: str | None = Query( None, description="Filter by step type (built-ins: 'tool', 'llm')" ), stage: str | None = Query(None, description="Filter by stage ('pre' or 'post')"), execution: str | None = Query(None, description="Filter by execution ('server' or 'sdk')"), tag: str | None = Query(None, description="Filter by tag"), + include_attachments: bool = Query( + False, + description=( + "When true, include direct agent associations, policy associations, " + "and target bindings for each listed control." + ), + ), + attachment_target_type: str | None = Query( + None, + min_length=1, + max_length=255, + description=( + "Optional target_type filter applied to the returned controls and " + "expanded target bindings. " + "Only used when include_attachments=true." + ), + ), + attachment_target_id: str | None = Query( + None, + min_length=1, + max_length=255, + description=( + "Optional target_id filter applied to the returned controls and " + "expanded target bindings. " + "Only used when include_attachments=true." + ), + ), db: AsyncSession = Depends(get_async_db), principal: Principal = Depends(require_operation(Operation.CONTROLS_READ)), + target_principal: Principal | None = Depends(_optional_attachment_target_principal), ) -> ListControlsResponse: """ List all controls with optional filtering and cursor-based pagination. @@ -872,10 +1191,16 @@ async def list_controls( name: Optional filter by name (partial, case-insensitive match) enabled: Optional filter by enabled status template_backed: Optional filter by whether the control is template-backed + cloned: Optional filter by whether the control was cloned from another control step_type: Optional filter by step type (built-ins: 'tool', 'llm') stage: Optional filter by stage ('pre' or 'post') execution: Optional filter by execution ('server' or 'sdk') tag: Optional filter by tag + include_attachments: Whether to include attachment details for listed controls + attachment_target_type: Optional target binding type filter for controls and + attachments + attachment_target_id: Optional target binding ID filter for controls and + attachments db: Database session (injected) Returns: @@ -884,8 +1209,30 @@ async def list_controls( Example: GET /controls?limit=10&enabled=true&step_type=tool """ + _validate_attachment_filters( + include_attachments=include_attachments, + attachment_target_type=attachment_target_type, + attachment_target_id=attachment_target_id, + ) + if target_principal is not None: + _ensure_same_namespace_authorization( + principal, + target_principal, + detail=( + "Control and target-binding read authorization resolved " + "to different namespaces." + ), + hint=( + "Use credentials that grant control read and target-binding read " + "in the same namespace." + ), + ) + control_service = ControlService(db) namespace_key = principal.namespace_key + filter_by_attachment = target_principal is not None and ( + attachment_target_type is not None or attachment_target_id is not None + ) page = await control_service.list_controls_page( namespace_key=namespace_key, cursor=cursor, @@ -893,15 +1240,29 @@ async def list_controls( name=name, enabled=enabled, template_backed=template_backed, + cloned=cloned, step_type=step_type, stage=stage, execution=execution, tag=tag, + attachment_target_type=attachment_target_type if filter_by_attachment else None, + attachment_target_id=attachment_target_id if filter_by_attachment else None, ) usage_by_control_id = await control_service.list_control_usage( [control.id for control in page.controls], namespace_key=namespace_key, ) + attachments_by_control_id = ( + await control_service.list_control_attachments( + [control.id for control in page.controls], + namespace_key=namespace_key, + target_type=attachment_target_type, + target_id=attachment_target_id, + include_targets=target_principal is not None, + ) + if include_attachments + else {} + ) # Build summaries (filtering already done at DB level) summaries: list[ControlSummary] = [] @@ -910,16 +1271,19 @@ async def list_controls( data = ctrl.data or {} scope = data.get("scope") or {} usage = usage_by_control_id.get(ctrl.id) + attachments = attachments_by_control_id.get(ctrl.id) summaries.append( ControlSummary( id=ctrl.id, name=ctrl.name, + cloned_from_control_id=ctrl.cloned_from_control_id, description=( data.get("description") or (data.get("template") or {}).get("description") ), enabled=data.get("enabled", True), execution=data.get("execution"), + action=data.get("action"), step_types=scope.get("step_types"), stages=scope.get("stages"), tags=data.get("tags", []), @@ -933,6 +1297,31 @@ async def list_controls( else None ), used_by_agents_count=usage.used_by_agents_count if usage is not None else 0, + attachments=( + ControlAttachments( + agents=[ + AgentRef(agent_name=agent_name) + for agent_name in attachments.agent_names + ], + policies=[ + PolicyRef(policy_id=policy_id) + for policy_id in attachments.policy_ids + ], + targets=[ + TargetAttachmentRef( + binding_id=target.binding_id, + target_type=target.target_type, + target_id=target.target_id, + enabled=target.enabled, + ) + for target in attachments.targets + ], + targets_total=attachments.targets_total, + targets_truncated=attachments.targets_truncated, + ) + if attachments is not None + else None + ), ) ) diff --git a/server/src/agent_control_server/models.py b/server/src/agent_control_server/models.py index cad73c23..c31ccddf 100644 --- a/server/src/agent_control_server/models.py +++ b/server/src/agent_control_server/models.py @@ -157,6 +157,13 @@ class Control(Base): UniqueConstraint( "namespace_key", "id", name="uq_controls_namespace_id" ), + # Hard deletes of clone sources are restricted. The request path + # soft-deletes controls so clone lineage remains intact. + ForeignKeyConstraint( + ["namespace_key", "cloned_from_control_id"], + ["controls.namespace_key", "controls.id"], + name="controls_cloned_from_control_fkey", + ), # Plain partial index on name preserves name-only lookup performance # while service code is still namespace-blind. Mirrors the pattern # used for agents and policies; the partial filter matches the @@ -167,6 +174,13 @@ class Control(Base): postgresql_where=text("deleted_at IS NULL"), sqlite_where=text("deleted_at IS NULL"), ), + Index( + "idx_controls_cloned_from", + "namespace_key", + "cloned_from_control_id", + postgresql_where=text("cloned_from_control_id IS NOT NULL"), + sqlite_where=text("cloned_from_control_id IS NOT NULL"), + ), ) id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True) @@ -178,6 +192,9 @@ class Control(Base): data: Mapped[dict[str, Any]] = mapped_column( JSONB, server_default=text("'{}'::jsonb"), nullable=False ) + cloned_from_control_id: Mapped[int | None] = mapped_column( + Integer, nullable=True + ) deleted_at: Mapped[dt.datetime | None] = mapped_column( DateTime(timezone=True), nullable=True ) diff --git a/server/src/agent_control_server/services/control_bindings.py b/server/src/agent_control_server/services/control_bindings.py index 6f00e5d7..f6b04d44 100644 --- a/server/src/agent_control_server/services/control_bindings.py +++ b/server/src/agent_control_server/services/control_bindings.py @@ -173,6 +173,45 @@ async def delete_by_natural_key( await self._db.flush() return True + async def set_enabled_by_natural_key( + self, + *, + namespace_key: str, + target_type: str, + target_id: str, + control_id: int, + enabled: bool, + ) -> ControlBinding: + """Update an existing binding by natural key. + + Unlike ``upsert_by_natural_key``, this never creates a binding. + It is intended for target-scoped callers that need to toggle an + already-attached control while preserving a clear 404 for missing + attachments. + """ + existing = await self._find_by_natural_key( + namespace_key=namespace_key, + target_type=target_type, + target_id=target_id, + control_id=control_id, + ) + if existing is None: + raise NotFoundError( + error_code=ErrorCode.CONTROL_BINDING_NOT_FOUND, + detail=( + "Control binding not found for the supplied " + "(target_type, target_id, control_id)." + ), + resource="ControlBinding", + hint=( + "Verify the target and control IDs, or attach the control " + "before updating the binding." + ), + ) + existing.enabled = enabled + await self._db.flush() + return existing + async def _find_by_natural_key( self, *, diff --git a/server/src/agent_control_server/services/controls.py b/server/src/agent_control_server/services/controls.py index 6c015310..293fc130 100644 --- a/server/src/agent_control_server/services/controls.py +++ b/server/src/agent_control_server/services/controls.py @@ -13,7 +13,7 @@ from agent_control_models.errors import ErrorCode, ValidationErrorItem from agent_control_models.policy import Control as APIControl from pydantic import ValidationError -from sqlalchemy import Integer, String, delete, func, literal, or_, select, union, union_all +from sqlalchemy import Integer, String, delete, exists, func, literal, or_, select, union, union_all from sqlalchemy.dialects.postgresql import insert as pg_insert from sqlalchemy.ext.asyncio import AsyncSession from sqlalchemy.sql import Select @@ -36,6 +36,8 @@ type AgentControlRenderedState = Literal["rendered", "unrendered", "all"] type AgentControlEnabledState = Literal["enabled", "disabled", "all"] +_MAX_INLINE_TARGET_ATTACHMENTS_PER_CONTROL = 20 + @dataclass(frozen=True) class RuntimeControl: @@ -74,6 +76,27 @@ class ControlUsage: used_by_agents_count: int +@dataclass(frozen=True) +class ControlTargetAttachment: + """Target binding attached to a control.""" + + binding_id: int + target_type: str + target_id: str + enabled: bool + + +@dataclass(frozen=True) +class ControlAttachmentSet: + """Direct attachments for a listed control.""" + + policy_ids: list[int] + agent_names: list[str] + targets: list[ControlTargetAttachment] + targets_total: int + targets_truncated: bool + + @dataclass(frozen=True) class ControlAssociations: """Policy and agent associations for a control.""" @@ -102,9 +125,15 @@ def create_control( namespace_key: str, name: str, data: dict[str, Any], + cloned_from_control_id: int | None = None, ) -> Control: """Create a new pending control row.""" - control = Control(namespace_key=namespace_key, name=name, data=data) + control = Control( + namespace_key=namespace_key, + name=name, + data=data, + cloned_from_control_id=cloned_from_control_id, + ) self._db.add(control) return control @@ -427,10 +456,13 @@ async def list_controls_page( name: str | None, enabled: bool | None, template_backed: bool | None, + cloned: bool | None, step_type: str | None, stage: str | None, execution: str | None, tag: str | None, + attachment_target_type: str | None = None, + attachment_target_id: str | None = None, ) -> ControlListPage: """Return paginated active controls for the browse endpoint.""" query = ( @@ -443,11 +475,18 @@ async def list_controls_page( name=name, enabled=enabled, template_backed=template_backed, + cloned=cloned, step_type=step_type, stage=stage, execution=execution, tag=tag, ) + query = self._apply_control_attachment_filters( + query, + namespace_key=namespace_key, + target_type=attachment_target_type, + target_id=attachment_target_id, + ) if cursor is not None: query = query.where(Control.id < cursor) @@ -464,11 +503,18 @@ async def list_controls_page( name=name, enabled=enabled, template_backed=template_backed, + cloned=cloned, step_type=step_type, stage=stage, execution=execution, tag=tag, ) + total_query = self._apply_control_attachment_filters( + total_query, + namespace_key=namespace_key, + target_type=attachment_target_type, + target_id=attachment_target_id, + ) total_result = await self._db.execute(total_query) total = cast(int, total_result.scalar_one()) @@ -535,6 +581,129 @@ async def list_control_usage( for control_id, agent_names in usage_names.items() } + async def list_control_attachments( + self, + control_ids: Sequence[int], + *, + namespace_key: str, + target_type: str | None = None, + target_id: str | None = None, + include_targets: bool = True, + ) -> dict[int, ControlAttachmentSet]: + """Return direct policy, direct agent, and target attachments for controls.""" + if not control_ids: + return {} + + unique_control_ids = list(dict.fromkeys(control_ids)) + policy_ids_by_control: dict[int, set[int]] = { + control_id: set() for control_id in unique_control_ids + } + agent_names_by_control: dict[int, set[str]] = { + control_id: set() for control_id in unique_control_ids + } + targets_by_control: dict[int, list[ControlTargetAttachment]] = { + control_id: [] for control_id in unique_control_ids + } + target_totals_by_control: dict[int, int] = { + control_id: 0 for control_id in unique_control_ids + } + + policy_result = await self._db.execute( + select(policy_controls.c.control_id, policy_controls.c.policy_id).where( + policy_controls.c.namespace_key == namespace_key, + policy_controls.c.control_id.in_(unique_control_ids), + ) + ) + for control_id, policy_id in policy_result.all(): + policy_ids_by_control[cast(int, control_id)].add(cast(int, policy_id)) + + agent_result = await self._db.execute( + select(agent_controls.c.control_id, agent_controls.c.agent_name).where( + agent_controls.c.namespace_key == namespace_key, + agent_controls.c.control_id.in_(unique_control_ids), + ) + ) + for control_id, agent_name in agent_result.all(): + agent_names_by_control[cast(int, control_id)].add(cast(str, agent_name)) + + if include_targets: + target_rank = func.row_number().over( + partition_by=ControlBinding.control_id, + order_by=ControlBinding.id.desc(), + ).label("target_rank") + target_total = func.count().over( + partition_by=ControlBinding.control_id + ).label("target_total") + target_query = ( + select( + ControlBinding.control_id, + ControlBinding.id, + ControlBinding.target_type, + ControlBinding.target_id, + ControlBinding.enabled, + target_rank, + target_total, + ) + .where( + ControlBinding.namespace_key == namespace_key, + ControlBinding.control_id.in_(unique_control_ids), + ) + ) + if target_type is not None: + target_query = target_query.where(ControlBinding.target_type == target_type) + if target_id is not None: + target_query = target_query.where(ControlBinding.target_id == target_id) + target_rows = target_query.subquery() + target_result = await self._db.execute( + select( + target_rows.c.control_id, + target_rows.c.id, + target_rows.c.target_type, + target_rows.c.target_id, + target_rows.c.enabled, + target_rows.c.target_total, + ) + .where( + target_rows.c.target_rank + <= _MAX_INLINE_TARGET_ATTACHMENTS_PER_CONTROL + ) + .order_by(target_rows.c.control_id, target_rows.c.target_rank) + ) + for ( + control_id, + binding_id, + binding_target_type, + binding_target_id, + enabled, + target_total, + ) in ( + target_result.all() + ): + typed_control_id = cast(int, control_id) + target_totals_by_control[typed_control_id] = cast(int, target_total) + targets_by_control[typed_control_id].append( + ControlTargetAttachment( + binding_id=cast(int, binding_id), + target_type=cast(str, binding_target_type), + target_id=cast(str, binding_target_id), + enabled=cast(bool, enabled), + ) + ) + + return { + control_id: ControlAttachmentSet( + policy_ids=sorted(policy_ids_by_control[control_id]), + agent_names=sorted(agent_names_by_control[control_id]), + targets=targets_by_control[control_id], + targets_total=target_totals_by_control[control_id], + targets_truncated=( + target_totals_by_control[control_id] + > len(targets_by_control[control_id]) + ), + ) + for control_id in unique_control_ids + } + async def list_active_control_counts_by_agent( self, agent_names: Sequence[str], @@ -820,6 +989,7 @@ def _apply_control_list_filters( name: str | None, enabled: bool | None, template_backed: bool | None, + cloned: bool | None, step_type: str | None, stage: str | None, execution: str | None, @@ -846,6 +1016,12 @@ def _apply_control_list_filters( else: stmt = stmt.where(~Control.data.has_key("template")) + if cloned is not None: + if cloned: + stmt = stmt.where(Control.cloned_from_control_id.is_not(None)) + else: + stmt = stmt.where(Control.cloned_from_control_id.is_(None)) + has_rendered_filter = any(f is not None for f in (step_type, stage, execution, tag)) if has_rendered_filter: stmt = stmt.where(Control.data.has_key("condition")) @@ -873,16 +1049,42 @@ def _apply_control_list_filters( return stmt + def _apply_control_attachment_filters( + self, + stmt: Select[Any], + *, + namespace_key: str, + target_type: str | None, + target_id: str | None, + ) -> Select[Any]: + """Restrict a control list to controls with matching target bindings.""" + if target_type is None and target_id is None: + return stmt + + binding_exists = exists().where( + ControlBinding.namespace_key == namespace_key, + ControlBinding.control_id == Control.id, + ) + if target_type is not None: + binding_exists = binding_exists.where(ControlBinding.target_type == target_type) + if target_id is not None: + binding_exists = binding_exists.where(ControlBinding.target_id == target_id) + return stmt.where(binding_exists) + @staticmethod def _build_snapshot(control: Control) -> dict[str, Any]: """Serialize the persisted control state stored in version history.""" deleted_at = control.deleted_at.isoformat() if control.deleted_at is not None else None - cloned_control_id = cast(int | None, getattr(control, "cloned_control_id", None)) + cloned_from_control_id = cast( + int | None, getattr(control, "cloned_from_control_id", None) + ) return { "name": control.name, "data": control.data, "deleted_at": deleted_at, - "cloned_control_id": cloned_control_id, + "cloned_from_control_id": cloned_from_control_id, + # Legacy snapshot alias; remove after consumers have migrated. + "cloned_control_id": cloned_from_control_id, } diff --git a/server/tests/test_auth_framework.py b/server/tests/test_auth_framework.py index a95f0252..5f31c52f 100644 --- a/server/tests/test_auth_framework.py +++ b/server/tests/test_auth_framework.py @@ -386,6 +386,19 @@ async def test_http_upstream_fails_closed_on_5xx(): assert "500" in exc_info.value.detail +@pytest.mark.asyncio +@pytest.mark.parametrize("status", [400, 422]) +async def test_http_upstream_unexpected_4xx_reports_upstream_rejection(status): + provider = _build_upstream(lambda req: httpx.Response(status, text="bad request")) + + with pytest.raises(APIError) as exc_info: + await provider.authorize(_build_request(), Operation.CONTROL_BINDINGS_WRITE) + + assert exc_info.value.status_code == 502 + assert exc_info.value.error_code == "AUTH_UPSTREAM_REJECTED" + assert str(status) in exc_info.value.detail + + @pytest.mark.asyncio async def test_http_upstream_surfaces_rate_limit_distinctly(): """Upstream 429 must surface a rate-limit-specific detail and hint.""" diff --git a/server/tests/test_control_bindings_endpoints.py b/server/tests/test_control_bindings_endpoints.py index 6cdebf7e..8333bb95 100644 --- a/server/tests/test_control_bindings_endpoints.py +++ b/server/tests/test_control_bindings_endpoints.py @@ -5,11 +5,12 @@ import uuid from typing import Any +from agent_control_server.auth_framework import Operation, Principal, set_authorizer +from agent_control_server.models import DEFAULT_NAMESPACE_KEY from fastapi.testclient import TestClient from .utils import VALID_CONTROL_PAYLOAD - _BINDINGS_URL = "/api/v1/control-bindings" @@ -318,6 +319,83 @@ def test_upsert_by_key_updates_updated_at_on_existing_row( assert after_upsert["updated_at"] != initial_updated_at +def test_patch_by_key_updates_existing_binding(client: TestClient) -> None: + control_id = _create_control(client) + binding_id = _create_binding(client, control_id=control_id)["binding_id"] + body = { + "target_type": "env", + "target_id": "prod", + "control_id": control_id, + "enabled": False, + } + + resp = client.patch(f"{_BINDINGS_URL}/by-key", json=body) + + assert resp.status_code == 200, resp.text + assert resp.json() == {"success": True, "enabled": False} + fetched = client.get(f"{_BINDINGS_URL}/{binding_id}").json() + assert fetched["enabled"] is False + + +def test_patch_by_key_returns_404_without_creating_binding(client: TestClient) -> None: + control_id = _create_control(client) + body = { + "target_type": "env", + "target_id": "prod", + "control_id": control_id, + "enabled": False, + } + + resp = client.patch(f"{_BINDINGS_URL}/by-key", json=body) + + assert resp.status_code == 404 + assert resp.json()["error_code"] == "CONTROL_BINDING_NOT_FOUND" + bindings = client.get( + _BINDINGS_URL, + params={"target_type": "env", "target_id": "prod", "control_id": control_id}, + ).json()["bindings"] + assert bindings == [] + + +def test_patch_by_key_passes_target_context_to_authorizer( + client: TestClient, +) -> None: + control_id = _create_control(client) + _create_binding(client, control_id=control_id) + calls: list[tuple[Operation, dict[str, Any] | None]] = [] + + class RecordingAuthorizer: + async def authorize( + self, + request: Any, + operation: Operation, + context: dict[str, Any] | None = None, + ) -> Principal: + del request + calls.append((operation, context)) + return Principal(namespace_key=DEFAULT_NAMESPACE_KEY, is_admin=True) + + set_authorizer(RecordingAuthorizer()) + + resp = client.patch( + f"{_BINDINGS_URL}/by-key", + json={ + "target_type": "env", + "target_id": "prod", + "control_id": control_id, + "enabled": False, + }, + ) + + assert resp.status_code == 200, resp.text + assert calls == [ + ( + Operation.CONTROL_BINDINGS_WRITE, + {"target_type": "env", "target_id": "prod"}, + ) + ] + + def test_delete_by_key_removes_existing_binding(client: TestClient) -> None: control_id = _create_control(client) client.put( @@ -366,6 +444,11 @@ def test_non_admin_cannot_use_by_key_endpoints( upsert_resp = non_admin_client.put(f"{_BINDINGS_URL}/by-key", json=body) assert upsert_resp.status_code == 403 + patch_resp = non_admin_client.patch( + f"{_BINDINGS_URL}/by-key", json={**body, "enabled": False} + ) + assert patch_resp.status_code == 403 + delete_resp = non_admin_client.post( f"{_BINDINGS_URL}/by-key:delete", json=body ) diff --git a/server/tests/test_control_versions.py b/server/tests/test_control_versions.py index f387a1f6..2af4fed2 100644 --- a/server/tests/test_control_versions.py +++ b/server/tests/test_control_versions.py @@ -53,6 +53,7 @@ def test_create_control_creates_initial_version_row(client: TestClient) -> None: assert version.snapshot["name"] == control_name assert version.snapshot["data"]["description"] == VALID_CONTROL_PAYLOAD["description"] assert version.snapshot["deleted_at"] is None + assert version.snapshot["cloned_from_control_id"] is None assert version.snapshot["cloned_control_id"] is None diff --git a/server/tests/test_controls_additional.py b/server/tests/test_controls_additional.py index dfbb15f5..5d1277c3 100644 --- a/server/tests/test_controls_additional.py +++ b/server/tests/test_controls_additional.py @@ -5,22 +5,30 @@ from collections.abc import AsyncGenerator from copy import deepcopy from types import SimpleNamespace +from typing import Any from unittest.mock import AsyncMock, MagicMock import pytest from agent_control_evaluators import RegexEvaluatorConfig from agent_control_models import ConditionNode +from agent_control_models.errors import ErrorCode from fastapi.testclient import TestClient -from sqlalchemy import text +from sqlalchemy import select, text from sqlalchemy.exc import IntegrityError from sqlalchemy.ext.asyncio import AsyncSession from sqlalchemy.orm import Session -from agent_control_server.auth_framework import Principal +from agent_control_server.auth_framework import Operation, Principal, set_authorizer from agent_control_server.db import get_async_db from agent_control_server.endpoints import controls as controls_module +from agent_control_server.errors import BadRequestError, ForbiddenError from agent_control_server.main import app -from agent_control_server.models import DEFAULT_NAMESPACE_KEY, Control +from agent_control_server.models import ( + DEFAULT_NAMESPACE_KEY, + Control, + ControlBinding, + ControlVersion, +) from .conftest import engine from .utils import VALID_CONTROL_PAYLOAD @@ -60,6 +68,503 @@ def _set_control_data(client: TestClient, control_id: int, data: dict) -> None: assert resp.status_code == 200, resp.text +def test_clone_and_bind_creates_cloned_control_binding_and_version( + client: TestClient, +) -> None: + source_id, source_name = _create_control(client) + + resp = client.post( + f"/api/v1/controls/{source_id}/clone-and-bind", + json={ + "target_binding": { + "target_type": "log_stream", + "target_id": "logstream-123", + "enabled": False, + } + }, + ) + + assert resp.status_code == 200, resp.text + body = resp.json() + clone_id = body["id"] + binding_id = body["binding_id"] + assert clone_id != source_id + assert body["name"].startswith(f"{source_name}-clone-") + assert body["cloned_from_control_id"] == source_id + + with Session(engine) as session: + source = session.get_one(Control, source_id) + clone = session.get_one(Control, clone_id) + binding = session.execute( + select(ControlBinding).where(ControlBinding.id == binding_id) + ).scalar_one() + version = session.execute( + select(ControlVersion).where(ControlVersion.control_id == clone_id) + ).scalar_one() + + assert clone.namespace_key == source.namespace_key + assert clone.data == source.data + assert clone.cloned_from_control_id == source_id + assert binding.control_id == clone_id + assert binding.target_type == "log_stream" + assert binding.target_id == "logstream-123" + assert binding.enabled is False + assert version.version_num == 1 + assert version.event_type == "cloned" + assert version.note == f"Cloned from control {source_id}" + assert version.snapshot["cloned_from_control_id"] == source_id + assert version.snapshot["cloned_control_id"] == source_id + + get_resp = client.get(f"/api/v1/controls/{clone_id}") + assert get_resp.status_code == 200 + assert get_resp.json()["cloned_from_control_id"] == source_id + + +def test_control_clone_lineage_enforces_same_namespace() -> None: + source = Control( + namespace_key=DEFAULT_NAMESPACE_KEY, + name=f"source-{uuid.uuid4()}", + data=deepcopy(VALID_CONTROL_PAYLOAD), + ) + clone = Control( + namespace_key="other-namespace", + name=f"clone-{uuid.uuid4()}", + data=deepcopy(VALID_CONTROL_PAYLOAD), + cloned_from_control_id=1, + ) + + with Session(engine) as session: + session.add(source) + session.flush() + clone.cloned_from_control_id = int(source.id) + session.add(clone) + with pytest.raises(IntegrityError): + session.commit() + + +def test_clone_and_bind_generated_name_falls_back_for_legacy_name( + client: TestClient, +) -> None: + legacy_name = "legacy control name" + with engine.begin() as conn: + conn.execute( + text( + "INSERT INTO controls (name, data) VALUES (:name, CAST(:data AS JSONB))" + ), + { + "name": legacy_name, + "data": json.dumps(VALID_CONTROL_PAYLOAD), + }, + ) + row = conn.execute( + text("SELECT id FROM controls WHERE name = :name"), + {"name": legacy_name}, + ).fetchone() + assert row is not None + source_id = row[0] + + resp = client.post( + f"/api/v1/controls/{source_id}/clone-and-bind", + json={ + "target_binding": { + "target_type": "log_stream", + "target_id": "logstream-legacy-name", + }, + }, + ) + + assert resp.status_code == 200, resp.text + assert resp.json()["name"].startswith(f"control-{source_id}-clone-") + + +def test_list_controls_filters_by_cloned_state(client: TestClient) -> None: + source_id, _ = _create_control(client, name=f"Root-{uuid.uuid4()}") + clone_name = f"Clone-{uuid.uuid4()}" + clone_resp = client.post( + f"/api/v1/controls/{source_id}/clone-and-bind", + json={ + "name": clone_name, + "target_binding": { + "target_type": "log_stream", + "target_id": "logstream-456", + }, + }, + ) + assert clone_resp.status_code == 200, clone_resp.text + clone_id = clone_resp.json()["id"] + + root_resp = client.get("/api/v1/controls", params={"cloned": False, "limit": 100}) + assert root_resp.status_code == 200 + root_ids = {control["id"] for control in root_resp.json()["controls"]} + assert source_id in root_ids + assert clone_id not in root_ids + + clone_list_resp = client.get( + "/api/v1/controls", params={"cloned": True, "limit": 100} + ) + assert clone_list_resp.status_code == 200 + cloned_controls = clone_list_resp.json()["controls"] + cloned_ids = {control["id"] for control in cloned_controls} + assert clone_id in cloned_ids + assert source_id not in cloned_ids + listed_clone = next(control for control in cloned_controls if control["id"] == clone_id) + assert listed_clone["cloned_from_control_id"] == source_id + + +def test_clone_and_bind_returns_conflict_for_duplicate_clone_name( + client: TestClient, +) -> None: + _, existing_name = _create_control(client) + source_id, _ = _create_control(client) + + resp = client.post( + f"/api/v1/controls/{source_id}/clone-and-bind", + json={ + "name": existing_name, + "target_binding": { + "target_type": "log_stream", + "target_id": "logstream-789", + }, + }, + ) + + assert resp.status_code == 409 + assert resp.json()["error_code"] == "CONTROL_NAME_CONFLICT" + + +def test_clone_and_bind_integrity_error_name_conflict_returns_409( + client: TestClient, + monkeypatch: pytest.MonkeyPatch, +) -> None: + source_id, _ = _create_control(client) + + async def fail_create_version( + self: controls_module.ControlService, + control: Control, + *, + event_type: str, + note: str, + ) -> None: + _ = (self, control, event_type, note) + raise _make_integrity_error("idx_controls_namespace_name_active") + + monkeypatch.setattr( + controls_module.ControlService, + "create_version", + fail_create_version, + ) + + resp = client.post( + f"/api/v1/controls/{source_id}/clone-and-bind", + json={ + "name": f"race-{uuid.uuid4()}", + "target_binding": { + "target_type": "log_stream", + "target_id": "logstream-race", + }, + }, + ) + + assert resp.status_code == 409 + assert resp.json()["error_code"] == "CONTROL_NAME_CONFLICT" + + +def test_clone_and_bind_generated_name_retries_preflight_conflicts( + client: TestClient, + monkeypatch: pytest.MonkeyPatch, +) -> None: + source_id, source_name = _create_control(client, name=f"source-{uuid.uuid4()}") + first_suffix = "1111111111111111" + second_suffix = "2222222222222222" + _create_control(client, name=f"{source_name}-clone-{first_suffix}") + suffixes = iter([first_suffix, second_suffix]) + + def fake_uuid4() -> SimpleNamespace: + return SimpleNamespace(hex=next(suffixes)) + + monkeypatch.setattr(controls_module.uuid, "uuid4", fake_uuid4) + + resp = client.post( + f"/api/v1/controls/{source_id}/clone-and-bind", + json={ + "target_binding": { + "target_type": "log_stream", + "target_id": "logstream-retry-name", + }, + }, + ) + + assert resp.status_code == 200, resp.text + assert resp.json()["name"] == f"{source_name}-clone-{second_suffix}" + + +def test_clone_and_bind_rolls_back_clone_when_binding_fails( + client: TestClient, + monkeypatch: pytest.MonkeyPatch, +) -> None: + source_id, _ = _create_control(client) + clone_name = f"CloneRollback-{uuid.uuid4()}" + + async def fail_create_binding(*args: Any, **kwargs: Any) -> None: + raise BadRequestError( + error_code=ErrorCode.CONTROL_BINDING_INCOMPATIBLE, + detail="Binding failed after clone creation.", + resource="ControlBinding", + ) + + monkeypatch.setattr( + controls_module.ControlBindingsService, + "create_binding", + fail_create_binding, + ) + + resp = client.post( + f"/api/v1/controls/{source_id}/clone-and-bind", + json={ + "name": clone_name, + "target_binding": { + "target_type": "log_stream", + "target_id": "logstream-rollback", + }, + }, + ) + + assert resp.status_code == 400 + with Session(engine) as session: + clone = session.execute( + select(Control).where(Control.name == clone_name) + ).scalar_one_or_none() + assert clone is None + + +def test_clone_and_bind_locks_source_control( + client: TestClient, + monkeypatch: pytest.MonkeyPatch, +) -> None: + source_id, _ = _create_control(client) + original_get_active = controls_module.ControlService.get_active_control_or_404 + seen_for_update: list[bool] = [] + + async def recording_get_active( + self: controls_module.ControlService, + control_id_arg: int, + *, + namespace_key: str | None = None, + for_update: bool = False, + ) -> Control: + seen_for_update.append(for_update) + return await original_get_active( + self, + control_id_arg, + namespace_key=namespace_key, + for_update=for_update, + ) + + monkeypatch.setattr( + controls_module.ControlService, + "get_active_control_or_404", + recording_get_active, + ) + + resp = client.post( + f"/api/v1/controls/{source_id}/clone-and-bind", + json={ + "target_binding": { + "target_type": "log_stream", + "target_id": "logstream-lock", + }, + }, + ) + + assert resp.status_code == 200, resp.text + assert seen_for_update == [True] + + +def test_clone_and_bind_rejects_auth_namespace_mismatch(client: TestClient) -> None: + source_id, _ = _create_control(client) + + class MismatchedNamespaceAuthorizer: + async def authorize( + self, + request: Any, + operation: Operation, + context: dict[str, Any] | None = None, + ) -> Principal: + namespace_key = ( + "other-namespace" + if operation == Operation.CONTROL_BINDINGS_WRITE + else DEFAULT_NAMESPACE_KEY + ) + return Principal(namespace_key=namespace_key, is_admin=True) + + set_authorizer(MismatchedNamespaceAuthorizer()) + + resp = client.post( + f"/api/v1/controls/{source_id}/clone-and-bind", + json={ + "target_binding": { + "target_type": "log_stream", + "target_id": "logstream-mismatch", + }, + }, + ) + + assert resp.status_code == 403 + assert resp.json()["error_code"] == "AUTH_INSUFFICIENT_PRIVILEGES" + + +def test_clone_and_bind_requires_source_read_authorization( + client: TestClient, +) -> None: + source_id, _ = _create_control(client) + calls: list[tuple[Operation, dict[str, Any] | None]] = [] + + class ReadMismatchAuthorizer: + async def authorize( + self, + request: Any, + operation: Operation, + context: dict[str, Any] | None = None, + ) -> Principal: + calls.append((operation, context)) + namespace_key = ( + "other-namespace" + if operation == Operation.CONTROLS_READ + else DEFAULT_NAMESPACE_KEY + ) + return Principal(namespace_key=namespace_key, is_admin=True) + + set_authorizer(ReadMismatchAuthorizer()) + + resp = client.post( + f"/api/v1/controls/{source_id}/clone-and-bind", + json={ + "target_binding": { + "target_type": "log_stream", + "target_id": "logstream-read-auth", + }, + }, + ) + + assert resp.status_code == 403 + assert resp.json()["error_code"] == "AUTH_INSUFFICIENT_PRIVILEGES" + read_contexts = [ + context for operation, context in calls if operation == Operation.CONTROLS_READ + ] + assert read_contexts == [None] + + +def test_clone_and_bind_context_tolerates_invalid_body_shapes( + client: TestClient, +) -> None: + resp = client.post( + "/api/v1/controls/1/clone-and-bind", + content="{", + headers={"Content-Type": "application/json"}, + ) + assert resp.status_code == 422 + + list_resp = client.post("/api/v1/controls/1/clone-and-bind", json=[]) + assert list_resp.status_code == 422 + + bad_target_resp = client.post( + "/api/v1/controls/1/clone-and-bind", + json={"target_binding": "not-an-object"}, + ) + assert bad_target_resp.status_code == 422 + + +def test_clone_and_bind_context_drops_invalid_target_fields( + client: TestClient, +) -> None: + calls: list[tuple[Operation, dict[str, Any] | None]] = [] + + class RecordingAuthorizer: + async def authorize( + self, + request: Any, + operation: Operation, + context: dict[str, Any] | None = None, + ) -> Principal: + calls.append((operation, context)) + return Principal(namespace_key=DEFAULT_NAMESPACE_KEY, is_admin=True) + + set_authorizer(RecordingAuthorizer()) + + resp = client.post( + "/api/v1/controls/1/clone-and-bind", + json={ + "target_binding": { + "target_type": ["log_stream"], + "target_id": {"id": "logstream-invalid"}, + }, + }, + ) + + assert resp.status_code == 422 + binding_contexts = [ + context + for operation, context in calls + if operation == Operation.CONTROL_BINDINGS_WRITE + ] + assert binding_contexts == [{}] + + +def test_clone_and_bind_context_drops_overlong_target_fields( + client: TestClient, +) -> None: + calls: list[tuple[Operation, dict[str, Any] | None]] = [] + + class RecordingAuthorizer: + async def authorize( + self, + request: Any, + operation: Operation, + context: dict[str, Any] | None = None, + ) -> Principal: + calls.append((operation, context)) + return Principal(namespace_key=DEFAULT_NAMESPACE_KEY, is_admin=True) + + set_authorizer(RecordingAuthorizer()) + + resp = client.post( + "/api/v1/controls/1/clone-and-bind", + json={ + "target_binding": { + "target_type": "x" * 256, + "target_id": "logstream-invalid", + }, + }, + ) + + assert resp.status_code == 422 + binding_contexts = [ + context + for operation, context in calls + if operation == Operation.CONTROL_BINDINGS_WRITE + ] + assert binding_contexts == [{}] + + +def test_clone_and_bind_rejects_unknown_target_binding_fields( + client: TestClient, +) -> None: + source_id, _ = _create_control(client) + + resp = client.post( + f"/api/v1/controls/{source_id}/clone-and-bind", + json={ + "target_binding": { + "target_type": "log_stream", + "target_id": "logstream-extra", + "unknown_field": "ignored-before", + }, + }, + ) + + assert resp.status_code == 422 + + @pytest.mark.parametrize( "constraint_name", ["idx_controls_name_active", "idx_controls_namespace_name_active"], @@ -260,6 +765,7 @@ def test_list_controls_filters_and_pagination(client: TestClient) -> None: control = resp.json()["controls"][0] assert control["name"] == control3_name assert control["enabled"] is True + assert control["action"] == {"decision": "deny", "steering_context": None} # When: paginating resp = client.get("/api/v1/controls", params={"limit": 1}) @@ -696,19 +1202,337 @@ def test_delete_control_force_dissociates_direct_agent_links(client: TestClient) assert list_resp.json()["pagination"]["total"] == 0 -def _create_target_binding(client: TestClient, *, control_id: int) -> int: +def _create_target_binding( + client: TestClient, + *, + control_id: int, + target_type: str = "env", + target_id: str = "prod", + enabled: bool = True, +) -> int: resp = client.put( "/api/v1/control-bindings", json={ - "target_type": "env", - "target_id": "prod", + "target_type": target_type, + "target_id": target_id, "control_id": control_id, + "enabled": enabled, }, ) assert resp.status_code == 200, resp.text return int(resp.json()["binding_id"]) +def test_list_controls_returns_null_attachments_by_default( + client: TestClient, +) -> None: + control_id, control_name = _create_control(client, name=f"Attachments-{uuid.uuid4()}") + _set_control_data(client, control_id, deepcopy(VALID_CONTROL_PAYLOAD)) + + resp = client.get("/api/v1/controls", params={"name": control_name}) + + assert resp.status_code == 200, resp.text + controls = resp.json()["controls"] + assert len(controls) == 1 + assert controls[0]["id"] == control_id + assert controls[0]["attachments"] is None + + +def test_list_controls_filters_by_target_attachment_before_pagination( + client: TestClient, +) -> None: + prefix = f"AttachmentFilter-{uuid.uuid4()}" + target_id = f"ls-{uuid.uuid4()}" + matching_control_id, _ = _create_control(client, name=f"{prefix}-matching") + _set_control_data(client, matching_control_id, deepcopy(VALID_CONTROL_PAYLOAD)) + matching_binding_id = _create_target_binding( + client, + control_id=matching_control_id, + target_type="log_stream", + target_id=target_id, + ) + + newer_unmatched_control_id, _ = _create_control(client, name=f"{prefix}-unmatched") + _set_control_data(client, newer_unmatched_control_id, deepcopy(VALID_CONTROL_PAYLOAD)) + + resp = client.get( + "/api/v1/controls", + params={ + "name": prefix, + "include_attachments": "true", + "attachment_target_type": "log_stream", + "attachment_target_id": target_id, + "limit": 1, + }, + ) + + assert resp.status_code == 200, resp.text + body = resp.json() + assert body["pagination"]["total"] == 1 + assert body["pagination"]["has_more"] is False + controls = body["controls"] + assert len(controls) == 1 + assert controls[0]["id"] == matching_control_id + assert controls[0]["id"] != newer_unmatched_control_id + assert controls[0]["attachments"]["targets"] == [ + { + "binding_id": matching_binding_id, + "target_type": "log_stream", + "target_id": target_id, + "enabled": True, + } + ] + assert controls[0]["attachments"]["targets_total"] == 1 + assert controls[0]["attachments"]["targets_truncated"] is False + + +def test_list_controls_expands_filtered_control_attachments( + client: TestClient, +) -> None: + control_id, control_name = _create_control(client, name=f"Attachments-{uuid.uuid4()}") + _set_control_data(client, control_id, deepcopy(VALID_CONTROL_PAYLOAD)) + + policy_resp = client.put("/api/v1/policies", json={"name": f"pol-{uuid.uuid4()}"}) + assert policy_resp.status_code == 200 + policy_id = policy_resp.json()["policy_id"] + policy_assoc_resp = client.post(f"/api/v1/policies/{policy_id}/controls/{control_id}") + assert policy_assoc_resp.status_code == 200 + + agent_name = f"agent-{uuid.uuid4().hex[:12]}" + init_resp = client.post( + "/api/v1/agents/initAgent", + json={"agent": {"agent_name": agent_name}, "steps": []}, + ) + assert init_resp.status_code == 200 + agent_assoc_resp = client.post(f"/api/v1/agents/{agent_name}/controls/{control_id}") + assert agent_assoc_resp.status_code == 200 + + included_binding_id = _create_target_binding( + client, + control_id=control_id, + target_type="log_stream", + target_id="ls-prod", + enabled=False, + ) + _create_target_binding( + client, + control_id=control_id, + target_type="log_stream", + target_id="ls-dev", + ) + _create_target_binding( + client, + control_id=control_id, + target_type="environment", + target_id="prod", + ) + + resp = client.get( + "/api/v1/controls", + params={ + "name": control_name, + "include_attachments": "true", + "attachment_target_type": "log_stream", + "attachment_target_id": "ls-prod", + }, + ) + + assert resp.status_code == 200, resp.text + controls = resp.json()["controls"] + assert len(controls) == 1 + assert controls[0]["attachments"] == { + "agents": [{"agent_name": agent_name}], + "policies": [{"policy_id": policy_id}], + "targets": [ + { + "binding_id": included_binding_id, + "target_type": "log_stream", + "target_id": "ls-prod", + "enabled": False, + } + ], + "targets_total": 1, + "targets_truncated": False, + } + + +def test_list_controls_caps_inline_target_attachments( + client: TestClient, +) -> None: + control_id, control_name = _create_control(client, name=f"Attachments-{uuid.uuid4()}") + _set_control_data(client, control_id, deepcopy(VALID_CONTROL_PAYLOAD)) + binding_ids = [ + _create_target_binding( + client, + control_id=control_id, + target_type="log_stream", + target_id=f"ls-{index}", + ) + for index in range(25) + ] + + resp = client.get( + "/api/v1/controls", + params={ + "name": control_name, + "include_attachments": "true", + }, + ) + + assert resp.status_code == 200, resp.text + attachments = resp.json()["controls"][0]["attachments"] + assert len(attachments["targets"]) == 20 + assert attachments["targets_total"] == 25 + assert attachments["targets_truncated"] is True + assert [target["binding_id"] for target in attachments["targets"]] == list( + reversed(binding_ids[-20:]) + ) + + +def test_list_controls_omits_targets_without_binding_read_authorization( + client: TestClient, +) -> None: + control_id, control_name = _create_control(client, name=f"Attachments-{uuid.uuid4()}") + _set_control_data(client, control_id, deepcopy(VALID_CONTROL_PAYLOAD)) + _create_target_binding( + client, + control_id=control_id, + target_type="log_stream", + target_id="ls-prod", + ) + calls: list[tuple[Operation, dict[str, Any] | None]] = [] + + class BindingReadDenyAuthorizer: + async def authorize( + self, + request: Any, + operation: Operation, + context: dict[str, Any] | None = None, + ) -> Principal: + calls.append((operation, context)) + if operation == Operation.CONTROL_BINDINGS_READ: + raise ForbiddenError( + error_code=ErrorCode.AUTH_INSUFFICIENT_PRIVILEGES, + detail="No target read access.", + ) + return Principal(namespace_key=DEFAULT_NAMESPACE_KEY, is_admin=True) + + set_authorizer(BindingReadDenyAuthorizer()) + + resp = client.get( + "/api/v1/controls", + params={ + "name": control_name, + "include_attachments": "true", + }, + ) + + assert resp.status_code == 200, resp.text + controls = resp.json()["controls"] + assert controls[0]["attachments"] == { + "agents": [], + "policies": [], + "targets": [], + "targets_total": 0, + "targets_truncated": False, + } + assert (Operation.CONTROL_BINDINGS_READ, {}) in calls + + +def test_list_controls_rejects_target_filter_without_binding_read_authorization( + client: TestClient, +) -> None: + control_id, control_name = _create_control(client, name=f"Attachments-{uuid.uuid4()}") + _set_control_data(client, control_id, deepcopy(VALID_CONTROL_PAYLOAD)) + _create_target_binding( + client, + control_id=control_id, + target_type="log_stream", + target_id="ls-prod", + ) + calls: list[tuple[Operation, dict[str, Any] | None]] = [] + + class BindingReadDenyAuthorizer: + async def authorize( + self, + request: Any, + operation: Operation, + context: dict[str, Any] | None = None, + ) -> Principal: + calls.append((operation, context)) + if operation == Operation.CONTROL_BINDINGS_READ: + raise ForbiddenError( + error_code=ErrorCode.AUTH_INSUFFICIENT_PRIVILEGES, + detail="No target read access.", + ) + return Principal(namespace_key=DEFAULT_NAMESPACE_KEY, is_admin=True) + + set_authorizer(BindingReadDenyAuthorizer()) + + resp = client.get( + "/api/v1/controls", + params={ + "name": control_name, + "include_attachments": "true", + "attachment_target_type": "log_stream", + "attachment_target_id": "ls-prod", + }, + ) + + assert resp.status_code == 403 + assert resp.json()["error_code"] == "AUTH_INSUFFICIENT_PRIVILEGES" + assert ( + Operation.CONTROL_BINDINGS_READ, + {"target_type": "log_stream", "target_id": "ls-prod"}, + ) in calls + + +def test_list_controls_rejects_attachment_namespace_mismatch( + client: TestClient, +) -> None: + control_id, control_name = _create_control(client, name=f"Attachments-{uuid.uuid4()}") + _set_control_data(client, control_id, deepcopy(VALID_CONTROL_PAYLOAD)) + + class MismatchedBindingReadAuthorizer: + async def authorize( + self, + request: Any, + operation: Operation, + context: dict[str, Any] | None = None, + ) -> Principal: + namespace_key = ( + "other-namespace" + if operation == Operation.CONTROL_BINDINGS_READ + else DEFAULT_NAMESPACE_KEY + ) + return Principal(namespace_key=namespace_key, is_admin=True) + + set_authorizer(MismatchedBindingReadAuthorizer()) + + resp = client.get( + "/api/v1/controls", + params={ + "name": control_name, + "include_attachments": "true", + }, + ) + + assert resp.status_code == 403 + assert resp.json()["error_code"] == "AUTH_INSUFFICIENT_PRIVILEGES" + + +def test_list_controls_rejects_attachment_filters_without_expansion( + client: TestClient, +) -> None: + resp = client.get( + "/api/v1/controls", + params={"attachment_target_type": "log_stream"}, + ) + + assert resp.status_code == 422 + assert resp.json()["error_code"] == "VALIDATION_ERROR" + + def test_delete_control_blocks_when_target_binding_exists( client: TestClient, ) -> None: diff --git a/server/tests/test_data_model_v1_alembic_migration.py b/server/tests/test_data_model_v1_alembic_migration.py index 9e6764fa..53334732 100644 --- a/server/tests/test_data_model_v1_alembic_migration.py +++ b/server/tests/test_data_model_v1_alembic_migration.py @@ -17,6 +17,7 @@ PRE_MIGRATION_REVISION = "c1e9f9c4a1d2" MIGRATION_REVISION = "a7f3b1e0d9c5" OBSERVABILITY_NAMESPACE_REVISION = "b6f4c2d8e9a1" +CLONE_LINEAGE_REVISION = "e2b7f4a9c6d1" _BASE_DB_URL = make_url(db_config.get_url()) pytestmark = pytest.mark.skipif( @@ -103,6 +104,37 @@ def _assert_observability_namespace_schema(engine: Engine) -> None: assert "ix_events_agent_time" not in indexes +def _pg_index_definition(engine: Engine, index_name: str) -> str: + with engine.begin() as conn: + return str( + conn.execute( + text( + """ + SELECT indexdef + FROM pg_indexes + WHERE tablename = 'controls' AND indexname = :index_name + """ + ), + {"index_name": index_name}, + ).scalar_one() + ) + + +def _pg_constraint_definition(engine: Engine, constraint_name: str) -> tuple[str, str]: + with engine.begin() as conn: + row = conn.execute( + text( + """ + SELECT pg_get_constraintdef(oid) AS definition, confdeltype + FROM pg_constraint + WHERE conname = :constraint_name + """ + ), + {"constraint_name": constraint_name}, + ).one() + return str(row.definition), str(row.confdeltype) + + def test_upgrade_applies_namespace_columns_and_constraints( alembic_config: Config, temp_engine: Engine ) -> None: @@ -292,6 +324,78 @@ def test_observability_namespace_migration_recovers_when_primary_key_preexists( _assert_observability_namespace_schema(temp_engine) +def test_control_clone_lineage_migration_adds_composite_fk_and_partial_index( + alembic_config: Config, temp_engine: Engine +) -> None: + command.upgrade(alembic_config, CLONE_LINEAGE_REVISION) + + assert "cloned_from_control_id" in _column_names(temp_engine, "controls") + assert "controls_cloned_from_control_fkey" in _foreign_key_names( + temp_engine, "controls" + ) + assert "idx_controls_cloned_from" in _index_names(temp_engine, "controls") + + constraint_def, delete_action = _pg_constraint_definition( + temp_engine, + "controls_cloned_from_control_fkey", + ) + assert ( + "FOREIGN KEY (namespace_key, cloned_from_control_id) " + "REFERENCES controls(namespace_key, id)" + ) in constraint_def + assert delete_action == "a" + + index_def = _pg_index_definition(temp_engine, "idx_controls_cloned_from") + assert "CREATE INDEX idx_controls_cloned_from" in index_def + assert "ON public.controls USING btree (namespace_key, cloned_from_control_id)" in index_def + assert "WHERE (cloned_from_control_id IS NOT NULL)" in index_def + + with temp_engine.begin() as conn: + source_id = conn.execute( + text( + """ + INSERT INTO controls (namespace_key, name, data) + VALUES ('ns-one', 'source', '{}'::jsonb) + RETURNING id + """ + ) + ).scalar_one() + conn.execute( + text( + """ + INSERT INTO controls (namespace_key, name, data, cloned_from_control_id) + VALUES ('ns-one', 'clone', '{}'::jsonb, :source_id) + """ + ), + {"source_id": source_id}, + ) + + with pytest.raises(Exception): + with temp_engine.begin() as conn: + conn.execute( + text( + """ + INSERT INTO controls ( + namespace_key, name, data, cloned_from_control_id + ) + VALUES ('ns-two', 'bad-clone', '{}'::jsonb, :source_id) + """ + ), + {"source_id": source_id}, + ) + + command.downgrade(alembic_config, OBSERVABILITY_NAMESPACE_REVISION) + + assert "cloned_from_control_id" not in _column_names(temp_engine, "controls") + assert "controls_cloned_from_control_fkey" not in _foreign_key_names( + temp_engine, "controls" + ) + assert "idx_controls_cloned_from" not in _index_names(temp_engine, "controls") + indexes = _index_names(temp_engine, "control_execution_events") + assert "ix_events_namespace_agent_time" in indexes + assert "ix_events_agent_time" not in indexes + + def test_downgrade_rejects_cross_namespace_agents_duplicates( alembic_config: Config, temp_engine: Engine ) -> None: diff --git a/server/tests/test_principal_namespace_flow.py b/server/tests/test_principal_namespace_flow.py index 0ca1bca8..8f16a795 100644 --- a/server/tests/test_principal_namespace_flow.py +++ b/server/tests/test_principal_namespace_flow.py @@ -187,6 +187,18 @@ def test_principal_namespace_scopes_cross_namespace_writes(app: FastAPI) -> None ).status_code == 404 ) + assert ( + ns_b.patch( + "/api/v1/control-bindings/by-key", + json={ + "target_type": "env", + "target_id": "prod", + "control_id": control_id, + "enabled": False, + }, + ).status_code + == 404 + ) delete_binding = ns_b.post( "/api/v1/control-bindings/by-key:delete", json={