oauth-resource-server 0.3.0

OAuth 2.0 bearer-token resource server for Rust HTTP services: JWT access-token validation against a JWKS, RFC 9728 protected-resource metadata, RFC 6750 challenges, optional static API key, axum integration.
Documentation
// The crate documentation IS the README, so its Rust snippets run as doctests
// and the two cannot drift. Those snippets use the `serde`, `env` and `axum`
// features, so the README is included only when all three are on (as with
// `--all-features`, which CI and docs.rs use); any narrower build gets the
// short pointer below instead, rather than doctests that cannot compile.
#![cfg_attr(
    all(feature = "serde", feature = "env", feature = "axum"),
    doc = include_str!("../README.md")
)]
// Linked for rustdoc readers; the README itself has no intra-doc links, since
// GitHub and crates.io would render them as literal brackets.
#![cfg_attr(
    all(feature = "serde", feature = "env", feature = "axum"),
    doc = "
## API map

| Item | Role |
|---|---|
| [`OAuthConfig`], [`OAuthConfig::resolve`] | The unvalidated settings, and their all-or-nothing validation into a [`ResolvedOAuthConfig`] or a [`ConfigError`]. [`KeyNaming`] decides how problems name settings. |
| [`OAuthValidator`] | Validates one token ([`OAuthValidator::validate`]), renders the challenges and the metadata document, and keeps the signing keys fresh ([`OAuthValidator::spawn_background_refresh`]). |
| [`OAuthValidator::builder`], [`OAuthValidatorBuilder`] | How the validator fetches its keys: extra TLS root certificates, a proxy, the fetch timeout, a key set to start from. |
| [`OAuthValidator::key_set_status`], [`KeySetStatus`], [`RefreshError`] | A passive, no-I/O view of the signing keys held, for readiness probes and status pages ([`OAuthValidator::is_ready`]). |
| [`AuthorizedToken`], [`TokenRejection`] | The two outcomes of a validation. |
| [`authenticate`], [`Credential`] | Framework-free checking of several candidate credentials against a static token and OAuth. |
| [`authenticate_with_static_tokens`], [`StaticTokens`], [`StaticTokenMatch`], [`StaticTokensError`] | The same check against several labeled static tokens (zero-downtime key rotation, one key per client), reporting which one matched. |
| [`refusal`], [`refusal_with_static_challenge`], [`Refusal`], [`DEFAULT_STATIC_CHALLENGE`] | Framework-free mapping of a [`TokenRejection`] to its status (401/403) and `WWW-Authenticate` challenge — the same decision both layers make. |
| [`AuthorizedToken::require_scopes`], [`MissingScopes`], [`refusal_for_scopes`], [`OAuthValidator::insufficient_scope_challenge_for`] | Per-route and per-operation scopes on top of the validator's: the all-of check, and the 403 whose challenge names the scopes that request needs. |
| [`Algorithm`], [`parse_algorithm`], [`AlgorithmError`] | The JWS algorithms a config may allow (never HMAC or `none`). |
| [`static_token_policy`], [`StaticTokenDecision`] | The startup decision about a static API key alongside OAuth. |
| [`axum::AuthLayer`], [`axum::require_auth`], [`axum::metadata_router`] | The axum integration (feature `axum`), including extractors for [`Credential`], [`AuthorizedToken`] and [`StaticTokenMatch`], and the per-handler scope extractor [`axum::Scoped`]. |
| [`http_layer::HttpAuthLayer`], [`http_layer::HttpAuthLayerBuilder`], [`http_layer::RequireScopes`] | A `tower` layer for any `http::Request<B>` service, whatever its body types (feature `tower`, implied by `axum`), and the per-route scope layer both layers share. |
| [`env::oauth_config_from_env`], [`env::secret_from_env`], [`env::static_tokens_from_env`] | Configuration from environment variables (feature `env`), including a current and a next static key for rotation. |"
)]
#![cfg_attr(
    all(feature = "serde", feature = "env", feature = "axum", feature = "mcp"),
    doc = "| [`mcp::McpToolScopes`] | Per-tool scopes for an MCP server's JSON-RPC endpoint (feature `mcp`). |"
)]
#![cfg_attr(
    all(
        feature = "serde",
        feature = "env",
        feature = "axum",
        not(feature = "mcp")
    ),
    doc = "| `mcp::McpToolScopes` | Per-tool scopes for an MCP server's JSON-RPC endpoint (feature `mcp`, not enabled in this build). |"
)]
#![cfg_attr(
    all(
        feature = "serde",
        feature = "env",
        feature = "axum",
        feature = "metrics"
    ),
    doc = "| [`observability`] | The metric names the `metrics` feature reports through the `metrics` facade, and their descriptions (feature `metrics`). |"
)]
#![cfg_attr(
    all(
        feature = "serde",
        feature = "env",
        feature = "axum",
        not(feature = "metrics")
    ),
    doc = "| `observability` | The metric names the `metrics` feature reports through the `metrics` facade (feature `metrics`, not enabled in this build). |"
)]
// The last row links the `testing` module, which exists only with that feature;
// without it the row is rendered with no link, so a `serde,env,axum` doc build
// has no unresolved intra-doc link.
#![cfg_attr(
    all(
        feature = "serde",
        feature = "env",
        feature = "axum",
        feature = "testing"
    ),
    doc = "| [`testing`] | Fixtures for your tests (feature `testing`). |"
)]
#![cfg_attr(
    all(
        feature = "serde",
        feature = "env",
        feature = "axum",
        not(feature = "testing")
    ),
    doc = "| `testing` | Fixtures for your tests (feature `testing`, not enabled in this build). |"
)]
#![cfg_attr(
    not(all(feature = "serde", feature = "env", feature = "axum")),
    doc = "OAuth 2.0 bearer-token resource server for Rust HTTP services: JWT \
           access-token validation against a JWKS (RFC 9068), RFC 9728 \
           protected-resource metadata, RFC 6750 `WWW-Authenticate` challenges, an \
           optional static API key alongside OAuth, and axum integration.\n\n\
           The full guide is this crate's README, which becomes the crate \
           documentation when it is built with the `serde`, `env` and `axum` \
           features (as on docs.rs): <https://docs.rs/oauth-resource-server>."
)]
#![cfg_attr(docsrs, feature(doc_cfg))]
#![warn(missing_docs)]
#![forbid(unsafe_code)]

