From 7615da64bace8c57ded6b4da875a5d8d79ee3b31 Mon Sep 17 00:00:00 2001 From: tercel Date: Mon, 30 Nov 2026 11:41:19 +0800 Subject: [PATCH] fix(python): close Beta.1 audit and binding gaps Signed-off-by: tercel --- python/pyproject.toml | 1 + python/src/apcore/_post_validation_policy.py | 2 +- python/src/apcore/bindings.py | 77 ++++++++------------ python/src/apcore/context.py | 4 + python/src/apcore/decorator.py | 27 ++++--- python/src/apcore/sys_modules/identity.py | 6 +- python/tests/sys_modules/test_control.py | 19 +++++ python/tests/test_bindings.py | 40 +++++++++- python/uv.lock | 2 + 9 files changed, 117 insertions(+), 61 deletions(-) diff --git a/python/pyproject.toml b/python/pyproject.toml index 2b969202..59a6be3e 100644 --- a/python/pyproject.toml +++ b/python/pyproject.toml @@ -47,6 +47,7 @@ dependencies = [ "pydantic>=2.7,<3", "jsonschema>=4.21,<5", "referencing>=0.30,<1", + "typing-extensions>=4.7,<5", ] [project.urls] diff --git a/python/src/apcore/_post_validation_policy.py b/python/src/apcore/_post_validation_policy.py index 09d55d17..e59931d8 100644 --- a/python/src/apcore/_post_validation_policy.py +++ b/python/src/apcore/_post_validation_policy.py @@ -29,7 +29,7 @@ from apcore.pipeline import PipelineContext _SAFE_INT = (1 << 53) - 1 -_RULE_ID = re.compile(r"[A-Za-z0-9_.-]{1,64}\Z") +_RULE_ID = re.compile(r"[A-Za-z0-9][A-Za-z0-9_.-]{0,63}\Z") _EVALUATOR_TIMEOUT_SECONDS = 1.0 diff --git a/python/src/apcore/bindings.py b/python/src/apcore/bindings.py index 93142065..65260e42 100644 --- a/python/src/apcore/bindings.py +++ b/python/src/apcore/bindings.py @@ -14,11 +14,7 @@ from pydantic import BaseModel from apcore.config import Config -from apcore.decorator import ( - FunctionModule, - generate_input_model, - generate_output_model, -) +from apcore.decorator import FunctionModule from apcore.errors import ( BindingCallableNotFoundError, BindingFileInvalidError, @@ -517,15 +513,14 @@ def resolve_target(self, target_string: str) -> Callable: def _resolve_schema( self, binding: dict[str, Any], - func: Callable, binding_file_dir: pathlib.Path, schema_loader: SchemaLoader, config: Config | None, *, file_path: str, module_id: str, - ) -> tuple[type[BaseModel], type[BaseModel]]: - """Resolve input/output schema per protocol-spec ยง5.12.2.""" + ) -> tuple[type[BaseModel] | None, type[BaseModel] | None, bool]: + """Resolve supplied schemas and indicate whether inference requires strict schemas.""" modes = _detect_schema_modes(binding) if len(modes) > 1: raise BindingSchemaModeConflictError( @@ -543,7 +538,7 @@ def _resolve_schema( f"binding '{module_id}': explicit schema mode requires both 'input_schema' and 'output_schema'" ), ) - return _binding_models(schema_loader, binding, file_path) + return (*_binding_models(schema_loader, binding, file_path), False) # Mode 2: external reference if "schema_ref" in binding: @@ -567,7 +562,7 @@ def _resolve_schema( raise BindingFileInvalidError( file_path=str(ref_path), reason="Schema reference and its input/output schemas must be mappings" ) - return _binding_models(schema_loader, ref_data, str(ref_path)) + return (*_binding_models(schema_loader, ref_data, str(ref_path)), False) # Mode 3: explicit auto_schema OR mode 4: implicit auto (default) try: @@ -585,25 +580,7 @@ def _resolve_schema( file_path=file_path, remediation="auto_schema is explicitly false; provide input_schema/output_schema or schema_ref instead", ) - # Implicit default: auto_schema true (permissive) - if auto_mode is None: - auto_mode = "permissive" - - try: - input_schema = generate_input_model(func) - output_schema = generate_output_model(func) - except (FuncMissingTypeHintError, FuncMissingReturnTypeError) as exc: - raise BindingSchemaInferenceFailedError( - target=binding["target"], - module_id=module_id, - file_path=file_path, - ) from exc - - if auto_mode == "strict": - self._enforce_strict_or_raise(input_schema, "input", module_id=module_id, file_path=file_path) - self._enforce_strict_or_raise(output_schema, "output", module_id=module_id, file_path=file_path) - - return input_schema, output_schema + return None, None, auto_mode == "strict" def _enforce_strict_or_raise( self, @@ -642,9 +619,8 @@ def _create_module_from_binding( metadata = {**(metadata or {}), "display": display} func = self.resolve_target(binding["target"]) - input_schema, output_schema = self._resolve_schema( + input_schema, output_schema, strict = self._resolve_schema( binding, - func, binding_file_dir, schema_loader, config, @@ -652,17 +628,28 @@ def _create_module_from_binding( module_id=module_id, ) - return FunctionModule( - func=func, - module_id=module_id, - description=binding.get("description"), - documentation=binding.get("documentation"), - tags=binding.get("tags"), - version=binding.get("version", "1.0.0"), - annotations=binding.get("annotations"), - metadata=metadata, - display=display, - input_schema=input_schema, - output_schema=output_schema, - resources=binding.get("resources"), - ) + try: + module = FunctionModule( + func=func, + module_id=module_id, + description=binding.get("description"), + documentation=binding.get("documentation"), + tags=binding.get("tags"), + version=binding.get("version", "1.0.0"), + annotations=binding.get("annotations"), + metadata=metadata, + display=display, + input_schema=input_schema, + output_schema=output_schema, + resources=binding.get("resources"), + ) + except (FuncMissingTypeHintError, FuncMissingReturnTypeError) as exc: + raise BindingSchemaInferenceFailedError( + target=binding["target"], + module_id=module_id, + file_path=file_path, + ) from exc + if strict: + self._enforce_strict_or_raise(module.input_schema, "input", module_id=module_id, file_path=file_path) + self._enforce_strict_or_raise(module.output_schema, "output", module_id=module_id, file_path=file_path) + return module diff --git a/python/src/apcore/context.py b/python/src/apcore/context.py index 6f089e0a..145d66c8 100644 --- a/python/src/apcore/context.py +++ b/python/src/apcore/context.py @@ -470,12 +470,16 @@ def create( def with_progress_reporter(self, callback: ProgressReporter | None) -> Context[T]: """Return a context with its own progress callback binding.""" + if callback is not None and not callable(callback): + raise InvalidInputError("Progress reporter must be a function") context = self._with_local_binding() context._progress_reporter = callback return context def with_elicitation_handler(self, callback: ElicitationHandler | None) -> Context[T]: """Return a context with its own request-for-input callback binding.""" + if callback is not None and not callable(callback): + raise InvalidInputError("Elicitation handler must be a function") context = self._with_local_binding() context._elicitation_handler = callback return context diff --git a/python/src/apcore/decorator.py b/python/src/apcore/decorator.py index 90bd6c36..0beed659 100644 --- a/python/src/apcore/decorator.py +++ b/python/src/apcore/decorator.py @@ -132,27 +132,32 @@ def _has_object_output(annotation: Any, *, root: bool = False) -> bool: return issubclass(cls, BaseModel) or (issubclass(cls, Mapping) if root else cls is dict) -class _TypedDictOutput(RootModel): +class _ObjectRootOutput(RootModel): @classmethod def __get_pydantic_json_schema__(cls, schema: CoreSchema, handler: GetJsonSchemaHandler) -> dict[str, Any]: # Protocol adapters consume an explicit object-shaped root schema. return handler.resolve_ref_schema(super().__get_pydantic_json_schema__(schema, handler)) -def _output_model(return_type: Any) -> type[BaseModel]: +def _infer_output(return_type: Any) -> tuple[type[BaseModel], bool]: + """Infer the output schema and whether its wire shape needs a result envelope.""" origin = get_origin(return_type) or return_type if return_type is type(None) or origin is dict: - return create_model("OutputModel", __config__=ConfigDict(extra="allow")) - if is_typeddict(origin): - return typing.cast(type[BaseModel], _TypedDictOutput.__class_getitem__(return_type)) - if isinstance(return_type, type) and issubclass(return_type, BaseModel) and _has_object_output(return_type): - return return_type - return create_model("OutputModel", result=(return_type, ...)) + return create_model("OutputModel", __config__=ConfigDict(extra="allow")), False + base_type = get_args(return_type)[0] if origin is Annotated else return_type + if is_typeddict(base_type): + return typing.cast(type[BaseModel], _ObjectRootOutput.__class_getitem__(return_type)), False + if isinstance(base_type, type) and issubclass(base_type, BaseModel) and _has_object_output(base_type): + if origin is Annotated: + return typing.cast(type[BaseModel], _ObjectRootOutput.__class_getitem__(return_type)), False + return base_type, False + return create_model("OutputModel", result=(return_type, ...)), True def generate_output_model(func: Callable) -> type[BaseModel]: """Generate an object schema for a function's declared return type.""" - return _output_model(_output_annotation(func)) + schema, _ = _infer_output(_output_annotation(func)) + return schema def _context_param_name(func: Any) -> str | None: @@ -221,9 +226,7 @@ def __init__( self.input_schema = input_schema if input_schema is not None else generate_input_model(func, param_descs) wrap_result = False if output_schema is None: - return_type = _output_annotation(func) - output_schema = _output_model(return_type) - wrap_result = return_type is not type(None) and not _has_object_output(return_type) + output_schema, wrap_result = _infer_output(_output_annotation(func)) self.output_schema = output_schema context_param_name = _context_param_name(func) diff --git a/python/src/apcore/sys_modules/identity.py b/python/src/apcore/sys_modules/identity.py index d04d2890..e80297bb 100644 --- a/python/src/apcore/sys_modules/identity.py +++ b/python/src/apcore/sys_modules/identity.py @@ -31,6 +31,9 @@ ) _IDENTITY_REDACTED_TOKEN: str = "" +_IDENTITY_RESERVED_KEYS = frozenset( + {"id", "type", "roles", "actor_id", "subject_id", "delegation_depth", "issuer", "scopes", "on_behalf_of"} +) def _extract_caller_id(context: Any) -> str: @@ -98,8 +101,7 @@ def _identity_snapshot(identity: Any) -> dict[str, Any]: attrs = getattr(identity, "attrs", None) or {} if isinstance(attrs, dict): for key, value in attrs.items(): - # Don't shadow the canonical id/type/roles keys. - if key in snapshot: + if key in _IDENTITY_RESERVED_KEYS: continue snapshot[key] = _redact_nested(_redact_identity_attr(str(key), value), frozenset()) return snapshot diff --git a/python/tests/sys_modules/test_control.py b/python/tests/sys_modules/test_control.py index 2b869f8b..ec689fdb 100644 --- a/python/tests/sys_modules/test_control.py +++ b/python/tests/sys_modules/test_control.py @@ -7,6 +7,7 @@ import os import time from pathlib import Path +from types import SimpleNamespace from typing import Any from unittest.mock import MagicMock, patch @@ -15,6 +16,7 @@ from apcore.approval import AutoApproveHandler from apcore.client import APCore from apcore.config import Config +from apcore.context import Identity from apcore.errors import InvalidInputError, ModuleDisabledError, ModuleError, ModuleNotFoundError, ReloadFailedError from apcore.events.emitter import ApCoreEvent, EventEmitter from apcore.module import ModuleAnnotations @@ -26,9 +28,26 @@ _default_toggle_state, check_module_disabled, ) +from apcore.sys_modules.identity import _extract_identity_dict from apcore.sys_modules.overrides import InMemoryOverridesStore +def test_audit_identity_filters_reserved_attributes(): + identity = Identity( + id="sample", + type="user", + attrs=dict.fromkeys( + ("id", "type", "roles", "actor_id", "subject_id", "delegation_depth", "issuer", "scopes", "on_behalf_of"), + "attribute", + ) | {"display_name": "Sample"}, + ) + assert _extract_identity_dict(SimpleNamespace(identity=identity)) == { + "id": "sample", + "type": "user", + "display_name": "Sample", + } + + # --------------------------------------------------------------------------- # Helpers # --------------------------------------------------------------------------- diff --git a/python/tests/test_bindings.py b/python/tests/test_bindings.py index e260d433..1f0646b7 100644 --- a/python/tests/test_bindings.py +++ b/python/tests/test_bindings.py @@ -2,10 +2,13 @@ from __future__ import annotations -import sys import json +import sys +from typing import Annotated import pytest +from pydantic import BaseModel, RootModel +from typing_extensions import TypedDict from apcore.bindings import BindingLoader from apcore.decorator import FunctionModule @@ -22,6 +25,41 @@ from apcore.registry import Registry +class _Response(BaseModel): + name: str + + +class _ResponseDict(TypedDict): + name: str + + +_MixedRoot = RootModel[dict[str, str] | list[str]] + + +@pytest.mark.parametrize( + ("annotation", "value", "expected"), + [ + (_Response | None, _Response(name="sample"), {"result": {"name": "sample"}}), + (_ResponseDict | None, {"name": "sample"}, {"result": {"name": "sample"}}), + (_Response | None, None, {"result": None}), + (Annotated[_Response, "metadata"], _Response(name="sample"), {"name": "sample"}), + (Annotated[_ResponseDict, "metadata"], {"name": "sample"}, {"name": "sample"}), + (_MixedRoot, _MixedRoot({"name": "sample"}), {"result": {"name": "sample"}}), + ], +) +def test_binding_infers_result_envelope(loader, registry, tmp_path, monkeypatch, annotation, value, expected): + def respond(): + return value + + respond.__annotations__["return"] = annotation + monkeypatch.setattr(loader, "resolve_target", lambda _: respond) + source = tmp_path / "example.binding.yaml" + source.write_text("bindings:\n - module_id: test.response\n target: binding_helpers:respond\n") + loader.load_bindings(str(source), registry) + + assert Executor(registry=registry).call("test.response", {}) == expected + + @pytest.fixture def loader() -> BindingLoader: return BindingLoader() diff --git a/python/uv.lock b/python/uv.lock index 7152057b..37e56127 100644 --- a/python/uv.lock +++ b/python/uv.lock @@ -205,6 +205,7 @@ dependencies = [ { name = "jsonschema" }, { name = "pydantic" }, { name = "referencing" }, + { name = "typing-extensions" }, ] [package.optional-dependencies] @@ -258,6 +259,7 @@ requires-dist = [ { name = "pyyaml", marker = "extra == 'discovery'", specifier = ">=6.0,<7" }, { name = "referencing", specifier = ">=0.30,<1" }, { name = "ruff", marker = "extra == 'dev'", specifier = ">=0.15.0,<0.17" }, + { name = "typing-extensions", specifier = ">=4.7,<5" }, { name = "watchdog", marker = "extra == 'discovery'", specifier = ">=3.0" }, ] provides-extras = ["config", "discovery", "events", "observability", "all", "dev"]