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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions .github/workflows/core-candidate.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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))
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion .github/workflows/python.yml
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ permissions:
contents: read

env:
CORE_REF: 625aa3ecbd1d0343fe62ab18c0a9943c17495199
CORE_REF: e4e2329de4ce8fa45669572ef9bd81c48da0d746

jobs:
test:
Expand Down
6 changes: 3 additions & 3 deletions .github/workflows/rust.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
2 changes: 1 addition & 1 deletion .github/workflows/typescript.yml
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ permissions:
contents: read

env:
CORE_REF: 625aa3ecbd1d0343fe62ab18c0a9943c17495199
CORE_REF: e4e2329de4ce8fa45669572ef9bd81c48da0d746

jobs:
test:
Expand Down
14 changes: 14 additions & 0 deletions a2a/docs/features/auth.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`
Expand Down
2 changes: 1 addition & 1 deletion a2a/python/pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
10 changes: 9 additions & 1 deletion a2a/python/src/apcore_a2a/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -26,6 +33,7 @@
"Authenticator",
"JWTAuthenticator",
"ClaimMapping",
"DelegatedClaims",
"AuthMiddleware",
"auth_identity_var",
# Adapters
Expand Down
14 changes: 14 additions & 0 deletions a2a/python/src/apcore_a2a/adapters/card_visibility.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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}
Expand Down
3 changes: 2 additions & 1 deletion a2a/python/src/apcore_a2a/auth/__init__.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
"""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

__all__ = [
"Authenticator",
"JWTAuthenticator",
"ClaimMapping",
"DelegatedClaims",
"AuthMiddleware",
"auth_identity_var",
]
101 changes: 101 additions & 0 deletions a2a/python/src/apcore_a2a/auth/_delegation.py
Original file line number Diff line number Diff line change
@@ -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)
44 changes: 37 additions & 7 deletions a2a/python/src/apcore_a2a/auth/jwt.py
Original file line number Diff line number Diff line change
Expand Up @@ -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__)

Expand Down Expand Up @@ -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__(
Expand All @@ -69,17 +73,30 @@ 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
self._issuer = issuer
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

Expand All @@ -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.
Expand All @@ -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,
Expand All @@ -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:
Expand All @@ -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

Expand Down
5 changes: 4 additions & 1 deletion a2a/python/src/apcore_a2a/auth/middleware.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
Loading
Loading