From 46b9c485eccfdf2a80907608c620240cee3d86cd Mon Sep 17 00:00:00 2001 From: Joshua Jeon Date: Wed, 18 Nov 2026 10:59:53 -0800 Subject: [PATCH 1/6] fix(server): Return 422 for invalid clone-and-bind targets [SAO-20817] --- .../endpoints/controls.py | 38 ++++++----- .../tests/test_control_bindings_endpoints.py | 63 ++++++++++++++++++- server/tests/test_controls_additional.py | 32 ++++++---- 3 files changed, 104 insertions(+), 29 deletions(-) diff --git a/server/src/agent_control_server/endpoints/controls.py b/server/src/agent_control_server/endpoints/controls.py index 5d8b5b9a..7fd0c3c2 100644 --- a/server/src/agent_control_server/endpoints/controls.py +++ b/server/src/agent_control_server/endpoints/controls.py @@ -1,7 +1,7 @@ import datetime as dt import uuid from copy import deepcopy -from typing import Any +from typing import Any, TypeGuard from agent_control_engine import list_evaluators from agent_control_models import ControlDefinition, TemplateControlInput, UnrenderedTemplateControl @@ -95,7 +95,7 @@ _SLUG_NAME_ADAPTER = TypeAdapter(SlugName) -def _is_target_context_value(value: object) -> bool: +def _is_target_context_value(value: object) -> TypeGuard[str]: return ( isinstance(value, str) and bool(value) @@ -120,22 +120,28 @@ def _ensure_same_namespace_authorization( async def _clone_and_bind_context(request: Request) -> dict[str, Any]: - """Surface clone target identifiers to the authorization context.""" + """Validate the clone target before requesting binding authorization.""" 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 {} + except Exception: # noqa: BLE001 invalid JSON is reported as a client error below + body = None + target_binding = body.get("target_binding") if isinstance(body, dict) else None + target_type = target_binding.get("target_type") if isinstance(target_binding, dict) else None + target_id = target_binding.get("target_id") if isinstance(target_binding, dict) else None + if ( + not _is_target_context_value(target_type) + or not target_type.strip() + or not _is_target_context_value(target_id) + or not target_id.strip() + ): + raise APIValidationError( + error_code=ErrorCode.VALIDATION_ERROR, + detail="Clone-and-bind requires a target_binding with target_type and target_id.", + hint=( + "Pass target_binding.target_type and target_binding.target_id in the JSON body, " + "not as query parameters." + ), + ) return { "target_type": target_type, "target_id": target_id, diff --git a/server/tests/test_control_bindings_endpoints.py b/server/tests/test_control_bindings_endpoints.py index ecce0d0a..3466d84d 100644 --- a/server/tests/test_control_bindings_endpoints.py +++ b/server/tests/test_control_bindings_endpoints.py @@ -1,4 +1,4 @@ -"""HTTP-level coverage for the ``/control-bindings`` endpoints.""" +"""HTTP-level coverage for binding endpoints and target authorization.""" from __future__ import annotations @@ -132,6 +132,67 @@ def upstream_auth(request: httpx.Request) -> httpx.Response: storage.assert_not_awaited() +def test_clone_and_bind_query_only_target_does_not_reach_orbit_binding_check( + client: TestClient, monkeypatch: pytest.MonkeyPatch, orbit_upstream_url: str +) -> None: + # Given: the incident's query-only request and an Orbit-style missing-target rejection. + operations: list[str] = [] + + def upstream_auth(request: httpx.Request) -> httpx.Response: + operation = json.loads(request.content)["operation"] + operations.append(operation) + if operation == Operation.CONTROL_BINDINGS_WRITE.value: + return httpx.Response(400, json={"detail": "Target context is required."}) + return httpx.Response(200, json={"namespace_key": DEFAULT_NAMESPACE_KEY}) + + upstream_client = httpx.AsyncClient(transport=httpx.MockTransport(upstream_auth)) + with _configured_orbit_authorizer(monkeypatch, orbit_upstream_url, upstream_client): + # When: target identifiers appear in the URL but no JSON body is sent. + response = client.post( + "/api/v1/controls/342/clone-and-bind", + params={"target_type": "log_stream", "target_id": str(uuid.uuid4())}, + ) + + # Then: Agent Control reports a client error before the binding authorization call. + assert response.status_code == 422, response.text + assert response.json()["error_code"] == "VALIDATION_ERROR" + assert "target_binding" in response.json()["hint"] + assert operations == [Operation.CONTROLS_CREATE.value, Operation.CONTROLS_READ.value] + + +def test_clone_and_bind_valid_target_still_requires_orbit_binding_grant( + client: TestClient, monkeypatch: pytest.MonkeyPatch, orbit_upstream_url: str +) -> None: + # Given: a valid nested target body and a binding-write denial from Orbit. + control_id = _create_control(client) + target_id = str(uuid.uuid4()) + payloads: list[dict[str, Any]] = [] + + def upstream_auth(request: httpx.Request) -> httpx.Response: + payload = json.loads(request.content) + payloads.append(payload) + if payload["operation"] == Operation.CONTROL_BINDINGS_WRITE.value: + return httpx.Response(403, json={"detail": "Binding denied."}) + return httpx.Response(200, json={"namespace_key": DEFAULT_NAMESPACE_KEY}) + + upstream_client = httpx.AsyncClient(transport=httpx.MockTransport(upstream_auth)) + with _configured_orbit_authorizer(monkeypatch, orbit_upstream_url, upstream_client): + # When: a caller tries to bind a clone to that target. + response = client.post( + f"/api/v1/controls/{control_id}/clone-and-bind", + json={"target_binding": {"target_type": "log_stream", "target_id": target_id}}, + ) + + # Then: the target reaches Orbit and the denial remains a 403. + assert response.status_code == 403, response.text + assert [payload["operation"] for payload in payloads] == [ + Operation.CONTROLS_CREATE.value, + Operation.CONTROLS_READ.value, + Operation.CONTROL_BINDINGS_WRITE.value, + ] + assert payloads[-1]["context"] == {"target_type": "log_stream", "target_id": target_id} + + def test_orbit_binding_list_pagination_keeps_target_filter( client: TestClient, monkeypatch: pytest.MonkeyPatch, orbit_upstream_url: str ) -> None: diff --git a/server/tests/test_controls_additional.py b/server/tests/test_controls_additional.py index 48ce817d..9203ddc1 100644 --- a/server/tests/test_controls_additional.py +++ b/server/tests/test_controls_additional.py @@ -473,8 +473,22 @@ def test_clone_and_bind_context_tolerates_invalid_body_shapes( assert bad_target_resp.status_code == 422 -def test_clone_and_bind_context_drops_invalid_target_fields( +@pytest.mark.parametrize( + ("body", "query"), + [ + (None, "?target_type=log_stream&target_id=stream-1"), + ({"target_type": "log_stream", "target_id": "stream-1"}, ""), + ({"target_binding": {}}, ""), + ({"target_binding": {"target_type": "log_stream"}}, ""), + ({"target_binding": {"target_type": " ", "target_id": "stream-1"}}, ""), + ({"target_binding": {"target_type": ["log_stream"], "target_id": "stream-1"}}, ""), + ], + ids=["query-only", "flat-body", "empty-target", "partial-target", "blank-target", "wrong-type"], +) +def test_clone_and_bind_rejects_missing_target_before_binding_authorization( client: TestClient, + body: dict[str, Any] | None, + query: str, ) -> None: calls: list[tuple[Operation, dict[str, Any] | None]] = [] @@ -490,23 +504,17 @@ async def authorize( 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"}, - }, - }, - ) + resp = client.post(f"/api/v1/controls/1/clone-and-bind{query}", json=body) assert resp.status_code == 422 + assert resp.json()["error_code"] == "VALIDATION_ERROR" + assert "target_binding" in resp.json()["hint"] binding_contexts = [ context for operation, context in calls if operation == Operation.CONTROL_BINDINGS_WRITE ] - assert binding_contexts == [{}] + assert binding_contexts == [] def test_clone_and_bind_context_drops_overlong_target_fields( @@ -542,7 +550,7 @@ async def authorize( for operation, context in calls if operation == Operation.CONTROL_BINDINGS_WRITE ] - assert binding_contexts == [{}] + assert binding_contexts == [] def test_clone_and_bind_rejects_unknown_target_binding_fields( From 2d28627cec989c8c7d12ec90832ba528aed81c15 Mon Sep 17 00:00:00 2001 From: Joshua Jeon Date: Wed, 18 Nov 2026 11:28:19 -0800 Subject: [PATCH 2/6] fix(server): Reuse target validation for binding writes [SAO-20817] --- .../auth_framework/providers/http_upstream.py | 12 +- .../auth_framework/target_context.py | 30 +++++ .../endpoints/control_bindings.py | 23 ++-- .../endpoints/controls.py | 22 ++-- .../tests/test_control_bindings_endpoints.py | 113 ++++++++++++++++++ 5 files changed, 166 insertions(+), 34 deletions(-) create mode 100644 server/src/agent_control_server/auth_framework/target_context.py 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 86b78da8..eb73c058 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 @@ -72,6 +72,7 @@ ) from ...logging_utils import get_logger from ..core import Operation, Principal, RequestAuthorizer +from ..target_context import complete_target_context _logger = get_logger(__name__) @@ -372,16 +373,7 @@ async def authorize( self._config.binding_list_requires_target and operation == Operation.CONTROL_BINDINGS_READ ): - target_context = context or {} - target_type = target_context.get("target_type") - target_id = target_context.get("target_id") - has_complete_target = ( - isinstance(target_type, str) - and bool(target_type.strip()) - and isinstance(target_id, str) - and bool(target_id.strip()) - ) - if not has_complete_target: + if complete_target_context(context, max_length=None) is None: raise APIValidationError( error_code=ErrorCode.VALIDATION_ERROR, detail=( diff --git a/server/src/agent_control_server/auth_framework/target_context.py b/server/src/agent_control_server/auth_framework/target_context.py new file mode 100644 index 00000000..5f88fc13 --- /dev/null +++ b/server/src/agent_control_server/auth_framework/target_context.py @@ -0,0 +1,30 @@ +"""Validate the target pair forwarded to management authorization.""" + +from collections.abc import Mapping + +_MAX_TARGET_FIELD_LENGTH = 255 + + +def complete_target_context( + context: Mapping[str, object] | None, + *, + max_length: int | None = _MAX_TARGET_FIELD_LENGTH, +) -> dict[str, str] | None: + """Return a usable target pair without changing the caller's values. + + Body-bearing binding models limit fields to 255 characters. The GET list + endpoint has no such limit, so its caller passes ``max_length=None``. + """ + if context is None: + return None + target_type = context.get("target_type") + target_id = context.get("target_id") + if not isinstance(target_type, str) or not isinstance(target_id, str): + return None + if not target_type.strip() or not target_id.strip(): + return None + if max_length is not None and ( + len(target_type) > max_length or len(target_id) > max_length + ): + return None + return {"target_type": target_type, "target_id": target_id} diff --git a/server/src/agent_control_server/endpoints/control_bindings.py b/server/src/agent_control_server/endpoints/control_bindings.py index 93fc2d82..d76d4bc1 100644 --- a/server/src/agent_control_server/endpoints/control_bindings.py +++ b/server/src/agent_control_server/endpoints/control_bindings.py @@ -26,8 +26,9 @@ from ..auth_framework import Operation, Principal, get_authorizer, require_operation from ..auth_framework.core import IdentityResolver +from ..auth_framework.target_context import complete_target_context from ..db import AsyncSessionLocal, get_async_db -from ..errors import BadRequestError, ForbiddenError, NotFoundError +from ..errors import APIValidationError, BadRequestError, ForbiddenError, NotFoundError from ..models import ControlBinding from ..services.control_bindings import ControlBindingsService @@ -38,7 +39,7 @@ async def _binding_body_context(request: Request) -> dict[str, Any]: - """Surface ``(target_type, target_id)`` to the authorization context. + """Validate and surface the body target before binding authorization. The body-bearing binding endpoints carry the target identifiers in the request payload. Authorization providers can use those @@ -49,14 +50,16 @@ async def _binding_body_context(request: Request) -> dict[str, Any]: """ try: body = await request.json() - except Exception: # noqa: BLE001 malformed JSON falls through to endpoint validation - return {} - if not isinstance(body, dict): - return {} - return { - "target_type": body.get("target_type"), - "target_id": body.get("target_id"), - } + except Exception: # noqa: BLE001 invalid JSON is reported as a client error below + body = None + target_context = complete_target_context(body if isinstance(body, dict) else None) + if target_context is None: + raise APIValidationError( + error_code=ErrorCode.VALIDATION_ERROR, + detail="Binding writes require target_type and target_id in the JSON body.", + hint="Pass both target_type and target_id in the JSON body, not as query parameters.", + ) + return target_context async def _binding_list_context(request: Request) -> dict[str, Any]: diff --git a/server/src/agent_control_server/endpoints/controls.py b/server/src/agent_control_server/endpoints/controls.py index 7fd0c3c2..d51a056e 100644 --- a/server/src/agent_control_server/endpoints/controls.py +++ b/server/src/agent_control_server/endpoints/controls.py @@ -1,7 +1,7 @@ import datetime as dt import uuid from copy import deepcopy -from typing import Any, TypeGuard +from typing import Any from agent_control_engine import list_evaluators from agent_control_models import ControlDefinition, TemplateControlInput, UnrenderedTemplateControl @@ -43,6 +43,7 @@ from sqlalchemy.ext.asyncio import AsyncSession from ..auth_framework import Operation, Principal, get_authorizer, require_operation +from ..auth_framework.target_context import complete_target_context from ..db import get_async_db from ..errors import ( APIError, @@ -95,7 +96,7 @@ _SLUG_NAME_ADAPTER = TypeAdapter(SlugName) -def _is_target_context_value(value: object) -> TypeGuard[str]: +def _is_target_context_value(value: object) -> bool: return ( isinstance(value, str) and bool(value) @@ -126,14 +127,10 @@ async def _clone_and_bind_context(request: Request) -> dict[str, Any]: except Exception: # noqa: BLE001 invalid JSON is reported as a client error below body = None target_binding = body.get("target_binding") if isinstance(body, dict) else None - target_type = target_binding.get("target_type") if isinstance(target_binding, dict) else None - target_id = target_binding.get("target_id") if isinstance(target_binding, dict) else None - if ( - not _is_target_context_value(target_type) - or not target_type.strip() - or not _is_target_context_value(target_id) - or not target_id.strip() - ): + target_context = complete_target_context( + target_binding if isinstance(target_binding, dict) else None + ) + if target_context is None: raise APIValidationError( error_code=ErrorCode.VALIDATION_ERROR, detail="Clone-and-bind requires a target_binding with target_type and target_id.", @@ -142,10 +139,7 @@ async def _clone_and_bind_context(request: Request) -> dict[str, Any]: "not as query parameters." ), ) - return { - "target_type": target_type, - "target_id": target_id, - } + return target_context def _attachment_target_context(request: Request) -> dict[str, str] | None: diff --git a/server/tests/test_control_bindings_endpoints.py b/server/tests/test_control_bindings_endpoints.py index 3466d84d..76e362cc 100644 --- a/server/tests/test_control_bindings_endpoints.py +++ b/server/tests/test_control_bindings_endpoints.py @@ -132,6 +132,42 @@ def upstream_auth(request: httpx.Request) -> httpx.Response: storage.assert_not_awaited() +def test_target_required_binding_list_keeps_existing_long_query_behavior( + client: TestClient, monkeypatch: pytest.MonkeyPatch, orbit_upstream_url: str +) -> None: + # Given: GET has no field-length limit, unlike the body-bearing binding models. + target_id = "x" * 256 + payloads: list[dict[str, Any]] = [] + + def upstream_auth(request: httpx.Request) -> httpx.Response: + payloads.append(json.loads(request.content)) + return httpx.Response( + 200, + json={ + "namespace_key": DEFAULT_NAMESPACE_KEY, + "target_type": "log_stream", + "target_id": target_id, + }, + ) + + upstream_client = httpx.AsyncClient(transport=httpx.MockTransport(upstream_auth)) + with _configured_orbit_authorizer(monkeypatch, orbit_upstream_url, upstream_client): + # When: a complete target pair exceeds the body model's length limit. + response = client.get( + _BINDINGS_URL, + params={"target_type": "log_stream", "target_id": target_id}, + ) + + # Then: GET still delegates that complete target to Orbit. + assert response.status_code == 200, response.text + assert payloads == [ + { + "operation": Operation.CONTROL_BINDINGS_READ.value, + "context": {"target_type": "log_stream", "target_id": target_id}, + } + ] + + def test_clone_and_bind_query_only_target_does_not_reach_orbit_binding_check( client: TestClient, monkeypatch: pytest.MonkeyPatch, orbit_upstream_url: str ) -> None: @@ -193,6 +229,83 @@ def upstream_auth(request: httpx.Request) -> httpx.Response: assert payloads[-1]["context"] == {"target_type": "log_stream", "target_id": target_id} +@pytest.mark.parametrize( + ("method", "path"), + [ + ("PUT", _BINDINGS_URL), + ("PATCH", f"{_BINDINGS_URL}/by-key"), + ("PUT", f"{_BINDINGS_URL}/by-key"), + ("POST", f"{_BINDINGS_URL}/by-key:delete"), + ], +) +def test_binding_write_missing_body_target_rejects_before_orbit( + client: TestClient, + monkeypatch: pytest.MonkeyPatch, + orbit_upstream_url: str, + method: str, + path: str, +) -> None: + # Given: a body-bearing binding route and Orbit's missing-target rejection. + upstream_requests: list[httpx.Request] = [] + + def upstream_auth(request: httpx.Request) -> httpx.Response: + upstream_requests.append(request) + return httpx.Response(400, json={"detail": "Target context is required."}) + + upstream_client = httpx.AsyncClient(transport=httpx.MockTransport(upstream_auth)) + with _configured_orbit_authorizer(monkeypatch, orbit_upstream_url, upstream_client): + # When: control_id is supplied without the required target pair. + response = client.request(method, path, json={"control_id": 1}) + + # Then: the request is rejected locally as invalid client input. + assert response.status_code == 422, response.text + assert response.json()["error_code"] == "VALIDATION_ERROR" + assert upstream_requests == [] + + +@pytest.mark.parametrize( + ("method", "path"), + [ + ("PUT", _BINDINGS_URL), + ("PATCH", f"{_BINDINGS_URL}/by-key"), + ("PUT", f"{_BINDINGS_URL}/by-key"), + ("POST", f"{_BINDINGS_URL}/by-key:delete"), + ], +) +def test_binding_write_valid_target_preserves_orbit_denial( + client: TestClient, + monkeypatch: pytest.MonkeyPatch, + orbit_upstream_url: str, + method: str, + path: str, +) -> None: + # Given: a complete target pair and a permission denial from Orbit. + target_id = str(uuid.uuid4()) + payloads: list[dict[str, Any]] = [] + + def upstream_auth(request: httpx.Request) -> httpx.Response: + payloads.append(json.loads(request.content)) + return httpx.Response(403, json={"detail": "Binding denied."}) + + upstream_client = httpx.AsyncClient(transport=httpx.MockTransport(upstream_auth)) + with _configured_orbit_authorizer(monkeypatch, orbit_upstream_url, upstream_client): + # When: the caller sends a valid body to the binding route. + response = client.request( + method, + path, + json={"target_type": "log_stream", "target_id": target_id, "control_id": 1}, + ) + + # Then: the target pair reaches Orbit and its denial is not converted to 422. + assert response.status_code == 403, response.text + assert payloads == [ + { + "operation": Operation.CONTROL_BINDINGS_WRITE.value, + "context": {"target_type": "log_stream", "target_id": target_id}, + } + ] + + def test_orbit_binding_list_pagination_keeps_target_filter( client: TestClient, monkeypatch: pytest.MonkeyPatch, orbit_upstream_url: str ) -> None: From f82844539182e7411f3dd389ff5d8ac82cd07fe8 Mon Sep 17 00:00:00 2001 From: Joshua Jeon Date: Wed, 18 Nov 2026 11:33:02 -0800 Subject: [PATCH 3/6] ci(ui): Pin Playwright runner to Ubuntu 24.04 [SAO-20817] --- .github/workflows/ci.yml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 71cb3cbf..f7978fcf 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -86,7 +86,8 @@ jobs: token: ${{ secrets.CODECOV_TOKEN }} ui-ci: - runs-on: ubuntu-latest + # Playwright 1.57 cannot install Chromium dependencies on Ubuntu 26.04. + runs-on: ubuntu-24.04 steps: - name: Checkout uses: actions/checkout@v4 From 36d6fe124c4032025b76f0a0e6b447e23c914fe7 Mon Sep 17 00:00:00 2001 From: Joshua Jeon Date: Wed, 18 Nov 2026 11:46:44 -0800 Subject: [PATCH 4/6] test(server): Cover invalid binding JSON before authorization [SAO-20817] --- .../endpoints/control_bindings.py | 5 +-- .../tests/test_control_bindings_endpoints.py | 33 +++++++++++++++++++ 2 files changed, 34 insertions(+), 4 deletions(-) diff --git a/server/src/agent_control_server/endpoints/control_bindings.py b/server/src/agent_control_server/endpoints/control_bindings.py index d76d4bc1..c86642ef 100644 --- a/server/src/agent_control_server/endpoints/control_bindings.py +++ b/server/src/agent_control_server/endpoints/control_bindings.py @@ -48,10 +48,7 @@ async def _binding_body_context(request: Request) -> dict[str, Any]: FastAPI caches the parsed body, so the endpoint's own Pydantic request model still binds normally. """ - try: - body = await request.json() - except Exception: # noqa: BLE001 invalid JSON is reported as a client error below - body = None + body = await request.json() target_context = complete_target_context(body if isinstance(body, dict) else None) if target_context is None: raise APIValidationError( diff --git a/server/tests/test_control_bindings_endpoints.py b/server/tests/test_control_bindings_endpoints.py index 76e362cc..d561a89d 100644 --- a/server/tests/test_control_bindings_endpoints.py +++ b/server/tests/test_control_bindings_endpoints.py @@ -263,6 +263,39 @@ def upstream_auth(request: httpx.Request) -> httpx.Response: assert upstream_requests == [] +@pytest.mark.parametrize( + "body", + [ + pytest.param(b"{", id="malformed-json"), + pytest.param(b"[]", id="non-object-json"), + ], +) +def test_binding_write_invalid_json_shape_rejects_before_orbit( + client: TestClient, + monkeypatch: pytest.MonkeyPatch, + orbit_upstream_url: str, + body: bytes, +) -> None: + # FastAPI rejects malformed or non-object JSON before binding authorization. + upstream_requests: list[httpx.Request] = [] + + def upstream_auth(request: httpx.Request) -> httpx.Response: + upstream_requests.append(request) + return httpx.Response(400, json={"detail": "Target context is required."}) + + upstream_client = httpx.AsyncClient(transport=httpx.MockTransport(upstream_auth)) + with _configured_orbit_authorizer(monkeypatch, orbit_upstream_url, upstream_client): + response = client.put( + _BINDINGS_URL, + content=body, + headers={"Content-Type": "application/json"}, + ) + + assert response.status_code == 422, response.text + assert response.json()["error_code"] == "VALIDATION_ERROR" + assert upstream_requests == [] + + @pytest.mark.parametrize( ("method", "path"), [ From 0136ba86361397b334bd306e15ff1911f9f6f169 Mon Sep 17 00:00:00 2001 From: Joshua Jeon Date: Wed, 18 Nov 2026 12:35:44 -0800 Subject: [PATCH 5/6] fix(server): Handle empty binding request bodies [SAO-20817] --- .../endpoints/control_bindings.py | 6 ++- .../tests/test_control_bindings_endpoints.py | 42 +++++++++++++++++++ 2 files changed, 47 insertions(+), 1 deletion(-) diff --git a/server/src/agent_control_server/endpoints/control_bindings.py b/server/src/agent_control_server/endpoints/control_bindings.py index c86642ef..9d77f8b3 100644 --- a/server/src/agent_control_server/endpoints/control_bindings.py +++ b/server/src/agent_control_server/endpoints/control_bindings.py @@ -48,7 +48,11 @@ async def _binding_body_context(request: Request) -> dict[str, Any]: FastAPI caches the parsed body, so the endpoint's own Pydantic request model still binds normally. """ - body = await request.json() + try: + body = await request.json() + except ValueError: + # FastAPI does not parse an empty or non-JSON body before this dependency. + body = None target_context = complete_target_context(body if isinstance(body, dict) else None) if target_context is None: raise APIValidationError( diff --git a/server/tests/test_control_bindings_endpoints.py b/server/tests/test_control_bindings_endpoints.py index d561a89d..65e0aff8 100644 --- a/server/tests/test_control_bindings_endpoints.py +++ b/server/tests/test_control_bindings_endpoints.py @@ -296,6 +296,48 @@ def upstream_auth(request: httpx.Request) -> httpx.Response: assert upstream_requests == [] +@pytest.mark.parametrize( + ("method", "path"), + [ + ("PUT", _BINDINGS_URL), + ("PATCH", f"{_BINDINGS_URL}/by-key"), + ("PUT", f"{_BINDINGS_URL}/by-key"), + ("POST", f"{_BINDINGS_URL}/by-key:delete"), + ], +) +@pytest.mark.parametrize("body_shape", ["no-body", "text-plain"]) +def test_binding_write_unparsed_body_returns_client_error_before_orbit( + client: TestClient, + monkeypatch: pytest.MonkeyPatch, + orbit_upstream_url: str, + method: str, + path: str, + body_shape: str, +) -> None: + # FastAPI leaves these bodies unparsed before the auth context builder runs. + upstream_requests: list[httpx.Request] = [] + + def upstream_auth(request: httpx.Request) -> httpx.Response: + upstream_requests.append(request) + return httpx.Response(400, json={"detail": "Target context is required."}) + + upstream_client = httpx.AsyncClient(transport=httpx.MockTransport(upstream_auth)) + with _configured_orbit_authorizer(monkeypatch, orbit_upstream_url, upstream_client): + kwargs: dict[str, Any] = {} + if body_shape == "text-plain": + kwargs = {"content": b"{", "headers": {"Content-Type": "text/plain"}} + response = client.request( + method, + path, + params={"target_type": "log_stream", "target_id": "stream-42"}, + **kwargs, + ) + + assert response.status_code == 422, response.text + assert response.json()["error_code"] == "VALIDATION_ERROR" + assert upstream_requests == [] + + @pytest.mark.parametrize( ("method", "path"), [ From 476bd423e4c121b53cb535a6d693a6423bfd11e8 Mon Sep 17 00:00:00 2001 From: Joshua Jeon Date: Wed, 18 Nov 2026 13:10:14 -0800 Subject: [PATCH 6/6] fix(server): Align target validation contracts [SAO-20817] --- models/src/agent_control_models/server.py | 3 +- .../endpoints/controls.py | 29 ++++++------------- .../tests/test_control_bindings_endpoints.py | 28 +++++++++++++++++- server/tests/test_controls_additional.py | 12 +++++++- 4 files changed, 49 insertions(+), 23 deletions(-) diff --git a/models/src/agent_control_models/server.py b/models/src/agent_control_models/server.py index a96b0410..f7726ba6 100644 --- a/models/src/agent_control_models/server.py +++ b/models/src/agent_control_models/server.py @@ -686,9 +686,10 @@ class PatchControlResponse(BaseModel): # Control binding requests / responses. +# Keep opaque identifiers unchanged while rejecting values made only of whitespace. ControlBindingTargetField = Annotated[ str, - StringConstraints(min_length=1, max_length=255), + StringConstraints(min_length=1, max_length=255, pattern=r"\S"), ] diff --git a/server/src/agent_control_server/endpoints/controls.py b/server/src/agent_control_server/endpoints/controls.py index d51a056e..34ee0aa2 100644 --- a/server/src/agent_control_server/endpoints/controls.py +++ b/server/src/agent_control_server/endpoints/controls.py @@ -89,21 +89,12 @@ "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.", @@ -124,7 +115,7 @@ async def _clone_and_bind_context(request: Request) -> dict[str, Any]: """Validate the clone target before requesting binding authorization.""" try: body = await request.json() - except Exception: # noqa: BLE001 invalid JSON is reported as a client error below + except ValueError: # empty or non-JSON body is validated below body = None target_binding = body.get("target_binding") if isinstance(body, dict) else None target_context = complete_target_context( @@ -144,16 +135,12 @@ async def _clone_and_bind_context(request: Request) -> dict[str, Any]: def _attachment_target_context(request: Request) -> dict[str, str] | None: """Return target context only when both attachment identifiers are valid.""" - target_type = request.query_params.get("attachment_target_type") - target_id = request.query_params.get("attachment_target_id") - if ( - target_type is None - or target_id is None - or not _is_target_context_value(target_type) - or not _is_target_context_value(target_id) - ): - return None - return {"target_type": target_type, "target_id": target_id} + return complete_target_context( + { + "target_type": request.query_params.get("attachment_target_type"), + "target_id": request.query_params.get("attachment_target_id"), + } + ) async def _optional_attachment_target_principal(request: Request) -> Principal | None: @@ -1181,6 +1168,7 @@ async def list_controls( None, min_length=1, max_length=255, + pattern=r"\S", description=( "Optional target_type filter applied to the returned controls and " "expanded target bindings. " @@ -1191,6 +1179,7 @@ async def list_controls( None, min_length=1, max_length=255, + pattern=r"\S", description=( "Optional target_id filter applied to the returned controls and " "expanded target bindings. " diff --git a/server/tests/test_control_bindings_endpoints.py b/server/tests/test_control_bindings_endpoints.py index 65e0aff8..8acd9189 100644 --- a/server/tests/test_control_bindings_endpoints.py +++ b/server/tests/test_control_bindings_endpoints.py @@ -263,6 +263,32 @@ def upstream_auth(request: httpx.Request) -> httpx.Response: assert upstream_requests == [] +@pytest.mark.parametrize( + ("method", "path"), + [ + ("PUT", _BINDINGS_URL), + ("PATCH", f"{_BINDINGS_URL}/by-key"), + ("PUT", f"{_BINDINGS_URL}/by-key"), + ("POST", f"{_BINDINGS_URL}/by-key:delete"), + ], +) +def test_binding_write_invalid_target_precedes_authentication( + unauthenticated_client: TestClient, + method: str, + path: str, +) -> None: + # Target-shape errors precede auth; a complete target still requires credentials. + invalid = unauthenticated_client.request(method, path, json={"control_id": 1}) + valid = unauthenticated_client.request( + method, + path, + json={"control_id": 1, "target_type": "log_stream", "target_id": "stream-42"}, + ) + + assert invalid.status_code == 422, invalid.text + assert valid.status_code == 401, valid.text + + @pytest.mark.parametrize( "body", [ @@ -276,7 +302,7 @@ def test_binding_write_invalid_json_shape_rejects_before_orbit( orbit_upstream_url: str, body: bytes, ) -> None: - # FastAPI rejects malformed or non-object JSON before binding authorization. + # FastAPI rejects malformed JSON; the context builder rejects non-object JSON. upstream_requests: list[httpx.Request] = [] def upstream_auth(request: httpx.Request) -> httpx.Response: diff --git a/server/tests/test_controls_additional.py b/server/tests/test_controls_additional.py index 9203ddc1..ffdac72d 100644 --- a/server/tests/test_controls_additional.py +++ b/server/tests/test_controls_additional.py @@ -1491,9 +1491,19 @@ async def authorize( [ {"include_attachments": "true", "attachment_target_type": "log_stream"}, {"include_attachments": "true", "attachment_target_id": "ls-prod"}, + { + "include_attachments": "true", + "attachment_target_type": " ", + "attachment_target_id": "ls-prod", + }, + { + "include_attachments": "true", + "attachment_target_type": "log_stream", + "attachment_target_id": "\t", + }, ], ) -def test_list_controls_rejects_incomplete_attachment_filters_without_auth_call( +def test_list_controls_rejects_invalid_attachment_filters_without_auth_call( client: TestClient, params: dict[str, str], ) -> None: