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
4 changes: 4 additions & 0 deletions packages/oauth/src/keycardai/oauth/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
"""

from .client import AsyncClient, Client
from .client_auth import ClientAuthentication, ClientAuthenticator
from .exceptions import (
PERMANENT_ERROR_CODES,
AuthenticationError,
Expand Down Expand Up @@ -119,6 +120,9 @@
"TokenTypeHint",
"PKCECodeChallengeMethod",
"WellKnownEndpoint",
# === Client Authentication ===
"ClientAuthentication",
"ClientAuthenticator",
# === HTTP Auth Strategies ===
"AuthStrategy",
"BasicAuth",
Expand Down
72 changes: 72 additions & 0 deletions packages/oauth/src/keycardai/oauth/client_auth.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
"""Client authentication, an optional capability of a credential.

A credential that implements ClientAuthenticator returns the headers and
form fields that authenticate the client on one request. The capability is
separate from ApplicationCredential, so a credential implemented outside the
SDK does not need it.
"""

from dataclasses import dataclass, field
from typing import Protocol, runtime_checkable

from .exceptions import ConfigError


@dataclass(frozen=True)
class ClientAuthentication:
"""Headers and form fields that authenticate the client on one request.

Holds only client authentication. It never includes a grant parameter
such as ``grant_type`` or ``subject_token_type``.

Both fields hold secrets, such as a Basic header or a client assertion,
so ``repr()`` leaves them out.
"""

headers: dict[str, str] = field(default_factory=dict, repr=False)
form_fields: dict[str, str] = field(default_factory=dict, repr=False)


@runtime_checkable
class ClientAuthenticator(Protocol):
"""A credential that can authenticate the client on any endpoint.

A credential may also define ``check_client_authentication()``, which
raises ConfigError when the credential cannot authenticate the client.
require_client_authenticator calls it.
"""

async def client_authentication(
self, *, issuer: str, endpoint: str
) -> ClientAuthentication:
"""Return the client authentication for one request.

Call it once per request. An assertion-based credential signs or
fetches a new assertion on every call.

Args:
issuer: The zone's issuer. A multi-zone credential selects its
zone by it and fails for an unknown zone.
endpoint: The URL the request goes to. An assertion-based
credential signs it as the assertion's ``aud``.
"""
...


def require_client_authenticator(credential: object) -> ClientAuthenticator:
"""Return ``credential`` as a ClientAuthenticator.

Call it before sending any request.

Raises:
ConfigError: The credential does not provide client authentication,
or its ``check_client_authentication()`` raised.
"""
if not isinstance(credential, ClientAuthenticator):
raise ConfigError(
f"{type(credential).__name__} does not provide client authentication"
)
check = getattr(credential, "check_client_authentication", None)
if callable(check):
check()
return credential
119 changes: 110 additions & 9 deletions packages/oauth/src/keycardai/oauth/server/credentials.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,9 +29,11 @@
AuthStrategy,
BasicAuth,
ClientConfig,
ConfigError,
MultiZoneBasicAuth,
NoneAuth,
)
from keycardai.oauth.client_auth import ClientAuthentication
from keycardai.oauth.types.models import JsonWebKeySet, TokenExchangeRequest
from keycardai.oauth.types.oauth import GrantType, TokenEndpointAuthMethod

Expand All @@ -40,6 +42,7 @@
CredentialDiscoveryError,
EKSWorkloadIdentityConfigurationError,
EKSWorkloadIdentityRuntimeError,
WebIdentityConfigurationError,
WorkloadIdentityConfigurationError,
WorkloadIdentityRuntimeError,
)
Expand All @@ -64,6 +67,10 @@ class ApplicationCredential(Protocol):
Application credential providers are responsible for preparing token exchange
requests with the appropriate authentication parameters based on the workload's
credential type (none, private key JWT, cloud workload identity, etc.).

Client authentication is a separate, optional capability:
keycardai.oauth.client_auth.ClientAuthenticator. ClientSecret,
WebIdentity, and WorkloadIdentity implement it.
"""

def get_http_client_auth(self) -> AuthStrategy:
Expand Down Expand Up @@ -152,6 +159,23 @@ async def prepare_token_exchange_request(
subject_token_type="urn:ietf:params:oauth:token-type:access_token",
)

async def client_authentication(
self, *, issuer: str, endpoint: str
) -> ClientAuthentication:
"""Return the Basic header for ``issuer``. No form fields.

A multi-zone credential selects the zone by ``issuer``.

Raises:
ConfigError: A multi-zone credential has no credentials for
``issuer``.
"""
try:
headers = self.get_http_client_auth().apply_headers(issuer)
except KeyError as e:
raise ConfigError(f"ClientSecret has no credentials for {issuer}") from e
return ClientAuthentication(headers=dict(headers))


class WebIdentity:
"""Private key JWT client assertion provider.
Expand All @@ -163,8 +187,15 @@ class WebIdentity:
Example:
provider = WebIdentity(
server_name="My Server",
storage_dir="./server_keys"
storage_dir="./server_keys",
client_id="registered-client-id",
)

Args:
client_id: The registered OAuth client ID, signed as the assertion's
``iss`` and ``sub``. Required for client authentication. Token
exchange uses the auth context's ``resource_client_id`` when
present, and this value otherwise.
"""