// Without a TLS backend reqwest cannot fetch an https JWKS, and every real
// authorization server serves its keys over https — the validator would build,
// then fail closed on every token. Refuse at compile time instead. No cfg(test)
// or docs exemption: `cargo test` and `cargo doc` build with the default
// feature set, which includes `rustls-tls`.
#[cfg(not(any(
    feature = "rustls-tls",
    feature = "rustls-tls-native-roots",
    feature = "native-tls"
)))]
compile_error!(
    "oauth-resource-server needs a TLS backend for JWKS fetches: enable the `rustls-tls` \
     (default), `rustls-tls-native-roots` or `native-tls` feature"
);

mod algorithms;
mod builder;
mod challenge;
pub mod config;
mod jwks;
mod token;
mod validator;

mod authenticate;
mod observe;
mod policy;
mod refusal;

#[cfg(feature = "env")]
#[cfg_attr(docsrs, doc(cfg(feature = "env")))]
pub mod env;

#[cfg(feature = "tower")]
#[cfg_attr(docsrs, doc(cfg(feature = "tower")))]
pub mod http_layer;

#[cfg(feature = "axum")]
#[cfg_attr(docsrs, doc(cfg(feature = "axum")))]
pub mod axum;

#[cfg(feature = "mcp")]
#[cfg_attr(docsrs, doc(cfg(feature = "mcp")))]
pub mod mcp;

#[cfg(feature = "metrics")]
#[cfg_attr(docsrs, doc(cfg(feature = "metrics")))]
pub mod observability;

// Entry points for the `fuzz/` cargo-fuzz crate into internals that are not
// public API. cargo-fuzz sets `--cfg fuzzing`; no ordinary build (including
// docs.rs and every CI job but `fuzz.yml`) compiles this module. cargo-fuzz
// sets the cfg for every crate in the build, so a project that fuzzes ITSELF
// while depending on this crate compiles this one with `fuzzing` on as well.
// That works either way: the module needs the `axum` and `testing` features
// (`bearer_credential`, `resolved_config`), and is simply left out unless a
// build enables both.
#[cfg(all(fuzzing, feature = "axum", feature = "testing"))]
#[doc(hidden)]
pub mod __fuzz;

#[cfg(any(test, feature = "testing"))]
#[cfg_attr(docsrs, doc(cfg(feature = "testing")))]
pub mod testing;

pub use algorithms::{Algorithm, AlgorithmError, DEFAULT_ALGORITHMS, parse_algorithm};
pub use authenticate::{
    Credential, StaticTokenMatch, StaticTokens, StaticTokensError, authenticate,
    authenticate_with_static_tokens,
};
pub use builder::OAuthValidatorBuilder;
pub use challenge::PROTECTED_RESOURCE_METADATA_PREFIX;
pub use config::{
    ConfigError, ConfigProblem, DEFAULT_LEEWAY_SECS, DEFAULT_PRINCIPAL_CLAIMS,
    DEFAULT_SCOPE_CLAIMS, KeyNaming, KeyNamingBuf, MAX_LEEWAY_SECS, MAX_TOKEN_AGE_SECS,
    OAuthConfig, ProblemKind, ResolvedOAuthConfig,
};
pub use jwks::{
    DEFAULT_FETCH_TIMEOUT, KeySetStatus, MAX_FETCH_TIMEOUT, MIN_FETCH_TIMEOUT, RefreshError,
    RefreshErrorKind,
};
pub use policy::{NoAuthConfigured, StaticTokenDecision, static_token_policy};
pub use refusal::{
    DEFAULT_STATIC_CHALLENGE, Refusal, refusal, refusal_for_scopes, refusal_with_static_challenge,
};
pub use token::{AuthorizedToken, InvalidToken, InvalidTokenKind, MissingScopes, TokenRejection};
pub use validator::{OAuthValidator, ValidatorError};