Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
3 changes: 2 additions & 1 deletion models/src/agent_control_models/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"),
]


Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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__)

Expand Down Expand Up @@ -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=(
Expand Down
30 changes: 30 additions & 0 deletions server/src/agent_control_server/auth_framework/target_context.py
Original file line number Diff line number Diff line change
@@ -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}
24 changes: 14 additions & 10 deletions server/src/agent_control_server/endpoints/control_bindings.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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
Expand All @@ -49,14 +50,17 @@ 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 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(
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]:
Expand Down
63 changes: 26 additions & 37 deletions server/src/agent_control_server/endpoints/controls.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -88,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.",
Expand All @@ -120,40 +112,35 @@ 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 {}
return {
"target_type": target_type,
"target_id": target_id,
}
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(
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.",
hint=(
"Pass target_binding.target_type and target_binding.target_id in the JSON body, "
"not as query parameters."
),
)
return target_context


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:
Expand Down Expand Up @@ -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. "
Expand All @@ -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. "
Expand Down
Loading
Loading