_DEFAULT_STORAGE_DIR = "./server_keys"
Expand All @@ -179,8 +210,10 @@ def __init__(
audience_config: str | dict[str, str] | None = None,
# Backward-compatible alias
mcp_server_name: str | None = None,
client_id: str | None = None,
):
server_name = server_name or mcp_server_name
self.client_id = client_id

if storage is not None:
self._storage = storage
Expand Down Expand Up @@ -237,7 +270,7 @@ def set_client_config(
raise ValueError(
"auth_info with 'resource_server_url' is required for WebIdentity"
)
config.client_id = auth_info["resource_client_id"]
config.client_id = self._signing_client_id(auth_info)
config.auto_register_client = False
config.client_jwks_url = self.identity_manager.get_client_jwks_url(
resource_server_url
Expand Down Expand Up @@ -266,15 +299,10 @@ async def prepare_token_exchange_request(
resource: str,
auth_info: Mapping[str, str | None] | None = None,
) -> TokenExchangeRequest:
resource_client_id = auth_info.get("resource_client_id") if auth_info else None
if resource_client_id is None:
raise ValueError(
"auth_info with 'resource_client_id' is required for WebIdentity"
)

client_id = self._signing_client_id(auth_info)
audience = await _get_token_exchange_audience(client)
client_assertion = self.identity_manager.create_client_assertion(
issuer=resource_client_id,
issuer=client_id,
audience=audience,
)

Expand All @@ -286,6 +314,63 @@ async def prepare_token_exchange_request(
client_assertion=client_assertion,
)

def _signing_client_id(self, auth_info: Mapping[str, str | None] | None) -> str:
"""Return the auth context's ``resource_client_id``, else the option.

Raises:
WebIdentityConfigurationError: Neither is set.
"""
client_id = (auth_info.get("resource_client_id") if auth_info else None) or (
self.client_id
)
if not client_id:
raise WebIdentityConfigurationError(
"WebIdentity needs auth_info with 'resource_client_id' or the "
"client_id option"
)
return client_id

def check_client_authentication(self) -> None:
"""Raise unless client authentication can sign an assertion.

Raises:
WebIdentityConfigurationError: The ``client_id`` option is not
set.
"""
if not self.client_id:
raise WebIdentityConfigurationError(
"WebIdentity client authentication requires client_id"
)

async def client_authentication(
self, *, issuer: str, endpoint: str
) -> ClientAuthentication:
"""Return a newly signed client assertion for ``endpoint``.

The assertion's ``iss`` and ``sub`` are the ``client_id`` option and
its ``aud`` is ``endpoint``. ``audience_config`` does not apply. A
Keycard zone rejects any other ``aud`` with ``invalid_client``.

Raises:
WebIdentityConfigurationError: The ``client_id`` option is not
set, or ``endpoint`` is empty. No assertion is signed.
"""
self.check_client_authentication()
assert self.client_id is not None
if not endpoint:
raise WebIdentityConfigurationError(
"WebIdentity client authentication requires an endpoint"
)
assertion = self.identity_manager.create_client_assertion(
issuer=self.client_id, audience=endpoint
)
return ClientAuthentication(
form_fields={
"client_assertion": assertion,
"client_assertion_type": GrantType.JWT_BEARER_CLIENT_ASSERTION.value,
}
)


# Source identifiers carried on WorkloadIdentityConfigurationError and
# WorkloadIdentityRuntimeError, for branching on which token source failed.
Expand Down Expand Up @@ -597,6 +682,22 @@ async def prepare_token_exchange_request(
client_id=self.client_id,
)

async def client_authentication(
self, *, issuer: str, endpoint: str
) -> ClientAuthentication:
"""Return the source's current token as the client assertion.

The form fields are ``client_assertion``, ``client_assertion_type``,
and ``client_id`` when configured. No headers.
"""
form_fields = {
"client_assertion": await self._fetch_identity_token(),
"client_assertion_type": GrantType.JWT_BEARER_CLIENT_ASSERTION.value,
}
if self.client_id:
form_fields["client_id"] = self.client_id
return ClientAuthentication(form_fields=form_fields)


class EKSWorkloadIdentity(WorkloadIdentity):
"""EKS workload identity provider using mounted tokens.
Expand Down
12 changes: 11 additions & 1 deletion packages/oauth/src/keycardai/oauth/server/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@

from typing import Any

from keycardai.oauth.exceptions import classify_discovery_failure
from keycardai.oauth.exceptions import ConfigError, classify_discovery_failure


class OAuthServerError(Exception):
Expand Down Expand Up @@ -674,6 +674,16 @@ def __init__(
super().__init__(message, details=details)


class WebIdentityConfigurationError(ConfigError, ValueError):

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Every other error in this file derives from OAuthServerError, so except OAuthServerError misses this one. Worth adding it as a base too?

"""WebIdentity has no client ID to sign as the assertion's ``iss``.

Raised when neither the auth context's ``resource_client_id`` nor the
``client_id`` option is set, or when client authentication has no
endpoint to sign as ``aud``. It is also a ValueError, so
``except ValueError`` catches it.
"""


class CredentialDiscoveryError(OAuthServerError):
"""Raised when discover_credential cannot pick one credential from the environment.

Expand Down
Loading
Loading