diff --git a/.github/workflows/core-candidate.yml b/.github/workflows/core-candidate.yml index 3bb93b27..e3c4f001 100644 --- a/.github/workflows/core-candidate.yml +++ b/.github/workflows/core-candidate.yml @@ -201,7 +201,7 @@ jobs: assert core_path == installed.locate_file("apcore/__init__.py").resolve() assert toolkit_path == toolkit_expected.resolve() if os.environ["CORE_MODE"] == "candidate": - assert installed.version == "1.0.0a4" + assert installed.version == "1.0.0a5" origin = json.loads(installed.read_text("direct_url.json") or "{}") assert origin.get("url") == Path(os.environ["CORE_INSTALL"]).resolve().as_uri() assert callable(getattr(Executor, "stream_with_completion", None)) @@ -340,7 +340,7 @@ jobs: assert.ok(coreEntry.startsWith(core + sep)); assert.equal(toolkitEntry, realpathSync(resolve(process.env.TOOLKIT_ROOT, 'dist/index.js'))); if (process.env.CORE_MODE === 'candidate') { - assert.equal(coreVersion, '1.0.0-alpha.4'); + assert.equal(coreVersion, '1.0.0-alpha.5'); assert.equal(typeof Executor.prototype.streamWithCompletion, 'function'); assert.equal(typeof APCore.prototype.streamWithCompletion, 'function'); } else { @@ -406,7 +406,7 @@ jobs: crate="${crates[0]}" version="${crate##*/apcore-}" version="${version%.crate}" - if [[ "$version" != 1.0.0-alpha.4 ]]; then + if [[ "$version" != 1.0.0-alpha.5 ]]; then echo "Expected the alpha.3 Core crate." >&2 exit 1 fi diff --git a/.github/workflows/python.yml b/.github/workflows/python.yml index 4ff90bad..580969fd 100644 --- a/.github/workflows/python.yml +++ b/.github/workflows/python.yml @@ -15,7 +15,7 @@ permissions: contents: read env: - CORE_REF: 625aa3ecbd1d0343fe62ab18c0a9943c17495199 + CORE_REF: e4e2329de4ce8fa45669572ef9bd81c48da0d746 jobs: test: diff --git a/.github/workflows/rust.yml b/.github/workflows/rust.yml index d943f761..93f1b3a7 100644 --- a/.github/workflows/rust.yml +++ b/.github/workflows/rust.yml @@ -22,9 +22,9 @@ permissions: env: # The released lockfiles already reference these prereleases. Bootstrap CI # from the reviewed Core commit while those versions are unpublished. - CORE_REF: 625aa3ecbd1d0343fe62ab18c0a9943c17495199 - CORE_CRATE_VERSION: 1.0.0-alpha.4 - CORE_CRATE_SHA256: 7d5e08c5bbc5cddf5c72b121cbec90c1c551993dbee7c7cc88e30950941b63ad + CORE_REF: e4e2329de4ce8fa45669572ef9bd81c48da0d746 + CORE_CRATE_VERSION: 1.0.0-alpha.5 + CORE_CRATE_SHA256: 1d19939071ba2c589815c061dfb1ff827862e5f1f52251e88297d49eec500a90 jobs: source: diff --git a/.github/workflows/typescript.yml b/.github/workflows/typescript.yml index 1ee59bc9..66debac7 100644 --- a/.github/workflows/typescript.yml +++ b/.github/workflows/typescript.yml @@ -15,7 +15,7 @@ permissions: contents: read env: - CORE_REF: 625aa3ecbd1d0343fe62ab18c0a9943c17495199 + CORE_REF: e4e2329de4ce8fa45669572ef9bd81c48da0d746 jobs: test: diff --git a/a2a/docs/features/auth.md b/a2a/docs/features/auth.md index 1ef31041..fd5e0393 100644 --- a/a2a/docs/features/auth.md +++ b/a2a/docs/features/auth.md @@ -18,6 +18,20 @@ description: "Auth module spec: JWT/Bearer authentication for the A2A server, va JWT/Bearer authentication for the A2A server. Validates tokens, maps claims to apcore `Identity`, bridges identity to the Executor via ASGI ContextVar. Mirrors apcore-mcp's auth module pattern. +## Delegated JWT Authority + +JWT scope projection is opt-in. Configure the expected issuer and audience alongside the signature verification key and algorithm allowlist. The authenticator requires `sub`, `iss`, `aud`, and `exp` and validates `nbf` and `iat` when supplied. In permissive mode a request without credentials retains anonymous access. A supplied credential must verify and satisfy the configured claim mapping. + +In Python, pass `delegated_claims=DelegatedClaims(...)` to `JWTAuthenticator`. In TypeScript, pass `delegatedClaims` in the authenticator options. In Rust, call `with_delegated_claims(DelegatedClaims { ... })` on the authenticator. The optional provider and outer actor roles fields are `scp_claim` and `actor_roles_claim`, with camelCase names in TypeScript. + +The standard `scope` claim is a space-delimited scope-token string. An explicitly configured provider claim such as `scp` can contain a scope string or an array of scope tokens. If both claims are present, their normalized sets must agree. An empty provider array grants zero scopes. + +The top-level `sub` identifies the root subject. The outermost `act` identifies the current actor and contributes one active delegation link. Actor roles come from a configured field on that outer object. Further nested `act` claims are bounded history and do not participate in the ACL or ownership. Configure a nonempty top-level `scopes` condition on each ACL rule that grants access to a scoped identity. Use `subject_types` and `subject_roles` to evaluate the root subject. + +A scoped task is owned by the issuer-qualified actor and subject. Access to the task and its results is evaluated with the current authority. A token refresh for the same actor and subject retains ownership. + +The `apcore:` owner prefix is reserved for scope-aware storage. When migrating an existing task or push-notification store that uses literal legacy IDs with this prefix, update those owner keys to `apcore:legacy:` followed by the original ID. + ## Components ### 1. `Authenticator` Protocol — `auth/protocol.py` diff --git a/a2a/python/pyproject.toml b/a2a/python/pyproject.toml index 3d3b5ab8..8070efa6 100644 --- a/a2a/python/pyproject.toml +++ b/a2a/python/pyproject.toml @@ -26,7 +26,7 @@ classifiers = [ "Framework :: AsyncIO", ] dependencies = [ - "apcore[config,discovery]==1.0.0a4", + "apcore[config,discovery]==1.0.0a5", "apcore-toolkit==0.15.1a2", "a2a-sdk[http-server]>=1.1.2", "starlette>=0.40.0", diff --git a/a2a/python/src/apcore_a2a/__init__.py b/a2a/python/src/apcore_a2a/__init__.py index 2d517609..ebf38b5b 100644 --- a/a2a/python/src/apcore_a2a/__init__.py +++ b/a2a/python/src/apcore_a2a/__init__.py @@ -4,7 +4,14 @@ from apcore_a2a._serve import async_serve, serve from apcore_a2a.adapters import AgentCardBuilder, ErrorMapper, PartConverter, SchemaConverter, SkillMapper -from apcore_a2a.auth import Authenticator, AuthMiddleware, ClaimMapping, JWTAuthenticator, auth_identity_var +from apcore_a2a.auth import ( + Authenticator, + AuthMiddleware, + ClaimMapping, + DelegatedClaims, + JWTAuthenticator, + auth_identity_var, +) from apcore_a2a.client import A2AClient from apcore_a2a.event_subscriber import A2AEventSubscriber, register_a2a_subscriber from apcore_a2a.openapi_backend import openapi_backend @@ -26,6 +33,7 @@ "Authenticator", "JWTAuthenticator", "ClaimMapping", + "DelegatedClaims", "AuthMiddleware", "auth_identity_var", # Adapters diff --git a/a2a/python/src/apcore_a2a/adapters/card_visibility.py b/a2a/python/src/apcore_a2a/adapters/card_visibility.py index 8bd0041f..de1521c9 100644 --- a/a2a/python/src/apcore_a2a/adapters/card_visibility.py +++ b/a2a/python/src/apcore_a2a/adapters/card_visibility.py @@ -127,6 +127,18 @@ def _decide(acl: Any, caller_id: str | None, skill_id: str, ctx: Any | None) -> return decision.access == "allow", bool(decision.approval_required) +def scoped_skill_callable(executor: Any, skill_id: str, identity: Any) -> bool: + descriptor = getattr(executor, "get_callable_descriptor", None) + if not callable(descriptor): + return False + try: + context = _acl_context(identity) + return context is not None and descriptor(skill_id, context) is not None + except Exception: + logger.debug("Scoped skill access could not be verified", exc_info=True) + return False + + def skill_access(executor: Any, skill_ids: list[str], identity: Any | None) -> dict[str, bool]: """The skills the ACL permits ``identity`` to invoke, each mapped to whether invoking it needs a human first. @@ -152,6 +164,8 @@ def skill_access(executor: Any, skill_ids: list[str], identity: Any | None) -> d traffic it was written for. The authenticated principal travels in the context instead, where the ``identity_types`` / ``roles`` conditions see it. """ + if getattr(identity, "scopes", None) is not None: + return {skill_id: False for skill_id in skill_ids if scoped_skill_callable(executor, skill_id, identity)} acl = executor_acl(executor) if acl is None: return {skill_id: False for skill_id in skill_ids} diff --git a/a2a/python/src/apcore_a2a/auth/__init__.py b/a2a/python/src/apcore_a2a/auth/__init__.py index 1e545ccd..40233890 100644 --- a/a2a/python/src/apcore_a2a/auth/__init__.py +++ b/a2a/python/src/apcore_a2a/auth/__init__.py @@ -1,6 +1,6 @@ """Auth: Authenticator Protocol, JWTAuthenticator, AuthMiddleware.""" -from apcore_a2a.auth.jwt import ClaimMapping, JWTAuthenticator +from apcore_a2a.auth.jwt import ClaimMapping, DelegatedClaims, JWTAuthenticator from apcore_a2a.auth.middleware import AuthMiddleware, auth_identity_var from apcore_a2a.auth.protocol import Authenticator @@ -8,6 +8,7 @@ "Authenticator", "JWTAuthenticator", "ClaimMapping", + "DelegatedClaims", "AuthMiddleware", "auth_identity_var", ] diff --git a/a2a/python/src/apcore_a2a/auth/_delegation.py b/a2a/python/src/apcore_a2a/auth/_delegation.py new file mode 100644 index 00000000..fdd25c0c --- /dev/null +++ b/a2a/python/src/apcore_a2a/auth/_delegation.py @@ -0,0 +1,101 @@ +"""Strict projection of verified RFC 8693 JWT claims.""" + +from __future__ import annotations + +import math +import re +from dataclasses import dataclass, replace +from typing import Any + +from apcore import Identity + +_SCOPE_TOKEN = re.compile(r"[\x21\x23-\x5b\x5d-\x7e]+") + + +@dataclass(frozen=True) +class DelegatedClaims: + """Opt in to JWT scopes and optionally select provider and actor-role claims.""" + + scp_claim: str | None = None + actor_roles_claim: str | None = None + + def __post_init__(self) -> None: + for claim in (self.scp_claim, self.actor_roles_claim): + if claim is not None and (not isinstance(claim, str) or not claim): + raise ValueError("JWT claim names must be nonempty strings") + + +def _scopes(value: Any, *, allow_array: bool = False) -> tuple[str, ...]: + if isinstance(value, str): + scopes = value.split(" ") + elif allow_array and isinstance(value, list): + scopes = value + else: + raise ValueError("Invalid JWT scope representation") + if not all(isinstance(scope, str) and _SCOPE_TOKEN.fullmatch(scope) for scope in scopes): + raise ValueError("Invalid JWT scope token") + return tuple(sorted(set(scopes))) + + +def _token_scopes(payload: dict[str, Any], mapping: DelegatedClaims) -> tuple[str, ...]: + standard = _scopes(payload["scope"]) if "scope" in payload else None + alternate = ( + _scopes(payload[mapping.scp_claim], allow_array=True) + if mapping.scp_claim is not None and mapping.scp_claim in payload + else None + ) + if standard is None and alternate is None: + raise ValueError("JWT must carry a configured scope claim") + if standard is not None and alternate is not None and standard != alternate: + raise ValueError("JWT scope claims disagree") + return standard if standard is not None else alternate or () + + +def _nonempty_string(value: Any) -> bool: + return isinstance(value, str) and bool(value) + + +def _validate_times(payload: dict[str, Any]) -> None: + for claim in ("exp", "nbf", "iat"): + if claim in payload: + value = payload[claim] + if type(value) not in (int, float) or not math.isfinite(value): + raise ValueError("JWT time claim must be numeric") + + +def _outer_actor(value: Any, mapping: DelegatedClaims, issuer: str) -> Identity: + node = value + for _ in range(8): + if not isinstance(node, dict) or not _nonempty_string(node.get("sub")): + raise ValueError("JWT act claim must contain a subject") + if "iss" in node and not _nonempty_string(node["iss"]): + raise ValueError("JWT actor issuer must be a nonempty string") + if "act" not in node: + break + node = node["act"] + else: + raise ValueError("JWT actor history is too deep") + + actor_type = value.get("type", "agent") + if not _nonempty_string(actor_type): + raise ValueError("JWT actor type must be a nonempty string") + roles = value.get(mapping.actor_roles_claim, []) if mapping.actor_roles_claim is not None else [] + if not isinstance(roles, list) or not all(_nonempty_string(role) for role in roles): + raise ValueError("Mapped JWT actor roles must be an array of strings") + return Identity(value["sub"], actor_type, tuple(roles), issuer=issuer) + + +def project_delegated_identity(payload: dict[str, Any], identity: Identity, mapping: DelegatedClaims) -> Identity: + """Map verified claims to one active link and validate bounded actor history.""" + issuer = payload["iss"] + subject_id = payload["sub"] + if not _nonempty_string(issuer) or not _nonempty_string(subject_id): + raise ValueError("JWT issuer and subject must be nonempty strings") + _validate_times(payload) + scopes = _token_scopes(payload, mapping) + mapped_claims = {"act", "scope", mapping.scp_claim} + attrs = {key: value for key, value in identity.attrs.items() if key not in mapped_claims} + subject = replace(identity, id=subject_id, attrs=attrs, issuer=issuer, scopes=scopes) + if "act" not in payload: + return subject + return subject.delegate(_outer_actor(payload["act"], mapping, issuer), scopes) diff --git a/a2a/python/src/apcore_a2a/auth/jwt.py b/a2a/python/src/apcore_a2a/auth/jwt.py index 67d7c1a5..14b72fef 100644 --- a/a2a/python/src/apcore_a2a/auth/jwt.py +++ b/a2a/python/src/apcore_a2a/auth/jwt.py @@ -8,6 +8,9 @@ import jwt as pyjwt from apcore import Identity +from apcore.errors import InvalidInputError + +from apcore_a2a.auth._delegation import DelegatedClaims, project_delegated_identity logger = logging.getLogger(__name__) @@ -58,6 +61,7 @@ class JWTAuthenticator: issuer: Expected ``iss`` claim (optional). claim_mapping: Maps JWT claims to Identity fields. require_claims: Claims that must be present in the token. + delegated_claims: Enable verified JWT scope and actor projection. """ def __init__( @@ -69,7 +73,13 @@ def __init__( issuer: str | None = None, claim_mapping: ClaimMapping | None = None, require_claims: list[str] | None = None, + delegated_claims: DelegatedClaims | None = None, ) -> None: + if delegated_claims is not None and ( + not isinstance(issuer, str) or not issuer or not isinstance(audience, str) or not audience + ): + raise ValueError("JWT delegation requires an expected issuer and audience") + self._delegated_claims = delegated_claims self._key = key self._algorithms = algorithms or ["HS256"] self._audience = audience @@ -77,9 +87,16 @@ def __init__( self._claim_mapping = claim_mapping or ClaimMapping() self._require_claims: list[str] = require_claims if require_claims is not None else ["sub"] + @property + def rejects_invalid_credentials(self) -> bool: + """Reject a supplied invalid credential even in permissive middleware.""" + return self._delegated_claims is not None + def authenticate(self, headers: dict[str, str]) -> Identity | None: """Extract Bearer token from headers, decode, and return Identity.""" - auth_header = headers.get("authorization", "") + auth_header = headers.get("authorization") or ( + headers.get("Authorization", "") if self._delegated_claims is not None else "" + ) if not auth_header.lower().startswith("bearer "): return None @@ -91,7 +108,15 @@ def authenticate(self, headers: dict[str, str]) -> Identity | None: if payload is None: return None - return self._payload_to_identity(payload) + identity = self._payload_to_identity(payload) + mapping = self._delegated_claims + if identity is None or mapping is None: + return identity + try: + return project_delegated_identity(payload, identity, mapping) + except (InvalidInputError, KeyError, OverflowError, TypeError, ValueError): + logger.debug("JWT delegation claim validation failed") + return None def security_schemes(self) -> dict: """Return security scheme descriptors for this authenticator. @@ -104,14 +129,17 @@ def _decode_token(self, token: str) -> dict[str, Any] | None: """Decode and validate a JWT token. Returns None on any error.""" try: options: dict[str, Any] = {} - if self._require_claims: - options["require"] = self._require_claims + required = self._require_claims + if self._delegated_claims is not None: + required = list(dict.fromkeys([*required, "sub", "iss", "aud", "exp"])) + if required: + options["require"] = required # Disable PyJWT's RFC sub-type enforcement (PyJWT >= 2.10 rejects a # non-string `sub`). The canonical cross-language rule coerces a scalar # numeric/boolean `sub` to a string in ``_claim_to_string`` and rejects # only null/array/object; deferring the check there keeps Python aligned # with the Rust/TS SDKs. - options["verify_sub"] = False + options["verify_sub"] = self._delegated_claims is not None kwargs: dict[str, Any] = { "jwt": token, @@ -123,9 +151,11 @@ def _decode_token(self, token: str) -> dict[str, Any] | None: kwargs["audience"] = self._audience if self._issuer is not None: kwargs["issuer"] = self._issuer + if self._delegated_claims is not None: + kwargs["leeway"] = 30 return pyjwt.decode(**kwargs) - except pyjwt.InvalidTokenError: + except (pyjwt.InvalidTokenError, TypeError, ValueError, OverflowError): logger.debug("JWT validation failed", exc_info=True) return None except Exception: @@ -141,7 +171,7 @@ def _payload_to_identity(self, payload: dict[str, Any]) -> Identity | None: and non-scalar role elements are dropped. """ mapping = self._claim_mapping - identity_id = _claim_to_string(payload.get(mapping.id_claim)) + identity_id = _claim_to_string(payload.get("sub" if self._delegated_claims is not None else mapping.id_claim)) if identity_id is None: return None diff --git a/a2a/python/src/apcore_a2a/auth/middleware.py b/a2a/python/src/apcore_a2a/auth/middleware.py index e5abfe67..0ccba2fe 100644 --- a/a2a/python/src/apcore_a2a/auth/middleware.py +++ b/a2a/python/src/apcore_a2a/auth/middleware.py @@ -81,7 +81,10 @@ async def __call__(self, scope: dict[str, Any], receive: Any, send: Any) -> None headers = extract_headers(scope) identity = self._authenticator.authenticate(headers) - if identity is None and self._require_auth: + invalid_credential = ( + "authorization" in headers and getattr(self._authenticator, "rejects_invalid_credentials", False) is True + ) + if identity is None and (self._require_auth or invalid_credential): method = scope.get("method", "UNKNOWN") client = scope.get("client") remote = f"{client[0]}:{client[1]}" if client else "unknown" diff --git a/a2a/python/src/apcore_a2a/server/context.py b/a2a/python/src/apcore_a2a/server/context.py index 882d6bb9..7168a502 100644 --- a/a2a/python/src/apcore_a2a/server/context.py +++ b/a2a/python/src/apcore_a2a/server/context.py @@ -25,17 +25,28 @@ from a2a.auth.user import UnauthenticatedUser, User from a2a.server.context import ServerCallContext from a2a.server.routes import DefaultServerCallContextBuilder +from apcore import Identity from starlette.requests import Request from apcore_a2a.auth.middleware import auth_identity_var +TASK_OWNER_KEY = "apcoreOwner" +TASK_SKILL_KEY = "apcoreSkill" +_OWNER_PREFIX = "apcore:" + +def scoped_owner(identity: Any) -> str | None: + if not isinstance(identity, Identity): + return None + owner = identity.owner_key() + return owner if isinstance(owner, str) else None + class IdentityUser(User): """Adapts an apcore ``Identity`` to a2a-sdk's ``User`` interface. - ``user_name`` is the identity id, which is what ``resolve_user_scope`` uses - as the owner key — the same principal the executor puts on the apcore - ``Context``, so governance and task scoping name the same caller. + ``user_name`` exposes the task owner key resolved by the SDK. Scoped + identities use the Core owner binding. Ordinary identities use their + identity ID outside the reserved owner namespace. """ def __init__(self, identity: Any) -> None: @@ -47,7 +58,11 @@ def is_authenticated(self) -> bool: @property def user_name(self) -> str: - return str(self._identity.id) + owner = scoped_owner(self._identity) + if owner is not None: + return f"{_OWNER_PREFIX}scoped:{owner}" + legacy = str(self._identity.id) + return f"{_OWNER_PREFIX}legacy:{legacy}" if legacy.startswith(_OWNER_PREFIX) else legacy @property def identity(self) -> Any: diff --git a/a2a/python/src/apcore_a2a/server/executor.py b/a2a/python/src/apcore_a2a/server/executor.py index 1289c973..e804de29 100644 --- a/a2a/python/src/apcore_a2a/server/executor.py +++ b/a2a/python/src/apcore_a2a/server/executor.py @@ -26,11 +26,13 @@ TaskStatus, TaskStatusUpdateEvent, ) +from apcore import Identity from google.protobuf.timestamp_pb2 import Timestamp # Imported at module level — no circular dependency (middleware.py does not import executor.py) from apcore_a2a.adapters.errors import GOVERNANCE_REFUSAL_CODES, carries_caller_detail, sanitize_message from apcore_a2a.auth.middleware import auth_identity_var +from apcore_a2a.server.context import TASK_OWNER_KEY, TASK_SKILL_KEY, identity_of, scoped_owner logger = logging.getLogger(__name__) _Result = TypeVar("_Result") @@ -177,20 +179,27 @@ def retire_unacknowledged_status(_: asyncio.Task[Any]) -> None: async def _execute(self, context: RequestContext, event_queue: EventQueue, run: _TaskExecution) -> None: # a2a-sdk 1.0: Establish the Task in the store before any TaskStatusUpdateEvent context_id = context.context_id or context.task_id + request_identity = identity_of(getattr(context, "call_context", None)) + identity = request_identity if isinstance(request_identity, Identity) else auth_identity_var.get() + raw_metadata = context.message.metadata if context.message else None + metadata: dict = dict(raw_metadata) if raw_metadata else {} + skill_id = metadata.get("skillId") + owner = scoped_owner(identity) initial_task = Task( id=context.task_id, context_id=context_id, status=_make_status(TaskState.TASK_STATE_SUBMITTED), ) + if owner is not None: + initial_task.metadata.update({TASK_OWNER_KEY: owner}) + if isinstance(skill_id, str): + initial_task.metadata.update({TASK_SKILL_KEY: skill_id}) await event_queue.enqueue_event(initial_task) if run.stopped.is_set(): return # 1. Get skill_id from message metadata # metadata is a protobuf Struct; convert to dict for .get() access - raw_metadata = context.message.metadata if context.message else None - metadata: dict = dict(raw_metadata) if raw_metadata else {} - skill_id = metadata.get("skillId") if not skill_id: self._notify("submitted", "failed") await self._fail(context, event_queue, "Missing required parameter: metadata.skillId") @@ -231,7 +240,6 @@ async def _execute(self, context: RequestContext, event_queue: EventQueue, run: return # 4. Build apcore Identity context with CancelToken (P0-B) - identity = auth_identity_var.get() apcore_ctx = None token = None try: diff --git a/a2a/python/src/apcore_a2a/server/factory.py b/a2a/python/src/apcore_a2a/server/factory.py index 52755c65..2aab4e03 100644 --- a/a2a/python/src/apcore_a2a/server/factory.py +++ b/a2a/python/src/apcore_a2a/server/factory.py @@ -4,7 +4,11 @@ import asyncio import contextlib +import hmac +import json import logging +import re +import secrets import time import warnings from collections.abc import AsyncGenerator, Awaitable @@ -30,7 +34,8 @@ TaskState, TaskStatusUpdateEvent, ) -from a2a.utils.errors import TaskNotCancelableError +from a2a.utils.constants import DEFAULT_LIST_TASKS_PAGE_SIZE +from a2a.utils.errors import InvalidParamsError, TaskNotCancelableError, TaskNotFoundError from apcore.error_formatter import ErrorFormatterRegistry from starlette.applications import Starlette from starlette.middleware import Middleware @@ -42,14 +47,17 @@ from apcore_a2a._config import register_a2a_namespace from apcore_a2a.adapters.agent_card import AgentCardBuilder -from apcore_a2a.adapters.card_visibility import build_extended_card, build_public_card +from apcore_a2a.adapters.card_visibility import build_extended_card, build_public_card, scoped_skill_callable from apcore_a2a.adapters.errors import ErrorMapper from apcore_a2a.adapters.parts import PartConverter from apcore_a2a.adapters.schema import SchemaConverter from apcore_a2a.adapters.skill_mapper import SkillMapper from apcore_a2a.server.context import ( + TASK_OWNER_KEY, + TASK_SKILL_KEY, AuthIdentityServerCallContextBuilder, anonymous_context, + scoped_owner, ) from apcore_a2a.server.context import ( identity_of as _identity_of, @@ -71,6 +79,8 @@ class _SDKVersionedTaskStore: logger = logging.getLogger(__name__) _SaveResult = TypeVar("_SaveResult") +_SCOPED_PAGE_TOKEN = re.compile(r"v1\.([1-9][0-9]{0,14})\.([0-9a-f]{64})") +_SCOPED_SCAN_PAGE_SIZE = 100 class _ObservedTaskStore: @@ -79,10 +89,93 @@ class _ObservedTaskStore: def __init__(self, store: Any, executor: ApCoreAgentExecutor) -> None: self._store = store self._executor = executor + self._page_token_key = secrets.token_bytes(32) def __getattr__(self, name: str) -> Any: return getattr(self._store, name) + def _can_read(self, task: Task, context: ServerCallContext) -> bool: + identity = _identity_of(context) + owner = scoped_owner(identity) + recorded_owner = dict(task.metadata).get(TASK_OWNER_KEY) + if owner != recorded_owner: + return False + if owner is None: + return True + skill = dict(task.metadata).get(TASK_SKILL_KEY) + return isinstance(skill, str) and scoped_skill_callable(self._executor._executor, skill, identity) + + def _visible_page(self, page: ListTasksResponse, context: ServerCallContext) -> ListTasksResponse: + visible = [task for task in page.tasks if self._can_read(task, context)] + if len(visible) == len(page.tasks): + return page + response = ListTasksResponse() + response.CopyFrom(page) + del response.tasks[:] + response.tasks.extend(visible) + response.total_size = len(visible) + if page.tasks and not self._can_read(page.tasks[-1], context): + response.ClearField("next_page_token") + return response + + async def get(self, task_id: str, context: ServerCallContext) -> Task | None: + task = await self._store.get(task_id, context) + return task if task is not None and self._can_read(task, context) else None + + async def list(self, params: ListTasksRequest, context: ServerCallContext) -> ListTasksResponse: + identity = _identity_of(context) + if scoped_owner(identity) is None: + return self._visible_page(await self._store.list(params, context), context) + return await self._list_scoped(params, context, identity.authority_key()) + + async def _list_scoped( + self, params: ListTasksRequest, context: ServerCallContext, authority: str + ) -> ListTasksResponse: + page_size = params.page_size or DEFAULT_LIST_TASKS_PAGE_SIZE + if page_size < 1: + raise InvalidParamsError(message="pageSize must be a positive integer") + + query = ListTasksRequest() + query.CopyFrom(params) + query.ClearField("page_token") + query.ClearField("page_size") + principal = json.dumps([context.tenant, authority]).encode() + binding = principal + b"\0" + query.SerializeToString(deterministic=True) + offset = 0 + if params.page_token: + cursor = _SCOPED_PAGE_TOKEN.fullmatch(params.page_token) + if cursor is None or not hmac.compare_digest(cursor[2], self._sign_offset(binding, cursor[1])): + raise InvalidParamsError(message="Invalid page token") + offset = int(cursor[1]) + + # Page and count the visible results, never expose storage cursors or counts. + query.page_size = _SCOPED_SCAN_PAGE_SIZE + tasks = [] + visible_total = 0 + seen_tokens: set[str] = set() + while True: + page = await self._store.list(query, context) + for task in page.tasks: + if self._can_read(task, context): + if offset <= visible_total < offset + page_size: + tasks.append(task) + visible_total += 1 + if not page.next_page_token: + break + if page.next_page_token in seen_tokens: + raise RuntimeError("TaskStore repeated a pagination token") + seen_tokens.add(page.next_page_token) + query.page_token = page.next_page_token + + next_offset = offset + len(tasks) + next_token = ( + f"v1.{next_offset}.{self._sign_offset(binding, str(next_offset))}" if next_offset < visible_total else "" + ) + return ListTasksResponse(tasks=tasks, page_size=page_size, total_size=visible_total, next_page_token=next_token) + + def _sign_offset(self, binding: bytes, offset: str) -> str: + return hmac.digest(self._page_token_key, offset.encode("ascii") + b"\0" + binding, "sha256").hex() + async def save(self, task: Task, context: ServerCallContext) -> None: await self._save(task, context, self._store.save(task, context)) @@ -111,19 +204,33 @@ async def save( ) async def get(self, task_id: str, context: ServerCallContext) -> StoredTask | None: - return await self._store.get(task_id, context) - - async def list(self, params: ListTasksRequest, context: ServerCallContext) -> ListTasksResponse: - return await self._store.list(params, context) + record = await self._store.get(task_id, context) + return record if record is not None and self._can_read(record.task, context) else None async def delete(self, task_id: str, context: ServerCallContext) -> None: await self._store.delete(task_id, context) class _TerminalAwareRequestHandler(DefaultRequestHandler): + async def _check_scoped_continuation(self, params: SendMessageRequest, context: ServerCallContext) -> None: + task_id = params.message.task_id + if not task_id or scoped_owner(_identity_of(context)) is None: + return + stored = await self.task_store.get(task_id, context) + if stored is None: + raise TaskNotFoundError + task = stored.task if not isinstance(stored, Task) else stored + if dict(task.metadata).get(TASK_SKILL_KEY) != dict(params.message.metadata).get("skillId"): + raise InvalidParamsError(message="A scoped task continuation must use the original skill") + + async def on_message_send(self, params: SendMessageRequest, context: ServerCallContext) -> Any: + await self._check_scoped_continuation(params, context) + return await super().on_message_send(params, context) + async def on_message_send_stream( self, params: SendMessageRequest, context: ServerCallContext ) -> AsyncGenerator[Event, None]: + await self._check_scoped_continuation(params, context) task_id: str | None = None reported_outcome = False async with contextlib.aclosing(super().on_message_send_stream(params, context)) as stream: diff --git a/a2a/python/tests/auth/test_delegated_jwt.py b/a2a/python/tests/auth/test_delegated_jwt.py new file mode 100644 index 00000000..6e9b04ec --- /dev/null +++ b/a2a/python/tests/auth/test_delegated_jwt.py @@ -0,0 +1,100 @@ +"""Verified JWT scope and delegation are explicitly opt-in.""" + +from __future__ import annotations + +import inspect +import time +from typing import Any + +import jwt +import pytest +from starlette.applications import Starlette +from starlette.middleware import Middleware +from starlette.responses import JSONResponse +from starlette.routing import Route +from starlette.testclient import TestClient + +from apcore_a2a import DelegatedClaims, JWTAuthenticator +from apcore_a2a.auth import AuthMiddleware + +_KEY = "scope-enabled-test-verifier-32-bytes" +_ISSUER = "https://issuer.example" +_AUDIENCE = "audience.example" + + +def _auth() -> JWTAuthenticator: + return JWTAuthenticator( + _KEY, + issuer=_ISSUER, + audience=_AUDIENCE, + delegated_claims=DelegatedClaims(scp_claim="scp", actor_roles_claim="roles"), + ) + + +def _token(**claims: Any) -> str: + return jwt.encode( + {"iss": _ISSUER, "sub": "subject", "aud": _AUDIENCE, "exp": time.time() + 120, **claims}, + _KEY, + algorithm="HS256", + ) + + +async def _authenticate(token: str): + identity = _auth().authenticate({"authorization": f"Bearer {token}"}) + return await identity if inspect.isawaitable(identity) else identity + + +@pytest.mark.asyncio +async def test_verified_scope_has_one_active_edge_and_uses_only_outer_actor_roles() -> None: + actor = {"sub": "current", "roles": ["operator"], "act": {"sub": "past", "roles": ["admin"]}} + first = await _authenticate(_token(scope="read write", scp=["write", "read"], roles=["owner"], act=actor)) + actor["act"] = {"sub": "different-past", "roles": ["superuser"]} + refreshed = await _authenticate(_token(scope="write read", roles=["owner"], act=actor)) + assert first is not None and refreshed is not None + assert first.delegation_depth == 1 + assert first.id == "current" and first.roles == ("operator",) + assert first.root_subject.id == "subject" and first.root_subject.roles == ("owner",) + assert first.scopes == ("read", "write") + assert first.issuer == first.root_subject.issuer == _ISSUER + assert first.authority_key() == refreshed.authority_key() + assert first.owner_key() == refreshed.owner_key() + explicit_empty = await _authenticate(_token(scp=[])) + assert explicit_empty is not None and explicit_empty.scopes == () + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "claims", + [ + {}, + {"scope": ""}, + {"scope": "read write"}, + {"scope": "read\twrite"}, + {"scope": "read", "scp": ["write"]}, + {"scope": "read", "iss": "other"}, + {"scope": "read", "aud": "other"}, + {"scope": "read", "sub": None}, + {"scope": "read", "exp": 1}, + {"scope": "read", "iat": "1"}, + {"scope": "read", "nbf": 9e9}, + {"scope": "read", "act": {"sub": "actor", "act": None}}, + {"scope": "read", "act": {"sub": "actor", "iss": False}}, + {"scope": "read", "act": {"sub": "actor", "roles": ["operator", 1]}}, + ], +) +async def test_projection_rejects_invalid_verified_claims(claims: dict[str, Any]) -> None: + assert await _authenticate(_token(**claims)) is None + + +def test_permissive_middleware_refuses_a_bad_credential_but_allows_no_credential() -> None: + async def endpoint(_request): + return JSONResponse({"ok": True}) + + app = Starlette( + routes=[Route("/", endpoint)], + middleware=[Middleware(AuthMiddleware, authenticator=_auth(), require_auth=False)], + ) + with TestClient(app) as client: + assert client.get("/").status_code == 200 + assert client.get("/", headers={"Authorization": "Bearer invalid"}).status_code == 401 + assert client.get("/", headers={"Authorization": f"Bearer {_token(scope='read')}"}).status_code == 200 diff --git a/a2a/python/tests/security/test_task_scoping.py b/a2a/python/tests/security/test_task_scoping.py index 20ab31bf..c414b6d7 100644 --- a/a2a/python/tests/security/test_task_scoping.py +++ b/a2a/python/tests/security/test_task_scoping.py @@ -87,7 +87,7 @@ def _rpc(client: TestClient, who: str, method: str, params: dict, *, v1: bool = return client.post("/", content=body, headers=headers).json() -def _submit(client: TestClient, who: str, message_id: str) -> str: +def _submit(client: TestClient, who: str, message_id: str, skill_id: str = "echo") -> str: """Run one task as ``who`` and return its id.""" response = _rpc( client, @@ -98,7 +98,7 @@ def _submit(client: TestClient, who: str, message_id: str) -> str: "role": "user", "messageId": message_id, "parts": [{"kind": "text", "text": "{}"}], - "metadata": {"skillId": "echo"}, + "metadata": {"skillId": skill_id}, } }, ) @@ -249,3 +249,74 @@ def test_without_an_authenticator_every_caller_shares_one_owner_bucket(): # A second, differently-credentialed caller sees it, because with no # authenticator configured there is only one principal. assert _rpc(client, "someone-else", "tasks/get", {"id": task_id})["result"]["id"] == task_id + + +def test_delegated_task_ownership_uses_subject_and_current_scope(): + from a2a.server.tasks.inmemory_task_store import InMemoryTaskStore + from a2a.types import ListTasksRequest + from apcore import Executor, Registry + from apcore.acl import ACL, ACLRule + + class Module: + description = "Return the operation result" + input_schema = {"type": "object"} + output_schema = {"type": "object"} + + def execute(self, inputs, context): + return {"result": "ok"} + + class Auth(_BearerIsPrincipal): + def authenticate(self, headers): + principal = super().authenticate(headers) + if principal is None: + return None + subject, scope = principal.id.split("/") + scopes = scope.split(",") + root = Identity(subject, scopes=scopes, issuer="issuer") + return root.delegate(Identity("same-actor", issuer="issuer"), scopes) + + class SingleRowStore(InMemoryTaskStore): + async def list(self, params, context): + query = ListTasksRequest() + query.CopyFrom(params) + query.page_size = 1 + return await super().list(query, context) + + registry = Registry() + registry.register("echo", Module()) + registry.register("restricted", Module()) + acl = ACL([ + ACLRule(["@external"], ["echo"], "allow", conditions={"scopes": ["run"]}), + ACLRule(["@external"], ["restricted"], "allow", conditions={"scopes": ["admin"]}), + ]) + with Executor(registry, acl=acl) as executor: + app, _ = A2AServerFactory().create( + registry, executor, name="Task scoping", description="d", version="1", url="http://localhost", + auth=Auth(), task_store=SingleRowStore(), + ) + with TestClient(app) as client: + task_id = _submit(client, "alice/run", "m-delegated") + assert _rpc(client, "alice/run", "GetTask", {"id": task_id}, v1=True)["result"]["id"] == task_id + for principal in ("bob/run", "alice/read"): + failure = _rpc(client, principal, "GetTask", {"id": task_id}, v1=True)["error"] + assert failure["message"] == "Task not found" + listing = _rpc(client, principal, "ListTasks", {}, v1=True)["result"] + assert not listing.get("tasks") + + recent = _submit(client, "alice/run,admin", "m-visible") + hidden = _submit(client, "alice/run,admin", "m-hidden", "restricted") + query = {"pageSize": 1} + page = _rpc(client, "alice/run", "ListTasks", query, v1=True)["result"] + assert [task["id"] for task in page["tasks"]] == [recent] + assert page["totalSize"] == 2 + token = page["nextPageToken"] + assert hidden not in token + for principal in ("alice/admin", "bob/run"): + replay = _rpc(client, principal, "ListTasks", {**query, "pageToken": token}, v1=True) + assert replay["error"]["message"] == "Invalid page token" + replay = _rpc(client, "alice/run", "ListTasks", {**query, "contextId": hidden, "pageToken": token}, v1=True) + assert replay["error"]["message"] == "Invalid page token" + page = _rpc(client, "alice/run", "ListTasks", {**query, "pageToken": token}, v1=True)["result"] + assert [task["id"] for task in page["tasks"]] == [task_id] + assert page["totalSize"] == 2 + assert not page.get("nextPageToken") diff --git a/a2a/rust/Cargo.lock b/a2a/rust/Cargo.lock index 1f41a70a..4f6c6456 100644 --- a/a2a/rust/Cargo.lock +++ b/a2a/rust/Cargo.lock @@ -92,9 +92,9 @@ dependencies = [ [[package]] name = "apcore" -version = "1.0.0-alpha.4" +version = "1.0.0-alpha.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7d5e08c5bbc5cddf5c72b121cbec90c1c551993dbee7c7cc88e30950941b63ad" +checksum = "1d19939071ba2c589815c061dfb1ff827862e5f1f52251e88297d49eec500a90" dependencies = [ "async-stream", "async-trait", diff --git a/a2a/rust/Cargo.toml b/a2a/rust/Cargo.toml index 4c69cd00..ebf91850 100644 --- a/a2a/rust/Cargo.toml +++ b/a2a/rust/Cargo.toml @@ -27,7 +27,7 @@ default = [] openapi = ["apcore-toolkit/http-proxy"] [dependencies] -apcore = { version = "=1.0.0-alpha.4", default-features = false, features = ["discovery", "sys-modules"] } +apcore = { version = "=1.0.0-alpha.5", default-features = false, features = ["discovery", "sys-modules"] } # `default-features = false` so `http-proxy` — a *default* feature of the # toolkit — is reached through this crate's `openapi` feature instead of being # enabled unconditionally. The unconditional import (`deep_resolve_refs`) is diff --git a/a2a/rust/src/auth/delegation.rs b/a2a/rust/src/auth/delegation.rs new file mode 100644 index 00000000..1274e792 --- /dev/null +++ b/a2a/rust/src/auth/delegation.rs @@ -0,0 +1,157 @@ +//! Projection of verified RFC 8693 JWT claims into Core authority. + +use std::collections::{BTreeSet, HashMap}; + +use serde_json::Value; + +use apcore::context::Identity; + +pub(super) const DELEGATED_CLOCK_SKEW: u64 = 30; + +/// Enable JWT scope projection and optionally map provider and actor claims. +#[derive(Debug, Clone, Default)] +pub struct DelegatedClaims { + /// Optional provider claim that may carry a scope string or array. + pub scp_claim: Option, + /// Optional role-list claim on the current `act` object. + pub actor_roles_claim: Option, +} + +fn scope_set(value: &Value, allow_array: bool) -> Option> { + fn valid(token: &str) -> bool { + !token.is_empty() + && token + .bytes() + .all(|byte| matches!(byte, b'!' | b'#'..=b'[' | b']'..=b'~')) + } + + if let Some(value) = value.as_str() { + return value + .split(' ') + .map(|token| valid(token).then_some(token)) + .collect(); + } + if !allow_array { + return None; + } + value + .as_array()? + .iter() + .map(|token| token.as_str().filter(|token| valid(token))) + .collect() +} + +fn scopes(payload: &HashMap, mapping: &DelegatedClaims) -> Option> { + let standard = match payload.get("scope") { + Some(value) => Some(scope_set(value, false)?), + None => None, + }; + let provider = match mapping + .scp_claim + .as_ref() + .and_then(|name| payload.get(name)) + { + Some(value) => Some(scope_set(value, true)?), + None => None, + }; + if matches!((&standard, &provider), (Some(left), Some(right)) if left != right) { + return None; + } + Some( + standard + .or(provider)? + .into_iter() + .map(str::to_owned) + .collect(), + ) +} + +fn nonempty_string(value: &Value) -> Option<&str> { + value.as_str().filter(|text| !text.is_empty()) +} + +fn outer_actor(value: &Value, mapping: &DelegatedClaims, issuer: &str) -> Option { + let outer = value.as_object()?; + let mut node = outer; + for depth in 1..=8 { + nonempty_string(node.get("sub")?)?; + if let Some(issuer) = node.get("iss") { + nonempty_string(issuer)?; + } + let Some(next) = node.get("act") else { break }; + if depth == 8 { + return None; + } + node = next.as_object()?; + } + let actor_type = match outer.get("type") { + Some(value) => nonempty_string(value)?, + None => "agent", + }; + let roles = match mapping + .actor_roles_claim + .as_ref() + .and_then(|name| outer.get(name)) + { + Some(value) => value + .as_array()? + .iter() + .map(|value| nonempty_string(value).map(str::to_owned)) + .collect::>>()?, + None => Vec::new(), + }; + Identity::new( + nonempty_string(outer.get("sub")?)?.into(), + actor_type.into(), + roles, + HashMap::new(), + ) + .with_authority(None, Some(issuer.into())) + .ok() +} + +pub(super) fn project( + payload: &HashMap, + mapped: &Identity, + mapping: &DelegatedClaims, +) -> Option { + if [&mapping.scp_claim, &mapping.actor_roles_claim] + .into_iter() + .flatten() + .any(String::is_empty) + { + return None; + } + let issuer = nonempty_string(payload.get("iss")?)?; + let subject_id = nonempty_string(payload.get("sub")?)?; + let now = jsonwebtoken::get_current_timestamp() as f64; + for claim in ["exp", "nbf", "iat"] { + if let Some(value) = payload.get(claim) { + let timestamp = value.as_f64()?; + if claim != "exp" && timestamp > now + DELEGATED_CLOCK_SKEW as f64 { + return None; + } + } + } + let scopes = scopes(payload, mapping)?; + let mut attrs = mapped.attrs().clone(); + attrs.remove("act"); + attrs.remove("scope"); + if let Some(name) = &mapping.scp_claim { + attrs.remove(name); + } + let subject = Identity::new( + subject_id.into(), + mapped.identity_type().into(), + mapped.roles().to_vec(), + attrs, + ) + .with_authority(Some(scopes.clone()), Some(issuer.into())) + .ok()?; + match payload.get("act") { + Some(value) => subject + .delegate(outer_actor(value, mapping, issuer)?, scopes) + .ok(), + None => Some(subject), + } +} diff --git a/a2a/rust/src/auth/jwt.rs b/a2a/rust/src/auth/jwt.rs index 4dc6a5f7..19e65efa 100644 --- a/a2a/rust/src/auth/jwt.rs +++ b/a2a/rust/src/auth/jwt.rs @@ -7,6 +7,8 @@ use serde::{Deserialize, Serialize}; use serde_json::Value; use std::collections::HashMap; +pub use super::delegation::DelegatedClaims; +use super::delegation::{project, DELEGATED_CLOCK_SKEW}; use super::protocol::Authenticator; #[derive(Debug, Clone)] @@ -49,6 +51,7 @@ pub struct JWTAuthenticator { audience: Option, /// Expected `iss` claim; verified when set (Python/TS parity). issuer: Option, + delegated_claims: Option, } impl JWTAuthenticator { @@ -61,6 +64,7 @@ impl JWTAuthenticator { algorithms: vec![Algorithm::HS256], audience: None, issuer: None, + delegated_claims: None, } } @@ -98,6 +102,14 @@ impl JWTAuthenticator { self } + /// Enable projection of a verified JWT's scopes and outer actor into Core authority. + /// A configured issuer and audience are required in this mode. + #[must_use] + pub fn with_delegated_claims(mut self, claims: DelegatedClaims) -> Self { + self.delegated_claims = Some(claims); + self + } + /// Build the appropriate `DecodingKey` for the configured algorithm family. /// /// HS* algorithms treat `key` as a raw HMAC secret; RS* / PS* and ES* @@ -164,6 +176,14 @@ impl Authenticator for JWTAuthenticator { if let Some(iss) = &self.issuer { validation.set_issuer(&[iss]); } + if self.delegated_claims.is_some() { + if self.issuer.as_deref()?.is_empty() || self.audience.as_deref()?.is_empty() { + return None; + } + validation.set_required_spec_claims(&["exp", "iss", "aud", "sub"]); + validation.validate_nbf = true; + validation.leeway = DELEGATED_CLOCK_SKEW; + } let data = decode::(token, &key, &validation).ok()?; let claims = data.claims.extra; @@ -180,7 +200,11 @@ impl Authenticator for JWTAuthenticator { // (Python returns None, TS returns null). Numeric/bool id values are // coerced to their string form to match Python str() / TS String(); // null/array/object are not valid ids and reject. - let id = claims.get(&mapping.id_claim).and_then(claim_to_string)?; + let id = if self.delegated_claims.is_some() { + claims.get("sub")?.as_str()?.to_owned() + } else { + claims.get(&mapping.id_claim).and_then(claim_to_string)? + }; // Coerce every array element via claim_to_string to match Python // `tuple(str(r) for r in raw_roles)` / TS `rawRoles.map(String)`; only @@ -206,7 +230,15 @@ impl Authenticator for JWTAuthenticator { } } - Some(Identity::new(id, identity_type, roles, attrs)) + let identity = Identity::new(id, identity_type, roles, attrs); + match &self.delegated_claims { + Some(mapping) => project(&claims, &identity, mapping), + None => Some(identity), + } + } + + fn rejects_invalid_credentials(&self) -> bool { + self.delegated_claims.is_some() } fn security_schemes(&self) -> Option { @@ -431,4 +463,139 @@ mod tests { let t2 = token(&json!({ "sub": "bob", "tenant": "t1" })); assert!(auth.authenticate(&bearer(&t2)).await.is_some()); } + + fn delegated_auth() -> JWTAuthenticator { + JWTAuthenticator::new(SECRET) + .with_audience("a2a") + .with_issuer("issuer") + .with_claim_mapping(ClaimMapping { + attrs_claims: vec!["act".into(), "scope".into(), "scp".into(), "tenant".into()], + ..ClaimMapping::default() + }) + .with_delegated_claims(DelegatedClaims { + scp_claim: Some("scp".into()), + actor_roles_claim: Some("trustedRoles".into()), + }) + } + + fn valid_delegated_claims() -> Value { + json!({ + "sub": "subject", "iss": "issuer", "aud": ["another", "a2a"], + "exp": jsonwebtoken::get_current_timestamp() + 300, + "scope": "write read read", "scp": ["read", "write"], + "roles": ["subject-role"], "tenant": "tenant1", + "act": { + "sub": "actor", "trustedRoles": ["actor-role"], "roles": ["unmapped"], + "act": { "sub": "historical", "trustedRoles": ["ignored-admin"] } + }, + }) + } + + #[tokio::test] + async fn scoped_jwt_uses_only_the_current_actor_and_root_subject() { + let claims = valid_delegated_claims(); + let auth = delegated_auth(); + let current = auth.authenticate(&bearer(&token(&claims))).await.unwrap(); + assert_eq!(current.id(), "actor"); + assert_eq!(current.identity_type(), "agent"); + assert_eq!(current.roles(), &["actor-role"]); + assert_eq!(current.issuer(), Some("issuer")); + assert_eq!(current.scopes().unwrap(), &["read", "write"]); + let root = current.root_subject(); + assert_eq!(root.id(), "subject"); + assert_eq!(root.roles(), &["subject-role"]); + assert_eq!(root.attrs().len(), 1); + assert_eq!(root.get_attr("tenant"), Some(&json!("tenant1"))); + assert_eq!(current.delegation_depth(), 1); + + let mut refreshed = claims; + refreshed["act"]["act"] = json!({"sub": "another-history", "iss": "a-different-issuer"}); + let updated = auth + .authenticate(&bearer(&token(&refreshed))) + .await + .unwrap(); + assert_eq!(current.authority_key(), updated.authority_key()); + assert_eq!(current.owner_key(), updated.owner_key()); + + let mut direct = valid_delegated_claims(); + let direct_claims = direct.as_object_mut().unwrap(); + direct_claims.remove("act"); + direct_claims.remove("scope"); + direct_claims.insert("scp".into(), json!([])); + let identity = auth.authenticate(&bearer(&token(&direct))).await.unwrap(); + assert_eq!(identity.id(), "subject"); + assert_eq!(identity.delegation_depth(), 0); + assert!(identity.scopes().is_some_and(<[_]>::is_empty)); + } + + #[tokio::test] + async fn scoped_jwt_requires_verified_claims_and_bounded_history() { + let auth = delegated_auth(); + let claims = valid_delegated_claims(); + let now = jsonwebtoken::get_current_timestamp(); + for (claim, invalid_value) in [ + ("iss", json!("wrong-issuer")), + ("aud", json!("wrong-audience")), + ("sub", json!(45)), + ("exp", json!(now - 300)), + ("exp", json!("invalid")), + ("nbf", json!(now + 300)), + ("nbf", json!(true)), + ("iat", json!(now + 300)), + ("iat", Value::Null), + ("scope", json!("read write")), + ("scope", json!(["read", "write"])), + ("scp", json!(["different"])), + ("act", json!({"sub": "actor", "act": {"roles": ["admin"]}})), + ("act", json!({"sub": "actor", "trustedRoles": [false]})), + ] { + let mut invalid = claims.clone(); + invalid[claim] = invalid_value; + assert!( + auth.authenticate(&bearer(&token(&invalid))).await.is_none(), + "{claim}: {invalid}" + ); + } + for required in ["iss", "aud", "sub", "exp"] { + let mut missing = claims.clone(); + missing.as_object_mut().unwrap().remove(required); + assert!( + auth.authenticate(&bearer(&token(&missing))).await.is_none(), + "{required}" + ); + } + let mut missing_scope = claims.clone(); + let map = missing_scope.as_object_mut().unwrap(); + map.remove("scope"); + map.remove("scp"); + assert!(auth + .authenticate(&bearer(&token(&missing_scope))) + .await + .is_none()); + + let mut actor = json!({"sub": "old"}); + for _ in 0..8 { + actor = json!({"sub": "actor", "act": actor}); + } + let mut too_deep = claims.clone(); + too_deep["act"] = actor; + assert!(auth + .authenticate(&bearer(&token(&too_deep))) + .await + .is_none()); + + let wrong_signature = encode( + &Header::new(Algorithm::HS256), + &claims, + &EncodingKey::from_secret(b"another-key"), + ) + .unwrap(); + assert!(auth.authenticate(&bearer(&wrong_signature)).await.is_none()); + let unconfigured = + JWTAuthenticator::new(SECRET).with_delegated_claims(DelegatedClaims::default()); + assert!(unconfigured + .authenticate(&bearer(&token(&claims))) + .await + .is_none()); + } } diff --git a/a2a/rust/src/auth/middleware.rs b/a2a/rust/src/auth/middleware.rs index 4fdc84ed..f9b2a853 100644 --- a/a2a/rust/src/auth/middleware.rs +++ b/a2a/rust/src/auth/middleware.rs @@ -105,20 +105,11 @@ where .map(|(k, v)| (k.as_str().to_string(), v.to_str().unwrap_or("").to_string())) .collect(); - // Exempt paths (discovery, health) are never rejected, but a caller - // that does present valid credentials is still identified: the Agent - // Card is ACL-filtered per caller, so serving it anonymously to an - // authenticated client would hide skills that client may invoke. - if exempt { - if let Some(identity) = authenticator.authenticate(&headers).await { - req.extensions_mut().insert(identity); - } - return inner.call(req).await; - } - + let invalid_credential_is_fatal = headers.contains_key("authorization") + && authenticator.rejects_invalid_credentials(); match authenticator.authenticate(&headers).await { None => { - if require_auth { + if (!exempt && require_auth) || invalid_credential_is_fatal { // JSON body + headers match Python/TS middleware so clients // get a consistent error shape across all three SDKs. let body = serde_json::json!({ @@ -242,6 +233,37 @@ mod tests { assert_eq!(resp.status(), 200); } + #[tokio::test] + async fn permissive_scoped_auth_rejects_a_supplied_invalid_credential() { + use crate::{DelegatedClaims, JWTAuthenticator}; + + let layer = AuthMiddlewareLayer::with_require_auth( + Arc::new( + JWTAuthenticator::new("key") + .with_issuer("issuer") + .with_audience("a2a") + .with_delegated_claims(DelegatedClaims::default()), + ), + vec![], + false, + ); + let endpoint = layer.layer(ok_service()); + let anonymous = Request::builder() + .uri("/jsonrpc") + .body(Body::empty()) + .unwrap(); + assert_eq!( + endpoint.clone().oneshot(anonymous).await.unwrap().status(), + 200 + ); + let invalid = Request::builder() + .uri("/jsonrpc") + .header("authorization", "Bearer invalid") + .body(Body::empty()) + .unwrap(); + assert_eq!(endpoint.oneshot(invalid).await.unwrap().status(), 401); + } + #[tokio::test] async fn exempt_path_skips_auth() { let layer = diff --git a/a2a/rust/src/auth/mod.rs b/a2a/rust/src/auth/mod.rs index c9474c8f..24d08b30 100644 --- a/a2a/rust/src/auth/mod.rs +++ b/a2a/rust/src/auth/mod.rs @@ -1,5 +1,6 @@ //! Authentication and authorization for A2A endpoints. +mod delegation; pub mod jwt; pub mod middleware; pub mod protocol; diff --git a/a2a/rust/src/auth/protocol.rs b/a2a/rust/src/auth/protocol.rs index bd626ca0..cac355d1 100644 --- a/a2a/rust/src/auth/protocol.rs +++ b/a2a/rust/src/auth/protocol.rs @@ -9,4 +9,9 @@ use std::collections::HashMap; pub trait Authenticator: Send + Sync { async fn authenticate(&self, headers: &HashMap) -> Option; fn security_schemes(&self) -> Option; + + /// Refuse a supplied invalid credential even when authentication is optional. + fn rejects_invalid_credentials(&self) -> bool { + false + } } diff --git a/a2a/rust/src/lib.rs b/a2a/rust/src/lib.rs index a693c7c3..c27c6119 100644 --- a/a2a/rust/src/lib.rs +++ b/a2a/rust/src/lib.rs @@ -31,7 +31,7 @@ pub use crate::apcore_a2a::{ }; // Re-exports: auth -pub use crate::auth::jwt::{ClaimMapping, JWTAuthenticator}; +pub use crate::auth::jwt::{ClaimMapping, DelegatedClaims, JWTAuthenticator}; pub use crate::auth::middleware::{AuthMiddlewareLayer, AuthMiddlewareService, AUTH_IDENTITY}; pub use crate::auth::protocol::Authenticator; diff --git a/a2a/rust/src/server/executor.rs b/a2a/rust/src/server/executor.rs index 64bc40a9..965ff59c 100644 --- a/a2a/rust/src/server/executor.rs +++ b/a2a/rust/src/server/executor.rs @@ -79,6 +79,14 @@ impl ApCoreAgentExecutor { self.executor.acl.clone() } + /// Check current scoped access using the Core pipeline's silent discovery gate. + pub(crate) fn scoped_skill_visible(&self, skill_id: &str, identity: &Identity) -> bool { + let ctx = self.acl_context(Some(identity.clone())); + self.executor + .get_callable_definition(skill_id, None, Some(&ctx)) + .is_some() + } + /// Build an apcore `Context` carrying the authenticated identity, the /// cancel token and a global deadline (`now + execution_timeout`, fractional /// seconds since UNIX epoch per the apcore Rust contract). diff --git a/a2a/rust/src/server/handlers.rs b/a2a/rust/src/server/handlers.rs index 18ae0a2e..f0b1bb87 100644 --- a/a2a/rust/src/server/handlers.rs +++ b/a2a/rust/src/server/handlers.rs @@ -177,6 +177,18 @@ fn acl_filtered_card( identity: Option<&Identity>, hide_approval_gated: bool, ) -> Value { + if let Some(identity) = identity.filter(|identity| identity.scopes().is_some()) { + let mut filtered = card.clone(); + if let Some(skills) = filtered.get_mut("skills").and_then(Value::as_array_mut) { + skills.retain(|skill| { + skill + .get("id") + .and_then(Value::as_str) + .is_some_and(|id| executor.scoped_skill_visible(id, identity)) + }); + } + return filtered; + } let Some(acl) = executor.acl() else { return card.clone(); }; @@ -324,6 +336,9 @@ impl FilteredCard { executor: &ApCoreAgentExecutor, identity: Option<&Identity>, ) -> Arc { + if identity.is_some_and(|identity| identity.scopes().is_some()) { + return Arc::new(acl_filtered_card(&self.card, executor, identity, false)); + } let key = OwnerId::from_identity(identity).as_str().to_string(); if let Some(cached) = self.cache.lock().unwrap().get(&key) { return cached.clone(); @@ -725,7 +740,7 @@ async fn fail_task( history: vec![], }; let task_json = serde_json::to_value(&task).unwrap(); - save_task(state, task_id, task_json.clone(), ctx).await?; + save_task(state, task_id, task_json.clone(), ctx, None).await?; notify_push( state, task_id, @@ -759,8 +774,14 @@ async fn failed_task_stream( artifacts: vec![], history: vec![], }; - if let Err((code, message)) = - save_task(state, &task_id, serde_json::to_value(&task).unwrap(), ctx).await + if let Err((code, message)) = save_task( + state, + &task_id, + serde_json::to_value(&task).unwrap(), + ctx, + None, + ) + .await { return Json(rpc_error(&id, code, &message)).into_response(); } @@ -811,6 +832,7 @@ async fn handle_send( message, }) => return fail_task(state, &task_id, &context_id, ctx, message).await, }; + check_scoped_continuation(state, ctx, params).await?; // Reject unknown skills with a FAILED task (Python/TS parity). if !state.skill_ids.contains(&skill_id) { @@ -829,7 +851,14 @@ async fn handle_send( let running = state.running_tasks.register(&task_id, ctx); let execution = &running.execution; - save_task(state, &task_id, serde_json::to_value(&task).unwrap(), ctx).await?; + save_task( + state, + &task_id, + serde_json::to_value(&task).unwrap(), + ctx, + Some(&skill_id), + ) + .await?; let result = state .executor @@ -857,7 +886,7 @@ async fn handle_send( } } let task_json = serde_json::to_value(&task).unwrap(); - save_task(state, &task_id, task_json.clone(), ctx).await?; + save_task(state, &task_id, task_json.clone(), ctx, Some(&skill_id)).await?; drop(terminal); // Deliver the terminal status to any registered webhook. @@ -894,6 +923,9 @@ async fn handle_stream( message, }) => return failed_task_stream(state, task_id, context_id, ctx, id, message).await, }; + if let Err((code, message)) = check_scoped_continuation(state, ctx, params).await { + return Json(rpc_error(&id, code, &message)).into_response(); + } let running = state.running_tasks.register(&task_id, ctx); @@ -919,6 +951,7 @@ async fn handle_stream( &task_id, serde_json::to_value(&task).unwrap(), &ctx2, + Some(&skill_id), ) .await { @@ -957,6 +990,7 @@ async fn handle_stream( &task_id, serde_json::to_value(&task).unwrap(), &ctx2, + Some(&skill_id), ) .await { @@ -999,10 +1033,12 @@ async fn handle_stream( "Execution timed out", ))); } - let chunks = - state2 - .executor - .stream_channel(skill_id, inputs, identity, execution.token.clone()); + let chunks = state2.executor.stream_channel( + skill_id.clone(), + inputs, + identity, + execution.token.clone(), + ); forward_artifacts(&state2, &task, chunks, &tx, &id).await }; let mut canceled = execution.client_canceled.subscribe(); @@ -1036,6 +1072,7 @@ async fn handle_stream( &task_id, serde_json::to_value(&task).unwrap(), &ctx2, + Some(&skill_id), ) .await { @@ -1153,11 +1190,15 @@ async fn handle_get( /// (`a2a-python`'s `OwnerResolver`, `a2a-js`'s per-context bucket); the spec /// repo is silent on it, so this follows upstream. async fn handle_list(state: &AppState, ctx: &CallContext) -> Result, (i32, String)> { - state + let tasks = state .task_store .list(&ListParams::new(), ctx) .await - .map_err(|e| store_failure("task store list", e)) + .map_err(|e| store_failure("task store list", e))?; + Ok(tasks + .into_iter() + .filter_map(|task| visible_task(state, ctx, task).map(|record| record.task)) + .collect()) } /// `tasks/cancel` — signal cooperative cancellation and mark the task canceled. @@ -1187,12 +1228,12 @@ async fn handle_cancel( // Another principal's task reads back as absent, so it is reported as // missing rather than as forbidden. - let stored = read_task(state, task_id, ctx) + let stored = read_task_record(state, task_id, ctx) .await? .ok_or((CODE_TASK_NOT_FOUND, "Task not found".to_string()))?; // A task whose stored JSON cannot be read back is unusable, not cancelable. - let mut task: Task = serde_json::from_value(stored) + let mut task: Task = serde_json::from_value(stored.task) .map_err(|_| (CODE_TASK_NOT_FOUND, "Task not found".to_string()))?; if task.status.state.is_terminal() { @@ -1213,7 +1254,14 @@ async fn handle_cancel( let task_json = serde_json::to_value(&task).unwrap(); // Persist the accepted cancellation before waking the worker. The store // write is serialized with local execution's competing terminal write. - save_task(state, task_id, task_json.clone(), ctx).await?; + save_task( + state, + task_id, + task_json.clone(), + ctx, + stored.skill.as_deref(), + ) + .await?; if let Some(execution) = &execution { execution .client_canceled @@ -1256,11 +1304,10 @@ async fn owned_task_id<'a>( CODE_INVALID_PARAMS, "Missing required parameter: id".to_string(), ))?; - match state.task_store.get(task_id, ctx).await { - Ok(Some(_)) => Ok(task_id), - Ok(None) => Err((CODE_TASK_NOT_FOUND, "Task not found".to_string())), - Err(e) => Err(store_failure(&format!("task store read for {task_id}"), e)), - } + read_task(state, task_id, ctx) + .await? + .map(|_| task_id) + .ok_or((CODE_TASK_NOT_FOUND, "Task not found".to_string())) } /// `tasks/pushNotificationConfig/set` — register a webhook for a task. @@ -1340,6 +1387,11 @@ async fn notify_push(state: &AppState, task_id: &str, ctx: &CallContext, event: Ok(None) => return, Err(_) => return, }; + if ctx.scoped_identity().is_some() + && !matches!(read_task(state, task_id, ctx).await, Ok(Some(_))) + { + return; + } let url = match cfg.get("url").and_then(Value::as_str) { Some(u) => u.to_string(), None => return, @@ -1406,9 +1458,13 @@ async fn store_operation( async fn save_task( state: &AppState, task_id: &str, - task: Value, + mut task: Value, ctx: &CallContext, + skill: Option<&str>, ) -> Result<(), (i32, String)> { + if ctx.scoped_identity().is_some() { + task[TASK_AUTHORITY] = json!({"owner": ctx.owner().as_str(), "skill": skill}); + } store_operation( state, &format!("task store write for {task_id}"), @@ -1422,12 +1478,68 @@ async fn read_task( task_id: &str, ctx: &CallContext, ) -> Result, (i32, String)> { - store_operation( + Ok(read_task_record(state, task_id, ctx) + .await? + .map(|record| record.task)) +} + +const TASK_AUTHORITY: &str = "_apcoreTaskAuthority"; + +struct VisibleTask { + task: Value, + skill: Option, +} + +/// Check the durable binding before exposing a task and strip private metadata from the wire. +fn visible_task(state: &AppState, ctx: &CallContext, mut task: Value) -> Option { + let binding = task + .as_object_mut() + .and_then(|object| object.remove(TASK_AUTHORITY)); + let Some(identity) = ctx.scoped_identity() else { + return binding + .is_none() + .then_some(VisibleTask { task, skill: None }); + }; + let binding = binding?; + let owner = binding.get("owner").and_then(Value::as_str)?; + let skill = binding.get("skill").and_then(Value::as_str)?; + if owner != ctx.owner().as_str() || !state.executor.scoped_skill_visible(skill, identity) { + return None; + } + Some(VisibleTask { + task, + skill: Some(skill.to_owned()), + }) +} + +async fn read_task_record( + state: &AppState, + task_id: &str, + ctx: &CallContext, +) -> Result, (i32, String)> { + let task = store_operation( state, &format!("task store read for {task_id}"), state.task_store.get(task_id, ctx), ) - .await + .await?; + Ok(task.and_then(|task| visible_task(state, ctx, task))) +} + +async fn check_scoped_continuation( + state: &AppState, + ctx: &CallContext, + params: &Value, +) -> Result<(), (i32, String)> { + if let (Some(_), Some(task_id)) = ( + ctx.scoped_identity(), + params.pointer("/message/taskId").and_then(Value::as_str), + ) { + if read_task(state, task_id, ctx).await?.is_none() { + return Err((CODE_TASK_NOT_FOUND, "Task not found".to_string())); + } + } + Ok(()) } fn canceled_by_client() -> TaskStatus { diff --git a/a2a/rust/src/storage/mod.rs b/a2a/rust/src/storage/mod.rs index e2f37150..10faea2e 100644 --- a/a2a/rust/src/storage/mod.rs +++ b/a2a/rust/src/storage/mod.rs @@ -32,6 +32,8 @@ use apcore::context::Identity; #[derive(Clone, Debug, Default, PartialEq, Eq, Hash, PartialOrd, Ord)] pub struct OwnerId(String); +const OWNER_PREFIX: &str = "apcore:"; + impl OwnerId { /// The shared bucket for requests carrying no authenticated identity. pub fn anonymous() -> Self { @@ -40,7 +42,17 @@ impl OwnerId { /// The owner for a request's authenticated principal. pub fn from_identity(identity: Option<&Identity>) -> Self { - Self(identity.map(|i| i.id().to_string()).unwrap_or_default()) + let Some(identity) = identity else { + return Self::anonymous(); + }; + if let Some(owner) = identity.owner_key() { + return Self(format!("{OWNER_PREFIX}scoped:{owner}")); + } + let id = identity.id(); + if id.starts_with(OWNER_PREFIX) { + return Self(format!("{OWNER_PREFIX}legacy:{id}")); + } + Self(id.to_owned()) } /// The owner as a string; empty for the anonymous bucket. @@ -67,15 +79,27 @@ impl std::fmt::Display for OwnerId { /// arbitrary state bag later is then a non-breaking change. Upstream's /// equivalent (`a2a-python`'s `ServerCallContext`) grew exactly those fields /// over time. -#[derive(Clone, Debug, Default)] +#[derive(Clone, Default)] pub struct CallContext { owner: OwnerId, + scoped_identity: Option, +} + +impl std::fmt::Debug for CallContext { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("CallContext") + .field("owner", &self.owner) + .finish_non_exhaustive() + } } impl CallContext { /// A context for an explicit owner. pub fn new(owner: OwnerId) -> Self { - Self { owner } + Self { + owner, + scoped_identity: None, + } } /// A context for the shared anonymous bucket. @@ -85,13 +109,22 @@ impl CallContext { /// A context for a request's authenticated principal. pub fn from_identity(identity: Option<&Identity>) -> Self { - Self::new(OwnerId::from_identity(identity)) + Self { + owner: OwnerId::from_identity(identity), + scoped_identity: identity + .filter(|identity| identity.scopes().is_some()) + .cloned(), + } } /// The principal this call is scoped to. pub fn owner(&self) -> &OwnerId { &self.owner } + + pub(crate) fn scoped_identity(&self) -> Option<&Identity> { + self.scoped_identity.as_ref() + } } /// Filtering and pagination options for [`TaskStore::list`]. @@ -158,6 +191,8 @@ impl StoreError { /// - [`list`](TaskStore::list) **must** return only `ctx.owner()`'s tasks. /// - [`save`](TaskStore::save) **must** store under `ctx.owner()`. Two owners /// may hold the same task id without seeing each other's copy. +/// - Store the complete JSON value. Scoped tasks carry private adapter metadata +/// for an authorization check when read, including after a restart. /// /// The simplest way to satisfy all four at once is to bucket by owner — key the /// backing map (or the database's primary key) on `(owner, task_id)` rather @@ -353,6 +388,17 @@ mod tests { json!({ "id": id, "status": { "state": "completed" } }) } + #[test] + fn scoped_owner_namespace_is_disjoint_from_legacy_ids() { + let identity = Identity::new("alice".into(), "user".into(), vec![], HashMap::new()) + .with_authority(Some(vec!["read".into()]), Some("issuer".into())) + .unwrap(); + let owner = OwnerId::from_identity(Some(&identity)); + let legacy = Identity::new(owner.as_str().into(), "user".into(), vec![], HashMap::new()); + assert_ne!(owner, OwnerId::from_identity(Some(&legacy))); + assert_ne!(owner, OwnerId::anonymous()); + } + #[tokio::test] async fn two_owners_may_hold_the_same_task_id_without_seeing_each_other() { // Bucketing, not a global id -> owner index: the same id in two buckets diff --git a/a2a/rust/tests/integration.rs b/a2a/rust/tests/integration.rs index 90bf14f1..4054432a 100644 --- a/a2a/rust/tests/integration.rs +++ b/a2a/rust/tests/integration.rs @@ -1244,6 +1244,125 @@ async fn advertised_skills(router: axum::Router, bearer: &str) -> Vec { skill_ids(&body_json(router.oneshot(req).await.unwrap()).await) } +#[tokio::test] +async fn delegated_jwt_rechecks_current_skill_access_for_cards_and_task_operations() { + use apcore::acl::{ACLRule, ACL}; + use apcore::config::Config; + use apcore::executor::Executor; + use apcore_a2a::{ + A2AServerFactory, ApCoreAgentExecutor, CreateOptions, DelegatedClaims, + InMemoryPushConfigStore, InMemoryTaskStore, JWTAuthenticator, PartConverter, + SchemaConverter, + }; + use jsonwebtoken::{encode, Algorithm, EncodingKey, Header}; + + const KEY: &str = "a2a-test-key"; + let auth = JWTAuthenticator::new(KEY) + .with_issuer("tenant-issuer") + .with_audience("a2a") + .with_delegated_claims(DelegatedClaims::default()); + let mut rule = ACLRule::new(vec!["@external".into()], vec!["test.echo".into()], "allow"); + rule.conditions = Some(json!({"scopes": ["echo:read"], "subject_roles": ["allowed"]})); + let auth = Arc::new(auth); + let tasks = Arc::new(InMemoryTaskStore::new()); + let push = Arc::new(InMemoryPushConfigStore::new()); + let make_app = || { + let registry = echo_registry(); + let mut executor = Executor::new(registry.clone(), Config::default()); + executor.set_acl(ACL::new(vec![rule.clone()], "deny", None)); + let agent = Arc::new(ApCoreAgentExecutor::new( + Arc::new(executor), + PartConverter::new(SchemaConverter::new()), + 300, + )); + let options = CreateOptions::new(agent, "agent", "Test agent", "0.1", "http://localhost") + .with_auth(auth.clone()) + .with_task_store(tasks.clone()) + .with_push_config_store(push.clone()); + A2AServerFactory::new().create(®istry, options).0 + }; + let app = make_app(); + + let sign = |subject, scope, history| { + encode( + &Header::new(Algorithm::HS256), + &json!({ + "sub": subject, "iss": "tenant-issuer", "aud": "a2a", + "exp": jsonwebtoken::get_current_timestamp() + 120, + "roles": ["allowed"], "scope": scope, + "act": {"sub": "shared-actor", "act": {"sub": history, "roles": ["allowed"]}} + }), + &EncodingKey::from_secret(KEY.as_bytes()), + ) + .unwrap() + }; + let broad = sign("alice", "echo:read echo:write", "old-actor"); + let refreshed = sign("alice", "echo:read", "new-actor"); + let narrowed = sign("alice", "echo:write", "new-actor"); + let other_subject = sign("bob", "echo:read echo:write", "old-actor"); + assert_eq!(advertised_skills(app.clone(), &broad).await, ["test.echo"]); + assert!(advertised_skills(app.clone(), &narrowed).await.is_empty()); + + let rpc = |method: &str, params: Value| json!({"jsonrpc": "2.0", "id": "1", "method": method, "params": params}); + let send_params = json!({ + "message": {"messageId": "m1", "role": "ROLE_USER", "parts": [{"data": {"result": "alice-only"}}]}, + "metadata": {"skillId": "test.echo"} + }); + let submitted = post_rpc_as( + app.clone(), + &broad, + rpc("message/send", send_params.clone()), + ) + .await; + assert_eq!( + submitted["result"]["status"]["state"], + "TASK_STATE_COMPLETED" + ); + let task_id = submitted["result"]["id"].as_str().unwrap(); + let set = post_rpc_as(app.clone(), &broad, rpc("tasks/pushNotificationConfig/set", json!({"id": task_id, "pushNotificationConfig": {"url": "https://example.test/events"}}))).await; + assert_eq!(set["result"]["taskId"], task_id); + drop(app); + let app = make_app(); + + for bearer in [&narrowed, &other_subject] { + for method in [ + "tasks/get", + "tasks/cancel", + "tasks/pushNotificationConfig/get", + "tasks/pushNotificationConfig/delete", + ] { + let reply = post_rpc_as(app.clone(), bearer, rpc(method, json!({"id": task_id}))).await; + assert_eq!(reply["error"]["code"], -32001, "{method}: {reply}"); + } + let listing = post_rpc_as(app.clone(), bearer, rpc("ListTasks", json!({}))).await; + assert_eq!(listing["result"]["tasks"], json!([])); + let mut continuation = send_params.clone(); + continuation["message"]["taskId"] = json!(task_id); + let reply = post_rpc_as(app.clone(), bearer, rpc("message/send", continuation)).await; + assert_eq!(reply["error"]["code"], -32001); + } + + let owned = post_rpc_as( + app.clone(), + &refreshed, + rpc("tasks/get", json!({"id": task_id})), + ) + .await; + assert_eq!(owned["result"], submitted["result"]); + let listing = post_rpc_as(app.clone(), &refreshed, rpc("ListTasks", json!({}))).await; + assert_eq!(listing["result"]["tasks"], json!([submitted["result"]])); + let config = post_rpc_as( + app, + &refreshed, + rpc("tasks/pushNotificationConfig/get", json!({"id": task_id})), + ) + .await; + assert_eq!( + config["result"]["pushNotificationConfig"]["url"], + "https://example.test/events" + ); +} + /// Skills the **public** card advertises (srs FR-AGC-003) — no credentials, /// resolved for the anonymous principal at build time. async fn public_skills(router: axum::Router) -> Vec { diff --git a/a2a/typescript/package.json b/a2a/typescript/package.json index 7299482b..ddcfd2d8 100644 --- a/a2a/typescript/package.json +++ b/a2a/typescript/package.json @@ -33,7 +33,7 @@ }, "dependencies": { "@a2a-js/sdk": ">=1.0.1", - "apcore-js": "1.0.0-alpha.4", + "apcore-js": "1.0.0-alpha.5", "apcore-toolkit": "0.15.1-alpha.2", "express": "^5.1.0", "jsonwebtoken": "^9.0.3", diff --git a/a2a/typescript/pnpm-lock.yaml b/a2a/typescript/pnpm-lock.yaml index 3705f2e1..a2dacd0e 100644 --- a/a2a/typescript/pnpm-lock.yaml +++ b/a2a/typescript/pnpm-lock.yaml @@ -12,8 +12,8 @@ importers: specifier: '>=1.0.1' version: 1.0.1(express@5.2.1) apcore-js: - specifier: 1.0.0-alpha.4 - version: 1.0.0-alpha.4(typescript@5.9.3) + specifier: 1.0.0-alpha.5 + version: 1.0.0-alpha.5(typescript@5.9.3) apcore-toolkit: specifier: 0.15.1-alpha.2 version: 0.15.1-alpha.2(@sinclair/typebox@0.34.48)(typescript@5.9.3) @@ -656,8 +656,8 @@ packages: ajv@8.20.0: resolution: {integrity: sha512-Thbli+OlOj+iMPYFBVBfJ3OmCAnaSyNn4M1vz9T6Gka5Jt9ba/HIR56joy65tY6kx/FCF5VXNB819Y7/GUrBGA==} - apcore-js@1.0.0-alpha.4: - resolution: {integrity: sha512-APFaeBqZ0u0BCmeDzGOJ05Byt16zY96NAlqUiRtIEDY51lzLNP4mfr6B6aicBvFZ1Lg4UQDmVKumpkxjXaOiyA==} + apcore-js@1.0.0-alpha.5: + resolution: {integrity: sha512-VmPRnT/S5O2N1nnMsoomOUFCf9kY4Jqe/UfyPCvh1xb8HccEshsQsvqReds652vMQCQ6i0xmcJZA4OKfWHRUJw==} engines: {node: '>=20.0.0'} peerDependencies: typescript: ^5.5.0 @@ -1951,7 +1951,7 @@ snapshots: json-schema-traverse: 1.0.0 require-from-string: 2.0.2 - apcore-js@1.0.0-alpha.4(typescript@5.9.3): + apcore-js@1.0.0-alpha.5(typescript@5.9.3): dependencies: '@sinclair/typebox': 0.34.48 js-yaml: 4.3.2 @@ -1963,7 +1963,7 @@ snapshots: dependencies: '@sinclair/typebox': 0.34.48 ajv: 8.20.0 - apcore-js: 1.0.0-alpha.4(typescript@5.9.3) + apcore-js: 1.0.0-alpha.5(typescript@5.9.3) js-yaml: 4.3.2 transitivePeerDependencies: - typescript diff --git a/a2a/typescript/src/adapters/card-visibility.ts b/a2a/typescript/src/adapters/card-visibility.ts index e319dd30..6cfcc0f7 100644 --- a/a2a/typescript/src/adapters/card-visibility.ts +++ b/a2a/typescript/src/adapters/card-visibility.ts @@ -134,6 +134,16 @@ function aclContext(identity: Identity | null): unknown { } } +/** Check the active Core invocation gate before a scoped skill is disclosed. */ +export function scopedSkillCallable(executor: unknown, skillId: string, identity: Identity): boolean { + const backend = executor as { getCallableDescriptor?(id: string, context: Context): unknown } | null; + try { + return backend?.getCallableDescriptor?.(skillId, Context.create(identity)) != null; + } catch { + return false; + } +} + /** * `[authorized, approvalRequired]` for one skill, from apcore's ACL. * @@ -186,6 +196,12 @@ export function skillAccess( identity: Identity | null, ): Map { const access = new Map(); + if (identity?.scopes !== undefined) { + for (const skillId of skillIds) { + if (scopedSkillCallable(executor, skillId, identity)) access.set(skillId, false); + } + return access; + } const acl = executorAcl(executor); if (acl === null) { for (const skillId of skillIds) access.set(skillId, false); diff --git a/a2a/typescript/src/auth/index.ts b/a2a/typescript/src/auth/index.ts index c6b78517..e8bb0549 100644 --- a/a2a/typescript/src/auth/index.ts +++ b/a2a/typescript/src/auth/index.ts @@ -1,4 +1,5 @@ export type { Authenticator } from "./types.js"; -export { JWTAuthenticator, type ClaimMapping } from "./jwt.js"; +export { JWTAuthenticator } from "./jwt.js"; +export type { ClaimMapping, DelegatedClaims, JWTAuthenticatorOptions } from "./jwt.js"; export { createAuthMiddleware } from "./middleware.js"; export { authIdentityStore, getAuthIdentity } from "./storage.js"; diff --git a/a2a/typescript/src/auth/jwt.ts b/a2a/typescript/src/auth/jwt.ts index d2153eda..f2d2b119 100644 --- a/a2a/typescript/src/auth/jwt.ts +++ b/a2a/typescript/src/auth/jwt.ts @@ -1,5 +1,6 @@ import jwt from "jsonwebtoken"; import { createIdentity, type Identity } from "apcore-js"; +import { readDelegatedJwtAuthority, validateDelegatedClaims, type DelegatedClaims } from "apcore-toolkit"; import type { Authenticator } from "./types.js"; export interface ClaimMapping { @@ -15,8 +16,12 @@ export interface JWTAuthenticatorOptions { issuer?: string; claimMapping?: ClaimMapping; requireClaims?: string[]; + /** Opt in to scope and actor projection from a verified token. */ + delegatedClaims?: DelegatedClaims; } +export type { DelegatedClaims }; + /** * Coerce a JWT claim value to a string using the canonical cross-language rule. * @@ -38,10 +43,11 @@ export class JWTAuthenticator implements Authenticator { private issuer?: string; private claimMapping: Required; private requireClaims: string[]; + private readonly delegatedClaims?: DelegatedClaims; constructor(key: string, opts?: JWTAuthenticatorOptions) { this.key = key; - this.algorithms = opts?.algorithms ?? ["HS256"]; + this.algorithms = [...(opts?.algorithms ?? ["HS256"])]; this.audience = opts?.audience; this.issuer = opts?.issuer; this.claimMapping = { @@ -51,10 +57,20 @@ export class JWTAuthenticator implements Authenticator { attrsClaims: opts?.claimMapping?.attrsClaims ?? [], }; this.requireClaims = opts?.requireClaims ?? ["sub"]; + if (opts?.delegatedClaims !== undefined) { + if (!this.key || this.algorithms.includes("none")) { + throw new TypeError("Delegated JWT claims require signed algorithms and a verification key"); + } + this.delegatedClaims = validateDelegatedClaims(opts.delegatedClaims, this.issuer, this.audience); + } + } + + get rejectInvalidCredentials(): boolean { + return this.delegatedClaims !== undefined; } authenticate(headers: Record): Identity | null { - const authHeader = headers.authorization ?? ""; + const authHeader = headers.authorization ?? (this.delegatedClaims ? headers.Authorization ?? "" : ""); if (!authHeader.toLowerCase().startsWith("bearer ")) return null; const token = authHeader.slice(7).trim(); @@ -63,7 +79,11 @@ export class JWTAuthenticator implements Authenticator { const payload = this.decodeToken(token); if (!payload) return null; - return this.payloadToIdentity(payload); + try { + return this.payloadToIdentity(payload); + } catch { + return null; + } } securitySchemes(): Record { @@ -77,15 +97,17 @@ export class JWTAuthenticator implements Authenticator { }; if (this.audience) opts.audience = this.audience; if (this.issuer) opts.issuer = this.issuer; + if (this.delegatedClaims) opts.clockTolerance = 30; const payload = jwt.verify(token, this.key, opts); if (typeof payload === "string") return null; + const claims = payload as Record; for (const claim of this.requireClaims) { - if (!(claim in payload)) return null; + if (!Object.hasOwn(claims, claim) || (this.delegatedClaims && claims[claim] == null)) return null; } - return payload as Record; + return claims; } catch { return null; } @@ -93,9 +115,11 @@ export class JWTAuthenticator implements Authenticator { private payloadToIdentity(payload: Record): Identity | null { const mapping = this.claimMapping; + const delegation = this.delegatedClaims; + const authority = delegation && readDelegatedJwtAuthority(payload, delegation, Math.floor(Date.now() / 1000)); // The id claim must coerce to a scalar string, or the token is rejected // (canonical rule: a non-scalar `sub` is not a valid identity id). - const id = claimToString(payload[mapping.idClaim]); + const id = authority?.subjectId ?? claimToString(payload[mapping.idClaim]); if (id === null) return null; // Only an absent/null/non-scalar type falls back to "user"; an explicit @@ -106,11 +130,13 @@ export class JWTAuthenticator implements Authenticator { ? rawRoles.map(claimToString).filter((r): r is string => r !== null) : []; - const attrs: Record = {}; - for (const claim of mapping.attrsClaims) { - if (claim in payload) attrs[claim] = payload[claim]; - } + const attrs = Object.fromEntries(mapping.attrsClaims + .filter(key => Object.hasOwn(payload, key) && (!delegation || !["act", "scope", delegation.scpClaim].includes(key))) + .map(key => [key, payload[key]])); - return createIdentity(id, identityType, roles, attrs); + if (!authority) return createIdentity(id, identityType, roles, attrs); + const { issuer, scopes, actor } = authority; + const subject = createIdentity(id, identityType, roles, attrs, { issuer, scopes }); + return actor ? subject.delegate(createIdentity(actor.id, actor.type, actor.roles, {}, { issuer }), scopes) : subject; } } diff --git a/a2a/typescript/src/auth/middleware.ts b/a2a/typescript/src/auth/middleware.ts index caa63b56..65618c6b 100644 --- a/a2a/typescript/src/auth/middleware.ts +++ b/a2a/typescript/src/auth/middleware.ts @@ -39,7 +39,8 @@ export function createAuthMiddleware(opts: AuthMiddlewareOptions) { const identity = authenticator.authenticate(headers); - if (identity === null && requireAuth) { + const badCredential = authenticator.rejectInvalidCredentials === true && Object.hasOwn(req.headers, "authorization"); + if (identity === null && (requireAuth || badCredential)) { res.status(401).set("WWW-Authenticate", "Bearer").json({ error: "Unauthorized", detail: "Missing or invalid Bearer token", diff --git a/a2a/typescript/src/auth/types.ts b/a2a/typescript/src/auth/types.ts index 4cae71a7..5469370e 100644 --- a/a2a/typescript/src/auth/types.ts +++ b/a2a/typescript/src/auth/types.ts @@ -2,5 +2,7 @@ import type { Identity } from "apcore-js"; export interface Authenticator { authenticate(headers: Record): Identity | null; + /** Reject a provided credential that did not authenticate even in permissive mode. */ + readonly rejectInvalidCredentials?: boolean; securitySchemes(): Record; } diff --git a/a2a/typescript/src/index.ts b/a2a/typescript/src/index.ts index e7292b11..86af8e60 100644 --- a/a2a/typescript/src/index.ts +++ b/a2a/typescript/src/index.ts @@ -23,7 +23,7 @@ export { A2AEventSubscriber, createA2AEventSubscriber } from "./event-subscriber export type { A2AEventSubscriberOptions } from "./event-subscriber.js"; // Auth -export type { Authenticator, ClaimMapping } from "./auth/index.js"; +export type { Authenticator, ClaimMapping, DelegatedClaims, JWTAuthenticatorOptions } from "./auth/index.js"; export { JWTAuthenticator } from "./auth/index.js"; export { createAuthMiddleware } from "./auth/index.js"; export { authIdentityStore, getAuthIdentity } from "./auth/index.js"; diff --git a/a2a/typescript/src/server/context.ts b/a2a/typescript/src/server/context.ts index 2a7a6c69..792e718a 100644 --- a/a2a/typescript/src/server/context.ts +++ b/a2a/typescript/src/server/context.ts @@ -1,15 +1,24 @@ import type { Request } from "express"; +import { createHash } from "node:crypto"; import { ServerCallContext, UnauthenticatedUser } from "@a2a-js/sdk/server"; import type { User } from "@a2a-js/sdk/server"; import type { Identity } from "apcore-js"; import { getAuthIdentity } from "../auth/storage.js"; +export const TASK_OWNER_KEY = "apcoreOwner"; +export const TASK_SKILL_KEY = "apcoreSkill"; +const OWNER_PREFIX = "apcore:"; + +export function scopedOwner(identity: Identity | null): string | null { + const owner = identity?.ownerKey?.() ?? null; + return owner === null ? null : createHash("sha256").update("apcore-a2a-owner-v1\0" + owner).digest("hex"); +} + /** * Adapts an apcore `Identity` to a2a-js's `User` interface. * - * `userName` is the identity id, which is what a2a-js's `resolveUserScope` uses - * as the owner key -- the same principal the executor puts on the apcore - * `Context`, so governance and task scoping name the same caller. + * `userName` identifies the owner's bucket in a2a-js. The scoped namespace + * binds the actor and effective subject while staying stable on scope refresh. */ export class IdentityUser implements User { constructor(readonly identity: Identity) {} @@ -19,7 +28,10 @@ export class IdentityUser implements User { } get userName(): string { - return this.identity.id; + const owner = scopedOwner(this.identity); + if (owner !== null) return `${OWNER_PREFIX}scoped:${owner}`; + const legacy = this.identity.id; + return legacy.startsWith(OWNER_PREFIX) ? `${OWNER_PREFIX}legacy:${legacy}` : legacy; } } @@ -79,7 +91,7 @@ export function anonymousContext(): ServerCallContext { * Returns `null` for `UnauthenticatedUser`, which is the value the card filter * treats as the anonymous principal. */ -export function identityOf(context: ServerCallContext): Identity | null { - const user = context.user as { identity?: Identity } | undefined; +export function identityOf(context: ServerCallContext | undefined): Identity | null { + const user = context?.user as { identity?: Identity } | undefined; return user?.identity ?? null; } diff --git a/a2a/typescript/src/server/executor.ts b/a2a/typescript/src/server/executor.ts index 095ef3e9..8326a68a 100644 --- a/a2a/typescript/src/server/executor.ts +++ b/a2a/typescript/src/server/executor.ts @@ -18,6 +18,7 @@ import { } from "../adapters/errors.js"; import type { PartConverter } from "../adapters/parts.js"; import type { Registry } from "../adapters/agent-card.js"; +import { identityOf, scopedOwner, TASK_OWNER_KEY, TASK_SKILL_KEY } from "./context.js"; /** * This package's default error-redaction policy, used when no deployment has @@ -175,6 +176,8 @@ export class ApCoreAgentExecutor implements AgentExecutor { clientCancellation: new AbortController(), }; this.executions.set(eventBus, task); + const requestedSkill = context.userMessage?.metadata?.skillId; + const owner = scopedOwner(identityOf(context.context) ?? getAuthIdentity()); eventBus.publish( AgentEvent.task({ id: taskId, @@ -182,16 +185,16 @@ export class ApCoreAgentExecutor implements AgentExecutor { status: makeStatus(TaskState.TASK_STATE_SUBMITTED), artifacts: [], history: [], - metadata: undefined, + metadata: owner === null || typeof requestedSkill !== "string" + ? undefined : { [TASK_OWNER_KEY]: owner, [TASK_SKILL_KEY]: requestedSkill }, }), ); if (task.terminal !== undefined) return; // 2. Get skillId from message metadata - const metadata = context.userMessage?.metadata ?? {}; - const skillId = metadata.skillId as string | undefined; - if (!skillId) { + const skillId = requestedSkill; + if (typeof skillId !== "string" || !skillId) { this.publishOutcome(task, eventBus, "submitted", "failed", "Missing required parameter: metadata.skillId"); return; } diff --git a/a2a/typescript/src/server/factory.ts b/a2a/typescript/src/server/factory.ts index 87a54869..67ead081 100644 --- a/a2a/typescript/src/server/factory.ts +++ b/a2a/typescript/src/server/factory.ts @@ -22,6 +22,7 @@ import { AgentCardBuilder, type Registry } from "../adapters/agent-card.js"; import { buildExtendedCard, buildPublicCard, + scopedSkillCallable, type RegistryLike, } from "../adapters/card-visibility.js"; import { getAuthIdentity } from "../auth/storage.js"; @@ -338,7 +339,10 @@ export class A2AServerFactory { Promise.resolve(buildExtendedCard(fullCard, executor, identityOf(context))) : undefined; - const requestHandler = new A2ATaskRequestHandler(agentCard, taskStore, apcoreExecutor, extendedAgentCardProvider); + const requestHandler = new A2ATaskRequestHandler( + agentCard, taskStore, apcoreExecutor, extendedAgentCardProvider, + (skillId, identity) => scopedSkillCallable(executor, skillId, identity), + ); // Build Express app const app = express(); diff --git a/a2a/typescript/src/server/task-persistence.ts b/a2a/typescript/src/server/task-persistence.ts index d8ed6654..d4141757 100644 --- a/a2a/typescript/src/server/task-persistence.ts +++ b/a2a/typescript/src/server/task-persistence.ts @@ -1,12 +1,16 @@ import { AsyncLocalStorage } from "node:async_hooks"; +import { createHmac, randomBytes, timingSafeEqual } from "node:crypto"; import { TaskState } from "@a2a-js/sdk"; import type { - AgentCard, CancelTaskRequest, SendMessageRequest, StreamResponse, Task, TaskStatus, + AgentCard, CancelTaskRequest, Message, SendMessageRequest, StreamResponse, Task, TaskStatus, } from "@a2a-js/sdk"; +import { RequestMalformedError, TaskNotFoundError } from "@a2a-js/sdk/errors"; import { DefaultRequestHandler, resolveUserScope } from "@a2a-js/sdk/server"; import type { AgentExecutionEvent, AgentExecutor, ExecutionEventBus, ExtendedAgentCardProvider, RequestContext, ServerCallContext, TaskStore, } from "@a2a-js/sdk/server"; +import type { Identity } from "apcore-js"; +import { identityOf, scopedOwner, TASK_OWNER_KEY, TASK_SKILL_KEY } from "./context.js"; const TERMINAL_STATES = new Set([ TaskState.TASK_STATE_COMPLETED, @@ -15,6 +19,10 @@ const TERMINAL_STATES = new Set([ TaskState.TASK_STATE_REJECTED, ]); +const DEFAULT_PAGE_SIZE = 50; +const SCOPED_SCAN_PAGE_SIZE = 100; +const SCOPED_PAGE_TOKEN = /^v1\.([1-9][0-9]{0,14})\.([0-9a-f]{64})$/; + function isTerminal(state: TaskState | undefined): boolean { return state !== undefined && TERMINAL_STATES.has(state); } @@ -37,8 +45,21 @@ class TaskPersistence implements TaskStore { private readonly claimKeys = new WeakMap>(); private readonly abandoned = new WeakSet(); private readonly watches = new WeakMap void>(); + private readonly pageTokenKey = randomBytes(32); + + constructor( + private readonly store: TaskStore, + private readonly canUseScopedSkill?: (skillId: string, identity: Identity) => boolean, + ) {} - constructor(private readonly store: TaskStore) {} + private canRead(task: Task, context: ServerCallContext): boolean { + const identity = identityOf(context); + const owner = scopedOwner(identity); + if ((task.metadata?.[TASK_OWNER_KEY] ?? null) !== owner) return false; + if (owner === null) return true; + const skill = task.metadata?.[TASK_SKILL_KEY]; + return identity !== null && typeof skill === "string" && this.canUseScopedSkill?.(skill, identity) === true; + } cancel(taskId: string, run: () => Promise): Promise { return this.cancelRequests.run(taskId, run); @@ -78,6 +99,7 @@ class TaskPersistence implements TaskStore { this.abandon(context); throw error; } + if (task && !this.canRead(task, context)) return undefined; if (!task || this.cancelRequests.getStore() !== taskId || isTerminal(task.status?.state)) { return task; } @@ -99,7 +121,7 @@ class TaskPersistence implements TaskStore { if (this.cancelRequests.getStore() === task.id && state === TaskState.TASK_STATE_CANCELED) { // The SDK can reach its direct-write fallback with a stale Store snapshot. const current = await this.store.load(task.id, context); - if (!current || isTerminal(current.status?.state)) return; + if (!current || !this.canRead(current, context) || isTerminal(current.status?.state)) return; const claim = this.terminalClaims.get(key); if (claim?.contextId === task.contextId && claim.status.state !== state) return; } @@ -123,8 +145,70 @@ class TaskPersistence implements TaskStore { } } - list(...args: Parameters): ReturnType { - return this.store.list(...args); + async list(...args: Parameters): ReturnType { + const [params, context] = args; + const identity = identityOf(context); + const authority = identity?.authorityKey?.(); + if (authority != null) return this.listScoped(params, context, authority); + + const page = await this.store.list(...args); + const tasks = page.tasks.filter(task => this.canRead(task, context)); + if (tasks.length === page.tasks.length) return page; + // The underlying cursor may contain the last task's id. Only expose a + // continuation if that task is visible to the current authority. + const lastTask = page.tasks.at(-1); + return { + ...page, tasks, totalSize: tasks.length, + nextPageToken: lastTask && this.canRead(lastTask, context) ? page.nextPageToken : "", + }; + } + + private async listScoped( + params: Parameters[0], context: ServerCallContext, authority: string, + ): ReturnType { + const pageSize = params.pageSize ?? DEFAULT_PAGE_SIZE; + if (!Number.isSafeInteger(pageSize) || pageSize < 1) { + throw new RequestMalformedError("pageSize must be a positive integer"); + } + const binding = JSON.stringify([ + context.tenant ?? null, authority, params.contextId, params.status, params.statusTimestampAfter, + params.historyLength, params.includeArtifacts, + ]); + let offset = 0; + if (params.pageToken) { + const cursor = SCOPED_PAGE_TOKEN.exec(params.pageToken); + if (!cursor || !timingSafeEqual(this.signOffset(binding, cursor[1]), Buffer.from(cursor[2], "hex"))) { + throw new RequestMalformedError("Invalid page token"); + } + offset = Number(cursor[1]); + } + + // Page and count the visible results, never expose storage cursors or counts. + const tasks: Task[] = []; + const seenTokens = new Set(); + let storageToken = ""; + let totalSize = 0; + do { + const page = await this.store.list({ ...params, pageSize: SCOPED_SCAN_PAGE_SIZE, pageToken: storageToken }, context); + for (const task of page.tasks) { + if (this.canRead(task, context)) { + if (offset <= totalSize && totalSize < offset + pageSize) tasks.push(task); + totalSize++; + } + } + storageToken = page.nextPageToken; + if (storageToken && seenTokens.has(storageToken)) throw new Error("TaskStore repeated a pagination token"); + seenTokens.add(storageToken); + } while (storageToken); + + const nextOffset = offset + tasks.length; + const nextPageToken = nextOffset < totalSize + ? `v1.${nextOffset}.${this.signOffset(binding, String(nextOffset)).toString("hex")}` : ""; + return { tasks, pageSize, totalSize, nextPageToken }; + } + + private signOffset(binding: string, offset: string): Buffer { + return createHmac("sha256", this.pageTokenKey).update(offset + "\0" + binding).digest(); } abandon(context: ServerCallContext): void { @@ -146,8 +230,9 @@ export class A2ATaskRequestHandler extends DefaultRequestHandler { store: TaskStore, agent: AgentExecutor, extendedAgentCardProvider?: ExtendedAgentCardProvider, + canUseScopedSkill?: (skillId: string, identity: Identity) => boolean, ) { - const persistence = new TaskPersistence(store); + const persistence = new TaskPersistence(store, canUseScopedSkill); super(card, persistence, { execute(context, bus) { persistence.observe(context, bus); @@ -160,6 +245,21 @@ export class A2ATaskRequestHandler extends DefaultRequestHandler { this.persistence = persistence; } + private async checkScopedContinuation(params: SendMessageRequest, context: ServerCallContext): Promise { + const taskId = params.message?.taskId; + if (!taskId || scopedOwner(identityOf(context)) === null) return; + const task = await this.persistence.load(taskId, context); + if (!task) throw new TaskNotFoundError("Task not found"); + if (task.metadata?.[TASK_SKILL_KEY] !== params.message?.metadata?.skillId) { + throw new RequestMalformedError("A scoped task continuation must use the original skill"); + } + } + + override async sendMessage(params: SendMessageRequest, context: ServerCallContext): Promise { + await this.checkScopedContinuation(params, context); + return super.sendMessage(params, context); + } + override cancelTask(params: CancelTaskRequest, context: ServerCallContext): Promise { return this.persistence.cancel(params.id, () => super.cancelTask(params, context)); } @@ -168,6 +268,7 @@ export class A2ATaskRequestHandler extends DefaultRequestHandler { params: SendMessageRequest, context: ServerCallContext, ): AsyncGenerator { try { + await this.checkScopedContinuation(params, context); yield* super.sendMessageStream(params, context); } finally { this.persistence.abandon(context); diff --git a/a2a/typescript/tests/auth/middleware.test.ts b/a2a/typescript/tests/auth/middleware.test.ts index be5b342a..122b1c1a 100644 --- a/a2a/typescript/tests/auth/middleware.test.ts +++ b/a2a/typescript/tests/auth/middleware.test.ts @@ -92,6 +92,16 @@ describe("createAuthMiddleware", () => { }); describe("authentication", () => { + it("rejects provided bad scoped credentials in permissive mode", () => { + const authenticator = { ...makeAuthenticator(null), rejectInvalidCredentials: true }; + const middleware = createAuthMiddleware({ authenticator, requireAuth: false }); + const malformed = makeRes(); + middleware(makeReq("/", "Bearer invalid"), malformed, next); + expect(malformed.statusCode).toBe(401); + expect(next).not.toHaveBeenCalled(); + middleware(makeReq("/"), makeRes(), next); + expect(next).toHaveBeenCalledOnce(); + }); it("returns 401 when auth fails and requireAuth is true", () => { const middleware = createAuthMiddleware({ authenticator: makeAuthenticator(null), diff --git a/a2a/typescript/tests/security/task-scoping.test.ts b/a2a/typescript/tests/security/task-scoping.test.ts index 63c75d68..971699d6 100644 --- a/a2a/typescript/tests/security/task-scoping.test.ts +++ b/a2a/typescript/tests/security/task-scoping.test.ts @@ -14,8 +14,11 @@ import { describe, it, expect, vi, afterAll } from "vitest"; import request from "supertest"; import type { Express } from "express"; import type { Server } from "node:http"; -import { createIdentity } from "apcore-js"; +import { InMemoryTaskStore } from "@a2a-js/sdk/server"; +import { ACL, Executor, Registry as CoreRegistry, createIdentity } from "apcore-js"; +import jwt from "jsonwebtoken"; import { A2AServerFactory } from "../../src/server/factory.js"; +import { JWTAuthenticator } from "../../src/auth/jwt.js"; import type { Registry } from "../../src/adapters/agent-card.js"; import type { Authenticator } from "../../src/auth/types.js"; @@ -126,13 +129,13 @@ async function rpc( } /** Run one task as `who` and return its id. */ -async function submit(app: Express, who: string, messageId: string): Promise { +async function submit(app: Express, who: string, messageId: string, skillId = "echo"): Promise { const body = await rpc(app, who, "SendMessage", { message: { messageId, role: "ROLE_USER", parts: [{ text: "{}" }], - metadata: { skillId: "echo" }, + metadata: { skillId }, }, }); expect(body.error, JSON.stringify(body)).toBeUndefined(); @@ -150,6 +153,122 @@ async function listTaskIds(app: Express, who: string): Promise { return tasks.map((t) => t.id).sort(); } +describe("verified delegated A2A task authority", () => { + const key = "a2a-signed-test-secret"; + const issuer = "https://issuer.example"; + const audience = "a2a-test"; + const skillId = "secure.echo"; + const auth = new JWTAuthenticator(key, { + issuer, audience, delegatedClaims: { scpClaim: "scp", actorRolesClaim: "currentRoles" }, + }); + + function signed(claims: Record = {}, secret = key): string { + return jwt.sign({ + iss: issuer, aud: audience, sub: "subject", exp: Math.floor(Date.now() / 1000) + 300, + scp: ["read", "write"], roles: ["subject-role"], + act: { sub: "same-actor", currentRoles: ["runner"], act: { sub: "prior", currentRoles: ["admin"] } }, + ...claims, + }, secret); + } + + it("validates the signed issuer, audience and time window before selecting a current actor", () => { + const current = auth.authenticate({ authorization: `Bearer ${signed()}` }); + expect(current?.roles).toEqual(["runner"]); + expect(current?.rootSubject.roles).toEqual(["subject-role"]); + expect(current?.delegationDepth).toBe(1); + expect(current?.scopes).toEqual(["read", "write"]); + for (const token of [signed({}, "different-key"), signed({ iss: "wrong" }), signed({ aud: "wrong" }), + signed({ iat: Math.floor(Date.now() / 1000) + 150 }), signed({ scope: "yes", scp: ["no"] })]) { + expect(auth.authenticate({ authorization: `Bearer ${token}` })).toBeNull(); + } + }); + + it("hides old task results, lists, and push subscriptions after scope or subject changes", async () => { + const registry = new CoreRegistry(); + await registry.register(skillId, { + description: "Echo a scoped result", + inputSchema: { type: "object" }, outputSchema: { type: "object" }, + execute: () => ({ value: "private" }), + }); + const executor = new Executor({ registry, acl: new ACL([{ + callers: ["@external"], targets: [skillId], effect: "allow", + conditions: { scopes: ["write"], roles: ["runner"], subject_roles: ["subject-role"] }, + }]) }); + const { app } = new A2AServerFactory().create(registry as never, executor, { + name: "Scoped Agent", description: "d", version: "1", url: "http://localhost", + auth, pushNotifications: true, + }); + const broad = signed(); + const result = await rpc(app, broad, "SendMessage", { + message: { messageId: "m-scoped", role: "ROLE_USER", parts: [{ text: "{}" }], metadata: { skillId } }, + }); + expect(result.error, JSON.stringify(result)).toBeUndefined(); + const task = (result.result as { task: { id: string } }).task.id; + expect((await rpc(app, signed(), "GetTask", { id: task })).result?.id).toBe(task); + expect(await listTaskIds(app, signed())).toEqual([task]); + for (const current of [signed({ scp: ["read"] }), signed({ sub: "other-subject" })]) { + expect((await rpc(app, current, "GetTask", { id: task })).error?.code).toBe(TASK_NOT_FOUND_CODE); + expect((await rpc(app, current, "ListTaskPushNotificationConfigs", { taskId: task })).error?.code).toBe(TASK_NOT_FOUND_CODE); + expect(await listTaskIds(app, current)).toEqual([]); + } + const invalid = await request(await serverFor(app)).post("/") + .set("Authorization", `Bearer ${signed({}, "different-key")}`).set("A2A-Version", "1.0") + .send({ jsonrpc: "2.0", id: "bad-token", method: "GetTask", params: { id: task } }); + expect(invalid.status).toBe(401); + }); + + it("pages through hidden tasks without exposing storage cursors or counts", async () => { + class SingleRowStore extends InMemoryTaskStore { + override list(...[params, context]: Parameters) { + return super.list({ ...params, pageSize: 1 }, context); + } + } + const registry = new CoreRegistry(); + const readSkill = "secure.read"; + for (const id of [skillId, readSkill]) { + await registry.register(id, { + description: "Return a scoped result", + inputSchema: { type: "object" }, outputSchema: { type: "object" }, + execute: () => ({ value: "private" }), + }); + } + const executor = new Executor({ registry, acl: new ACL([ + { callers: ["@external"], targets: [skillId], effect: "allow", conditions: { scopes: ["write"] } }, + { callers: ["@external"], targets: [readSkill], effect: "allow", conditions: { scopes: ["read"] } }, + ]) }); + const { app } = new A2AServerFactory().create(registry as never, executor, { + name: "Scoped Agent", description: "d", version: "1", url: "http://localhost", + auth, taskStore: new SingleRowStore(), + }); + const broad = signed(); + const oldest = await submit(app, broad, "m-old-visible", readSkill); + const recent = await submit(app, broad, "m-new-visible", readSkill); + const hidden = await submit(app, broad, "m-hidden", skillId); + const narrow = signed({ scp: ["read"] }); + const query = { status: "TASK_STATE_COMPLETED", pageSize: 1 }; + const page = await rpc(app, narrow, "ListTasks", query); + const first = page.result as { tasks: { id: string }[]; totalSize: number; nextPageToken: string }; + expect(page.error, JSON.stringify(page)).toBeUndefined(); + expect(first.tasks.map(task => task.id)).toEqual([recent]); + expect(first.totalSize).toBe(2); + const cursor = first.nextPageToken; + expect(cursor).toBeTruthy(); + expect(cursor).not.toContain(hidden); + for (const credential of [signed({ scp: ["write"] }), signed({ sub: "other", scp: ["read"] })]) { + const replay = await rpc(app, credential, "ListTasks", { ...query, pageToken: cursor }); + expect(replay.error?.message).toBe("Invalid page token"); + } + const replay = await rpc(app, narrow, "ListTasks", { ...query, contextId: hidden, pageToken: cursor }); + expect(replay.error?.message).toBe("Invalid page token"); + const next = await rpc(app, narrow, "ListTasks", { ...query, pageToken: cursor }); + const second = next.result as typeof first; + expect(next.error, JSON.stringify(next)).toBeUndefined(); + expect(second.tasks.map(task => task.id)).toEqual([oldest]); + expect(second.totalSize).toBe(2); + expect(second.nextPageToken ?? "").toBe(""); + }); +}); + describe("task scoping", () => { describe("reads", () => { it("hides another principal's task behind the same response as an unknown id", async () => { diff --git a/cli/python/pyproject.toml b/cli/python/pyproject.toml index 97f57b0b..3cab4119 100644 --- a/cli/python/pyproject.toml +++ b/cli/python/pyproject.toml @@ -26,7 +26,7 @@ classifiers = [ "Environment :: Console", ] dependencies = [ - "apcore[config,discovery]==1.0.0a4", + "apcore[config,discovery]==1.0.0a5", "apcore-toolkit[http-proxy]==0.15.1a2", "click>=8.1", "jsonschema>=4.20", diff --git a/cli/rust/Cargo.lock b/cli/rust/Cargo.lock index f6b12ffe..02bd27ea 100644 --- a/cli/rust/Cargo.lock +++ b/cli/rust/Cargo.lock @@ -133,9 +133,9 @@ checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" [[package]] name = "apcore" -version = "1.0.0-alpha.4" +version = "1.0.0-alpha.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7d5e08c5bbc5cddf5c72b121cbec90c1c551993dbee7c7cc88e30950941b63ad" +checksum = "1d19939071ba2c589815c061dfb1ff827862e5f1f52251e88297d49eec500a90" dependencies = [ "async-stream", "async-trait", diff --git a/cli/rust/Cargo.toml b/cli/rust/Cargo.toml index 2d4fb496..4ee2f6b5 100644 --- a/cli/rust/Cargo.toml +++ b/cli/rust/Cargo.toml @@ -21,7 +21,7 @@ name = "apcore_cli" path = "src/lib.rs" [dependencies] -apcore = { version = "=1.0.0-alpha.4", default-features = false, features = ["config"] } +apcore = { version = "=1.0.0-alpha.5", default-features = false, features = ["config"] } async-trait = "0.1" clap = { version = "4", features = ["derive", "env", "string"] } serde = { version = "1", features = ["derive"] } diff --git a/cli/typescript/package.json b/cli/typescript/package.json index cee57a3d..3108795c 100644 --- a/cli/typescript/package.json +++ b/cli/typescript/package.json @@ -30,7 +30,7 @@ "node": ">=20.0.0" }, "peerDependencies": { - "apcore-js": "1.0.0-alpha.4", + "apcore-js": "1.0.0-alpha.5", "apcore-toolkit": "0.15.1-alpha.2" }, "dependencies": { @@ -47,7 +47,7 @@ "@typescript-eslint/eslint-plugin": "^8.59.0", "@typescript-eslint/parser": "^8.59.0", "@vitest/coverage-v8": "^5.1.0", - "apcore-js": "1.0.0-alpha.4", + "apcore-js": "1.0.0-alpha.5", "apcore-toolkit": "0.15.1-alpha.2", "apdev-js": "^0.2.4", "eslint": "^10.2.1", diff --git a/cli/typescript/pnpm-lock.yaml b/cli/typescript/pnpm-lock.yaml index 85240567..3273dd2b 100644 --- a/cli/typescript/pnpm-lock.yaml +++ b/cli/typescript/pnpm-lock.yaml @@ -34,8 +34,8 @@ importers: specifier: ^5.1.0 version: 5.1.0(vitest@5.1.0) apcore-js: - specifier: 1.0.0-alpha.4 - version: 1.0.0-alpha.4(typescript@5.9.3) + specifier: 1.0.0-alpha.5 + version: 1.0.0-alpha.5(typescript@5.9.3) apcore-toolkit: specifier: 0.15.1-alpha.2 version: 0.15.1-alpha.2(@sinclair/typebox@0.34.48)(typescript@5.9.3) @@ -731,8 +731,8 @@ packages: any-promise@1.3.0: resolution: {integrity: sha512-7UvmKalWRt1wgjL1RrGxoSJW/0QZFIegpeGvZG9kjp8vrRu55XTHbwnqq2GpXm9uLbcuhxm3IqX9OB4MZR1b2A==} - apcore-js@1.0.0-alpha.4: - resolution: {integrity: sha512-APFaeBqZ0u0BCmeDzGOJ05Byt16zY96NAlqUiRtIEDY51lzLNP4mfr6B6aicBvFZ1Lg4UQDmVKumpkxjXaOiyA==} + apcore-js@1.0.0-alpha.5: + resolution: {integrity: sha512-VmPRnT/S5O2N1nnMsoomOUFCf9kY4Jqe/UfyPCvh1xb8HccEshsQsvqReds652vMQCQ6i0xmcJZA4OKfWHRUJw==} engines: {node: '>=20.0.0'} peerDependencies: typescript: ^5.5.0 @@ -1944,7 +1944,7 @@ snapshots: any-promise@1.3.0: {} - apcore-js@1.0.0-alpha.4(typescript@5.9.3): + apcore-js@1.0.0-alpha.5(typescript@5.9.3): dependencies: '@sinclair/typebox': 0.34.48 js-yaml: 4.3.2 @@ -1956,7 +1956,7 @@ snapshots: dependencies: '@sinclair/typebox': 0.34.48 ajv: 8.20.0 - apcore-js: 1.0.0-alpha.4(typescript@5.9.3) + apcore-js: 1.0.0-alpha.5(typescript@5.9.3) js-yaml: 4.3.2 transitivePeerDependencies: - typescript diff --git a/mcp/docs/features/jwt-authenticator.md b/mcp/docs/features/jwt-authenticator.md index 980ed703..76f62aac 100644 --- a/mcp/docs/features/jwt-authenticator.md +++ b/mcp/docs/features/jwt-authenticator.md @@ -72,6 +72,22 @@ graph TD ### Claim Mapping The authenticator supports a `claim_mapping` configuration that defines which JWT claims correspond to identity fields. By default, `sub` maps to `id`, `roles` to `roles`, and `type` to `type`. +### Delegated JWT Authority + +JWT scope projection is opt-in. Configure the expected issuer and audience alongside the signature verification key and algorithm allowlist. The authenticator requires `sub`, `iss`, `aud`, and `exp` and validates `nbf` and `iat` when supplied. In permissive mode a request without credentials retains anonymous access. A supplied credential must verify and satisfy the configured claim mapping. + +In Python, pass `delegated_claims=DelegatedClaims(...)` to `JWTAuthenticator`. In TypeScript, pass `delegatedClaims` in the authenticator options. In Rust, call `with_delegated_claims(DelegatedClaims { ... })` on the authenticator. The optional provider and outer actor roles fields are `scp_claim` and `actor_roles_claim`, with camelCase names in TypeScript. + +The standard `scope` claim is a space-delimited scope-token string. An explicitly configured provider claim such as `scp` can contain a scope string or an array of scope tokens. If both claims are present, their normalized sets must agree. An empty provider array grants zero scopes. + +The top-level `sub` identifies the root subject. The outermost `act` identifies the current actor and contributes one active delegation link. Actor roles come from a configured field on that outer object. Further nested `act` claims are bounded history and do not participate in the ACL or ownership. Configure a nonempty top-level `scopes` condition on each ACL rule that grants access to a scoped identity. Use `subject_types` and `subject_roles` to evaluate the root subject. + +A live scoped session binds to the authority that opened it. A refreshed token with equivalent authority can reuse the session. Open a new session when the effective scopes or roles change. Scoped tasks retain owner identity across a refresh and are checked against current authority. Approvals issued for one effective scope cannot be polled or resumed from another scope. + +TypeScript Streamable HTTP retains up to 1,000 scoped sessions per transport manager by default. `APCORE_MAX_SCOPED_HTTP_SESSIONS` sets the cap. At capacity the manager closes the least recently used idle session. It returns HTTP 503 when all slots are busy. Capacity eviction leaves submitted background work running. + +Scoped background work uses the Core task manager with its private in-memory store. Configure that manager to use scoped task submission. + ### Permissive Mode If `require_auth=False` is configured, the middleware will attempt to authenticate but will allow the request to proceed even if no token is provided. In this case, the tool will execute with an `Anonymous` identity, and the Executor's ACL will decide if the call is permitted. diff --git a/mcp/python/pyproject.toml b/mcp/python/pyproject.toml index ed1a111b..b5d72ddc 100644 --- a/mcp/python/pyproject.toml +++ b/mcp/python/pyproject.toml @@ -25,7 +25,7 @@ classifiers = [ "Topic :: Scientific/Engineering :: Artificial Intelligence", ] dependencies = [ - "apcore[config,discovery]==1.0.0a4", + "apcore[config,discovery]==1.0.0a5", "mcp>=1.26,<2.0", "jsonschema>=4.20,<5", "referencing>=0.30,<1", diff --git a/mcp/python/src/apcore_mcp/__init__.py b/mcp/python/src/apcore_mcp/__init__.py index 6f20226f..8a9c1edf 100644 --- a/mcp/python/src/apcore_mcp/__init__.py +++ b/mcp/python/src/apcore_mcp/__init__.py @@ -34,6 +34,7 @@ Authenticator, AuthMiddleware, ClaimMapping, + DelegatedClaims, JWTAuthenticator, auth_identity_var, get_current_identity, @@ -95,6 +96,7 @@ "Authenticator", "JWTAuthenticator", "ClaimMapping", + "DelegatedClaims", "AuthMiddleware", # Per-request identity context (cross-SDK parity with TS # ``getCurrentIdentity``/``identityStorage`` and Rust ``AUTH_IDENTITY``) diff --git a/mcp/python/src/apcore_mcp/adapters/approval.py b/mcp/python/src/apcore_mcp/adapters/approval.py index aa39c3e5..31a3ed54 100644 --- a/mcp/python/src/apcore_mcp/adapters/approval.py +++ b/mcp/python/src/apcore_mcp/adapters/approval.py @@ -144,7 +144,10 @@ def _store_failure_reason(exc: BaseException) -> str: def _approval_principal(identity: Identity | None) -> ApprovalPrincipal: - return (identity.type, identity.id) if isinstance(identity, Identity) else None + if not isinstance(identity, Identity): + return None + authority = getattr(identity, "authority_key", lambda: None)() + return authority if authority is not None else (identity.type, identity.id) def _is_public_approval_id(value: object) -> TypeGuard[str]: @@ -174,8 +177,14 @@ def _scope_for(request: ApprovalRequest, snapshot: str) -> ApprovalScope: material = b"apcore-final-scope-v1\0" + encoded else: material = snapshot.encode("utf-8") + principal = _approval_principal(request.context.identity) + authority = getattr(request, "authority_key", None) + if isinstance(principal, str) or authority is not None: + if not isinstance(principal, str) or authority != principal: + raise ValueError("Invalid approval authority binding") + material = b"apcore-delegated-approval-v1\0" + authority.encode("ascii") + b"\0" + material return ApprovalScope( - _approval_principal(request.context.identity), + principal, request.caller_id, request.module_id, sha256(material).hexdigest(), @@ -223,6 +232,10 @@ def scoped_approval_available(self) -> bool: def supports_final_scope(self) -> bool: return self.scoped_approval_available + @property + def supports_authority_scope(self) -> bool: + return self.scoped_approval_available + async def request_approval(self, request: ApprovalRequest) -> ApprovalResult: if not self.scoped_approval_available: return ApprovalResult(status="rejected", reason=_NO_PHASE_B) @@ -350,6 +363,10 @@ def __init__(self, handler: _ScopedMCPApprovalHandler) -> None: def supports_final_scope(self) -> bool: return getattr(self._handler, "supports_final_scope", None) is True + @property + def supports_authority_scope(self) -> bool: + return getattr(self._handler, "supports_authority_scope", None) is True + def _delivery_for(self, request: ApprovalRequest) -> _ApprovalDelivery | None: delivery = _approval_delivery.get() if ( diff --git a/mcp/python/src/apcore_mcp/approval_store.py b/mcp/python/src/apcore_mcp/approval_store.py index ec66fe04..bf36c542 100644 --- a/mcp/python/src/apcore_mcp/approval_store.py +++ b/mcp/python/src/apcore_mcp/approval_store.py @@ -48,7 +48,9 @@ async def resolve(self, approval_id: str, *, approved: bool, reason: str | None ... -ApprovalPrincipal = tuple[str, str] | None +# Scoped records carry the opaque native authority key. Legacy records retain +# the actor tuple, so the two forms cannot match one another. +ApprovalPrincipal = str | tuple[str, str] | None @dataclass(frozen=True) diff --git a/mcp/python/src/apcore_mcp/auth/__init__.py b/mcp/python/src/apcore_mcp/auth/__init__.py index ac499ad7..7dfddec6 100644 --- a/mcp/python/src/apcore_mcp/auth/__init__.py +++ b/mcp/python/src/apcore_mcp/auth/__init__.py @@ -2,7 +2,7 @@ from __future__ import annotations -from apcore_mcp.auth.jwt import ClaimMapping, JWTAuthenticator +from apcore_mcp.auth.jwt import ClaimMapping, DelegatedClaims, JWTAuthenticator from apcore_mcp.auth.middleware import AuthMiddleware, auth_identity_var, extract_headers from apcore_mcp.auth.protocol import Authenticator, Identity @@ -23,6 +23,7 @@ def get_current_identity() -> Identity | None: "Authenticator", "JWTAuthenticator", "ClaimMapping", + "DelegatedClaims", "AuthMiddleware", "auth_identity_var", "extract_headers", diff --git a/mcp/python/src/apcore_mcp/auth/_delegation.py b/mcp/python/src/apcore_mcp/auth/_delegation.py new file mode 100644 index 00000000..fdd25c0c --- /dev/null +++ b/mcp/python/src/apcore_mcp/auth/_delegation.py @@ -0,0 +1,101 @@ +"""Strict projection of verified RFC 8693 JWT claims.""" + +from __future__ import annotations + +import math +import re +from dataclasses import dataclass, replace +from typing import Any + +from apcore import Identity + +_SCOPE_TOKEN = re.compile(r"[\x21\x23-\x5b\x5d-\x7e]+") + + +@dataclass(frozen=True) +class DelegatedClaims: + """Opt in to JWT scopes and optionally select provider and actor-role claims.""" + + scp_claim: str | None = None + actor_roles_claim: str | None = None + + def __post_init__(self) -> None: + for claim in (self.scp_claim, self.actor_roles_claim): + if claim is not None and (not isinstance(claim, str) or not claim): + raise ValueError("JWT claim names must be nonempty strings") + + +def _scopes(value: Any, *, allow_array: bool = False) -> tuple[str, ...]: + if isinstance(value, str): + scopes = value.split(" ") + elif allow_array and isinstance(value, list): + scopes = value + else: + raise ValueError("Invalid JWT scope representation") + if not all(isinstance(scope, str) and _SCOPE_TOKEN.fullmatch(scope) for scope in scopes): + raise ValueError("Invalid JWT scope token") + return tuple(sorted(set(scopes))) + + +def _token_scopes(payload: dict[str, Any], mapping: DelegatedClaims) -> tuple[str, ...]: + standard = _scopes(payload["scope"]) if "scope" in payload else None + alternate = ( + _scopes(payload[mapping.scp_claim], allow_array=True) + if mapping.scp_claim is not None and mapping.scp_claim in payload + else None + ) + if standard is None and alternate is None: + raise ValueError("JWT must carry a configured scope claim") + if standard is not None and alternate is not None and standard != alternate: + raise ValueError("JWT scope claims disagree") + return standard if standard is not None else alternate or () + + +def _nonempty_string(value: Any) -> bool: + return isinstance(value, str) and bool(value) + + +def _validate_times(payload: dict[str, Any]) -> None: + for claim in ("exp", "nbf", "iat"): + if claim in payload: + value = payload[claim] + if type(value) not in (int, float) or not math.isfinite(value): + raise ValueError("JWT time claim must be numeric") + + +def _outer_actor(value: Any, mapping: DelegatedClaims, issuer: str) -> Identity: + node = value + for _ in range(8): + if not isinstance(node, dict) or not _nonempty_string(node.get("sub")): + raise ValueError("JWT act claim must contain a subject") + if "iss" in node and not _nonempty_string(node["iss"]): + raise ValueError("JWT actor issuer must be a nonempty string") + if "act" not in node: + break + node = node["act"] + else: + raise ValueError("JWT actor history is too deep") + + actor_type = value.get("type", "agent") + if not _nonempty_string(actor_type): + raise ValueError("JWT actor type must be a nonempty string") + roles = value.get(mapping.actor_roles_claim, []) if mapping.actor_roles_claim is not None else [] + if not isinstance(roles, list) or not all(_nonempty_string(role) for role in roles): + raise ValueError("Mapped JWT actor roles must be an array of strings") + return Identity(value["sub"], actor_type, tuple(roles), issuer=issuer) + + +def project_delegated_identity(payload: dict[str, Any], identity: Identity, mapping: DelegatedClaims) -> Identity: + """Map verified claims to one active link and validate bounded actor history.""" + issuer = payload["iss"] + subject_id = payload["sub"] + if not _nonempty_string(issuer) or not _nonempty_string(subject_id): + raise ValueError("JWT issuer and subject must be nonempty strings") + _validate_times(payload) + scopes = _token_scopes(payload, mapping) + mapped_claims = {"act", "scope", mapping.scp_claim} + attrs = {key: value for key, value in identity.attrs.items() if key not in mapped_claims} + subject = replace(identity, id=subject_id, attrs=attrs, issuer=issuer, scopes=scopes) + if "act" not in payload: + return subject + return subject.delegate(_outer_actor(payload["act"], mapping, issuer), scopes) diff --git a/mcp/python/src/apcore_mcp/auth/jwt.py b/mcp/python/src/apcore_mcp/auth/jwt.py index 608f9aec..952d96b8 100644 --- a/mcp/python/src/apcore_mcp/auth/jwt.py +++ b/mcp/python/src/apcore_mcp/auth/jwt.py @@ -8,7 +8,9 @@ import jwt as pyjwt from apcore import Identity +from apcore.errors import InvalidInputError +from apcore_mcp.auth._delegation import DelegatedClaims, project_delegated_identity from apcore_mcp.auth.protocol import Authenticator logger = logging.getLogger(__name__) @@ -45,6 +47,7 @@ class JWTAuthenticator: issuer: Expected ``iss`` claim (optional). claim_mapping: Maps JWT claims to Identity fields. require_claims: Claims that must be present in the token. + delegated_claims: Enable verified JWT scope and actor projection. """ def __init__( @@ -56,7 +59,13 @@ def __init__( issuer: str | None = None, claim_mapping: ClaimMapping | None = None, require_claims: list[str] | None = None, + delegated_claims: DelegatedClaims | None = None, ) -> None: + if delegated_claims is not None and ( + not isinstance(issuer, str) or not issuer or not isinstance(audience, str) or not audience + ): + raise ValueError("JWT delegation requires an expected issuer and audience") + self._delegated_claims = delegated_claims self._key = key self._algorithms = algorithms or ["HS256"] self._audience = audience @@ -64,6 +73,11 @@ def __init__( self._claim_mapping = claim_mapping or ClaimMapping() self._require_claims: list[str] = require_claims if require_claims is not None else ["sub"] + @property + def rejects_invalid_credentials(self) -> bool: + """Reject a supplied invalid credential even in permissive middleware.""" + return self._delegated_claims is not None + async def authenticate(self, headers: dict[str, str]) -> Identity | None: """Extract Bearer token from headers, decode, and return Identity. @@ -90,14 +104,25 @@ async def authenticate(self, headers: dict[str, str]) -> Identity | None: if payload is None: return None - return self._payload_to_identity(payload) + identity = self._payload_to_identity(payload) + mapping = self._delegated_claims + if identity is None or mapping is None: + return identity + try: + return project_delegated_identity(payload, identity, mapping) + except (InvalidInputError, KeyError, OverflowError, TypeError, ValueError): + logger.debug("JWT delegation claim validation failed") + return None def _decode_token(self, token: str) -> dict[str, Any] | None: """Decode and validate a JWT token. Returns None on any error.""" try: options: dict[str, Any] = {} - if self._require_claims: - options["require"] = self._require_claims + required = self._require_claims + if self._delegated_claims is not None: + required = list(dict.fromkeys([*required, "sub", "iss", "aud", "exp"])) + if required: + options["require"] = required kwargs: dict[str, Any] = { "jwt": token, @@ -116,14 +141,14 @@ def _decode_token(self, token: str) -> dict[str, Any] | None: kwargs["issuer"] = self._issuer return pyjwt.decode(**kwargs) - except pyjwt.InvalidTokenError: + except (pyjwt.InvalidTokenError, TypeError, ValueError, OverflowError): logger.debug("JWT validation failed", exc_info=True) return None def _payload_to_identity(self, payload: dict[str, Any]) -> Identity | None: """Convert a decoded JWT payload to an Identity.""" mapping = self._claim_mapping - identity_id = payload.get(mapping.id_claim) + identity_id = payload.get("sub" if self._delegated_claims is not None else mapping.id_claim) if identity_id is None: return None diff --git a/mcp/python/src/apcore_mcp/auth/middleware.py b/mcp/python/src/apcore_mcp/auth/middleware.py index 56e90a86..feb0c2d2 100644 --- a/mcp/python/src/apcore_mcp/auth/middleware.py +++ b/mcp/python/src/apcore_mcp/auth/middleware.py @@ -91,7 +91,10 @@ async def __call__(self, scope: dict[str, Any], receive: Any, send: Any) -> None headers = extract_headers(scope) identity = await call_authenticator(self._authenticator, headers) - if identity is None and self._require_auth: + invalid_credential = ( + "authorization" in headers and getattr(self._authenticator, "rejects_invalid_credentials", False) is True + ) + if identity is None and (self._require_auth or invalid_credential): logger.warning("Authentication failed for %s", path) await self._send_401(send) return diff --git a/mcp/python/src/apcore_mcp/server/async_task_bridge.py b/mcp/python/src/apcore_mcp/server/async_task_bridge.py index 5c4ada67..ccbcd5a1 100644 --- a/mcp/python/src/apcore_mcp/server/async_task_bridge.py +++ b/mcp/python/src/apcore_mcp/server/async_task_bridge.py @@ -15,11 +15,13 @@ import json import logging from collections.abc import Awaitable, Callable -from typing import Any +from dataclasses import dataclass +from typing import Any, Literal +from weakref import WeakKeyDictionary -from apcore import Context -from apcore.async_task import AsyncTaskManager, TaskInfo, TaskStatus -from apcore.errors import TaskLimitExceededError +from apcore import Context, Identity +from apcore.async_task import AsyncTaskManager, InMemoryTaskStore, TaskInfo, TaskStatus +from apcore.errors import ACLDeniedError, TaskLimitExceededError from apcore.trace_context import TraceContext, TraceParent from mcp import types as mcp_types @@ -92,6 +94,15 @@ def _preflight_to_dict(result: Any) -> dict[str, Any]: } +@dataclass +class _ScopedTaskBinding: + owner: str + state: Literal["pending", "published", "failed"] = "pending" + + +_SCOPED_TASK_OWNERS: WeakKeyDictionary[InMemoryTaskStore, dict[str, _ScopedTaskBinding]] = WeakKeyDictionary() + + class AsyncTaskBridge: """Thin routing layer in front of :class:`AsyncTaskManager`. @@ -127,6 +138,10 @@ def __init__( # mass-cancel tasks bound to a transport on disconnect. # Mirrors Rust's `session_tasks` map. self._session_tasks: dict[str, list[str]] = {} + # Ownership and task records must share the lifetime of the local store. + # This also covers a host explicitly reusing the same store in another manager. + store = getattr(manager, "_store", None) + self._scoped_task_owners = _SCOPED_TASK_OWNERS.setdefault(store, {}) if type(store) is InMemoryTaskStore else {} @classmethod def with_limits( @@ -190,8 +205,29 @@ async def submit( mass-cancel tasks bound to that session on transport disconnect. [A-D-019] """ + identity = context.identity if context is not None else None + owner = self._scoped_owner(identity) + if owner is not None and ( + not self._can_disclose(module_id, identity) + or getattr(self._manager, "supports_task_allocation_callback", False) is not True + or getattr(self._manager, "owns_private_task_store", False) is not True + ): + raise ACLDeniedError(None, module_id) + tracked_owners = [ + task_id for task_id, binding in self._scoped_task_owners.items() if binding.state != "pending" + ] + if tracked_owners: + live = {info.task_id for info in await self._manager.list_tasks_async()} + for task_id in tracked_owners: + if task_id not in live: + self._scoped_task_owners.pop(task_id, None) task_id = await self._submit_with_progress( - module_id, arguments, context, progress_token=progress_token, send_notification=send_notification + module_id, + arguments, + context, + owner=owner, + progress_token=progress_token, + send_notification=send_notification, ) if session_key is not None: self._session_tasks.setdefault(session_key, []).append(task_id) @@ -227,6 +263,7 @@ async def _submit_with_progress( arguments: dict[str, Any], context: Context | None, *, + owner: str | None = None, progress_token: Any | None = None, send_notification: Callable[[dict[str, Any]], Awaitable[None]] | None = None, ) -> str: @@ -235,7 +272,21 @@ async def _submit_with_progress( # route through MCP notifications/progress. if context is not None and progress_token is not None and send_notification is not None: self._install_progress_sink(context, progress_token, send_notification) - task_id = await self._manager.submit(module_id, arguments, context) + if owner is None: + task_id = await self._manager.submit(module_id, arguments, context) + else: + binding = _ScopedTaskBinding(owner) + + def reserve(task_id: str) -> None: + self._scoped_task_owners[task_id] = binding + + try: + task_id = await self._manager.submit(module_id, arguments, context, on_task_allocated=reserve) + binding.state = "published" + finally: + # A store may have persisted the record before reporting a failure. + if binding.state == "pending": + binding.state = "failed" if progress_token is not None and send_notification is not None: self._progress_bindings[task_id] = (progress_token, send_notification) return task_id @@ -361,15 +412,16 @@ async def handle_meta_tool( ) -> tuple[list[dict[str, Any]], bool, str | None]: """Dispatch a meta-tool call. Returns ``(content, is_error, trace_id)``.""" args = arguments or {} + identity = (router_extra or {}).get("identity") try: if name == "__apcore_task_submit": return await self._handle_submit_tool(args, resolve_descriptor, router_extra or {}) if name == "__apcore_task_status": - return self._handle_status_tool(args) + return await self._handle_status_tool(args, identity) if name == "__apcore_task_cancel": - return await self._handle_cancel_tool(args) + return await self._handle_cancel_tool(args, identity) if name == "__apcore_task_list": - return self._handle_list_tool(args) + return await self._handle_list_tool(args, identity) if name == "__apcore_module_preview": return await self._handle_preview_tool(args, router_extra or {}) except TaskLimitExceededError as exc: @@ -430,12 +482,14 @@ async def _handle_submit_tool( ) return self._text_response(envelope) - def _handle_status_tool(self, args: dict[str, Any]) -> tuple[list[dict[str, Any]], bool, str | None]: + async def _handle_status_tool( + self, args: dict[str, Any], identity: Identity | None + ) -> tuple[list[dict[str, Any]], bool, str | None]: task_id = args.get("task_id") if not isinstance(task_id, str) or not task_id: return self._error_response(ValueError("task_id is required")) - info = self._manager.get_status(task_id) - if info is None: + info = await self._manager.get_status_async(task_id) + if info is None or not self._can_access_task(info, identity): return self._text_response( {"error": "ASYNC_TASK_NOT_FOUND", "task_id": task_id}, is_error=True, @@ -453,11 +507,14 @@ def _handle_status_tool(self, args: dict[str, Any]) -> tuple[list[dict[str, Any] payload["error"] = info.error return self._text_response(payload) - async def _handle_cancel_tool(self, args: dict[str, Any]) -> tuple[list[dict[str, Any]], bool, str | None]: + async def _handle_cancel_tool( + self, args: dict[str, Any], identity: Identity | None + ) -> tuple[list[dict[str, Any]], bool, str | None]: task_id = args.get("task_id") if not isinstance(task_id, str) or not task_id: return self._error_response(ValueError("task_id is required")) - if self._manager.get_status(task_id) is None: + info = await self._manager.get_status_async(task_id) + if info is None or not self._can_access_task(info, identity): return self._text_response( {"error": "ASYNC_TASK_NOT_FOUND", "task_id": task_id}, is_error=True, @@ -467,7 +524,9 @@ async def _handle_cancel_tool(self, args: dict[str, Any]) -> tuple[list[dict[str self._progress_bindings.pop(task_id, None) return self._text_response({"task_id": task_id, "cancelled": cancelled}) - def _handle_list_tool(self, args: dict[str, Any]) -> tuple[list[dict[str, Any]], bool, str | None]: + async def _handle_list_tool( + self, args: dict[str, Any], identity: Identity | None + ) -> tuple[list[dict[str, Any]], bool, str | None]: status_filter: TaskStatus | None = None raw_status = args.get("status") if isinstance(raw_status, str): @@ -475,8 +534,30 @@ def _handle_list_tool(self, args: dict[str, Any]) -> tuple[list[dict[str, Any]], status_filter = TaskStatus(raw_status) except ValueError: return self._error_response(ValueError(f"Invalid status filter: {raw_status!r}")) - tasks = self._manager.list_tasks(status_filter) - return self._text_response({"tasks": [_task_info_to_dict(t) for t in tasks]}) + tasks = await self._manager.list_tasks_async(status_filter) + visible = [_task_info_to_dict(task) for task in tasks if self._can_access_task(task, identity)] + return self._text_response({"tasks": visible}) + + @staticmethod + def _scoped_owner(identity: Identity | None) -> str | None: + return getattr(identity, "owner_key", lambda: None)() + + def _can_disclose(self, module_id: str, identity: Identity | None) -> bool: + get_descriptor = getattr(self._executor, "get_callable_descriptor", None) + if not callable(get_descriptor): + return False + try: + return get_descriptor(module_id, Context.create(identity=identity)) is not None + except Exception: + logger.debug("Scoped task access could not be verified", exc_info=True) + return False + + def _can_access_task(self, task: TaskInfo, identity: Identity | None) -> bool: + binding = self._scoped_task_owners.get(task.task_id) + owner = self._scoped_owner(identity) + if binding is None: + return owner is None + return binding.state == "published" and binding.owner == owner and self._can_disclose(task.module_id, identity) async def _handle_preview_tool( self, diff --git a/mcp/python/src/apcore_mcp/server/factory.py b/mcp/python/src/apcore_mcp/server/factory.py index 2ad6fc18..e3c67d8a 100644 --- a/mcp/python/src/apcore_mcp/server/factory.py +++ b/mcp/python/src/apcore_mcp/server/factory.py @@ -31,7 +31,7 @@ from apcore_mcp.server.approval_bridge import ApprovalBridge, _approval_response_log, _protect_sdk_approval_logs from apcore_mcp.server.async_task_bridge import RESERVED_PREFIX, AsyncTaskBridge from apcore_mcp.server.router import ExecutionRouter, _descriptor_version_hint, _matches_registered_version -from apcore_mcp.server.transport import _protocol_source_var, transport_session_var +from apcore_mcp.server.transport import _protocol_source_var, _scoped_sse_request, transport_session_var logger = logging.getLogger(__name__) @@ -127,7 +127,12 @@ def _request_identity() -> Identity | None: scope = getattr(ctx.request, "scope", None) if ctx is not None else None if isinstance(scope, dict) and _REQUEST_IDENTITY_KEY in scope: identity = scope[_REQUEST_IDENTITY_KEY] - return identity if isinstance(identity, Identity) else None + if isinstance(identity, Identity): + return identity + if not _scoped_sse_request.get(): + return None + if _scoped_sse_request.get(): + raise RuntimeError("Missing authenticated request identity for the scoped SSE session") return auth_identity_var.get() diff --git a/mcp/python/src/apcore_mcp/server/transport.py b/mcp/python/src/apcore_mcp/server/transport.py index 42a42fa7..dfafd110 100644 --- a/mcp/python/src/apcore_mcp/server/transport.py +++ b/mcp/python/src/apcore_mcp/server/transport.py @@ -33,6 +33,7 @@ # Protocol selection belongs to the active transport, never client metadata. _protocol_source_var: ContextVar[str | None] = ContextVar("apcore_mcp_protocol_source", default=None) +_scoped_sse_request: ContextVar[bool] = ContextVar("apcore_mcp_scoped_sse_request", default=False) # [TM-4] Module-level ContextVar carrying the active transport session id. # The transport sets it inside :meth:`TransportManager._scoped_session` so @@ -63,11 +64,22 @@ def export_prometheus(self) -> str: ... @dataclass class _HTTPSessionOpening: - principal: tuple[str, str] | None + principal: str | tuple[str, str] | None + authority: str | None session_id: str | None = None closed: bool = False +@dataclass +class _SSEOwnerSessions: + transport: SseServerTransport + connections: int = 0 + + +def _current_authority() -> str | None: + return getattr(auth_identity_var.get(), "authority_key", lambda: None)() + + class _ScopedHTTPServer(Server): """Delegate each SDK-managed HTTP session through transport cleanup.""" @@ -82,11 +94,13 @@ async def handle_request( self, sessions: StreamableHTTPSessionManager, scope: Scope, receive: Receive, send: Send ) -> None: identity = auth_identity_var.get() - principal = (identity.type, identity.id) if identity is not None else None + owner = getattr(identity, "owner_key", lambda: None)() + authority = _current_authority() + principal = owner if owner is not None else (identity.type, identity.id) if identity is not None else None session_id = Headers(scope=scope).get("mcp-session-id") if session_id is not None: opening = self._owners.get(session_id) - if opening is None or opening.principal != principal: + if opening is None or opening.principal != principal or opening.authority != authority: response = JSONResponse( {"jsonrpc": "2.0", "id": "server-error", "error": {"code": -32600, "message": "Session not found"}}, status_code=404, @@ -100,7 +114,7 @@ async def handle_request( await sessions.handle_request(scope, receive, send) return - opening = _HTTPSessionOpening(principal) + opening = _HTTPSessionOpening(principal, authority) async def bind_session(message: Message) -> None: if message["type"] == "http.response.start" and message["status"] == 200 and not opening.closed: @@ -355,19 +369,47 @@ async def run_sse( logger.warning("SSE transport is deprecated. Use Streamable HTTP instead.") sse_transport = SseServerTransport("/messages/") + scoped_sessions: dict[str, _SSEOwnerSessions] = {} async def handle_sse(request: Any) -> Response: - # [TM-4] Each SSE connection is an independent protocol session; - # synthesize a per-connection id so its async tasks are tracked - # and cancelled when the SSE stream closes. - session_id = uuid.uuid4().hex - async with sse_transport.connect_sse(request.scope, request.receive, request._send) as ( - read_stream, - write_stream, - ): - await self._run_scoped(server, read_stream, write_stream, init_options, session_id) + owner = _current_authority() + transport = sse_transport + bucket = None + if owner is not None: + bucket = scoped_sessions.get(owner) + if bucket is None: + bucket = _SSEOwnerSessions(SseServerTransport("/messages/")) + scoped_sessions[owner] = bucket + transport = bucket.transport + bucket.connections += 1 + + scoped_request = _scoped_sse_request.set(bucket is not None) + try: + session_id = uuid.uuid4().hex + async with transport.connect_sse(request.scope, request.receive, request._send) as ( + read_stream, + write_stream, + ): + await self._run_scoped(server, read_stream, write_stream, init_options, session_id) + finally: + _scoped_sse_request.reset(scoped_request) + if bucket is not None and owner is not None: + bucket.connections -= 1 + if bucket.connections == 0: + scoped_sessions.pop(owner, None) return Response() + async def handle_messages(scope: Scope, receive: Receive, send: Send) -> None: + owner = _current_authority() + if owner is None: + await sse_transport.handle_post_message(scope, receive, send) + return + bucket = scoped_sessions.get(owner) + if bucket is None: + await Response("Could not find session", status_code=404)(scope, receive, send) + return + await bucket.transport.handle_post_message(scope, receive, send) + async def _health(request: Any) -> JSONResponse: return JSONResponse(self._build_health_response()) @@ -383,7 +425,7 @@ async def _metrics(request: Any) -> Response: routes.extend( [ Route("/sse", endpoint=handle_sse, methods=["GET"]), - Mount("/messages/", app=sse_transport.handle_post_message), + Mount("/messages/", app=handle_messages), ] ) diff --git a/mcp/python/tests/adapters/test_approval.py b/mcp/python/tests/adapters/test_approval.py index be1760c1..bee73a06 100644 --- a/mcp/python/tests/adapters/test_approval.py +++ b/mcp/python/tests/adapters/test_approval.py @@ -170,3 +170,31 @@ async def test_isinstance_check_passes(self) -> None: handler = ElicitationApprovalHandler() assert isinstance(handler, ApprovalHandler) + + +@pytest.mark.asyncio +async def test_storage_approval_binds_current_delegated_authority() -> None: + from apcore import Context, Identity, ModuleAnnotations + from apcore.approval import ApprovalRequest + + from apcore_mcp.adapters.approval import StorageBackedApprovalHandler + from apcore_mcp.approval_store import InMemoryApprovalStore + + store = InMemoryApprovalStore() + handler = StorageBackedApprovalHandler(store) + root = Identity("subject", scopes=["read", "write"], issuer="issuer") + actor = Identity("actor", issuer="issuer") + original = root.delegate(actor, ["read", "write"]) + narrowed = root.delegate(actor, ["read"]) + + def request(identity: Identity) -> ApprovalRequest: + return ApprovalRequest( + "test.run", {}, Context.create(identity), ModuleAnnotations(requires_approval=True), + authority_key=identity.authority_key(), + ) + + pending = await handler.request_approval(request(original)) + assert pending.approval_id is not None and pending.audit_id is not None + assert await store.resolve(pending.audit_id, approved=True) + assert (await handler.check_approval_for_call(pending.approval_id, request(narrowed))).status == "rejected" + assert (await handler.check_approval_for_call(pending.approval_id, request(original))).status == "approved" diff --git a/mcp/python/tests/auth/test_delegated_jwt.py b/mcp/python/tests/auth/test_delegated_jwt.py new file mode 100644 index 00000000..4bcf586f --- /dev/null +++ b/mcp/python/tests/auth/test_delegated_jwt.py @@ -0,0 +1,100 @@ +"""Verified JWT scope and delegation are explicitly opt-in.""" + +from __future__ import annotations + +import inspect +import time +from typing import Any + +import jwt +import pytest +from starlette.applications import Starlette +from starlette.middleware import Middleware +from starlette.responses import JSONResponse +from starlette.routing import Route +from starlette.testclient import TestClient + +from apcore_mcp import DelegatedClaims, JWTAuthenticator +from apcore_mcp.auth import AuthMiddleware + +_KEY = "scope-enabled-test-verifier-32-bytes" +_ISSUER = "https://issuer.example" +_AUDIENCE = "audience.example" + + +def _auth() -> JWTAuthenticator: + return JWTAuthenticator( + _KEY, + issuer=_ISSUER, + audience=_AUDIENCE, + delegated_claims=DelegatedClaims(scp_claim="scp", actor_roles_claim="roles"), + ) + + +def _token(**claims: Any) -> str: + return jwt.encode( + {"iss": _ISSUER, "sub": "subject", "aud": _AUDIENCE, "exp": time.time() + 120, **claims}, + _KEY, + algorithm="HS256", + ) + + +async def _authenticate(token: str): + identity = _auth().authenticate({"authorization": f"Bearer {token}"}) + return await identity if inspect.isawaitable(identity) else identity + + +@pytest.mark.asyncio +async def test_verified_scope_has_one_active_edge_and_uses_only_outer_actor_roles() -> None: + actor = {"sub": "current", "roles": ["operator"], "act": {"sub": "past", "roles": ["admin"]}} + first = await _authenticate(_token(scope="read write", scp=["write", "read"], roles=["owner"], act=actor)) + actor["act"] = {"sub": "different-past", "roles": ["superuser"]} + refreshed = await _authenticate(_token(scope="write read", roles=["owner"], act=actor)) + assert first is not None and refreshed is not None + assert first.delegation_depth == 1 + assert first.id == "current" and first.roles == ("operator",) + assert first.root_subject.id == "subject" and first.root_subject.roles == ("owner",) + assert first.scopes == ("read", "write") + assert first.issuer == first.root_subject.issuer == _ISSUER + assert first.authority_key() == refreshed.authority_key() + assert first.owner_key() == refreshed.owner_key() + explicit_empty = await _authenticate(_token(scp=[])) + assert explicit_empty is not None and explicit_empty.scopes == () + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "claims", + [ + {}, + {"scope": ""}, + {"scope": "read write"}, + {"scope": "read\twrite"}, + {"scope": "read", "scp": ["write"]}, + {"scope": "read", "iss": "other"}, + {"scope": "read", "aud": "other"}, + {"scope": "read", "sub": None}, + {"scope": "read", "exp": 1}, + {"scope": "read", "iat": "1"}, + {"scope": "read", "nbf": 9e9}, + {"scope": "read", "act": {"sub": "actor", "act": None}}, + {"scope": "read", "act": {"sub": "actor", "iss": False}}, + {"scope": "read", "act": {"sub": "actor", "roles": ["operator", 1]}}, + ], +) +async def test_projection_rejects_invalid_verified_claims(claims: dict[str, Any]) -> None: + assert await _authenticate(_token(**claims)) is None + + +def test_permissive_middleware_refuses_a_bad_credential_but_allows_no_credential() -> None: + async def endpoint(_request): + return JSONResponse({"ok": True}) + + app = Starlette( + routes=[Route("/", endpoint)], + middleware=[Middleware(AuthMiddleware, authenticator=_auth(), require_auth=False)], + ) + with TestClient(app) as client: + assert client.get("/").status_code == 200 + assert client.get("/", headers={"Authorization": "Bearer invalid"}).status_code == 401 + assert client.get("/", headers={"Authorization": f"Bearer {_token(scope='read')}"}).status_code == 200 diff --git a/mcp/python/tests/server/test_async_task_bridge.py b/mcp/python/tests/server/test_async_task_bridge.py index f7c84b85..eedc13ea 100644 --- a/mcp/python/tests/server/test_async_task_bridge.py +++ b/mcp/python/tests/server/test_async_task_bridge.py @@ -13,8 +13,9 @@ from typing import Any import pytest -from apcore.async_task import AsyncTaskManager, TaskStatus -from apcore.errors import TaskLimitExceededError +from apcore import Context, Identity +from apcore.async_task import AsyncTaskManager, TaskInfo, TaskStatus +from apcore.errors import ACLDeniedError, TaskLimitExceededError from apcore_mcp.server.async_task_bridge import META_TOOL_NAMES, AsyncTaskBridge from apcore_mcp.server.factory import MCPServerFactory @@ -294,7 +295,7 @@ def test_preview_meta_tool_is_registered() -> None: @pytest.mark.asyncio async def test_preview_meta_tool_returns_predicted_changes() -> None: """Preview drives executor.validate() and surfaces predicted_changes.""" - from apcore import Change, Context, PreviewResult, Registry + from apcore import Change, PreviewResult, Registry from apcore.executor import Executor from apcore.module import Module @@ -459,3 +460,116 @@ async def test_submit_tool_accepts_null_and_empty_arguments(value: object) -> No ) assert is_error is False + + +@pytest.mark.asyncio +async def test_scoped_background_task_rechecks_owner_and_current_access() -> None: + from apcore import Context, Executor, Identity, Registry + from apcore.acl import ACL, ACLRule + + class Module: + description = "Return the operation result" + input_schema = {"type": "object"} + output_schema = {"type": "object"} + + async def execute(self, inputs, context): + return {"result": "ok"} + + registry = Registry() + registry.register("task.run", Module()) + acl = ACL([ACLRule(["@external"], ["task.run"], "allow", conditions={"scopes": ["run"]})]) + actor = Identity("actor", issuer="issuer") + subject = Identity("subject", scopes=["read", "run"], issuer="issuer") + original = subject.delegate(actor, ["run"]) + narrowed = subject.delegate(actor, ["read"]) + different = Identity("other", scopes=["run"], issuer="issuer").delegate(actor, ["run"]) + with Executor(registry, acl=acl) as executor: + bridge = AsyncTaskBridge.with_limits(executor) + task_id = (await bridge.submit("task.run", {}, Context.create(original)))["task_id"] + try: + for identity in (None, narrowed, different): + _, denied, _ = await bridge.handle_meta_tool( + "__apcore_task_status", {"task_id": task_id}, router_extra={"identity": identity} + ) + assert denied + content, denied, _ = await bridge.handle_meta_tool( + "__apcore_task_status", {"task_id": task_id}, router_extra={"identity": original} + ) + assert not denied and json.loads(content[0]["text"])["task_id"] == task_id + finally: + await bridge.shutdown() + + +@pytest.mark.asyncio +@pytest.mark.parametrize("fail_after_write", [False, True]) +async def test_scoped_task_publication_waits_for_storage( + monkeypatch: pytest.MonkeyPatch, fail_after_write: bool +) -> None: + class Executor(_SlowExecutor): + def get_callable_descriptor(self, module_id: str, context: Context) -> object: + return object() + + allocating = asyncio.Event() + allow_store = asyncio.Event() + stored = asyncio.Event() + release = asyncio.Event() + + executor = Executor() + manager = AsyncTaskManager(executor) + save = manager._store.save + + async def delayed_save(info: TaskInfo) -> None: + scoped_pending = info.module_id == "task.scoped" and info.status == TaskStatus.PENDING + if scoped_pending: + allocating.set() + await allow_store.wait() + await save(info) + if scoped_pending: + stored.set() + await release.wait() + if fail_after_write: + raise RuntimeError("write acknowledged unsuccessfully") + + monkeypatch.setattr(manager._store, "save", delayed_save) + bridge = AsyncTaskBridge(manager) + observer = AsyncTaskBridge(manager) + aliased = AsyncTaskBridge(AsyncTaskManager(executor, store=manager._store)) + identity = Identity("account", scopes=["run"]) + + async def listed(current: Identity | None = None, via: AsyncTaskBridge = observer) -> list[str]: + content, failed, _ = await via.handle_meta_tool("__apcore_task_list", {}, router_extra={"identity": current}) + assert not failed + return [task["task_id"] for task in json.loads(content[0]["text"])["tasks"]] + + legacy_task = (await bridge.submit("task.legacy", {}, None))["task_id"] + scoped = asyncio.create_task(bridge.submit("task.scoped", {}, Context.create(identity))) + second_legacy: asyncio.Task[dict[str, Any]] | None = None + try: + with pytest.raises(ACLDeniedError): + await aliased.submit("task.scoped", {}, Context.create(identity)) + await asyncio.wait_for(allocating.wait(), timeout=2) + second_legacy = asyncio.create_task(bridge.submit("task.legacy", {}, None)) + # Let the other submission collect any stale owners before the store write. + await asyncio.sleep(0) + allow_store.set() + await asyncio.wait_for(stored.wait(), timeout=2) + assert await listed() == [legacy_task] + assert await listed(identity) == [] + release.set() + if fail_after_write: + with pytest.raises(RuntimeError, match="write acknowledged unsuccessfully"): + await scoped + assert await listed(identity) == [] + else: + task = await scoped + assert await listed(identity) == [task["task_id"]] + second_task = await second_legacy + assert await listed() == [legacy_task, second_task["task_id"]] + assert await listed(via=aliased) == [legacy_task, second_task["task_id"]] + finally: + allow_store.set() + release.set() + await asyncio.gather(scoped, return_exceptions=True) + if second_legacy is not None: + await asyncio.gather(second_legacy, return_exceptions=True) + await bridge.shutdown() diff --git a/mcp/python/tests/server/test_scoped_approval_wire.py b/mcp/python/tests/server/test_scoped_approval_wire.py index 1d3f58f5..681cdda0 100644 --- a/mcp/python/tests/server/test_scoped_approval_wire.py +++ b/mcp/python/tests/server/test_scoped_approval_wire.py @@ -9,7 +9,17 @@ import httpx import pytest -from apcore import AlwaysDenyHandler, Executor, Identity, Middleware, ModuleAnnotations, PolicyVerdict, Registry +from apcore import ( + ACL, + ACLRule, + AlwaysDenyHandler, + Executor, + Identity, + Middleware, + ModuleAnnotations, + PolicyVerdict, + Registry, +) from mcp.server.lowlevel import Server from mcp.shared import session as mcp_session from starlette.responses import JSONResponse @@ -18,6 +28,7 @@ from apcore_mcp.adapters.approval import _CORE_SCOPED_APPROVAL from apcore_mcp.approval_store import InMemoryApprovalStore from apcore_mcp.server.approval_bridge import _ApprovalLogMiddleware, _protect_sdk_approval_logs +from tests.auth.test_delegated_jwt import _auth, _token from tests.server.test_versioned_tool_wire import connected_client _TOOL = "fixture.approved_report" @@ -206,6 +217,57 @@ def authenticate(self, headers): assert "chunk:" in caplog.text # Unrelated HTTP debug logging remains available. +@_requires_scoped_core +async def test_delegated_jwt_binds_session_and_pending_approval() -> None: + registry = Registry() + report = Report() + registry.register(_TOOL, report) + acl = ACL(rules=[ACLRule( + callers=["@external"], targets=[_TOOL], effect="allow", conditions={"scopes": ["reports:read"]}, + )]) + store = InMemoryApprovalStore() + mcp = APCoreMCP(Executor(registry, acl=acl), approval_store=store, authenticator=_auth()) + + def credentials(subject: str, scope: str) -> str: + return f"Bearer {_token(sub=subject, scope=scope, act={'sub': 'reports-agent'})}" + + async with mcp.async_serve() as app, httpx.AsyncClient( + transport=httpx.ASGITransport(app=app), base_url="http://localhost", + ) as client, asyncio.timeout(5): + writer = _HttpSession(client, credentials("owner", "reports:read reports:write")) + other = _HttpSession(client, credentials("reader", "reports:read reports:write")) + await writer.initialize() + await other.initialize() + request = {"name": _TOOL, "arguments": {"count": 1}} + pending = await writer.request("tools/call", request) + approval = pending["_meta"]["apcore"]["approval"] + public_id, credential = approval["approvalId"], approval["resumeToken"] + poll = {"name": "__apcore_approval_check", "arguments": {"approval_id": public_id}} + denied = await client.post( + "/mcp/", headers={**writer.headers, "authorization": other.headers["authorization"]}, + json={"jsonrpc": "2.0", "id": 1, "method": "tools/list", "params": {}}, + ) + assert denied.status_code == 404 + + assert await store.resolve(public_id, approved=True) + retry = {**request, "_meta": {"approvalId": credential}} + assert (await other.request("tools/call", retry))["isError"] + narrow_credential = credentials("owner", "reports:read") + rejected_reuse = await client.delete( + "/mcp/", headers={**writer.headers, "authorization": narrow_credential}, + ) + assert rejected_reuse.status_code == 404 + narrowed = _HttpSession(client, narrow_credential) + await narrowed.initialize() + status = await narrowed.request("tools/call", poll) + assert json.loads(status["content"][0]["text"])["status"] == "rejected" + assert (await narrowed.request("tools/call", retry))["isError"] + + writer.headers["authorization"] = credentials("owner", "reports:write reports:read") + assert not (await writer.request("tools/call", retry))["isError"] + assert report.inputs == [{"count": 1}] + + @pytest.mark.skipif(_CORE_SCOPED_APPROVAL, reason="exercises the minimum Core compatibility path") async def test_legacy_core_reports_scoped_approval_unavailable() -> None: registry = Registry() diff --git a/mcp/rust/Cargo.lock b/mcp/rust/Cargo.lock index 33ba533e..420548a8 100644 --- a/mcp/rust/Cargo.lock +++ b/mcp/rust/Cargo.lock @@ -98,9 +98,9 @@ dependencies = [ [[package]] name = "apcore" -version = "1.0.0-alpha.4" +version = "1.0.0-alpha.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7d5e08c5bbc5cddf5c72b121cbec90c1c551993dbee7c7cc88e30950941b63ad" +checksum = "1d19939071ba2c589815c061dfb1ff827862e5f1f52251e88297d49eec500a90" dependencies = [ "async-stream", "async-trait", diff --git a/mcp/rust/Cargo.toml b/mcp/rust/Cargo.toml index 2df10dd2..b171ec21 100644 --- a/mcp/rust/Cargo.toml +++ b/mcp/rust/Cargo.toml @@ -22,7 +22,7 @@ all-features = true rustdoc-args = ["--cfg", "docsrs"] [dependencies] -apcore = { version = "=1.0.0-alpha.4", default-features = false, features = ["config", "sys-modules"] } +apcore = { version = "=1.0.0-alpha.5", default-features = false, features = ["config", "sys-modules"] } apcore-toolkit = "=0.15.1-alpha.2" mcp-embedded-ui = "0.5" tokio = { version = "1", features = ["full"] } diff --git a/mcp/rust/src/adapters/approval.rs b/mcp/rust/src/adapters/approval.rs index 89762a38..d70de16e 100644 --- a/mcp/rust/src/adapters/approval.rs +++ b/mcp/rust/src/adapters/approval.rs @@ -333,8 +333,14 @@ pub(crate) async fn scoped_approval_status( if !is_public_approval_id(audit_id) { return rejected("Approval record not found"); } - let principal = identity.map(ApprovalPrincipal::from); - match store.get_scoped_result(audit_id, principal.as_ref()).await { + let record = match identity.and_then(apcore::Identity::authority_key) { + Some(authority_key) => store.get_authority_result(audit_id, &authority_key).await, + None => { + let principal = identity.map(ApprovalPrincipal::from); + store.get_scoped_result(audit_id, principal.as_ref()).await + } + }; + match record { Ok(Some(record)) => stored_result(&record, Some(audit_id)), Ok(None) => rejected("Approval record not found"), Err(_) => store_error(), @@ -397,6 +403,10 @@ impl ApprovalHandler for StorageBackedApprovalHandler { self.store.supports_scoped_approval() } + fn supports_authority_scope(&self) -> bool { + self.store.supports_authority_scope() + } + async fn request_approval( &self, request: &ApprovalRequest, @@ -411,12 +421,19 @@ impl ApprovalHandler for StorageBackedApprovalHandler { let credential = format!("{audit_id}.{}", Uuid::new_v4().simple()); let verifier = credential_verifier(&credential); let scope = ApprovalScope::from(request); - if self - .store - .save_scoped_pending(&audit_id, &verifier, &scope) - .await - .is_err() - { + let saved = match request.authority_key() { + Some(authority_key) => { + self.store + .save_authority_pending(&audit_id, &verifier, &scope, &authority_key) + .await + } + None => { + self.store + .save_scoped_pending(&audit_id, &verifier, &scope) + .await + } + }; + if saved.is_err() { return Ok(store_error()); } @@ -440,7 +457,7 @@ impl ApprovalHandler for StorageBackedApprovalHandler { if resume_audit_id(audit_id).is_some() { return Ok(rejected("Approval record not found")); } - Ok(match self.store.get_result(audit_id).await { + Ok(match self.store.get_legacy_result(audit_id).await { Ok(Some(record)) => { let public_id = Uuid::parse_str(audit_id).is_ok().then_some(audit_id); let mut result = stored_result(&record, public_id); @@ -470,23 +487,29 @@ impl ApprovalHandler for StorageBackedApprovalHandler { }; let verifier = credential_verifier(credential); let scope = ApprovalScope::from(request); - Ok( - match self.store.consume_scoped(audit_id, &verifier, &scope).await { - Ok(Some(record)) => { - let pending = record.status == ApprovalStatus::Pending; - let mut result = stored_result(&record, Some(audit_id)); - if pending { - crate::server::approval_bridge::record_pending_approval( - request, audit_id, credential, - ); - result.approval_id = Some(credential.to_owned()); - } - result + let record = match request.authority_key() { + Some(authority_key) => { + self.store + .consume_authority_scoped(audit_id, &verifier, &scope, &authority_key) + .await + } + None => self.store.consume_scoped(audit_id, &verifier, &scope).await, + }; + Ok(match record { + Ok(Some(record)) => { + let pending = record.status == ApprovalStatus::Pending; + let mut result = stored_result(&record, Some(audit_id)); + if pending { + crate::server::approval_bridge::record_pending_approval( + request, audit_id, credential, + ); + result.approval_id = Some(credential.to_owned()); } - Ok(None) => rejected("Approval credential unavailable for this call"), - Err(_) => store_error(), - }, - ) + result + } + Ok(None) => rejected("Approval credential unavailable for this call"), + Err(_) => store_error(), + }) } } @@ -545,6 +568,89 @@ mod tests { assert!(anonymous.audit_id.is_none()); } + #[tokio::test] + async fn delegated_authority_binds_polling_and_one_time_consumption() { + fn request(subject: &str, scopes: &[&str]) -> ApprovalRequest { + let scope_set: Vec<_> = scopes.iter().map(|scope| (*scope).to_owned()).collect(); + let root = + apcore::Identity::new(subject.into(), "user".into(), vec![], Default::default()) + .with_authority( + Some(vec!["read".into(), "write".into()]), + Some("issuer".into()), + ) + .unwrap(); + let actor = + apcore::Identity::new("editor".into(), "user".into(), vec![], Default::default()); + let mut request = scoped_request(); + request.context = Some(apcore::Context::new( + root.delegate(actor, scope_set).unwrap(), + )); + request + } + let store = Arc::new(crate::approval_store::InMemoryApprovalStore::new()); + let handler = StorageBackedApprovalHandler::new(store.clone()); + let original = request("alice", &["read", "write"]); + let result = handler.request_approval(&original).await.unwrap(); + let audit_id = result.audit_id.as_deref().unwrap(); + let credential = result.approval_id.as_deref().unwrap(); + assert!(store.resolve(audit_id, true, None).await.unwrap()); + + for wrong in [ + scoped_request(), + request("bob", &["read", "write"]), + request("alice", &["read"]), + ] { + assert_eq!( + handler + .check_scoped_approval( + audit_id, + wrong.context.as_ref().unwrap().identity.as_ref() + ) + .await + .status, + "rejected" + ); + assert_eq!( + handler + .check_approval_for_call(credential, &wrong) + .await + .unwrap() + .status, + "rejected" + ); + } + assert_eq!( + handler.check_scoped_approval(audit_id, None).await.status, + "rejected" + ); + assert_eq!( + handler + .check_scoped_approval( + audit_id, + original.context.as_ref().unwrap().identity.as_ref() + ) + .await + .status, + "approved" + ); + assert_eq!( + handler + .check_approval_for_call(credential, &original) + .await + .unwrap() + .status, + "approved" + ); + assert_eq!( + handler + .check_approval_for_call(credential, &original) + .await + .unwrap() + .status, + "rejected" + ); + } + #[tokio::test] async fn approved_invocation_consumes_its_credential_once() { let store = Arc::new(crate::approval_store::InMemoryApprovalStore::new()); diff --git a/mcp/rust/src/apcore_mcp.rs b/mcp/rust/src/apcore_mcp.rs index 239fb0b3..a495d97e 100644 --- a/mcp/rust/src/apcore_mcp.rs +++ b/mcp/rust/src/apcore_mcp.rs @@ -1013,16 +1013,11 @@ impl APCoreMCP { // Cancel any task whose session_key matches, plus also // try treating the key as a direct task_id. let key = key.to_string(); + let identity = crate::AUTH_IDENTITY.try_with(Clone::clone).ok().flatten(); let output_lease = output_lease.clone(); let task = tokio::spawn(async move { let _output_lease = output_lease; - let n = b.cancel_session_tasks(&key).await; - if n == 0 { - // Best-effort direct-cancel fallback on client - // disconnect; a store error here has no caller - // left to report it to (apcore 0.31.0, D-81). - let _ = b.cancel(&key).await; - } + b.cancel_for_request(&key, identity.as_ref()).await; }); let mut tasks = cancellation_tasks .lock() @@ -1220,14 +1215,9 @@ impl APCoreMCP { server_handler = server_handler.with_cancel_handler(Arc::new(move |key: &str| { if let Some(b) = bridge_weak.upgrade() { let key = key.to_string(); + let identity = crate::AUTH_IDENTITY.try_with(Clone::clone).ok().flatten(); tokio::spawn(async move { - let n = b.cancel_session_tasks(&key).await; - if n == 0 { - // Best-effort direct-cancel fallback on client - // disconnect; a store error here has no caller - // left to report it to (apcore 0.31.0, D-81). - let _ = b.cancel(&key).await; - } + b.cancel_for_request(&key, identity.as_ref()).await; }); } })); @@ -3205,6 +3195,92 @@ mod tests { } } + #[tokio::test] + async fn signed_delegation_controls_live_mcp_discovery_and_invocation() { + use axum::body::{to_bytes, Body}; + use axum::http::{Request, StatusCode}; + use jsonwebtoken::{EncodingKey, Header}; + use tower::ServiceExt; + + const SECRET: &str = "mcp-delegation-wire-test"; + let mut executor = Executor::new( + make_test_registry(vec![("demo.echo", "Echo", vec![])]), + Config::default(), + ); + let mut grant = + apcore::ACLRule::new(vec!["@external".into()], vec!["demo.echo".into()], "allow"); + grant.conditions = + Some(json!({"scopes": ["echo"], "roles": ["worker"], "subject_roles": ["reviewer"]})); + executor.set_acl(apcore::ACL::new(vec![grant], "deny", None)); + let auth = crate::JWTAuthenticator::new( + SECRET, + None, + Some("mcp".into()), + Some("issuer".into()), + None, + None, + None, + ) + .with_delegated_claims(crate::DelegatedClaims { + actor_roles_claim: Some("roles".into()), + ..Default::default() + }); + let app = APCoreMCP::builder() + .backend(Arc::new(executor)) + .authenticator(auth) + .require_auth(false) + .build() + .unwrap() + .async_serve(AsyncServeOptions::default()) + .await + .unwrap(); + let token = |scope, actor_roles| { + jsonwebtoken::encode(&Header::default(), &json!({ + "sub": "alice", "iss": "issuer", "aud": "mcp", "exp": jsonwebtoken::get_current_timestamp() + 120, + "scope": scope, "roles": ["reviewer"], "act": {"sub": "worker", "roles": actor_roles, "act": {"sub": "prior", "roles": ["worker"]}} + }), &EncodingKey::from_secret(SECRET.as_bytes())).unwrap() + }; + let rpc = |bearer: String, method, params| { + let request = Request::post("/mcp") + .header("content-type", "application/json") + .header("authorization", format!("Bearer {bearer}")) + .body(Body::from( + json!({"jsonrpc": "2.0", "id": 1, "method": method, "params": params}) + .to_string(), + )) + .unwrap(); + app.clone().oneshot(request) + }; + let call = json!({"name": "demo.echo", "arguments": {"q": "hello"}, "_meta": {"identity": {"id": "forged", "type": "user", "scopes": ["echo"]}}}); + for (bearer, allowed) in [ + (token("echo other", vec!["worker"]), true), + (token("other", vec!["worker"]), false), + (token("echo", vec![]), false), + ] { + let response = rpc(bearer.clone(), "tools/list", json!({})).await.unwrap(); + let result: Value = + serde_json::from_slice(&to_bytes(response.into_body(), 65536).await.unwrap()) + .unwrap(); + assert_eq!( + result["result"]["tools"] + .as_array() + .unwrap() + .iter() + .any(|tool| tool["name"] == "demo.echo"), + allowed + ); + let response = rpc(bearer, "tools/call", call.clone()).await.unwrap(); + let result: Value = + serde_json::from_slice(&to_bytes(response.into_body(), 65536).await.unwrap()) + .unwrap(); + assert_eq!(result["result"]["isError"], !allowed, "{result}"); + } + let invalid = rpc("invalid".into(), "tools/list", json!({})) + .await + .unwrap(); + assert_eq!(invalid.status(), StatusCode::UNAUTHORIZED); + } + #[test] fn phase_b_requires_the_builtin_approval_gate_for_default_and_traced_calls() { use crate::approval_store::InMemoryApprovalStore; diff --git a/mcp/rust/src/approval_store.rs b/mcp/rust/src/approval_store.rs index 542a006b..6aea3f00 100644 --- a/mcp/rust/src/approval_store.rs +++ b/mcp/rust/src/approval_store.rs @@ -107,6 +107,11 @@ pub trait ApprovalStore: Send + Sync + 'static { false } + /// Opt in when the store binds delegated reads and atomic consumption to the authority key. + fn supports_authority_scope(&self) -> bool { + false + } + /// Persist a new pending approval record. async fn save_pending( &self, @@ -118,6 +123,14 @@ pub trait ApprovalStore: Send + Sync + 'static { /// Return the current record, or None if approval_id is unknown. async fn get_result(&self, approval_id: &str) -> StoreResult>; + /// Legacy status lookup. Authority-aware stores must exclude delegated records. + async fn get_legacy_result(&self, approval_id: &str) -> StoreResult> { + if self.supports_authority_scope() { + return Ok(None); + } + self.get_result(approval_id).await + } + /// Mark approval_id as approved or rejected. /// Returns false if the id is unknown or already resolved. async fn resolve( @@ -164,6 +177,41 @@ pub trait ApprovalStore: Send + Sync + 'static { Ok(None) } + /// Persist a scoped record bound to the supplied current Core authority. + async fn save_authority_pending( + &self, + _audit_id: &str, + _verifier: &ApprovalVerifier, + _scope: &ApprovalScope, + _authority_key: &str, + ) -> StoreResult<()> { + Err(io::Error::new( + io::ErrorKind::Unsupported, + "authority-scoped approval storage unavailable", + ) + .into()) + } + + /// Read status only for the current Core authority that requested the approval. + async fn get_authority_result( + &self, + _audit_id: &str, + _authority_key: &str, + ) -> StoreResult> { + Ok(None) + } + + /// Match the verifier, invocation and authority and atomically consume an approved record. + async fn consume_authority_scoped( + &self, + _audit_id: &str, + _verifier: &ApprovalVerifier, + _scope: &ApprovalScope, + _authority_key: &str, + ) -> StoreResult> { + Ok(None) + } + /// Start a background TTL sweep for this store, returning the spawned /// task handle (or `None` if the store needs no sweeping). /// @@ -192,6 +240,7 @@ struct InternalRecord { struct ScopedApproval { verifier: Option, scope: ApprovalScope, + authority_key: Option, } impl InternalRecord { @@ -315,6 +364,50 @@ impl InMemoryApprovalStore { ); Ok(()) } + + async fn insert_scoped( + &self, + audit_id: &str, + verifier: &ApprovalVerifier, + scope: &ApprovalScope, + authority_key: Option<&str>, + ) -> StoreResult<()> { + self.insert_pending( + audit_id, + &scope.module_id, + Some(ScopedApproval { + verifier: Some(*verifier), + scope: scope.clone(), + authority_key: authority_key.map(str::to_owned), + }), + ) + .await + } + + async fn consume_matching_scope( + &self, + audit_id: &str, + verifier: &ApprovalVerifier, + scope: &ApprovalScope, + authority_key: Option<&str>, + ) -> StoreResult> { + let mut records = self.records.lock().await; + let result = self.live_record(&mut records, audit_id).and_then(|record| { + let scoped = record.scoped.as_mut()?; + let matches_verifier = bool::from(scoped.verifier.as_ref()?.ct_eq(verifier)); + if !matches_verifier + || scoped.scope != *scope + || scoped.authority_key.as_deref() != authority_key + { + return None; + } + if record.status == ApprovalStatus::Approved { + scoped.verifier = None; + } + Some(record.snapshot()) + }); + Ok(result) + } } impl Default for InMemoryApprovalStore { @@ -329,6 +422,10 @@ impl ApprovalStore for InMemoryApprovalStore { true } + fn supports_authority_scope(&self) -> bool { + true + } + async fn save_pending( &self, approval_id: &str, @@ -345,6 +442,20 @@ impl ApprovalStore for InMemoryApprovalStore { .map(|record| record.snapshot())) } + async fn get_legacy_result(&self, approval_id: &str) -> StoreResult> { + let mut records = self.records.lock().await; + Ok(self + .live_record(&mut records, approval_id) + .filter(|record| { + record + .scoped + .as_ref() + .and_then(|scoped| scoped.authority_key.as_ref()) + .is_none() + }) + .map(|record| record.snapshot())) + } + async fn resolve( &self, approval_id: &str, @@ -376,15 +487,7 @@ impl ApprovalStore for InMemoryApprovalStore { verifier: &ApprovalVerifier, scope: &ApprovalScope, ) -> StoreResult<()> { - self.insert_pending( - audit_id, - &scope.module_id, - Some(ScopedApproval { - verifier: Some(*verifier), - scope: scope.clone(), - }), - ) - .await + self.insert_scoped(audit_id, verifier, scope, None).await } async fn get_scoped_result( @@ -394,8 +497,9 @@ impl ApprovalStore for InMemoryApprovalStore { ) -> StoreResult> { let mut records = self.records.lock().await; let result = self.live_record(&mut records, audit_id).and_then(|record| { - let scope = &record.scoped.as_ref()?.scope; - (scope.principal.as_ref() == principal).then(|| record.snapshot()) + let scoped = record.scoped.as_ref()?; + (scoped.authority_key.is_none() && scoped.scope.principal.as_ref() == principal) + .then(|| record.snapshot()) }); Ok(result) } @@ -405,20 +509,43 @@ impl ApprovalStore for InMemoryApprovalStore { audit_id: &str, verifier: &ApprovalVerifier, scope: &ApprovalScope, + ) -> StoreResult> { + self.consume_matching_scope(audit_id, verifier, scope, None) + .await + } + + async fn save_authority_pending( + &self, + audit_id: &str, + verifier: &ApprovalVerifier, + scope: &ApprovalScope, + authority_key: &str, + ) -> StoreResult<()> { + self.insert_scoped(audit_id, verifier, scope, Some(authority_key)) + .await + } + + async fn get_authority_result( + &self, + audit_id: &str, + authority_key: &str, ) -> StoreResult> { let mut records = self.records.lock().await; - let result = self.live_record(&mut records, audit_id).and_then(|record| { - let scoped = record.scoped.as_mut()?; - let matches_verifier = bool::from(scoped.verifier.as_ref()?.ct_eq(verifier)); - if !matches_verifier || scoped.scope != *scope { - return None; - } - if record.status == ApprovalStatus::Approved { - scoped.verifier = None; - } - Some(record.snapshot()) - }); - Ok(result) + Ok(self.live_record(&mut records, audit_id).and_then(|record| { + let scoped = record.scoped.as_ref()?; + (scoped.authority_key.as_deref() == Some(authority_key)).then(|| record.snapshot()) + })) + } + + async fn consume_authority_scoped( + &self, + audit_id: &str, + verifier: &ApprovalVerifier, + scope: &ApprovalScope, + authority_key: &str, + ) -> StoreResult> { + self.consume_matching_scope(audit_id, verifier, scope, Some(authority_key)) + .await } fn start_sweep(&self) -> Option> { diff --git a/mcp/rust/src/auth/delegation.rs b/mcp/rust/src/auth/delegation.rs new file mode 100644 index 00000000..c791a7dd --- /dev/null +++ b/mcp/rust/src/auth/delegation.rs @@ -0,0 +1,155 @@ +//! Projection of verified RFC 8693 JWT claims into Core authority. + +use std::collections::{BTreeSet, HashMap}; + +use serde_json::Value; + +use super::protocol::Identity; + +/// Enable JWT scope projection and optionally map provider and actor claims. +#[derive(Debug, Clone, Default)] +pub struct DelegatedClaims { + /// Optional provider claim that may carry a scope string or array. + pub scp_claim: Option, + /// Optional role-list claim on the current `act` object. + pub actor_roles_claim: Option, +} + +fn scope_set(value: &Value, allow_array: bool) -> Option> { + fn valid(token: &str) -> bool { + !token.is_empty() + && token + .bytes() + .all(|byte| matches!(byte, b'!' | b'#'..=b'[' | b']'..=b'~')) + } + + if let Some(value) = value.as_str() { + return value + .split(' ') + .map(|token| valid(token).then_some(token)) + .collect(); + } + if !allow_array { + return None; + } + value + .as_array()? + .iter() + .map(|token| token.as_str().filter(|token| valid(token))) + .collect() +} + +fn scopes(payload: &HashMap, mapping: &DelegatedClaims) -> Option> { + let standard = match payload.get("scope") { + Some(value) => Some(scope_set(value, false)?), + None => None, + }; + let provider = match mapping + .scp_claim + .as_ref() + .and_then(|name| payload.get(name)) + { + Some(value) => Some(scope_set(value, true)?), + None => None, + }; + if matches!((&standard, &provider), (Some(left), Some(right)) if left != right) { + return None; + } + Some( + standard + .or(provider)? + .into_iter() + .map(str::to_owned) + .collect(), + ) +} + +fn nonempty_string(value: &Value) -> Option<&str> { + value.as_str().filter(|text| !text.is_empty()) +} + +fn outer_actor(value: &Value, mapping: &DelegatedClaims, issuer: &str) -> Option { + let outer = value.as_object()?; + let mut node = outer; + for depth in 1..=8 { + nonempty_string(node.get("sub")?)?; + if let Some(issuer) = node.get("iss") { + nonempty_string(issuer)?; + } + let Some(next) = node.get("act") else { break }; + if depth == 8 { + return None; + } + node = next.as_object()?; + } + let actor_type = match outer.get("type") { + Some(value) => nonempty_string(value)?, + None => "agent", + }; + let roles = match mapping + .actor_roles_claim + .as_ref() + .and_then(|name| outer.get(name)) + { + Some(value) => value + .as_array()? + .iter() + .map(|value| nonempty_string(value).map(str::to_owned)) + .collect::>>()?, + None => Vec::new(), + }; + Identity::new( + nonempty_string(outer.get("sub")?)?.into(), + actor_type.into(), + roles, + HashMap::new(), + ) + .with_authority(None, Some(issuer.into())) + .ok() +} + +pub(super) fn project( + payload: &HashMap, + mapped: &Identity, + mapping: &DelegatedClaims, +) -> Option { + if [&mapping.scp_claim, &mapping.actor_roles_claim] + .into_iter() + .flatten() + .any(String::is_empty) + { + return None; + } + let issuer = nonempty_string(payload.get("iss")?)?; + let subject_id = nonempty_string(payload.get("sub")?)?; + let now = jsonwebtoken::get_current_timestamp() as f64; + for claim in ["exp", "nbf", "iat"] { + if let Some(value) = payload.get(claim) { + let timestamp = value.as_f64()?; + if claim != "exp" && timestamp > now + 30.0 { + return None; + } + } + } + let scopes = scopes(payload, mapping)?; + let mut attrs = mapped.attrs().clone(); + attrs.remove("act"); + attrs.remove("scope"); + if let Some(name) = &mapping.scp_claim { + attrs.remove(name); + } + let subject = Identity::new( + subject_id.into(), + mapped.identity_type().into(), + mapped.roles().to_vec(), + attrs, + ) + .with_authority(Some(scopes.clone()), Some(issuer.into())) + .ok()?; + match payload.get("act") { + Some(value) => subject + .delegate(outer_actor(value, mapping, issuer)?, scopes) + .ok(), + None => Some(subject), + } +} diff --git a/mcp/rust/src/auth/jwt.rs b/mcp/rust/src/auth/jwt.rs index c5b6d603..eaef426a 100644 --- a/mcp/rust/src/auth/jwt.rs +++ b/mcp/rust/src/auth/jwt.rs @@ -9,6 +9,8 @@ use tracing::debug; use crate::auth::protocol::{Authenticator, Identity}; +pub use super::delegation::DelegatedClaims; + /// Mapping from JWT claim names to Identity fields. /// /// Mirrors the Python `ClaimMapping` dataclass, controlling which JWT claims @@ -52,6 +54,7 @@ pub struct JWTAuthenticator { issuer: Option, claim_mapping: ClaimMapping, require_claims: Vec, + delegated_claims: Option, /// Whether unauthenticated requests should be rejected at this authenticator. /// /// NOTE [D1-004]: Python delegates this policy to `AuthMiddleware` rather than @@ -90,6 +93,7 @@ impl JWTAuthenticator { issuer, claim_mapping: claim_mapping.unwrap_or_default(), require_claims: require_claims.unwrap_or_else(|| vec!["sub".to_string()]), + delegated_claims: None, require_auth: require_auth.unwrap_or(true), } } @@ -142,11 +146,17 @@ impl JWTAuthenticator { self.require_auth } + /// Require verified issuer, audience and scope claims and project delegated authority. + pub fn with_delegated_claims(mut self, claims: DelegatedClaims) -> Self { + self.delegated_claims = Some(claims); + self + } + /// Decode and validate a JWT token. Returns `None` on any error. fn decode_token(&self, token: &str) -> Option> { // No usable key (unparseable PEM) — reject rather than fail open. let key = self.key.as_ref()?; - let mut validation = Validation::new(self.algorithms[0]); + let mut validation = Validation::new(*self.algorithms.first()?); if self.algorithms.len() > 1 { validation.algorithms = self.algorithms.clone(); } @@ -169,13 +179,16 @@ impl JWTAuthenticator { } // Configure required claims - validation.set_required_spec_claims( - &self - .require_claims - .iter() - .map(|s| s.as_str()) - .collect::>(), - ); + let mut required_claims: Vec<_> = self.require_claims.iter().map(String::as_str).collect(); + if self.delegated_claims.is_some() { + self.issuer.as_deref().filter(|issuer| !issuer.is_empty())?; + self.audience + .as_deref() + .filter(|audience| !audience.is_empty())?; + required_claims.extend(["sub", "iss", "aud", "exp"]); + validation.validate_nbf = true; + } + validation.set_required_spec_claims(&required_claims); match jsonwebtoken::decode::>(token, key, &validation) { Ok(token_data) => { @@ -267,6 +280,10 @@ impl JWTAuthenticator { #[async_trait] impl Authenticator for JWTAuthenticator { + fn rejects_invalid_credentials(&self) -> bool { + self.delegated_claims.is_some() + } + async fn authenticate(&self, headers: &HashMap) -> Option { // Case-insensitive lookup for "authorization" header let auth_header = headers @@ -275,7 +292,7 @@ impl Authenticator for JWTAuthenticator { .map(|(_, v)| v.as_str())?; // Check for "Bearer " prefix (case-insensitive) - if auth_header.len() < 7 || !auth_header[..7].eq_ignore_ascii_case("bearer ") { + if !auth_header.get(..7)?.eq_ignore_ascii_case("bearer ") { return None; } @@ -285,7 +302,11 @@ impl Authenticator for JWTAuthenticator { } let payload = self.decode_token(token)?; - self.payload_to_identity(&payload) + let identity = self.payload_to_identity(&payload)?; + match &self.delegated_claims { + Some(claims) => super::delegation::project(&payload, &identity, claims), + None => Some(identity), + } } } diff --git a/mcp/rust/src/auth/middleware.rs b/mcp/rust/src/auth/middleware.rs index bd627316..544c2efd 100644 --- a/mcp/rust/src/auth/middleware.rs +++ b/mcp/rust/src/auth/middleware.rs @@ -190,8 +190,12 @@ where AUTH_IDENTITY.scope(identity, inner.call(req)).await } else { let identity = authenticator.authenticate(&headers).await; + let invalid_credential = req + .headers() + .contains_key(axum::http::header::AUTHORIZATION) + && authenticator.rejects_invalid_credentials(); - if identity.is_none() && require_auth { + if identity.is_none() && (require_auth || invalid_credential) { warn!("Authentication failed for {}", path); return Ok(build_401_response()); } diff --git a/mcp/rust/src/auth/mod.rs b/mcp/rust/src/auth/mod.rs index 20c9b4cf..a318b92c 100644 --- a/mcp/rust/src/auth/mod.rs +++ b/mcp/rust/src/auth/mod.rs @@ -3,12 +3,13 @@ //! Provides JWT-based authentication, a Tower middleware layer for protecting //! HTTP endpoints, and task-local identity propagation. +mod delegation; pub mod jwt; pub mod middleware; pub mod protocol; // ---- Re-exports: public API surface ----------------------------------------- -pub use jwt::{ClaimMapping, JWTAuthenticator}; +pub use jwt::{ClaimMapping, DelegatedClaims, JWTAuthenticator}; // [D9-009] extract_headers is pub(crate) — not exported as part of public API. pub use middleware::{AuthMiddlewareLayer, AuthMiddlewareService, AUTH_IDENTITY}; pub use protocol::{Authenticator, Identity}; diff --git a/mcp/rust/src/auth/protocol.rs b/mcp/rust/src/auth/protocol.rs index 28720fef..1b876158 100644 --- a/mcp/rust/src/auth/protocol.rs +++ b/mcp/rust/src/auth/protocol.rs @@ -16,6 +16,11 @@ pub use apcore::Identity; /// an [`Identity`] if authentication succeeds, or `None` if it fails. #[async_trait] pub trait Authenticator: Send + Sync { + /// Reject a present invalid credential even when authentication is optional. + fn rejects_invalid_credentials(&self) -> bool { + false + } + /// Authenticate a request based on its headers. /// /// Returns `Some(Identity)` on success, `None` on failure. diff --git a/mcp/rust/src/lib.rs b/mcp/rust/src/lib.rs index e4207a17..bf0d4902 100644 --- a/mcp/rust/src/lib.rs +++ b/mcp/rust/src/lib.rs @@ -45,7 +45,7 @@ pub use crate::apcore_mcp::{AsyncServeOptions, ExplorerOptions, ServeOptions}; pub use crate::apcore_mcp::{async_serve, serve, to_openai_tools}; // ---- Re-exports: auth ------------------------------------------------------- -pub use crate::auth::jwt::{ClaimMapping, JWTAuthenticator}; +pub use crate::auth::jwt::{ClaimMapping, DelegatedClaims, JWTAuthenticator}; // [D9-009] extract_headers is internal (pub(crate)) — not re-exported. pub use crate::auth::middleware::{AuthMiddlewareLayer, AuthMiddlewareService, AUTH_IDENTITY}; pub use crate::auth::protocol::{Authenticator, Identity}; diff --git a/mcp/rust/src/server/async_task_bridge.rs b/mcp/rust/src/server/async_task_bridge.rs index c77b84f1..e7bb2bf2 100644 --- a/mcp/rust/src/server/async_task_bridge.rs +++ b/mcp/rust/src/server/async_task_bridge.rs @@ -25,7 +25,7 @@ // used elsewhere in this crate (see src/server/router.rs). #![allow(clippy::result_large_err)] -use std::collections::HashMap; +use std::collections::{HashMap, HashSet}; use std::sync::{Arc, Mutex}; use apcore::async_task::{AsyncTaskManager, TaskInfo, TaskStatus}; @@ -101,6 +101,9 @@ pub struct AsyncTaskBridge { /// session, so [`AsyncTaskBridge::cancel_session_tasks`] can cancel /// them cooperatively when the transport detects disconnect. session_tasks: Arc>>>, + /// Prevent readers from seeing a new task until its scoped owner is recorded. + scoped_task_owners: tokio::sync::RwLock>, + task_capacity: usize, } impl AsyncTaskBridge { @@ -126,6 +129,8 @@ impl AsyncTaskBridge { progress_tokens: Arc::new(Mutex::new(HashMap::new())), progress_senders: Arc::new(Mutex::new(HashMap::new())), session_tasks: Arc::new(Mutex::new(HashMap::new())), + scoped_task_owners: tokio::sync::RwLock::default(), + task_capacity: max_tasks, } } @@ -239,15 +244,27 @@ impl AsyncTaskBridge { "Background tasks do not support approval resumption", )); } + let owner = identity.as_ref().and_then(Identity::owner_key); let context: Context = identity.map_or_else(Context::anonymous, Context::new); context.data.write().insert( crate::adapters::approval::BACKGROUND_APPROVAL_CONTEXT_KEY.into(), Value::Bool(true), ); + let mut owners = self.scoped_task_owners.write().await; let task_id = self .manager .submit(module_id, inputs, Some(context)) .await?; + if let Some(owner) = owner { + if owners.len() >= self.task_capacity.saturating_mul(2) { + if let Ok(tasks) = self.manager.list_tasks(None) { + let live: HashSet<_> = tasks.into_iter().map(|task| task.task_id).collect(); + owners.retain(|id, _| live.contains(id)); + } + } + owners.insert(task_id.clone(), owner); + } + drop(owners); // Store progress sink: token + sender pair, mirroring the Python // `_install_progress_sink` and TS inline-closure patterns. [A-D-220] @@ -371,6 +388,11 @@ impl AsyncTaskBridge { let Some(mut info) = self.manager.get_status(task_id)? else { return Ok(None); }; + self.redact_task_result(&mut info); + Ok(Some(info)) + } + + fn redact_task_result(&self, info: &mut TaskInfo) { if info.status == TaskStatus::Completed { if let Some(result) = &info.result { if let Some(schema) = self.output_schemas.get(&info.module_id) { @@ -386,7 +408,7 @@ impl AsyncTaskBridge { } Err(_) => { tracing::debug!( - task_id = %task_id, + task_id = %info.task_id, module_id = %info.module_id, "task-result redactor panicked; falling back to unredacted result" ); @@ -395,7 +417,6 @@ impl AsyncTaskBridge { } } } - Ok(Some(info)) } /// Cancel a running or pending task. @@ -463,6 +484,70 @@ impl AsyncTaskBridge { n } + /// Handle a cancellation notification from a client, applying current authority. + pub(crate) async fn cancel_for_request(&self, key: &str, identity: Option<&Identity>) { + let session_tasks = self + .session_tasks + .lock() + .unwrap_or_else(|p| p.into_inner()) + .get(key) + .cloned() + .unwrap_or_default(); + let mut cancelled = false; + for id in session_tasks { + if self + .task_for_request(&id, identity) + .await + .is_ok_and(|task| task.is_some()) + { + cancelled |= self.cancel(&id).await.unwrap_or(false); + } + } + if !cancelled + && self + .task_for_request(key, identity) + .await + .is_ok_and(|task| task.is_some()) + { + let _ = self.cancel(key).await; + } + } + + fn may_access_task( + &self, + task: &TaskInfo, + context: &Context, + current_owner: Option<&str>, + stored_owner: Option<&str>, + ) -> bool { + stored_owner == current_owner + && (stored_owner.is_none() + || self + .executor + .get_callable_descriptor(&task.module_id, None, Some(context)) + .is_some()) + } + + async fn task_for_request( + &self, + task_id: &str, + identity: Option<&Identity>, + ) -> Result, apcore::errors::ModuleError> { + let owners = self.scoped_task_owners.read().await; + let current_owner = identity.and_then(Identity::owner_key); + let context = identity + .cloned() + .map_or_else(Context::anonymous, Context::new); + Ok(self.manager.get_status(task_id)?.filter(|task| { + self.may_access_task( + task, + &context, + current_owner.as_deref(), + owners.get(task_id).map(String::as_str), + ) + })) + } + /// List all tracked tasks, optionally filtered by status. /// /// # Errors @@ -613,9 +698,9 @@ impl AsyncTaskBridge { ) .await, ), - META_TOOL_STATUS => Some(self.handle_status(arguments)), - META_TOOL_CANCEL => Some(self.handle_cancel(arguments).await), - META_TOOL_LIST => Some(self.handle_list(arguments)), + META_TOOL_STATUS => Some(self.handle_status(arguments, identity.as_ref()).await), + META_TOOL_CANCEL => Some(self.handle_cancel(arguments, identity.as_ref()).await), + META_TOOL_LIST => Some(self.handle_list(arguments, identity.as_ref()).await), META_TOOL_PREVIEW => Some(self.handle_preview(arguments, identity).await), _ => None, } @@ -703,7 +788,11 @@ impl AsyncTaskBridge { })) } - fn handle_status(&self, arguments: &Value) -> Result { + async fn handle_status( + &self, + arguments: &Value, + identity: Option<&Identity>, + ) -> Result { // [A-D-AT-3] Reject an empty task_id up front; without this it // reached the registry and came back as ASYNC_TASK_NOT_FOUND instead of // an invalid-argument error, unlike Python and TypeScript. @@ -717,8 +806,11 @@ impl AsyncTaskBridge { "__apcore_task_status requires a non-empty 'task_id'", ) })?; - match self.get_status(task_id)? { - Some(info) => Ok(serde_json::to_value(info).unwrap_or(Value::Null)), + match self.task_for_request(task_id, identity).await? { + Some(mut info) => { + self.redact_task_result(&mut info); + Ok(serde_json::to_value(info).unwrap_or(Value::Null)) + } // [D11-014] Align with Python's `_text_response({"error": // "ASYNC_TASK_NOT_FOUND", "task_id": ...}, is_error=True)` — return // Ok(json_envelope) with an error payload rather than Err(...). @@ -732,7 +824,11 @@ impl AsyncTaskBridge { } } - async fn handle_cancel(&self, arguments: &Value) -> Result { + async fn handle_cancel( + &self, + arguments: &Value, + identity: Option<&Identity>, + ) -> Result { // [A-D-AT-3] Same non-empty requirement as handle_status. let task_id = arguments .get("task_id") @@ -748,7 +844,7 @@ impl AsyncTaskBridge { // Without this, unknown task_ids silently return `{cancelled: false}` — // callers can't distinguish "task existed and is uncancellable" from // "task never existed". Mirrors handle_status's existence-check path. - if self.get_status(task_id)?.is_none() { + if self.task_for_request(task_id, identity).await?.is_none() { return Ok(json!({ "error": "ASYNC_TASK_NOT_FOUND", "task_id": task_id, @@ -759,7 +855,11 @@ impl AsyncTaskBridge { Ok(json!({ "task_id": task_id, "cancelled": cancelled })) } - fn handle_list(&self, arguments: &Value) -> Result { + async fn handle_list( + &self, + arguments: &Value, + identity: Option<&Identity>, + ) -> Result { // [D11-102] Inspect the raw `status` value so non-string variants // (numbers, bools, arrays, objects) are rejected instead of silently // ignored by `as_str() → None`. @@ -785,10 +885,28 @@ impl AsyncTaskBridge { )); } }; + let owners = self.scoped_task_owners.read().await; + let current_owner = identity.and_then(Identity::owner_key); + let context = identity + .cloned() + .map_or_else(Context::anonymous, Context::new); let tasks = self.list_tasks(status_filter)?; let tasks_json: Vec = tasks .into_iter() - .map(|t| serde_json::to_value(t).unwrap_or(Value::Null)) + .filter(|task| { + self.may_access_task( + task, + &context, + current_owner.as_deref(), + owners.get(&task.task_id).map(String::as_str), + ) + }) + .map(|mut task| { + if current_owner.is_some() { + self.redact_task_result(&mut task); + } + serde_json::to_value(task).unwrap_or(Value::Null) + }) .collect(); Ok(json!({ "tasks": tasks_json })) } @@ -1168,6 +1286,75 @@ mod tests { ); } + #[tokio::test] + async fn delegated_tasks_require_both_current_grant_and_owner() { + fn identity(subject: &str, scopes: Vec) -> Identity { + let root = Identity::new(subject.into(), "user".into(), vec![], HashMap::new()) + .with_authority( + Some(vec!["run".into(), "read".into()]), + Some("issuer".into()), + ) + .unwrap(); + let actor = Identity::new("worker".into(), "agent".into(), vec![], HashMap::new()); + root.delegate(actor, scopes).unwrap() + } + let mut executor = make_executor_with_async("sample.run"); + Arc::get_mut(&mut executor) + .unwrap() + .set_acl(apcore::ACL::new( + serde_json::from_value(json!([{ + "callers": ["@external"], "targets": ["sample.run"], "effect": "allow", + "conditions": {"scopes": ["run"]} + }])) + .unwrap(), + "deny", + None, + )); + let bridge = AsyncTaskBridge::new(executor); + let owner = identity("alice", vec!["run".into(), "read".into()]); + let submitted = bridge + .handle_meta_tool( + META_TOOL_SUBMIT, + &json!({"module_id": "sample.run"}), + Some(owner.clone()), + None, + None, + Some("session"), + ) + .await + .unwrap() + .unwrap(); + let task_id = submitted["task_id"].as_str().unwrap(); + let task = json!({"task_id": task_id}); + for principal in [ + None, + Some(identity("bob", vec!["run".into()])), + Some(identity("alice", vec!["read".into()])), + ] { + for tool in [META_TOOL_STATUS, META_TOOL_CANCEL] { + let reply = bridge + .handle_meta_tool(tool, &task, principal.clone(), None, None, None) + .await + .unwrap() + .unwrap(); + assert_eq!(reply["error"], "ASYNC_TASK_NOT_FOUND", "{tool}"); + } + let reply = bridge + .handle_meta_tool(META_TOOL_LIST, &json!({}), principal, None, None, None) + .await + .unwrap() + .unwrap(); + assert_eq!(reply["tasks"], json!([])); + } + let refreshed = identity("alice", vec!["run".into()]); + let result = bridge + .handle_meta_tool(META_TOOL_STATUS, &task, Some(refreshed), None, None, None) + .await + .unwrap() + .unwrap(); + assert_eq!(result["task_id"], task_id); + } + #[tokio::test] async fn background_execution_rejects_only_calls_that_require_phase_b_approval() { use crate::adapters::approval::StorageBackedApprovalHandler; diff --git a/mcp/rust/src/server/router.rs b/mcp/rust/src/server/router.rs index 4cae2e7c..bb7904e7 100644 --- a/mcp/rust/src/server/router.rs +++ b/mcp/rust/src/server/router.rs @@ -1276,6 +1276,11 @@ impl ExecutionRouter { if let Some(approval_bridge) = &self.approval_bridge { if ApprovalBridge::is_meta_tool(tool_name) { let (value, is_error) = if approval_bridge.supports_scoped_approval() + || apcore_ctx + .identity + .as_ref() + .and_then(apcore::Identity::authority_key) + .is_some() || crate::server::approval_bridge::has_tool_response_context() { approval_bridge diff --git a/mcp/rust/src/server/transport.rs b/mcp/rust/src/server/transport.rs index 93007589..502d4aa6 100644 --- a/mcp/rust/src/server/transport.rs +++ b/mcp/rust/src/server/transport.rs @@ -954,7 +954,17 @@ struct HttpSession { requests: DirectRequests, } -type SessionOwner = (String, String); +#[derive(Clone, PartialEq, Eq)] +enum SessionOwner { + Legacy { + identity_type: String, + id: String, + }, + Scoped { + owner_key: String, + authority_key: String, + }, +} fn request_identity() -> Option { AUTH_IDENTITY.try_with(Clone::clone).ok().flatten() @@ -962,10 +972,17 @@ fn request_identity() -> Option { fn session_owner(identity: Option<&apcore::Identity>) -> Option { identity.map(|identity| { - ( - identity.identity_type().to_owned(), - identity.id().to_owned(), - ) + identity + .owner_key() + .zip(identity.authority_key()) + .map(|(owner_key, authority_key)| SessionOwner::Scoped { + owner_key, + authority_key, + }) + .unwrap_or_else(|| SessionOwner::Legacy { + identity_type: identity.identity_type().to_owned(), + id: identity.id().to_owned(), + }) }) } @@ -1576,6 +1593,7 @@ async fn sse_messages_handler( let owner = session_owner(identity.as_ref()); let sender = lock_sessions(&state.sessions) .get(&session_id) + // The long-lived stream receives tool results and carries elicitation replies. .filter(|session| session.owner == owner) .map(|session| session.sender.clone()); let Some(sender) = sender else { @@ -2556,6 +2574,104 @@ mod tests { ); } + fn scoped_test_identity(subject: &str, scopes: &[&str]) -> apcore::Identity { + let root = apcore::Identity::new( + subject.into(), + "user".into(), + Vec::new(), + Default::default(), + ) + .with_authority( + Some(vec!["read".into(), "write".into()]), + Some("issuer".into()), + ) + .unwrap(); + let actor = apcore::Identity::new( + "worker".into(), + "agent".into(), + Vec::new(), + Default::default(), + ); + root.delegate( + actor, + scopes.iter().map(|scope| (*scope).to_owned()).collect(), + ) + .unwrap() + } + + #[tokio::test] + async fn delegated_sse_binds_the_open_response_stream_to_its_authority() { + let app = sse_test_app(); + let original = scoped_test_identity("alice", &["read", "write"]); + let (_stream, id) = AUTH_IDENTITY + .scope(Some(original), open_sse_session(&app)) + .await; + for requester in [ + scoped_test_identity("bob", &["read", "write"]), + scoped_test_identity("alice", &["read"]), + ] { + let status = AUTH_IDENTITY + .scope(Some(requester), post_sse_message(&app, &id, 1)) + .await; + assert_eq!(status, StatusCode::BAD_REQUEST); + } + let equivalent = scoped_test_identity("alice", &["write", "read"]); + let status = AUTH_IDENTITY + .scope(Some(equivalent), post_sse_message(&app, &id, 2)) + .await; + assert_eq!(status, StatusCode::ACCEPTED); + } + + #[tokio::test] + async fn delegated_streamable_http_reuses_only_equivalent_authority() { + let app = Arc::new(TransportManager::new(None)) + .build_streamable_http_app(Arc::new(EchoHandler), None); + let original = scoped_test_identity("alice", &["read", "write"]); + let initialize = serde_json::json!({"jsonrpc":"2.0", "id":1, "method":"initialize"}); + let initial = AUTH_IDENTITY + .scope( + Some(original), + post_http_rpc(&app, None, initialize.clone()), + ) + .await; + let id = initial.headers()["mcp-session-id"] + .to_str() + .unwrap() + .to_string(); + let narrowed = scoped_test_identity("alice", &["read"]); + let ping = serde_json::json!({"jsonrpc":"2.0", "id":2, "method":"ping"}); + let other = scoped_test_identity("bob", &["read", "write"]); + for different in [other, narrowed.clone()] { + let denied = AUTH_IDENTITY + .scope( + Some(different), + post_http_rpc(&app, Some(&id), ping.clone()), + ) + .await; + assert_eq!(denied.status(), StatusCode::NOT_FOUND); + } + let refreshed = scoped_test_identity("alice", &["write", "read"]); + let accepted = AUTH_IDENTITY + .scope( + Some(refreshed), + post_http_rpc(&app, Some(&id), ping.clone()), + ) + .await; + assert_eq!(accepted.status(), StatusCode::OK); + let second_session = AUTH_IDENTITY + .scope( + Some(narrowed.clone()), + post_http_rpc(&app, None, initialize), + ) + .await; + let new_id = second_session.headers()["mcp-session-id"].to_str().unwrap(); + assert_ne!(id, new_id); + let accepted = AUTH_IDENTITY + .scope(Some(narrowed), post_http_rpc(&app, Some(new_id), ping)) + .await; + assert_eq!(accepted.status(), StatusCode::OK); + } + #[tokio::test] async fn sse_messages_post_returns_202_for_a_live_session() { let app = sse_test_app(); diff --git a/mcp/rust/tests/auth_test.rs b/mcp/rust/tests/auth_test.rs index 3cad488c..71f1a6e2 100644 --- a/mcp/rust/tests/auth_test.rs +++ b/mcp/rust/tests/auth_test.rs @@ -3,7 +3,7 @@ mod common; use apcore_mcp::auth::protocol::Authenticator; -use apcore_mcp::{ClaimMapping, JWTAuthenticator}; +use apcore_mcp::{ClaimMapping, DelegatedClaims, JWTAuthenticator}; use jsonwebtoken::{EncodingKey, Header}; use std::collections::HashMap; @@ -24,6 +24,156 @@ fn headers_with_token(token: &str) -> HashMap { h } +fn delegated_authenticator() -> JWTAuthenticator { + JWTAuthenticator::new( + TEST_SECRET, + None, + Some("mcp-service".into()), + Some("issuer".into()), + Some(ClaimMapping { + attrs_claims: Some(vec!["tenant".into(), "act".into()]), + ..ClaimMapping::default() + }), + None, + Some(false), + ) + .with_delegated_claims(DelegatedClaims { + scp_claim: Some("scp".into()), + actor_roles_claim: Some("current_roles".into()), + }) +} + +fn delegated_token_claims() -> serde_json::Value { + serde_json::json!({ + "iss": "issuer", + "aud": "mcp-service", + "sub": "alice", + "exp": jsonwebtoken::get_current_timestamp() + 120, + "roles": ["reviewer"], + "tenant": "engineering", + "scope": "docs:read docs:edit docs:read", + "scp": ["docs:edit", "docs:read"], + "act": { + "sub": "current", + "current_roles": ["worker"], + "act": {"sub": "prior", "current_roles": ["admin"]} + } + }) +} + +#[tokio::test] +async fn delegated_credentials_use_current_actor_and_verified_subject() { + let auth = delegated_authenticator(); + let mut claims = delegated_token_claims(); + let identity = auth + .authenticate(&headers_with_token(&make_token(&claims))) + .await + .unwrap(); + assert_eq!(identity.id(), "current"); + assert_eq!(identity.roles(), ["worker"]); + assert_eq!(identity.delegation_depth(), 1); + assert_eq!(identity.root_subject().id(), "alice"); + assert_eq!(identity.root_subject().roles(), ["reviewer"]); + assert_eq!(identity.root_subject().issuer(), Some("issuer")); + assert_eq!(identity.root_subject().attrs()["tenant"], "engineering"); + assert!(!identity.root_subject().attrs().contains_key("act")); + claims["act"]["act"]["sub"] = "replacement".into(); + let changed_history = auth + .authenticate(&headers_with_token(&make_token(&claims))) + .await + .unwrap(); + assert_eq!(changed_history.authority_key(), identity.authority_key()); + assert_eq!(changed_history.owner_key(), identity.owner_key()); +} + +#[tokio::test] +async fn delegated_credentials_reject_bad_signature_claims_and_conflicts() { + let auth = delegated_authenticator(); + let now = jsonwebtoken::get_current_timestamp(); + for (claim, invalid) in [ + ("iss", serde_json::json!("wrong")), + ("aud", serde_json::json!("wrong")), + ("exp", serde_json::json!(now - 120)), + ("iat", serde_json::json!(now + 120)), + ("nbf", serde_json::json!(now + 120)), + ("nbf", serde_json::json!(null)), + ("sub", serde_json::json!(123)), + ("scope", serde_json::json!("docs:read\tdocs:edit")), + ("scp", serde_json::json!(["docs:read"])), + ( + "act", + serde_json::json!({"sub":"actor", "act":{"type":"user"}}), + ), + ] { + let mut claims = delegated_token_claims(); + claims[claim] = invalid; + assert!( + auth.authenticate(&headers_with_token(&make_token(&claims))) + .await + .is_none(), + "{claim}" + ); + } + let mut claims = delegated_token_claims(); + for claim in ["exp", "iss", "aud", "sub"] { + let mut missing = claims.clone(); + missing.as_object_mut().unwrap().remove(claim); + assert!( + auth.authenticate(&headers_with_token(&make_token(&missing))) + .await + .is_none(), + "{claim}" + ); + } + let wrong_signature = jsonwebtoken::encode( + &Header::default(), + &claims, + &EncodingKey::from_secret(b"other-test-key"), + ) + .unwrap(); + assert!(auth + .authenticate(&headers_with_token(&wrong_signature)) + .await + .is_none()); + claims.as_object_mut().unwrap().remove("scope"); + claims["scp"] = serde_json::json!([]); + assert!(auth + .authenticate(&headers_with_token(&make_token(&claims))) + .await + .unwrap() + .scopes() + .unwrap() + .is_empty()); +} + +#[tokio::test] +async fn delegated_middleware_rejects_present_invalid_credentials_in_permissive_mode() { + use apcore_mcp::AuthMiddlewareLayer; + use axum::body::Body; + use axum::http::{Request, Response, StatusCode}; + use std::{convert::Infallible, sync::Arc}; + use tower::{ServiceBuilder, ServiceExt}; + + let service = ServiceBuilder::new() + .layer(AuthMiddlewareLayer::new(Arc::new(delegated_authenticator())).require_auth(false)) + .service(tower::service_fn(|_: Request| async { + Ok::<_, Infallible>(Response::new(Body::empty())) + })); + let invalid = Request::get("/mcp") + .header("Authorization", "Bearer invalid") + .body(Body::empty()) + .unwrap(); + assert_eq!( + service.clone().oneshot(invalid).await.unwrap().status(), + StatusCode::UNAUTHORIZED + ); + let anonymous = Request::get("/mcp").body(Body::empty()).unwrap(); + assert_eq!( + service.oneshot(anonymous).await.unwrap().status(), + StatusCode::OK + ); +} + // ---- JWTAuthenticator with valid tokens ------------------------------------ #[tokio::test] diff --git a/mcp/typescript/package.json b/mcp/typescript/package.json index 761ad74a..cfcf95d5 100644 --- a/mcp/typescript/package.json +++ b/mcp/typescript/package.json @@ -51,7 +51,7 @@ "dependencies": { "@modelcontextprotocol/sdk": "1.32.0", "ajv": "^8.17.1", - "apcore-js": "1.0.0-alpha.4", + "apcore-js": "1.0.0-alpha.5", "apcore-toolkit": "0.15.1-alpha.2", "jsonwebtoken": ">=9.0.3", "mcp-embedded-ui": ">=0.5.1" diff --git a/mcp/typescript/pnpm-lock.yaml b/mcp/typescript/pnpm-lock.yaml index e60a3b7e..68367132 100644 --- a/mcp/typescript/pnpm-lock.yaml +++ b/mcp/typescript/pnpm-lock.yaml @@ -15,8 +15,8 @@ importers: specifier: ^8.17.1 version: 8.20.0 apcore-js: - specifier: 1.0.0-alpha.4 - version: 1.0.0-alpha.4(typescript@5.9.3) + specifier: 1.0.0-alpha.5 + version: 1.0.0-alpha.5(typescript@5.9.3) apcore-toolkit: specifier: 0.15.1-alpha.2 version: 0.15.1-alpha.2(@sinclair/typebox@0.34.48)(typescript@5.9.3) @@ -619,8 +619,8 @@ packages: resolution: {integrity: sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==} engines: {node: '>=8'} - apcore-js@1.0.0-alpha.4: - resolution: {integrity: sha512-APFaeBqZ0u0BCmeDzGOJ05Byt16zY96NAlqUiRtIEDY51lzLNP4mfr6B6aicBvFZ1Lg4UQDmVKumpkxjXaOiyA==} + apcore-js@1.0.0-alpha.5: + resolution: {integrity: sha512-VmPRnT/S5O2N1nnMsoomOUFCf9kY4Jqe/UfyPCvh1xb8HccEshsQsvqReds652vMQCQ6i0xmcJZA4OKfWHRUJw==} engines: {node: '>=20.0.0'} peerDependencies: typescript: ^5.5.0 @@ -1938,7 +1938,7 @@ snapshots: dependencies: color-convert: 2.0.1 - apcore-js@1.0.0-alpha.4(typescript@5.9.3): + apcore-js@1.0.0-alpha.5(typescript@5.9.3): dependencies: '@sinclair/typebox': 0.34.48 js-yaml: 4.3.2 @@ -1950,7 +1950,7 @@ snapshots: dependencies: '@sinclair/typebox': 0.34.48 ajv: 8.20.0 - apcore-js: 1.0.0-alpha.4(typescript@5.9.3) + apcore-js: 1.0.0-alpha.5(typescript@5.9.3) js-yaml: 4.3.2 transitivePeerDependencies: - typescript diff --git a/mcp/typescript/src/adapters/approval.ts b/mcp/typescript/src/adapters/approval.ts index c5126173..0d97e45b 100644 --- a/mcp/typescript/src/adapters/approval.ts +++ b/mcp/typescript/src/adapters/approval.ts @@ -17,13 +17,16 @@ export interface ApprovalRequest { description?: string | null; arguments: Record; callerId?: string | null; + authorityKey?: string; context?: { data?: Record; - identity?: ApprovalPrincipal | null; + identity?: ApprovalIdentity | null; callerId?: string | null; } | null; } +type ApprovalIdentity = Pick & { authorityKey?(): string | null }; + export interface ApprovalResult { status: "approved" | "rejected" | "timeout" | "pending"; /** Human-readable explanation. Never used to carry the approval id. */ @@ -149,6 +152,16 @@ function sha256(value: string): string { return createHash("sha256").update(value).digest("hex"); } +export function approvalPrincipal(identity: ApprovalIdentity | null | undefined): ApprovalPrincipal | null { + if (!identity) return null; + const authority = identity.authorityKey?.() ?? null; + return { + type: identity.type, + id: identity.id, + ...(authority === null ? {} : { authorityKey: sha256("apcore-approval-authority-v1\0" + authority) }), + }; +} + function canonicalValue(value: unknown): unknown { if (value === null || typeof value === "string" || typeof value === "boolean" || (typeof value === "number" && Number.isFinite(value))) return value; @@ -180,8 +193,11 @@ function argumentsScopeDigest(request: ApprovalRequest, args: Record): ApprovalScope { const identity = request.context?.identity; + if ((identity?.authorityKey?.() ?? undefined) !== request.authorityKey) { + throw new Error("Invalid approval authority binding"); + } return { - principal: identity ? { type: identity.type, id: identity.id } : null, + principal: approvalPrincipal(identity), callerId: request.callerId ?? request.context?.callerId ?? null, moduleId: request.moduleId, argumentsDigest: argumentsScopeDigest(request, args), @@ -219,15 +235,20 @@ export class StorageBackedApprovalHandler { return supportsScopedCore() && supportsScopedApprovalStore(this.store); } + get supportsAuthorityScope(): boolean { + return this.supportsFinalScope && this.store.supportsAuthorityScope === true; + } + /** Bind the provider to the server's private foreground response path. */ forMcpServer(): Pick { + "supportsFinalScope" | "supportsAuthorityScope"> { const isForeground = (request: ApprovalRequest) => canIssueApprovalReply( request.moduleId, request.callerId ?? request.context?.callerId ?? null, request.context?.data, true, ); return { supportsFinalScope: this.supportsFinalScope, + supportsAuthorityScope: this.supportsAuthorityScope, requestApproval: async request => isForeground(request) ? this.requestApproval(request) : rejected("Scoped approval requires a direct tool call"), @@ -243,6 +264,9 @@ export class StorageBackedApprovalHandler { if (!supportsScopedCore() || !supportsScopedApprovalStore(this.store)) { return rejected("Scoped approval unavailable"); } + if (request.authorityKey !== undefined && !this.supportsAuthorityScope) { + return rejected("Approval authority binding unavailable"); + } const args = businessArguments(request); const contextData = request.context?.data; let scope: ApprovalScope; @@ -282,6 +306,7 @@ export class StorageBackedApprovalHandler { if (!isPublicApprovalId(approvalId) || !supportsScopedCore() || !supportsScopedApprovalStore(this.store)) { return rejected("Approval record not found"); } + if (principal?.authorityKey !== undefined && !this.supportsAuthorityScope) return rejected("Approval record not found"); try { const record = await this.store.getScopedResult(approvalId, principal); return record ? { status: record.status, auditId: approvalId } : rejected("Approval record not found"); @@ -295,6 +320,9 @@ export class StorageBackedApprovalHandler { if (!auditId || !supportsScopedCore() || !supportsScopedApprovalStore(this.store)) { return rejected("Approval credential unavailable for this call"); } + if (request.authorityKey !== undefined && !this.supportsAuthorityScope) { + return rejected("Approval credential unavailable for this call"); + } try { const scope = invocationScope(request, businessArguments(request)); const contextData = request.context?.data; diff --git a/mcp/typescript/src/approval-store.ts b/mcp/typescript/src/approval-store.ts index 6e5c0bc0..7f061174 100644 --- a/mcp/typescript/src/approval-store.ts +++ b/mcp/typescript/src/approval-store.ts @@ -19,6 +19,7 @@ export interface ApprovalRecord { export interface ApprovalPrincipal { readonly type: string; readonly id: string; + readonly authorityKey?: string; } export interface ApprovalScope { @@ -30,6 +31,8 @@ export interface ApprovalScope { /** Pluggable storage for Phase B approval state. */ export interface ApprovalStore { + /** The scoped methods compare authority as well as the legacy principal. */ + readonly supportsAuthorityScope?: boolean; savePending(approvalId: string, moduleId: string, arguments_: Record): Promise; getResult(approvalId: string): Promise; resolve(approvalId: string, options: { approved: boolean; reason?: string }): Promise; @@ -69,7 +72,8 @@ interface InternalRecord extends ApprovalRecord { } function samePrincipal(left: ApprovalPrincipal | null, right: ApprovalPrincipal | null): boolean { - return left === null || right === null ? left === right : left.type === right.type && left.id === right.id; + return left === null || right === null ? left === right : + left.type === right.type && left.id === right.id && left.authorityKey === right.authorityKey; } function sameScope(left: ApprovalScope, right: ApprovalScope): boolean { @@ -86,6 +90,8 @@ function publicRecord({ status, moduleId, reason, createdAt, resolvedAt }: Inter * between processes and lasts only until restart. */ export class InMemoryApprovalStore implements ScopedApprovalStore { + readonly supportsAuthorityScope = true; + private readonly resolvedTtlMs: number; private readonly pendingTtlMs: number; private readonly sweepIntervalMs: number; diff --git a/mcp/typescript/src/auth/hooks.ts b/mcp/typescript/src/auth/hooks.ts index f660b8cc..3bafed3e 100644 --- a/mcp/typescript/src/auth/hooks.ts +++ b/mcp/typescript/src/auth/hooks.ts @@ -53,7 +53,8 @@ export function buildExplorerAuthHook( const identity = await authenticator.authenticate(headersMap); if (!identity) { const requireAuth = options.requireAuth ?? authenticator.requireAuth ?? true; - if (requireAuth) { + const badCredential = authenticator.rejectInvalidCredentials === true && Object.hasOwn(headersMap, "authorization"); + if (requireAuth || badCredential) { throw new Error("Unauthorized"); } } diff --git a/mcp/typescript/src/auth/index.ts b/mcp/typescript/src/auth/index.ts index 68f53d50..882025d3 100644 --- a/mcp/typescript/src/auth/index.ts +++ b/mcp/typescript/src/auth/index.ts @@ -11,5 +11,5 @@ export type { Authenticator, Identity } from "./types.js"; export { JWTAuthenticator } from "./jwt.js"; -export type { ClaimMapping, JWTAuthenticatorOptions } from "./jwt.js"; +export type { ClaimMapping, DelegatedClaims, JWTAuthenticatorOptions } from "./jwt.js"; export { identityStorage, getCurrentIdentity } from "./storage.js"; diff --git a/mcp/typescript/src/auth/jwt.ts b/mcp/typescript/src/auth/jwt.ts index f29de320..cd33c06c 100644 --- a/mcp/typescript/src/auth/jwt.ts +++ b/mcp/typescript/src/auth/jwt.ts @@ -6,6 +6,7 @@ import jwt from "jsonwebtoken"; import { createIdentity, type Identity } from "apcore-js"; +import { readDelegatedJwtAuthority, validateDelegatedClaims, type DelegatedClaims } from "apcore-toolkit"; import type { Authenticator } from "./types.js"; /** Mapping from JWT claims to Identity fields. */ @@ -40,8 +41,12 @@ export interface JWTAuthenticatorOptions { requireClaims?: string[]; /** If true (default), unauthenticated requests are rejected. If false, they proceed without identity. */ requireAuth?: boolean; + /** Opt in to scope and actor projection from a verified token. */ + delegatedClaims?: DelegatedClaims; } +export type { DelegatedClaims }; + /** * Authenticator that verifies JWT Bearer tokens from the Authorization header. * @@ -58,6 +63,7 @@ export class JWTAuthenticator implements Authenticator { private readonly _claimMapping: Required> & { attrs?: string[] }; private readonly _requireClaims: string[]; private readonly _requireAuth: boolean; + private readonly _delegatedClaims?: DelegatedClaims; constructor(options: JWTAuthenticatorOptions) { const keyValue = options.key ?? options.secret; @@ -66,7 +72,7 @@ export class JWTAuthenticator implements Authenticator { // gracefully (return null) when authenticate() is called without a valid key. // requireAuth belongs on AuthMiddleware, not on the authenticator itself. this._secret = keyValue ?? ""; - this._algorithms = options.algorithms ?? ["HS256"]; + this._algorithms = [...(options.algorithms ?? ["HS256"])]; this._audience = options.audience; this._issuer = options.issuer; this._claimMapping = { @@ -77,6 +83,12 @@ export class JWTAuthenticator implements Authenticator { }; this._requireClaims = options.requireClaims ?? ["sub"]; this._requireAuth = options.requireAuth ?? true; + if (options.delegatedClaims !== undefined) { + if (!this._secret || this._algorithms.includes("none")) { + throw new TypeError("Delegated JWT claims require signed algorithms and a verification key"); + } + this._delegatedClaims = validateDelegatedClaims(options.delegatedClaims, this._issuer, this._audience); + } } /** Whether unauthenticated requests should be rejected. */ @@ -84,6 +96,10 @@ export class JWTAuthenticator implements Authenticator { return this._requireAuth; } + get rejectInvalidCredentials(): boolean { + return this._delegatedClaims !== undefined; + } + async authenticate(headers: Record): Promise { const authHeader = headers["authorization"] ?? headers["Authorization"]; if (!authHeader) return null; @@ -125,7 +141,9 @@ export class JWTAuthenticator implements Authenticator { if (value === undefined || value === null) return null; } - const rawId = claims[this._claimMapping.id]; + const mapping = this._delegatedClaims; + const authority = mapping && readDelegatedJwtAuthority(claims, mapping, Math.floor(Date.now() / 1000)); + const rawId = authority?.subjectId ?? claims[this._claimMapping.id]; if (rawId === undefined || rawId === null) return null; const id = String(rawId); // [D11-107] Match Python's `claims.get(...) or "user"` semantics — @@ -138,16 +156,14 @@ export class JWTAuthenticator implements Authenticator { const roles = Array.isArray(rawRoles) ? rawRoles.map(String) : []; // Extract attrs from payload - const attrs: Record = {}; - if (this._claimMapping.attrs) { - for (const key of this._claimMapping.attrs) { - if (key in claims) { - attrs[key] = claims[key]; - } - } - } - - return createIdentity(id, type, roles, attrs); + const attrs = Object.fromEntries((this._claimMapping.attrs ?? []) + .filter(key => Object.hasOwn(claims, key) && (!mapping || !["act", "scope", mapping.scpClaim].includes(key))) + .map(key => [key, claims[key]])); + + if (!authority) return createIdentity(id, type, roles, attrs); + const { issuer, scopes, actor } = authority; + const subject = createIdentity(id, type, roles, attrs, { issuer, scopes }); + return actor ? subject.delegate(createIdentity(actor.id, actor.type, actor.roles, {}, { issuer }), scopes) : subject; } catch { // Verification failed (expired, invalid signature, etc.) return null; diff --git a/mcp/typescript/src/auth/types.ts b/mcp/typescript/src/auth/types.ts index b3ba335e..0f0a0446 100644 --- a/mcp/typescript/src/auth/types.ts +++ b/mcp/typescript/src/auth/types.ts @@ -24,4 +24,6 @@ export interface Authenticator { authenticate(headers: Record): Promise; /** Whether unauthenticated requests should be rejected. Default true. */ readonly requireAuth?: boolean; + /** Reject a provided credential that did not authenticate even in permissive mode. */ + readonly rejectInvalidCredentials?: boolean; } diff --git a/mcp/typescript/src/index.ts b/mcp/typescript/src/index.ts index 93dd9a9e..b8e26f89 100644 --- a/mcp/typescript/src/index.ts +++ b/mcp/typescript/src/index.ts @@ -75,7 +75,7 @@ export type { BridgeContext } from "./server/context.js"; // ─── Auth Exports ──────────────────────────────────────────────────────────── export { JWTAuthenticator } from "./auth/jwt.js"; -export type { ClaimMapping, JWTAuthenticatorOptions } from "./auth/jwt.js"; +export type { ClaimMapping, DelegatedClaims, JWTAuthenticatorOptions } from "./auth/jwt.js"; export type { Authenticator, Identity } from "./auth/types.js"; export { identityStorage, getCurrentIdentity } from "./auth/storage.js"; export { buildExplorerAuthHook } from "./auth/hooks.js"; @@ -958,7 +958,6 @@ async function serveInternal( // aiperceivable/apcore-mcp#16 phase A: advertise `com.aiperceivable/management` // in `initialize` capabilities only for surfaces actually registered. const managementSurfaces = computeManagementSurfaces(registry); - const server = factory.createServer(name, version, managementSurfaces); let tools = factory.buildTools(registry, { tags, prefix }); tools = factory.attachAsyncMetaTools(tools, asyncBridge ?? undefined); const router = new ExecutionRouter(executor, { @@ -970,8 +969,13 @@ async function serveInternal( trace, asyncTaskBridge: asyncBridge ?? undefined, }); - factory.registerHandlers(server, tools, router, scopedApproval ? { approvalBridge: scopedApproval.bridge } : undefined); - factory.registerResourceHandlers(server, registry, router); + const createSessionServer = () => { + const server = factory.createServer(name, version, managementSurfaces); + factory.registerHandlers(server, tools, router, scopedApproval ? { approvalBridge: scopedApproval.bridge } : undefined); + factory.registerResourceHandlers(server, registry, router); + return server; + }; + const server = createSessionServer(); // Start dynamic tool registration listener if enabled if (options.dynamic) { @@ -1004,6 +1008,7 @@ async function serveInternal( } if (authenticator) { transportManager.setAuthenticator(authenticator); + transportManager.setScopedServerFactory?.(createSessionServer); } if (requireAuth !== undefined) { transportManager.setRequireAuth(requireAuth); @@ -1302,7 +1307,6 @@ export async function asyncServe( // aiperceivable/apcore-mcp#16 phase A: advertise `com.aiperceivable/management` // in `initialize` capabilities only for surfaces actually registered. const managementSurfaces = computeManagementSurfaces(registry); - const server = factory.createServer(name, version, managementSurfaces); let tools = factory.buildTools(registry, { tags, prefix }); tools = factory.attachAsyncMetaTools(tools, asyncBridge ?? undefined); const router = new ExecutionRouter(executor, { @@ -1314,8 +1318,13 @@ export async function asyncServe( trace, asyncTaskBridge: asyncBridge ?? undefined, }); - factory.registerHandlers(server, tools, router, scopedApproval ? { approvalBridge: scopedApproval.bridge } : undefined); - factory.registerResourceHandlers(server, registry, router); + const createSessionServer = () => { + const server = factory.createServer(name, version, managementSurfaces); + factory.registerHandlers(server, tools, router, scopedApproval ? { approvalBridge: scopedApproval.bridge } : undefined); + factory.registerResourceHandlers(server, registry, router); + return server; + }; + const server = createSessionServer(); // Start dynamic tool registration listener if enabled. The embedded handler // has no explicit stop hook, so the listener's teardown is wired into the @@ -1347,6 +1356,7 @@ export async function asyncServe( } if (authenticator) { transportManager.setAuthenticator(authenticator); + transportManager.setScopedServerFactory?.(createSessionServer); } if (requireAuth !== undefined) { transportManager.setRequireAuth(requireAuth); diff --git a/mcp/typescript/src/server/approval-bridge.ts b/mcp/typescript/src/server/approval-bridge.ts index 19ebc5af..f2bd2064 100644 --- a/mcp/typescript/src/server/approval-bridge.ts +++ b/mcp/typescript/src/server/approval-bridge.ts @@ -14,6 +14,7 @@ export type ApprovalMetaToolName = (typeof APPROVAL_META_TOOL_NAMES)[number]; export class ApprovalBridge { constructor(private readonly handler: { + readonly supportsAuthorityScope?: boolean; checkApproval?(approvalId: string): Promise<{ status: string }>; checkApprovalForPrincipal?( approvalId: string, principal: ApprovalPrincipal | null, @@ -78,6 +79,9 @@ export class ApprovalBridge { if (!this.available || !this.handler.checkApprovalForPrincipal) { return [[{ type: "text", text: "Scoped approval status unavailable" }], true, null]; } + if (principal?.authorityKey !== undefined && this.handler.supportsAuthorityScope !== true) { + return [[{ type: "text", text: JSON.stringify({ approval_id: approvalId, status: "rejected" }) }], false, null]; + } try { const result = await this.handler.checkApprovalForPrincipal(approvalId, principal); const status = result.status === "approved" || result.status === "pending" ? result.status : "rejected"; diff --git a/mcp/typescript/src/server/async-task-bridge.ts b/mcp/typescript/src/server/async-task-bridge.ts index 3fed7be0..dee51f54 100644 --- a/mcp/typescript/src/server/async-task-bridge.ts +++ b/mcp/typescript/src/server/async-task-bridge.ts @@ -14,6 +14,7 @@ import { InvalidInputError } from "apcore-js"; import { markBackgroundApprovalContext } from "../approval-reply.js"; +import { MCP_ELICIT_KEY, MCP_PROGRESS_KEY } from "../helpers.js"; import type { ModuleDescriptor } from "../types.js"; import { ErrorCodes } from "../types.js"; @@ -93,17 +94,20 @@ export interface TaskInfoProjection { /** * Minimal duck-typed `AsyncTaskManager` contract the bridge depends on. * - * This mirrors **apcore-js 0.32.3**, whose `submit` takes an options object and + * This mirrors apcore-js, whose `submit` takes an options object and * whose `getStatus` / `listTasks` are async. It is intentionally TS-local: * apcore-python and apcore-rust still expose positional `context` and sync * reads, so their bridges keep their own manager shape. The cross-language * contract is the MCP `__apcore_task_*` envelope, not this interface. */ export interface AsyncTaskManagerLike { + readonly supportsTaskAllocationCallback?: boolean; + readonly ownsPrivateTaskStore?: boolean; + readonly store?: object; submit( moduleId: string, inputs: Record, - opts?: { context?: unknown | null }, + opts?: { context?: unknown | null; onTaskAllocated?: (taskId: string) => void }, ): Promise; getStatus(taskId: string): Promise<{ taskId: string; @@ -140,6 +144,7 @@ export interface AsyncTaskManagerLike { * `predicted_changes` populated from `Module.preview()`. */ export interface ExecutorLike { + getCallableDescriptor?(moduleId: string, context?: unknown): unknown; validate( moduleId: string, inputs?: Record | null, @@ -170,6 +175,8 @@ export interface AsyncMetaTool { export interface AsyncTaskBridgeOptions { /** When false, `isAsyncModule()` always returns false — meta-tools are disabled. */ enabled?: boolean; + /** The task manager and bridge share an in-process task lifetime. */ + scopedTasks?: boolean; /** * Optional output-redactor invoked on completed task results before they are * returned from `__apcore_task_status`. Signature matches apcore-js's @@ -197,6 +204,30 @@ export interface AsyncTaskBridgeOptions { executor?: ExecutorLike; } +interface ScopedTaskBinding { + owner: string; + state: "pending" | "published" | "failed"; +} + +const scopedTaskOwners = new WeakMap>(); + +function makeDetachableCallback( + data: Record, key: string, fallback: null | undefined, +): (() => void) | undefined { + let send = data[key]; + if (typeof send !== "function") return undefined; + data[key] = async (...args: unknown[]): Promise => { + if (typeof send !== "function") return fallback; + try { + return await send(...args); + } catch (error) { + if (typeof send === "function") throw error; + return fallback; + } + }; + return () => { send = undefined; }; +} + /** * Routes MCP tool calls either to the synchronous Execution Router (default) * or to `AsyncTaskManager.submit()` for async-hinted modules. @@ -208,12 +239,17 @@ export class AsyncTaskBridge { private readonly _outputSchemaMap: Record>; private readonly _descriptorLookup?: AsyncTaskBridgeOptions["descriptorLookup"]; private readonly _executor?: ExecutorLike; + private readonly _scopedTasks: boolean; + private readonly _scopedTaskOwners: Map; /** - * Maps task_id → progressToken recorded at submit time so terminal- - * state notifications can be fanned out via the original token. + * Tracks notification tokens and callbacks bound to each task's transport. * [A-D-018] */ - private readonly _progressTokens = new Map(); + private readonly _taskNotifications = new Map void; + sessionKey?: string; + }>(); /** * Maps session/connection key → list of task ids launched from that * session so {@link cancelSessionTasks} can cancel them on transport @@ -228,6 +264,13 @@ export class AsyncTaskBridge { this._outputSchemaMap = options?.outputSchemaMap ?? {}; this._descriptorLookup = options?.descriptorLookup; this._executor = options?.executor; + this._scopedTasks = options?.scopedTasks === true; + // Share ownership with any bridge using the same in-memory store, including a host + // explicitly passing that instance to a second manager. + const store = manager.store; + const ownerKey = store && typeof store === "object" ? store : manager; + this._scopedTaskOwners = scopedTaskOwners.get(ownerKey) ?? new Map(); + scopedTaskOwners.set(ownerKey, this._scopedTaskOwners); } /** Whether async routing and meta-tools are enabled. */ @@ -280,6 +323,8 @@ export class AsyncTaskBridge { options?: { /** Optional MCP progress token (recorded for fan-out). [A-D-018] */ progressToken?: string | number; + /** Bind callbacks without binding the task itself to disconnect cancellation. */ + callbackSessionKey?: string; /** Optional session/connection key (recorded for cancelSessionTasks). [A-D-018] */ sessionKey?: string; /** @@ -291,6 +336,20 @@ export class AsyncTaskBridge { sendNotification?: (notification: Record) => Promise | void; }, ): Promise<{ task_id: string; status: "pending" }> { + const owner = this._scopedOwner(context); + if (owner !== null && (!this._scopedTasks || this._manager.supportsTaskAllocationCallback !== true || + this._manager.ownsPrivateTaskStore !== true || + !this._canDisclose(moduleId, context))) { + throw new Error("Async module is unavailable to this authority"); + } + const tracked = Array.from(this._scopedTaskOwners.entries()) + .filter(([, binding]) => binding.state !== "pending").map(([taskId]) => taskId); + if (tracked.length > 0) { + const live = new Set((await this._manager.listTasks()).map(info => info.taskId)); + for (const taskId of tracked) { + if (!live.has(taskId)) this._scopedTaskOwners.delete(taskId); + } + } // [D11-015] Install progress sink on the context BEFORE submitting, so the // module can emit mid-execution progress via context.data[MCP_PROGRESS_KEY]. // Mirrors Python's async_task_bridge.py _install_progress_sink() pattern. @@ -305,7 +364,7 @@ export class AsyncTaskBridge { const sendNotification = options.sendNotification; const contextData = (context as Record).data; if (contextData && typeof contextData === "object") { - (contextData as Record)["_mcp_progress"] = async ( + (contextData as Record)[MCP_PROGRESS_KEY] = async ( progress: number, total: number, ) => { @@ -319,13 +378,21 @@ export class AsyncTaskBridge { // Core preserves Context.data when it clones a context for the background job. // The marker carries no approval state or credentials. + const callbackSessionKey = options?.callbackSessionKey ?? options?.sessionKey; + let detach: (() => void) | undefined; if (context && typeof context === "object" && "data" in context && context.data && typeof context.data === "object") { markBackgroundApprovalContext(context.data); + if (callbackSessionKey !== undefined) { + const data = context.data as Record; + const detachProgress = makeDetachableCallback(data, MCP_PROGRESS_KEY, undefined); + const detachElicit = makeDetachableCallback(data, MCP_ELICIT_KEY, null); + if (detachProgress || detachElicit) detach = () => { detachProgress?.(); detachElicit?.(); }; + } } - const taskId = await this._manager.submit(moduleId, inputs, { context: context ?? null }); - if (options?.progressToken !== undefined) { - this._progressTokens.set(taskId, options.progressToken); + const taskId = await this._submitOwnedTask(moduleId, inputs, context ?? null, owner); + if (options?.progressToken !== undefined || detach) { + this._taskNotifications.set(taskId, { progressToken: options?.progressToken, detach, sessionKey: callbackSessionKey }); } if (options?.sessionKey !== undefined) { const list = this._sessionTasks.get(options.sessionKey) ?? []; @@ -335,6 +402,24 @@ export class AsyncTaskBridge { return { task_id: taskId, status: "pending" }; } + private async _submitOwnedTask( + moduleId: string, inputs: Record, context: unknown, owner: string | null, + ): Promise { + if (owner === null) return this._manager.submit(moduleId, inputs, { context }); + const binding: ScopedTaskBinding = { owner, state: "pending" }; + try { + const taskId = await this._manager.submit(moduleId, inputs, { + context, + onTaskAllocated: id => { this._scopedTaskOwners.set(id, binding); }, + }); + binding.state = "published"; + return taskId; + } finally { + // A store may have persisted the record before reporting a failure. + if (binding.state === "pending") binding.state = "failed"; + } + } + /** * Look up the progress token recorded for a task at submit time. * @@ -343,7 +428,7 @@ export class AsyncTaskBridge { * when no token was registered. [A-D-018] */ getProgressToken(taskId: string): string | number | undefined { - return this._progressTokens.get(taskId); + return this._taskNotifications.get(taskId)?.progressToken; } /** @@ -361,8 +446,8 @@ export class AsyncTaskBridge { // would drop the newly-tracked task. Mirrors Python's `pop()` and Rust's // `remove()` — both detach before yielding to manager.cancel. const taskIds = this._sessionTasks.get(sessionKey); + this.detachSessionTasks(sessionKey); if (!taskIds || taskIds.length === 0) return 0; - this._sessionTasks.delete(sessionKey); let cancelled = 0; for (const taskId of taskIds) { try { @@ -371,11 +456,20 @@ export class AsyncTaskBridge { } catch { // Cancel may fail if the task has already completed; swallow. } - this._progressTokens.delete(taskId); } return cancelled; } + /** Remove transport-specific state when an idle HTTP session is reclaimed. */ + detachSessionTasks(sessionKey: string): void { + this._sessionTasks.delete(sessionKey); + for (const [taskId, notification] of this._taskNotifications) { + if (notification.sessionKey !== sessionKey) continue; + notification.detach?.(); + this._taskNotifications.delete(taskId); + } + } + /** * Build the four MCP meta-tool definitions. Caller merges these with * the regular tool list returned by `tools/list`. @@ -485,6 +579,7 @@ export class AsyncTaskBridge { toolName: string, args: Record, context?: unknown | null, + callbackSessionKey?: string, ): Promise> { switch (toolName) { case META_TOOL_NAMES.SUBMIT: { @@ -541,7 +636,7 @@ export class AsyncTaskBridge { // but bridges that call handleMetaTool directly (toolkit/library // use) saw a raw Error without errorType or retryable hints. try { - return (await this.submit(moduleId, inputs, context)) as unknown as Record; + return (await this.submit(moduleId, inputs, context, { callbackSessionKey })) as unknown as Record; } catch (err: unknown) { if (_isTaskLimitExceeded(err)) { const e = err as Error & { details?: Record | null }; @@ -562,7 +657,7 @@ export class AsyncTaskBridge { throw new Error("__apcore_task_status requires task_id (string)"); } const info = await this._manager.getStatus(taskId); - if (!info) { + if (!info || !this._canReadTask(info, context)) { // [D10-003] Return envelope (matching Python's `(content, is_error=True, None)` // and Rust's `Ok(envelope)`). Throwing here would force the caller's catch path // to diverge from Python+Rust, breaking cross-SDK error handling. @@ -603,8 +698,11 @@ export class AsyncTaskBridge { // Without this, unknown task_ids silently return `{cancelled: false}` — // callers can't distinguish "task existed and is uncancellable" from // "task never existed". - if (!(await this._manager.getStatus(taskId))) { - this._progressTokens.delete(taskId); + const info = await this._manager.getStatus(taskId); + if (!info) { + this._taskNotifications.delete(taskId); + } + if (!info || !this._canReadTask(info, context)) { return { error: "ASYNC_TASK_NOT_FOUND", task_id: taskId, @@ -617,7 +715,7 @@ export class AsyncTaskBridge { // token whose caller has already been told the task is gone. Mirrors // Python's `_progress_bindings.pop(task_id, None)` and Rust's // `progress_tokens.remove(task_id)`. - this._progressTokens.delete(taskId); + this._taskNotifications.delete(taskId); return { task_id: taskId, cancelled }; } case META_TOOL_NAMES.PREVIEW: { @@ -728,13 +826,33 @@ export class AsyncTaskBridge { filter = status; } const tasks = await this._manager.listTasks(filter); - return { tasks: tasks.map((t) => this._projectTaskInfo(t)) }; + return { tasks: tasks.filter(t => this._canReadTask(t, context)).map(t => this._projectTaskInfo(t)) }; } default: throw new Error(`Unknown meta-tool: ${toolName}`); } } + private _scopedOwner(context: unknown): string | null { + const bound = context as { identity?: { ownerKey?(): string | null } | null } | null; + return bound?.identity?.ownerKey?.() ?? null; + } + + private _canDisclose(moduleId: string, context: unknown): boolean { + try { + return this._executor?.getCallableDescriptor?.(moduleId, context) != null; + } catch { + return false; + } + } + + private _canReadTask(info: { taskId: string; moduleId: string }, context: unknown): boolean { + const binding = this._scopedTaskOwners.get(info.taskId); + const owner = this._scopedOwner(context); + if (!binding) return owner === null; + return binding.state === "published" && binding.owner === owner && this._canDisclose(info.moduleId, context); + } + private _projectTaskInfo(info: { taskId: string; moduleId: string; @@ -795,6 +913,7 @@ export async function createAsyncTaskBridge( : undefined; return new AsyncTaskBridge(manager, { enabled: true, + scopedTasks: true, redactSensitive: typeof redactSensitive === "function" ? redactSensitive : () => { throw new Error("Output redaction failed"); }, diff --git a/mcp/typescript/src/server/factory.ts b/mcp/typescript/src/server/factory.ts index b170fc8d..a70c2fd1 100644 --- a/mcp/typescript/src/server/factory.ts +++ b/mcp/typescript/src/server/factory.ts @@ -34,7 +34,7 @@ import type { HandleCallExtra } from "./router.js"; import { buildTraceparent } from "./trace-context.js"; import { APCORE_META_TOOL_PREFIX, AsyncTaskBridge } from "./async-task-bridge.js"; import { ApprovalBridge } from "./approval-bridge.js"; -import { isApprovalResumeToken } from "../adapters/approval.js"; +import { approvalPrincipal, isApprovalResumeToken } from "../adapters/approval.js"; import { enableApprovalReplies, type ApprovalReplyCapture, type PendingApprovalReply } from "../approval-reply.js"; import { isMarkdownAvailable, @@ -771,7 +771,8 @@ export class MCPServerFactory { // Dispatch to approval bridge meta-tool if applicable (AFTER async bridge, // BEFORE the async-hint route in router.handleCall). if (approvalBridge && ApprovalBridge.isMetaTool(name)) { - const [apContent, apIsError] = await approvalBridge.handleMetaTool(name, toolArgs, handleCallExtra.identity ?? null); + const principal = approvalPrincipal(handleCallExtra.identity); + const [apContent, apIsError] = await approvalBridge.handleMetaTool(name, toolArgs, principal); const apTextContents = apContent.map(c => ({ type: "text" as const, text: c.text })); return { content: apTextContents, ...(apIsError ? { isError: true } : {}) }; } diff --git a/mcp/typescript/src/server/router.ts b/mcp/typescript/src/server/router.ts index 0e852b96..5d43d3d5 100644 --- a/mcp/typescript/src/server/router.ts +++ b/mcp/typescript/src/server/router.ts @@ -614,6 +614,7 @@ export class ExecutionRouter { toolName, args, context, + extra?.sessionId, ); const content: TextContentDict[] = [ { type: "text", text: await this._formatResult(metaResult) }, diff --git a/mcp/typescript/src/server/transport.ts b/mcp/typescript/src/server/transport.ts index 058a494c..6fe4b9c3 100644 --- a/mcp/typescript/src/server/transport.ts +++ b/mcp/typescript/src/server/transport.ts @@ -14,9 +14,15 @@ import { bindStdioWork, withStdioOutput } from "./stdio-output.js"; import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"; import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js"; import { SSEServerTransport } from "@modelcontextprotocol/sdk/server/sse.js"; +import { isInitializeRequest } from "@modelcontextprotocol/sdk/types.js"; import { hasApprovalReplies } from "../approval-reply.js"; -import type { Authenticator } from "../auth/types.js"; -import { identityStorage } from "../auth/storage.js"; +import type { Authenticator, Identity } from "../auth/types.js"; +import { getCurrentIdentity, identityStorage } from "../auth/storage.js"; + +function sessionPrincipal(identity: Identity | null): string | null { + // Legacy sessions keep their established per-request identity behavior. + return identity?.authorityKey?.() ?? null; +} /** Options for HTTP-based transports. */ export interface HttpTransportOptions { @@ -39,6 +45,14 @@ export interface UsageExporter { /** Default maximum request body size in bytes (4MB). */ const DEFAULT_MAX_BODY_BYTES = 4 * 1024 * 1024; +/** Default retained scoped Streamable HTTP sessions per manager. */ +const DEFAULT_MAX_SCOPED_HTTP_SESSIONS = 1000; + +function scopedHttpSessionLimit(): number { + const configured = Number(process.env.APCORE_MAX_SCOPED_HTTP_SESSIONS); + return Number.isSafeInteger(configured) && configured > 0 ? configured : DEFAULT_MAX_SCOPED_HTTP_SESSIONS; +} + /** Prometheus exposition format content-type. */ const PROMETHEUS_CONTENT_TYPE = "text/plain; version=0.0.4; charset=utf-8"; @@ -124,6 +138,19 @@ export class TransportManager { /** Explicit requireAuth override (when set, takes precedence over authenticator's own value). */ private _requireAuth?: boolean; + private readonly _httpSessionOwners = new WeakMap(); + private readonly _scopedHttpSessions = new Map(); + private readonly _scopedHttpActivity = new Map(); + private readonly _capacityEvictions = new WeakSet(); + private readonly _maxScopedHttpSessions = scopedHttpSessionLimit(); + private readonly _scopedSseTransports = new Set(); + private _scopedServerFactory?: () => Server; + + /** Allocate a separate protocol server for each scoped session. */ + setScopedServerFactory(factory: () => Server): void { + this._scopedServerFactory = factory; + } + /** * Optional AsyncTaskBridge — used to cancel session-bound async tasks * on transport disconnect via `cancelSessionTasks(sessionId)`. @@ -131,6 +158,7 @@ export class TransportManager { */ private _asyncTaskBridge?: { cancelSessionTasks(sessionKey: string): Promise; + detachSessionTasks?(sessionKey: string): void; }; /** @@ -214,6 +242,7 @@ export class TransportManager { */ setAsyncTaskBridge(bridge: { cancelSessionTasks(sessionKey: string): Promise; + detachSessionTasks?(sessionKey: string): void; }): void { // [D10-006] Reject null/undefined bridge (matching Python `TypeError`). // Silently storing null would surface later as a TypeError on first @@ -364,7 +393,8 @@ export class TransportManager { const identity = await this._authenticator.authenticate(headersMap); if (!identity) { const requireAuth = this._requireAuth ?? this._authenticator.requireAuth ?? true; - if (!requireAuth) { + const badCredential = this._authenticator.rejectInvalidCredentials === true && Object.hasOwn(req.headers, "authorization"); + if (!requireAuth && !badCredential) { return { identity: null, blocked: false }; } // [JWT-2] Unify 401 body shape with Python+Rust: @@ -408,7 +438,7 @@ export class TransportManager { * `buildStreamableHttpApp` (embeddable handler). */ private _createStreamableHandler( - transport: StreamableHTTPServerTransport, + defaultTransport: StreamableHTTPServerTransport, endpoint: string, urlBase: string, ): (req: IncomingMessage, res: ServerResponse) => Promise { @@ -440,12 +470,40 @@ export class TransportManager { return; } + const requestedSession = req.headers["mcp-session-id"]; + const transport = typeof requestedSession === "string" + ? this._scopedHttpSessions.get(requestedSession) ?? defaultTransport : defaultTransport; + if (requestedSession !== undefined && + (requestedSession !== transport.sessionId || + this._httpSessionOwners.get(transport) !== sessionPrincipal(identity))) { + res.writeHead(404, { "Content-Type": "application/json" }); + res.end(JSON.stringify({ jsonrpc: "2.0", error: { code: -32600, message: "Session not found" }, id: null })); + return; + } + const handleMcp = async () => { + let opening: StreamableHTTPServerTransport | undefined; + // A standalone GET is a listener. POST and replay requests can carry active work. + const tracksActivity = req.method !== "GET" || req.headers["last-event-id"] !== undefined; + const active = tracksActivity ? this._scopedHttpActivity.get(transport) : undefined; + if (active !== undefined) this._scopedHttpActivity.set(transport, active + 1); try { if (req.method === "POST" || req.method === "DELETE") { const body = await readBody(req); const parsed = body ? JSON.parse(body) : undefined; - await transport.handleRequest(req, res, parsed); + if (req.method === "POST" && requestedSession === undefined && identity?.scopes !== undefined && + this._scopedServerFactory && isInitializeRequest(parsed)) { + opening = await this._openScopedHttpTransport(); + if (!opening) { + res.writeHead(503, { "Content-Type": "application/json" }); + res.end(JSON.stringify({ + jsonrpc: "2.0", error: { code: -32000, message: "Scoped session capacity reached" }, id: null, + })); + return; + } + await this._scopedServerFactory().connect(opening); + } + await (opening ?? transport).handleRequest(req, res, parsed); } else { await transport.handleRequest(req, res); } @@ -460,16 +518,66 @@ export class TransportManager { res.writeHead(500).end("Internal Server Error"); } } + } finally { + if (opening && opening.sessionId === undefined) await opening.close(); + if (opening || active !== undefined) this._finishScopedHttpRequest(opening ?? transport); } }; // Wrap in identityStorage so getCurrentIdentity() works in the call chain - if (identity) { - await identityStorage.run(identity, handleMcp); - } else { - await handleMcp(); + await identityStorage.run(identity, handleMcp); + }; + } + + private async _openScopedHttpTransport(): Promise { + if (this._scopedHttpActivity.size >= this._maxScopedHttpSessions) { + // Map order records last completion. An opening or active request is never evicted. + for (const [candidate, active] of this._scopedHttpActivity) { + if (active !== 0 || !candidate.sessionId) continue; + this._scopedHttpSessions.delete(candidate.sessionId); + this._scopedHttpActivity.set(candidate, 1); + this._capacityEvictions.add(candidate); + await candidate.close(); + break; } + } + // Account for another opening that acquired a slot while close() awaited. + if (this._scopedHttpActivity.size >= this._maxScopedHttpSessions) return undefined; + const transport = this._newStreamableTransport(true); + this._scopedHttpActivity.set(transport, 1); + return transport; + } + + private _finishScopedHttpRequest(transport: StreamableHTTPServerTransport): void { + const active = this._scopedHttpActivity.get(transport); + if (active === undefined) return; + this._scopedHttpActivity.delete(transport); + this._scopedHttpActivity.set(transport, active - 1); + } + + private _newStreamableTransport(scoped = false): StreamableHTTPServerTransport { + const transport = new StreamableHTTPServerTransport({ + sessionIdGenerator: () => crypto.randomUUID(), + onsessioninitialized: (id) => { + this._httpSessionOwners.set(transport, sessionPrincipal(getCurrentIdentity())); + if (scoped) this._scopedHttpSessions.set(id, transport); + }, + }); + transport.onclose = () => { + this._httpSessionOwners.delete(transport); + this._scopedHttpActivity.delete(transport); + const sessionId = transport.sessionId; + if (!sessionId) return; + this._scopedHttpSessions.delete(sessionId); + if (this._capacityEvictions.delete(transport)) { + this._asyncTaskBridge?.detachSessionTasks?.(sessionId); + return; + } + this._asyncTaskBridge?.cancelSessionTasks(sessionId).catch((error: unknown) => { + console.warn(`cancelSessionTasks failed for streamable-http session ${sessionId}:`, error); + }); }; + return transport; } /** @@ -563,34 +671,7 @@ export class TransportManager { const endpoint = options.endpoint ?? "/mcp"; - const transport = new StreamableHTTPServerTransport({ - sessionIdGenerator: () => crypto.randomUUID(), - }); - - // [A-D-018] StreamableHTTP wiring: when the transport closes (server - // shutdown or SDK-internal session expiry), cancel any session-bound - // async tasks via the bridge. Mirrors the SSE-side onclose handler. - // Note: the SDK exposes a single onclose for the whole transport, - // not per-session — this fires once when the transport tears down, - // not on individual client disconnects. For per-client cancellation - // we'd need per-session-aware hooks the SDK does not currently - // provide. The transport-shutdown path is still a real cleanup - // point worth wiring. - if (this._asyncTaskBridge) { - const existing = transport.onclose; - transport.onclose = () => { - const sid = transport.sessionId; - if (sid && this._asyncTaskBridge) { - this._asyncTaskBridge.cancelSessionTasks(sid).catch((err: unknown) => { - console.warn( - `cancelSessionTasks failed for streamable-http session ${sid}:`, - err, - ); - }); - } - if (existing) existing(); - }; - } + const transport = this._newStreamableTransport(); await server.connect(transport); @@ -634,7 +715,7 @@ export class TransportManager { const endpoint = options.endpoint ?? "/sse"; const messagesEndpoint = "/messages"; - const transports = new Map(); + const transports = new Map(); const explorerNodeHandler = this._explorerNodeHandler; const explorerPrefix = this._explorerPrefix; @@ -664,10 +745,13 @@ export class TransportManager { // Establish SSE connection const transport = new SSEServerTransport(messagesEndpoint, res); const sessionId = transport.sessionId; - transports.set(sessionId, transport); + transports.set(sessionId, { transport, principal: sessionPrincipal(identity) }); + const scopedServer = identity?.scopes !== undefined ? this._scopedServerFactory?.() : undefined; + if (scopedServer) this._scopedSseTransports.add(transport); transport.onclose = () => { transports.delete(sessionId); + this._scopedSseTransports.delete(transport); // [A-D-018] Cooperatively cancel any async tasks bound to // this session when the client disconnects. if (this._asyncTaskBridge) { @@ -683,7 +767,7 @@ export class TransportManager { }; // Server.connect starts the SDK transport after installing callbacks. - await server.connect(transport); + await (scopedServer ?? server).connect(transport); } else if (url.pathname === messagesEndpoint && req.method === "POST") { // Route message to the correct session transport const sessionId = url.searchParams.get("sessionId"); @@ -692,8 +776,8 @@ export class TransportManager { return; } - const transport = transports.get(sessionId); - if (!transport) { + const session = transports.get(sessionId); + if (!session || session.principal !== sessionPrincipal(identity)) { res.writeHead(400).end("Unknown session"); return; } @@ -701,7 +785,7 @@ export class TransportManager { try { const body = await readBody(req); const parsed = body ? JSON.parse(body) : undefined; - await transport.handlePostMessage(req, res, parsed); + await session.transport.handlePostMessage(req, res, parsed); } catch (err) { if (!res.headersSent) { const message = err instanceof Error ? err.message : ""; @@ -764,40 +848,14 @@ export class TransportManager { }> { const endpoint = options?.endpoint ?? "/mcp"; - const transport = new StreamableHTTPServerTransport({ - sessionIdGenerator: () => crypto.randomUUID(), - }); - - // [A-D-018] StreamableHTTP wiring: when the transport closes (server - // shutdown or SDK-internal session expiry), cancel any session-bound - // async tasks via the bridge. Mirrors the SSE-side onclose handler. - // Note: the SDK exposes a single onclose for the whole transport, - // not per-session — this fires once when the transport tears down, - // not on individual client disconnects. For per-client cancellation - // we'd need per-session-aware hooks the SDK does not currently - // provide. The transport-shutdown path is still a real cleanup - // point worth wiring. - if (this._asyncTaskBridge) { - const existing = transport.onclose; - transport.onclose = () => { - const sid = transport.sessionId; - if (sid && this._asyncTaskBridge) { - this._asyncTaskBridge.cancelSessionTasks(sid).catch((err: unknown) => { - console.warn( - `cancelSessionTasks failed for streamable-http session ${sid}:`, - err, - ); - }); - } - if (existing) existing(); - }; - } + const transport = this._newStreamableTransport(); await server.connect(transport); const handler = this._createStreamableHandler(transport, endpoint, "http://localhost"); const close = async () => { + await this._closeScopedTransports(); await transport.close(); }; @@ -809,6 +867,7 @@ export class TransportManager { */ async close(): Promise { await this._closeStdio?.(); + await this._closeScopedTransports(); if (!this.httpServer) return; return new Promise((resolve) => { @@ -816,6 +875,11 @@ export class TransportManager { }); } + private async _closeScopedTransports(): Promise { + const transports = [...this._scopedHttpActivity.keys(), ...this._scopedSseTransports]; + await Promise.all(transports.map(transport => transport.close())); + } + /** * Validate host and port parameters for HTTP transports. * diff --git a/mcp/typescript/tests/auth/delegated-jwt.test.ts b/mcp/typescript/tests/auth/delegated-jwt.test.ts new file mode 100644 index 00000000..2c139187 --- /dev/null +++ b/mcp/typescript/tests/auth/delegated-jwt.test.ts @@ -0,0 +1,337 @@ +import { once } from "node:events"; +import { createServer } from "node:http"; +import type { AddressInfo } from "node:net"; +import { Client } from "@modelcontextprotocol/sdk/client/index.js"; +import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js"; +import { ACL, Context, Executor, Registry, createAnnotations } from "apcore-js"; +import { AsyncTaskManager, TaskStatus } from "apcore-js/full"; +import jwt from "jsonwebtoken"; +import { describe, expect, it, vi } from "vitest"; +import { + AsyncTaskBridge, asyncServe, createAsyncTaskBridge, elicit, InMemoryApprovalStore, JWTAuthenticator, + META_TOOL_NAMES, reportProgress, +} from "../../src/index.js"; + +const key = "signed-test-secret"; +const issuer = "https://issuer.example"; +const audience = "mcp-test"; + +function token(claims: Record = {}, secret = key): string { + const payload = { + iss: issuer, aud: audience, sub: "account", exp: Math.floor(Date.now() / 1000) + 300, + scope: "read write", roles: ["account-role"], + act: { sub: "actor", actorRoles: ["runner"], act: { sub: "history", actorRoles: ["admin"] } }, + ...claims, + }; + return jwt.sign(Object.fromEntries(Object.entries(payload).filter(([, value]) => value !== undefined)), secret); +} + +const auth = new JWTAuthenticator({ + key, issuer, audience, requireAuth: false, + delegatedClaims: { scpClaim: "scp", actorRolesClaim: "actorRoles" }, + claimMapping: { attrs: ["act"] }, +}); + +describe("delegated MCP JWT", () => { + it("projects only the verified current actor and normalized current scopes", async () => { + const identity = await auth.authenticate({ authorization: `Bearer ${token({ scp: ["write", "read", "read"] })}` }); + expect(identity?.id).toBe("actor"); + expect(identity?.roles).toEqual(["runner"]); + expect(identity?.scopes).toEqual(["read", "write"]); + expect(identity?.delegationDepth).toBe(1); + expect(identity?.rootSubject.id).toBe("account"); + expect(identity?.rootSubject.roles).toEqual(["account-role"]); + expect(identity?.rootSubject.attrs).toEqual({}); + }); + + it("rejects invalid signatures, missing authority, malformed chains and conflicting scope sources", async () => { + const now = Math.floor(Date.now() / 1000); + const actorHistory = Array.from({ length: 9 }).reduce( + (next, _, index) => ({ sub: `actor-${index}`, ...(next ? { act: next } : {}) }), undefined, + ); + const candidates = [ + token({}, "incorrect"), token({ iss: "untrusted" }), token({ aud: "other" }), + token({ exp: now - 60 }), token({ exp: undefined }), token({ nbf: now + 120 }), + token({ iat: now + 120 }), token({ scope: "read", scp: ["write"] }), + token({ scope: undefined }), token({ scope: "read\n" }), + token({ act: { sub: "actor", act: null } }), token({ act: actorHistory }), + ]; + for (const signed of candidates) { + expect(await auth.authenticate({ authorization: `Bearer ${signed}` })).toBeNull(); + } + const empty = await auth.authenticate({ authorization: `Bearer ${token({ scope: undefined, scp: [] })}` }); + expect(empty?.scopes).toEqual([]); + }); + + it("requires a signed algorithm and verification key in delegated mode", () => { + expect(() => new JWTAuthenticator({ key, issuer, audience, delegatedClaims: {}, algorithms: ["none"] })) + .toThrow("signed algorithms"); + expect(() => new JWTAuthenticator({ issuer, audience, delegatedClaims: {} })).toThrow("verification key"); + }); + + it("enforces signed ownership on the HTTP session and authority on polling and atomic resumption", async () => { + const moduleId = "sample.review"; + const registry = new Registry(); + await registry.register(moduleId, { + description: "Approve an example", + annotations: createAnnotations({ requiresApproval: true }), + inputSchema: { type: "object" }, outputSchema: { type: "object" }, + execute: () => ({ approved: true }), + }); + const store = new InMemoryApprovalStore(); + const app = await asyncServe(registry as never, { + async: false, approvalStore: store, authenticator: auth, + acl: new ACL([{ callers: ["@external"], targets: [moduleId], effect: "allow", conditions: { scopes: ["read"] } }]), + }); + const http = createServer(app.handler); + const client = new Client({ name: "mcp-delegation", version: "1" }); + const narrowed = new Client({ name: "mcp-narrowed", version: "1" }); + let credential = token(); + try { + http.listen(0, "127.0.0.1"); + await once(http, "listening"); + const url = new URL(`http://127.0.0.1:${(http.address() as AddressInfo).port}/mcp`); + await client.connect(new StreamableHTTPClientTransport(url, { + fetch: (input, options) => { + const headers = new Headers(options?.headers); + headers.set("Authorization", `Bearer ${credential}`); + return fetch(input, { ...options, headers }); + }, + })); + const pending = await client.callTool({ name: moduleId, arguments: {} }); + const approval = (pending._meta?.apcore as { approval: { approvalId: string; resumeToken: string } }).approval; + const resume = (session = client) => session.callTool({ name: moduleId, arguments: {}, _meta: { approvalId: approval.resumeToken } }); + + expect(await store.resolve(approval.approvalId, { approved: true })).toBe(true); + credential = token({ scope: "read" }); + await expect(client.listTools()).rejects.toThrow("Session not found"); + await narrowed.connect(new StreamableHTTPClientTransport(url, { + requestInit: { headers: { Authorization: `Bearer ${credential}` } }, + })); + const poll = await narrowed.callTool({ name: "__apcore_approval_check", arguments: { approval_id: approval.approvalId } }); + expect(JSON.parse((poll.content as { text: string }[])[0].text).status).toBe("rejected"); + expect((await resume(narrowed)).isError).toBe(true); + + credential = token({ sub: "other-account" }); + await expect(client.listTools()).rejects.toThrow("Session not found"); + credential = token({}, "incorrect"); + await expect(client.listTools()).rejects.toThrow("Unauthorized"); + credential = token(); + expect((await resume()).structuredContent).toEqual({ approved: true }); + expect((await resume()).isError).toBe(true); + } finally { + await client.close(); + await narrowed.close(); + await app.close(); + http.closeAllConnections(); + await new Promise(resolve => http.close(() => resolve())); + } + }); + + it.each(["hinted", "explicit"])("reclaims idle scoped HTTP sessions with %s background work", async (entry) => { + const moduleId = "sample.slow"; + const backgroundId = "sample.detached"; + let notifyStarted!: () => void; + let finishCall!: () => void; + let finishBackground!: () => void; + const started = new Promise(resolve => { notifyStarted = resolve; }); + const finish = new Promise(resolve => { finishCall = resolve; }); + const background = new Promise(resolve => { finishBackground = resolve; }); + const registry = new Registry(); + await registry.register(moduleId, { + description: "Wait for a test signal", + inputSchema: { type: "object" }, outputSchema: { type: "object" }, + execute: async () => { notifyStarted(); await finish; return { ok: true }; }, + }); + await registry.register(backgroundId, { + description: "Continue after the transport closes", + inputSchema: { type: "object" }, outputSchema: { type: "object" }, + annotations: createAnnotations({ extra: { mcp_async: "true" } }), + execute: async (_inputs, context) => { + await background; + if (!context) throw new Error("Missing task context"); + await reportProgress(context, 1, 1, "Done"); + expect(await elicit(context, "Continue?", { type: "object", properties: {} })).toBeNull(); + return { continued: true }; + }, + }); + vi.stubEnv("APCORE_MAX_SCOPED_HTTP_SESSIONS", "1"); + const app = await asyncServe(registry as never, { + async: true, authenticator: auth, + acl: new ACL([{ + callers: ["@external"], targets: [moduleId, backgroundId], effect: "allow", conditions: { scopes: ["read"] }, + }]), + }); + const http = createServer(app.handler); + const first = new Client({ name: "first", version: "1" }); + const next = new Client({ name: "next", version: "1" }); + const returning = new Client({ name: "returning", version: "1" }); + try { + http.listen(0, "127.0.0.1"); + await once(http, "listening"); + const url = new URL(`http://127.0.0.1:${(http.address() as AddressInfo).port}/mcp`); + const connect = (client: Client, subject: string) => client.connect(new StreamableHTTPClientTransport(url, { + requestInit: { headers: { Authorization: `Bearer ${token({ sub: subject })}` } }, + })); + await connect(first, "first-account"); + const active = first.callTool({ name: moduleId, arguments: {} }); + try { + await Promise.race([started, active.then(() => { throw new Error("Tool completed unexpectedly"); })]); + const rejected = await fetch(url, { + method: "POST", + headers: { + Authorization: `Bearer ${token({ sub: "next-account" })}`, + Accept: "application/json, text/event-stream", "Content-Type": "application/json", + }, + body: JSON.stringify({ + jsonrpc: "2.0", id: 1, method: "initialize", + params: { protocolVersion: "2025-03-26", capabilities: {}, clientInfo: { name: "next", version: "1" } }, + }), + }); + expect(rejected.status).toBe(503); + await rejected.text(); + } finally { + finishCall(); + await active; + } + const request = entry === "hinted" + ? { name: backgroundId, arguments: {} } + : { name: META_TOOL_NAMES.SUBMIT, arguments: { module_id: backgroundId, arguments: {} } }; + const submission = await first.callTool(request, undefined, { onprogress: vi.fn() }); + const text = (result: { content?: unknown }) => JSON.parse((result.content as { text: string }[])[0].text); + const task = text(submission); + expect(task).toMatchObject({ task_id: expect.any(String), status: "pending" }); + const status = (client: Client) => client.callTool({ + name: META_TOOL_NAMES.STATUS, arguments: { task_id: task.task_id }, + }); + await connect(next, "next-account"); + expect((await next.listTools()).tools.map(tool => tool.name)).toContain(moduleId); + await expect(first.listTools()).rejects.toThrow("Session not found"); + expect(text(await status(next))).toMatchObject({ error: "ASYNC_TASK_NOT_FOUND" }); + await connect(returning, "first-account"); + expect(text(await status(returning))).toMatchObject({ status: "running" }); + finishBackground(); + await expect.poll(async () => text(await status(returning))).toMatchObject({ + status: "completed", result: { continued: true }, + }); + } finally { + finishBackground(); + vi.unstubAllEnvs(); + await first.close(); + await next.close(); + await returning.close(); + await app.close(); + http.closeAllConnections(); + await new Promise(resolve => http.close(() => resolve())); + } + }); + + it("rechecks current scoped permission on tasks across sessions", async () => { + const moduleId = "sample.background"; + const registry = new Registry(); + await registry.register(moduleId, { + description: "Produce a governed result", + inputSchema: { type: "object" }, outputSchema: { type: "object" }, + execute: () => ({ privateResult: 42 }), + }); + const executor = new Executor({ registry, acl: new ACL([ + { callers: ["@external"], targets: [moduleId], effect: "allow", conditions: { scopes: ["write"] } }, + ]) }); + const bridge = (await createAsyncTaskBridge(executor))!; + const current = async (claims = {}) => Context.create(await auth.authenticate({ authorization: `Bearer ${token(claims)}` })); + try { + const owner = await current(); + const { task_id: taskId } = await bridge.submit(moduleId, {}, owner); + const read = (context: Context) => bridge.handleMetaTool(META_TOOL_NAMES.STATUS, { task_id: taskId }, context); + await expect.poll(() => read(owner)).toMatchObject({ status: "completed", result: { privateResult: 42 } }); + expect(await read(await current())).toMatchObject({ status: "completed" }); + for (const identity of [Context.create(), await current({ scope: "read" }), await current({ sub: "other" })]) { + expect(await read(identity)).toMatchObject({ error: "ASYNC_TASK_NOT_FOUND" }); + expect(await bridge.handleMetaTool(META_TOOL_NAMES.CANCEL, { task_id: taskId }, identity)) + .toMatchObject({ error: "ASYNC_TASK_NOT_FOUND" }); + expect(await bridge.handleMetaTool(META_TOOL_NAMES.LIST, {}, identity)).toEqual({ tasks: [] }); + } + } finally { + await bridge.manager.shutdown?.(); + } + }); + + it.each([false, true])("keeps scoped ownership private until publication succeeds (store failure %s)", async (fail) => { + const scopedId = "sample.scoped"; + const legacyId = "sample.legacy"; + const registry = new Registry(); + for (const moduleId of [scopedId, legacyId]) { + await registry.register(moduleId, { + description: "Produce a task result", + inputSchema: { type: "object" }, outputSchema: { type: "object" }, execute: () => ({}), + }); + } + const executor = new Executor({ registry, acl: new ACL([ + { callers: ["@external"], targets: [scopedId], effect: "allow", conditions: { scopes: ["write"] } }, + { callers: ["@external"], targets: [legacyId], effect: "allow" }, + ]) }); + let notifyAllocating!: () => void; + let allowWriteStart!: () => void; + let notifyStored!: () => void; + let allowWriteReturn!: () => void; + const allocating = new Promise(resolve => { notifyAllocating = resolve; }); + const allowStore = new Promise(resolve => { allowWriteStart = resolve; }); + const stored = new Promise(resolve => { notifyStored = resolve; }); + const release = new Promise(resolve => { allowWriteReturn = resolve; }); + const manager = new AsyncTaskManager({ executor }); + const save = manager.store.save.bind(manager.store); + vi.spyOn(manager.store, "save").mockImplementation(async task => { + const scopedPending = task.moduleId === scopedId && task.status === TaskStatus.PENDING; + if (scopedPending) { + notifyAllocating(); + await allowStore; + } + await save(task); + if (scopedPending) { + notifyStored(); + await release; + if (fail) throw new Error("write acknowledged unsuccessfully"); + } + }); + const bridge = new AsyncTaskBridge(manager, { executor, scopedTasks: true }); + const observer = new AsyncTaskBridge(manager, { executor, scopedTasks: true }); + const aliased = new AsyncTaskBridge(new AsyncTaskManager({ executor, store: manager.store }), { + executor, scopedTasks: true, + }); + const owner = Context.create(await auth.authenticate({ authorization: `Bearer ${token()}` })); + const legacy = Context.create(); + const { task_id: legacyTask } = await bridge.submit(legacyId, {}, legacy); + const scoped = bridge.submit(scopedId, {}, owner); + let secondLegacy: ReturnType | undefined; + try { + await expect(aliased.submit(scopedId, {}, owner)).rejects.toThrow("unavailable to this authority"); + await Promise.race([allocating, scoped.then(() => { throw new Error("Task unexpectedly published"); })]); + secondLegacy = bridge.submit(legacyId, {}, legacy); + // Let the other submission collect any stale owners before the store write. + await new Promise(resolve => { setImmediate(resolve); }); + allowWriteStart(); + await Promise.race([stored, scoped.then(() => { throw new Error("Task unexpectedly published"); })]); + const list = (context: Context, via = observer) => via.handleMetaTool(META_TOOL_NAMES.LIST, {}, context); + expect(await list(legacy)).toEqual({ tasks: [expect.objectContaining({ task_id: legacyTask })] }); + expect(await list(owner)).toEqual({ tasks: [] }); + allowWriteReturn(); + if (fail) { + await expect(scoped).rejects.toThrow("write acknowledged unsuccessfully"); + expect(await list(owner)).toEqual({ tasks: [] }); + } else { + const task = await scoped; + expect(await list(owner)).toEqual({ tasks: [expect.objectContaining({ task_id: task.task_id })] }); + } + const second = await secondLegacy; + expect(await list(legacy)).toEqual({ tasks: [ + expect.objectContaining({ task_id: legacyTask }), expect.objectContaining({ task_id: second.task_id }), + ] }); + expect(await list(legacy, aliased)).toEqual(await list(legacy)); + } finally { + allowWriteStart(); + allowWriteReturn(); + await Promise.allSettled([scoped, secondLegacy]); + await manager.shutdown(); + } + }); +}); diff --git a/mcp/typescript/tests/server/asyncTaskBridge.test.ts b/mcp/typescript/tests/server/asyncTaskBridge.test.ts index d9fbdf0e..f1299f53 100644 --- a/mcp/typescript/tests/server/asyncTaskBridge.test.ts +++ b/mcp/typescript/tests/server/asyncTaskBridge.test.ts @@ -1,4 +1,5 @@ import { describe, it, expect, vi } from "vitest"; +import { elicit, MCP_ELICIT_KEY, MCP_PROGRESS_KEY, reportProgress } from "../../src/helpers.js"; import { AsyncTaskBridge, META_TOOL_NAMES, @@ -542,6 +543,27 @@ describe("D11-015: Progress sink installation in submit()", () => { expect(context.data["_mcp_progress"]).toBeUndefined(); }); + + it("tolerates transport failure only after session detachment", async () => { + const bridge = new AsyncTaskBridge(buildManager()); + let rejectSend!: (error: Error) => void; + const sending = new Promise((_resolve, reject) => { rejectSend = reject; }); + const progress = vi.fn().mockRejectedValueOnce(new Error("active transport failure")).mockReturnValueOnce(sending); + const question = vi.fn(); + const context = { data: { [MCP_PROGRESS_KEY]: progress, [MCP_ELICIT_KEY]: question } }; + + await bridge.submit("my.module", {}, context, { sessionKey: "session", progressToken: "token" }); + await expect(reportProgress(context, 1)).rejects.toThrow("active transport failure"); + const inFlight = reportProgress(context, 2); + bridge.detachSessionTasks("session"); + rejectSend(new Error("connection closed")); + + await expect(inFlight).resolves.toBeUndefined(); + await expect(reportProgress(context, 3)).resolves.toBeUndefined(); + await expect(elicit(context, "Continue?")).resolves.toBeNull(); + expect(progress).toHaveBeenCalledTimes(2); + expect(question).not.toHaveBeenCalled(); + }); }); // D11-016: _projectTaskInfo only returns the 6 allowed keys + conditional result/error diff --git a/toolkit/python/pyproject.toml b/toolkit/python/pyproject.toml index faf3634d..8af01102 100644 --- a/toolkit/python/pyproject.toml +++ b/toolkit/python/pyproject.toml @@ -23,7 +23,7 @@ keywords = [ "toolkit", ] dependencies = [ - "apcore>=0.33.0,<=1.0.0a4", + "apcore>=0.33.0,<=1.0.0a5", "pydantic>=2.0", "PyYAML>=6.0", ] diff --git a/toolkit/rust/Cargo.lock b/toolkit/rust/Cargo.lock index 85f493cb..c1cab919 100644 --- a/toolkit/rust/Cargo.lock +++ b/toolkit/rust/Cargo.lock @@ -48,9 +48,9 @@ checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" [[package]] name = "apcore" -version = "1.0.0-alpha.4" +version = "1.0.0-alpha.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7d5e08c5bbc5cddf5c72b121cbec90c1c551993dbee7c7cc88e30950941b63ad" +checksum = "1d19939071ba2c589815c061dfb1ff827862e5f1f52251e88297d49eec500a90" dependencies = [ "async-stream", "async-trait", diff --git a/toolkit/rust/Cargo.toml b/toolkit/rust/Cargo.toml index 0a02e231..44712969 100644 --- a/toolkit/rust/Cargo.toml +++ b/toolkit/rust/Cargo.toml @@ -21,7 +21,7 @@ all-features = true rustdoc-args = ["--cfg", "docsrs"] [dependencies] -apcore = { version = ">=0.33.0, <=1.0.0-alpha.4", default-features = false } +apcore = { version = ">=0.33.0, <=1.0.0-alpha.5", default-features = false } serde = { version = "1", features = ["derive"] } # `preserve_order` is required for the toolkit's byte-equivalent tabular # formatters (csv / jsonl): object key order MUST match insertion order to diff --git a/toolkit/typescript/package.json b/toolkit/typescript/package.json index 127e8927..d0fcb719 100644 --- a/toolkit/typescript/package.json +++ b/toolkit/typescript/package.json @@ -57,7 +57,7 @@ }, "dependencies": { "ajv": "^8.17.0", - "apcore-js": ">=0.33.0 <1.0.0 || 1.0.0-alpha.2 || 1.0.0-alpha.3 || 1.0.0-alpha.4", + "apcore-js": ">=0.33.0 <1.0.0 || 1.0.0-alpha.2 || 1.0.0-alpha.3 || 1.0.0-alpha.4 || 1.0.0-alpha.5", "js-yaml": "^4.3.2" }, "peerDependencies": { diff --git a/toolkit/typescript/pnpm-lock.yaml b/toolkit/typescript/pnpm-lock.yaml index 02e91f82..c7c00122 100644 --- a/toolkit/typescript/pnpm-lock.yaml +++ b/toolkit/typescript/pnpm-lock.yaml @@ -15,7 +15,7 @@ importers: specifier: ^8.17.0 version: 8.20.0 apcore-js: - specifier: '>=0.33.0 <1.0.0 || 1.0.0-alpha.2 || 1.0.0-alpha.3 || 1.0.0-alpha.4' + specifier: '>=0.33.0 <1.0.0 || 1.0.0-alpha.2 || 1.0.0-alpha.3 || 1.0.0-alpha.4 || 1.0.0-alpha.5' version: 0.33.0 js-yaml: specifier: ^4.3.2 diff --git a/toolkit/typescript/src/auth/delegated-jwt.ts b/toolkit/typescript/src/auth/delegated-jwt.ts new file mode 100644 index 00000000..1e0d0a8a --- /dev/null +++ b/toolkit/typescript/src/auth/delegated-jwt.ts @@ -0,0 +1,105 @@ +/** Configuration for interpreting actor and scope claims of a verified JWT. */ +export interface DelegatedClaims { + readonly scpClaim?: string; + readonly actorRolesClaim?: string; +} + +interface TokenPrincipal { + readonly id: string; + readonly type: string; + readonly roles: readonly string[]; +} + +export interface DelegatedJwtAuthority { + readonly issuer: string; + readonly subjectId: string; + readonly scopes: readonly string[]; + readonly actor: TokenPrincipal | null; +} + +function nonemptyString(value: unknown): value is string { + return typeof value === 'string' && value.length > 0; +} + +function isRecord(value: unknown): value is Record { + return typeof value === 'object' && value !== null && !Array.isArray(value); +} + +export function validateDelegatedClaims( + mapping: DelegatedClaims, issuer?: string, audience?: string, +): DelegatedClaims { + if (!nonemptyString(issuer) || !nonemptyString(audience)) { + throw new TypeError('Delegated JWT claims require an expected issuer and audience'); + } + for (const name of [mapping.scpClaim, mapping.actorRolesClaim]) { + if (name !== undefined && !nonemptyString(name)) { + throw new TypeError('JWT claim names must be nonempty strings'); + } + } + return Object.freeze({ ...mapping }); +} + +function scopeTokens(value: unknown, arraysAllowed = false): string[] { + const tokens: unknown[] | undefined = typeof value === 'string' + ? value.split(' ') + : arraysAllowed && Array.isArray(value) ? value : undefined; + // RFC 6749 section 3.3 scope-token. A provider array can represent no scopes. + if (!tokens || !tokens.every(token => nonemptyString(token) && !/[^\x21\x23-\x5b\x5d-\x7e]/.test(token))) { + throw new TypeError('Invalid JWT scope representation'); + } + return [...new Set(tokens as string[])].sort(); +} + +function outerActor(value: unknown, mapping: DelegatedClaims): TokenPrincipal { + if (!isRecord(value)) throw new TypeError('Invalid JWT actor'); + let node: unknown = value; + for (let depth = 1; ; depth++) { + if (depth > 8 || !isRecord(node) || !nonemptyString(node.sub) || + (Object.hasOwn(node, 'iss') && !nonemptyString(node.iss))) { + throw new TypeError('Invalid JWT actor history'); + } + if (!Object.hasOwn(node, 'act')) break; + node = node.act; + } + const id = value.sub; + const type = Object.hasOwn(value, 'type') ? value.type : 'agent'; + const roleClaim = mapping.actorRolesClaim; + const roles = roleClaim !== undefined && Object.hasOwn(value, roleClaim) ? value[roleClaim] : []; + if (!nonemptyString(id) || !nonemptyString(type) || !Array.isArray(roles) || !roles.every(nonemptyString)) { + throw new TypeError('Invalid current JWT actor'); + } + return { id, type, roles: [...roles] }; +} + +/** Read authority from a payload after the adapter has verified signature, issuer, audience and validity window. */ +export function readDelegatedJwtAuthority( + claims: Record, mapping: DelegatedClaims, now: number, +): DelegatedJwtAuthority { + const { iss, sub, aud, exp, iat } = claims; + if (!nonemptyString(iss) || !nonemptyString(sub) || + !(nonemptyString(aud) || (Array.isArray(aud) && aud.length > 0 && aud.every(nonemptyString))) || + typeof exp !== 'number' || !Number.isFinite(exp)) { + throw new TypeError('JWT delegated authority requires issuer, subject, audience and expiry'); + } + for (const name of ['nbf', 'iat']) { + const time = claims[name]; + if (Object.hasOwn(claims, name) && (typeof time !== 'number' || !Number.isFinite(time))) { + throw new TypeError('Invalid JWT time claim'); + } + } + if (typeof iat === 'number' && iat > now + 30) throw new TypeError('JWT issued in the future'); + + const standard = Object.hasOwn(claims, 'scope') ? scopeTokens(claims.scope) : undefined; + const alternate = mapping.scpClaim !== undefined && Object.hasOwn(claims, mapping.scpClaim) + ? scopeTokens(claims[mapping.scpClaim], true) : undefined; + if (standard && alternate && (standard.length !== alternate.length || + standard.some((scope, index) => scope !== alternate[index]))) { + throw new TypeError('JWT scope claims disagree'); + } + const scopes = standard ?? alternate; + if (scopes === undefined) throw new TypeError('JWT must carry a configured scope claim'); + return { + issuer: iss, subjectId: sub, scopes, + actor: Object.hasOwn(claims, 'act') ? outerActor(claims.act, mapping) : null, + }; +} diff --git a/toolkit/typescript/src/index.ts b/toolkit/typescript/src/index.ts index 91e55302..4212aa90 100644 --- a/toolkit/typescript/src/index.ts +++ b/toolkit/typescript/src/index.ts @@ -262,3 +262,5 @@ export function inferAnnotationsFromMethod(method: string): ModuleAnnotations { export { createPrometheusServer } from './prometheus-server.js'; export type { PrometheusServerOptions } from './prometheus-server.js'; +export { readDelegatedJwtAuthority, validateDelegatedClaims } from './auth/delegated-jwt.js'; +export type { DelegatedClaims, DelegatedJwtAuthority } from './auth/delegated-jwt.js';