Skip to content

API: authweave-core

Framework-neutral principal, evidence, decision, and coordinator contracts.

Framework-neutral principal authentication contracts.

__all__ = ('AsyncRedisGetSet', 'AsyncRedisSet', 'AsyncRedisSetDelete', 'Authenticated', 'AuthenticationContext', 'AuthenticationCoordinator', 'AuthenticationDecision', 'AuthenticationEvidence', 'AuthenticationRuntime', 'AuthorizationValue', 'CredentialMatch', 'EvidenceValue', 'FailureCode', 'InMemoryReplayStore', 'Invalid', 'InvariantFailure', 'NotApplicable', 'PrincipalRef', 'ReplayOutcome', 'ReplayStore', 'RequestAuthenticationProvider', 'RequestView', 'RouteProviderPolicy', 'SecurityObservation', 'SecurityObservationContext', 'SecurityObserver', 'SecurityOperation', 'SecurityOutcome', 'SpiffePeerEvidence', 'TlsPeerEvidence', 'TraceCorrelation', 'Unavailable', '__version__', 'ambient_trace_correlation', 'current_trace_correlation', 'freeze_authorization_details', 'observe_security', 'validate_replay_key') module-attribute

__version__ = '8.0.2' module-attribute

AuthenticationDecision = NotApplicable | Authenticated | Invalid | Unavailable | InvariantFailure

AuthorizationValue = str | int | bool | tuple[AuthorizationValue, ...] | Mapping[str, AuthorizationValue] | None

EvidenceValue = str | int | bool

AsyncRedisGetSet

Bases: Protocol

The read and bounded write a cache adapter issues.

get(name)

Read one key.

set(name, value, /, *, ex)

Write one key with an expiry.

AsyncRedisSet

Bases: Protocol

The put-if-absent command a replay adapter issues.

Each protocol is declared structurally, and narrowed to exactly the commands and value types its adapter uses, so a caller supplies a client (or a double) without this package importing the optional redis dependency.

set(name, value, /, *, nx, ex)

Write one key with an expiry and put-if-absent semantics.

AsyncRedisSetDelete

Bases: Protocol

The put-if-absent and removal a single-use nonce adapter issues.

delete(name)

Delete one key.

set(name, value, /, *, nx, ex)

Write one key with an expiry and put-if-absent semantics.

Authenticated dataclass

Credential was fully verified.

AuthenticationContext dataclass

Authenticated subject, actor, delegation chain, and verified evidence.

__post_init__()

Freeze the delegation chain.

AuthenticationCoordinator

Route providers deterministically and stop on every owned failure.

__init__(providers)

Freeze and validate the provider inventory.

Raises:

Type Description
ValueError

If provider names or profiles are invalid or duplicated.

authenticate(request, runtime, policy) async

Authenticate through exactly one credential owner.

Returns:

Type Description
AuthenticationDecision

A terminal typed authentication decision.

AuthenticationEvidence dataclass

Verified, secret-free facts produced by an authentication provider.

__post_init__()

Validate bounded evidence and freeze extension and authorization data.

AuthenticationRuntime dataclass

Request-scoped execution limits and optional operational telemetry.

CredentialMatch

Bases: StrEnum

Credential ownership result returned by a provider matcher.

FailureCode

Bases: StrEnum

Stable neutral authentication failure codes.

InMemoryReplayStore

Bounded single-process reference replay store for tests and single-worker use.

This store is atomic only within one event loop and does not survive process restarts, so it is not a durable multi-worker replay defense. Production deployments must supply a shared durable store (for example Redis) that satisfies :class:ReplayStore.

__init__(*, capacity, time_source)

Bound the store capacity and inject a monotonic clock.

Raises:

Type Description
ValueError

If the capacity is not positive.

check_and_store(key, *, ttl_seconds) async

Atomically record key with a bounded TTL if not already present.

Returns:

Type Description
ReplayOutcome

The typed put-if-absent outcome.

Raises:

Type Description
ValueError

If the key is invalid or the TTL is not positive.

Invalid dataclass

Credential was owned but failed verification.

InvariantFailure dataclass

Provider or coordinator contract was violated.

NotApplicable dataclass

No allowed provider owns a credential presentation.

PrincipalRef dataclass

Stable principal identity with a verified classification.

__eq__(other)

Compare stable identity independently from classification.

Returns:

Type Description
bool

Whether issuer and subject match.

__hash__()

Hash the stable identity independently from classification.

Returns:

Type Description
int

Hash of issuer and subject.

__post_init__()

Validate bounded identity components.

ReplayOutcome

Bases: StrEnum

Result of an atomic put-if-absent against a replay/nonce store.

ReplayStore

Bases: Protocol

Atomic put-if-absent contract shared by protocol replay adapters.

Implementations must be atomic: a concurrent first presentation of the same key returns :attr:ReplayOutcome.STORED for exactly one caller and :attr:ReplayOutcome.REPLAY for the others. Store outage maps to :attr:ReplayOutcome.UNAVAILABLE and capacity exhaustion to :attr:ReplayOutcome.CAPACITY_EXCEEDED; adapters translate both into a fail-closed Unavailable decision on protected routes.

check_and_store(key, *, ttl_seconds) async

Record key if absent and report whether it was already present.

Returns:

Type Description
ReplayOutcome

The typed put-if-absent outcome.

RequestAuthenticationProvider

Bases: Protocol

Framework-neutral request authentication provider.

authenticate(request, runtime) async

Verify an owned credential presentation.

match(request)

Classify credential ownership without performing expensive verification.

RequestView dataclass

Immutable, framework-neutral projection of authentication inputs.

__post_init__()

Validate request metadata without collapsing duplicate headers.

Raises:

Type Description
ValueError

If request metadata is malformed.

header_values(name)

Return every value for a case-insensitive header name.

RouteProviderPolicy dataclass

Ordered-free set of provider names permitted for a route.

__post_init__()

Validate and deduplicate provider names.

Raises:

Type Description
ValueError

If a provider name is invalid or duplicated.

SecurityObservation

Bases: Protocol

One in-flight observation returned by a security observer.

set_outcome(outcome, *, reason_code=None)

Attach the bounded terminal outcome.

SecurityObservationContext

Bases: Protocol

Synchronous context manager spanning async-compatible security work.

__enter__()

Start the observation.

__exit__(typ, value, traceback)

Finish without suppressing application exceptions.

SecurityObserver

Bases: Protocol

Minimal implementation seam for optional telemetry packages.

current_correlation()

Return current trace correlation when one exists.

observe(operation, *, profile=None, principal_kind=None, credential_kind=None, links=())

Create one logical security observation.

SecurityOperation

Bases: StrEnum

Bounded logical security operations shared by AuthWeave packages.

SecurityOutcome

Bases: StrEnum

Bounded terminal outcomes safe for spans and metric dimensions.

SpiffePeerEvidence dataclass

Verified SPIFFE peer identity projected by a trusted validation boundary.

Identity is the SPIFFE ID alone. Short-lived SVIDs are never registered by certificate thumbprint.

__post_init__()

Reject malformed SPIFFE peer projections.

Raises:

Type Description
ValueError

If the SPIFFE ID, trust domain, or validity window is invalid.

TlsPeerEvidence dataclass

Verified TLS peer facts produced by a trusted termination boundary.

__post_init__()

Reject malformed or internally inconsistent TLS evidence.

Raises:

Type Description
ValueError

If a field is malformed or the validity interval is empty.

TraceCorrelation dataclass

Secret-free W3C-compatible trace/span identifiers.

__post_init__()

Reject malformed and invalid all-zero identifiers.

Raises:

Type Description
ValueError

If either identifier is not a valid lowercase W3C identifier.

Unavailable dataclass

Credential verification could not complete safely.

ambient_trace_correlation()

Return correlation installed by the innermost active security observation.

Returns:

Type Description
TraceCorrelation | None

Current correlation, or None when telemetry is disabled.

current_trace_correlation(observer)

Read correlation without letting telemetry affect security work.

Returns:

Type Description
TraceCorrelation | None

Current valid correlation, or None when unavailable.

freeze_authorization_details(details)

Freeze validated RFC 9396 authorization details into a bounded immutable form.

This helper enforces only neutral structural bounds and immutability. A provider may use it to bound untrusted JSON, but must apply its type-specific schema before constructing authentication evidence.

Returns:

Type Description
tuple[Mapping[str, AuthorizationValue], ...]

The frozen, immutable authorization-details tuple.

Raises:

Type Description
TypeError

If details are not an array or contain unsupported values.

ValueError

If the details exceed structural bounds.

observe_security(observer, operation, *, profile=None, principal_kind=None, credential_kind=None, links=())

Observe work while preserving body results, errors, and cancellation.

Yields:

Type Description
SecurityObservation

A failure-isolating observation handle, or a no-op handle.

validate_replay_key(key)

Reject empty or oversized replay keys before hitting the store.

Raises:

Type Description
ValueError

If the key is empty or exceeds the bounded length.