pub struct OAuth2ClientCredentials { /* private fields */ }Expand description
A TokenProvider implementing the OAuth 2.0 client credentials
grant (RFC 6749 §4.4) with caching and proactive refresh.
- Tokens are cached until shortly before expiry
(
with_refresh_leeway, default 30 s beforeexpires_inelapses, but never less than half the lifetime, so a short-lived token is still reused) and refreshed on demand. - Concurrent callers needing a refresh collapse into a single token request (single-flight), and all of them get that request’s outcome — its failure as well as its success, so a dead endpoint costs every waiting caller one timeout, not one each in turn.
- A failed refresh is remembered for
with_failure_backoff(default 1 s): callers in that window get the same error without a new request. - A caller that is cancelled mid-refresh does not strand the others: the attempt is marked abandoned and the next waiter starts a new one.
- The client secret is never logged, never echoed in errors, and redacted
from
Debugoutput.
Built on the crate’s own HTTP stack — no additional OAuth dependencies.
With the default tls-rustls feature the token endpoint may be https://
(the norm); without it, only http:// endpoints are reachable and an
https:// endpoint fails at construction with an actionable error.
Implementations§
Source§impl OAuth2ClientCredentials
impl OAuth2ClientCredentials
Sourcepub fn from_agent_card_trusting(
card: &AgentCard,
scheme_name: &str,
client_id: impl Into<String>,
client_secret: impl Into<String>,
trusted_token_hosts: &[&str],
) -> Result<OAuth2ClientCredentials, ClientError>
pub fn from_agent_card_trusting( card: &AgentCard, scheme_name: &str, client_id: impl Into<String>, client_secret: impl Into<String>, trusted_token_hosts: &[&str], ) -> Result<OAuth2ClientCredentials, ClientError>
from_agent_card, refusing a tokenUrl whose
host is not one of trusted_token_hosts.
from_agent_card sends the client secret wherever the card’s
tokenUrl points. That is only safe when the card itself is trusted;
use this constructor when it is not, and name the host your identity
provider runs on ("auth.example.com").
Hosts compare exactly: ASCII case is ignored, so is one trailing dot,
and the port and path are not part of a host. auth.example.com does
not admit auth.example.com.evil.example, evil-auth.example.com, or
https://[email protected]/ (whose host is
evil.example). An empty list refuses every card.
§Errors
Everything from_agent_card returns, and
ClientError::InvalidEndpoint when the tokenUrl’s host is not in
trusted_token_hosts; the message names the card’s origin and the
hosts that would have been accepted, never the secret.
Source§impl OAuth2ClientCredentials
impl OAuth2ClientCredentials
Sourcepub fn new(
token_url: impl Into<String>,
client_id: impl Into<String>,
client_secret: impl Into<String>,
) -> OAuth2ClientCredentials
pub fn new( token_url: impl Into<String>, client_id: impl Into<String>, client_secret: impl Into<String>, ) -> OAuth2ClientCredentials
Creates a provider for the given token endpoint and client credentials.
Sourcepub fn from_agent_card(
card: &AgentCard,
scheme_name: &str,
client_id: impl Into<String>,
client_secret: impl Into<String>,
) -> Result<OAuth2ClientCredentials, ClientError>
pub fn from_agent_card( card: &AgentCard, scheme_name: &str, client_id: impl Into<String>, client_secret: impl Into<String>, ) -> Result<OAuth2ClientCredentials, ClientError>
Reads the token endpoint from an agent card’s OAuth 2.0 client-credentials flow.
scheme_name is the key in the card’s securitySchemes map. Request
scopes with with_scopes — the card’s flow lists
the scopes the agent offers (with descriptions); which of them to
request is your decision.
§Security
The card is the peer’s own word, and the client secret is sent to
whatever https:// host its tokenUrl names. A card fetched over a
network you do not control, or from an agent you do not fully trust,
can name an endpoint of its choosing and receive client_id:client_secret
on the first token request (audit SEC-08). Use
from_agent_card_trusting and name
the host your identity provider runs on, or build the provider with
new from a URL you configured yourself. Plain
from_agent_card is for a card you verified, for example one read
through ClientBuilder::from_signed_card (feature signing).
§Errors
Returns ClientError::InvalidEndpoint when the scheme is missing,
is not an OAuth 2.0 scheme, has no client-credentials flow, or names a
tokenUrl that is plaintext http:// to a host other than loopback.
Sourcepub async fn from_oidc_issuer(
issuer: &str,
client_id: impl Into<String>,
client_secret: impl Into<String>,
) -> Result<OAuth2ClientCredentials, ClientError>
pub async fn from_oidc_issuer( issuer: &str, client_id: impl Into<String>, client_secret: impl Into<String>, ) -> Result<OAuth2ClientCredentials, ClientError>
Discovers the token endpoint from an OIDC issuer
(RFC 8414 / OIDC Discovery: {issuer}/.well-known/openid-configuration)
and creates a provider for it.
§Errors
Returns a ClientError when the discovery document cannot be
fetched or has no token_endpoint.
Sourcepub const fn allow_insecure_token_endpoint(self) -> OAuth2ClientCredentials
pub const fn allow_insecure_token_endpoint(self) -> OAuth2ClientCredentials
Allows a plaintext http:// token endpoint on a host other than
loopback. Off by default: the request carries the client secret, and
sent in the clear it can be read or replaced by anyone on the path.
For a network you trust end to end; the better answer is https://.
Sourcepub fn with_tls_config(self, tls: ClientConfig) -> OAuth2ClientCredentials
Available on crate feature tls-rustls only.
pub fn with_tls_config(self, tls: ClientConfig) -> OAuth2ClientCredentials
tls-rustls only.Connects to the token endpoint with tls: an identity provider behind
a private CA, or one that asks for a client certificate (mutual TLS, as
a service mesh or SPIFFE does).
Without this the roots are Mozilla’s plus those SSL_CERT_FILE and
SSL_CERT_DIR name, and no client certificate is presented. A
configuration given here is exact. Build one with
tls::tls_config_from_pem. Until
this setter existed the provider took no TLS configuration at all, and
every other outbound path of this crate did (audit B-03).
Sourcepub fn with_scopes<I, S>(self, scopes: I) -> OAuth2ClientCredentials
pub fn with_scopes<I, S>(self, scopes: I) -> OAuth2ClientCredentials
Sets the scopes to request (joined with spaces per RFC 6749 §3.3).
Sourcepub fn with_audience(
self,
audience: impl Into<String>,
) -> OAuth2ClientCredentials
pub fn with_audience( self, audience: impl Into<String>, ) -> OAuth2ClientCredentials
Sets the audience parameter (used by some authorization servers,
e.g. Auth0, to select the target API).
Sourcepub fn with_extra_param(
self,
key: impl Into<String>,
value: impl Into<String>,
) -> OAuth2ClientCredentials
pub fn with_extra_param( self, key: impl Into<String>, value: impl Into<String>, ) -> OAuth2ClientCredentials
Adds an extra form parameter to the token request.
Sourcepub const fn with_auth_style(
self,
style: TokenEndpointAuthStyle,
) -> OAuth2ClientCredentials
pub const fn with_auth_style( self, style: TokenEndpointAuthStyle, ) -> OAuth2ClientCredentials
Sets how client credentials are presented (default:
TokenEndpointAuthStyle::Basic).
Sourcepub const fn with_refresh_leeway(
self,
leeway: Duration,
) -> OAuth2ClientCredentials
pub const fn with_refresh_leeway( self, leeway: Duration, ) -> OAuth2ClientCredentials
Sets how long before expiry a cached token is refreshed (default 30 s).
Capped at half the token’s lifetime: a token that lives 20 s is cached for 10 s rather than not at all.
Sourcepub const fn with_request_timeout(
self,
timeout: Duration,
) -> OAuth2ClientCredentials
pub const fn with_request_timeout( self, timeout: Duration, ) -> OAuth2ClientCredentials
Sets the token-request timeout (default 30 s).
Sourcepub const fn with_failure_backoff(
self,
backoff: Duration,
) -> OAuth2ClientCredentials
pub const fn with_failure_backoff( self, backoff: Duration, ) -> OAuth2ClientCredentials
Sets how long a failed refresh is remembered (default 1 s).
Callers arriving within this window after a failure get the same
error immediately instead of a new token request. Duration::ZERO
turns the negative cache off; callers already waiting on an attempt
share its outcome either way.
Trait Implementations§
Source§impl Debug for OAuth2ClientCredentials
impl Debug for OAuth2ClientCredentials
Source§impl TokenProvider for OAuth2ClientCredentials
impl TokenProvider for OAuth2ClientCredentials
Source§fn access_token(
&self,
) -> Pin<Box<dyn Future<Output = Result<String, ClientError>> + Send + '_>>
fn access_token( &self, ) -> Pin<Box<dyn Future<Output = Result<String, ClientError>> + Send + '_>>
Source§fn invalidate(&self, token: &str)
fn invalidate(&self, token: &str)
token (HTTP 401), so it
should not hand that token out again. Read moreAuto Trait Implementations§
impl !Freeze for OAuth2ClientCredentials
impl !RefUnwindSafe for OAuth2ClientCredentials
impl !UnwindSafe for OAuth2ClientCredentials
impl Forget for OAuth2ClientCredentials
impl Move for OAuth2ClientCredentials
impl Send for OAuth2ClientCredentials
impl Sync for OAuth2ClientCredentials
impl Unpin for OAuth2ClientCredentials
impl UnsafeUnpin for OAuth2ClientCredentials
Blanket Implementations§
§impl<'a, T, E> AsTaggedExplicit<'a, E> for Twhere
T: 'a,
impl<'a, T, E> AsTaggedExplicit<'a, E> for Twhere
T: 'a,
§impl<'a, T, E> AsTaggedImplicit<'a, E> for Twhere
T: 'a,
impl<'a, T, E> AsTaggedImplicit<'a, E> for Twhere
T: 'a,
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
§impl<T> FutureExt for T
impl<T> FutureExt for T
§fn with_context(self, otel_cx: Context) -> WithContext<Self> ⓘ
fn with_context(self, otel_cx: Context) -> WithContext<Self> ⓘ
§fn with_current_context(self) -> WithContext<Self> ⓘ
fn with_current_context(self) -> WithContext<Self> ⓘ
§impl<T> Instrument for T
impl<T> Instrument for T
§fn instrument(self, span: Span) -> Instrumented<Self> ⓘ
fn instrument(self, span: Span) -> Instrumented<Self> ⓘ
§fn in_current_span(self) -> Instrumented<Self> ⓘ
fn in_current_span(self) -> Instrumented<Self> ⓘ
Source§impl<T> IntoEither for T
impl<T> IntoEither for T
Source§fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ
fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ
self into a Left variant of Either<Self, Self>
if into_left is true.
Converts self into a Right variant of Either<Self, Self>
otherwise. Read moreSource§fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
self into a Left variant of Either<Self, Self>
if into_left(&self) returns true.
Converts self into a Right variant of Either<Self, Self>
otherwise. Read more§impl<T> IntoRequest<T> for T
impl<T> IntoRequest<T> for T
§fn into_request(self) -> Request<T>
fn into_request(self) -> Request<T>
T in a tonic::Request§impl<L> LayerExt<L> for L
impl<L> LayerExt<L> for L
§fn named_layer<S>(&self, service: S) -> Layered<<L as Layer<S>>::Service, S>where
L: Layer<S>,
fn named_layer<S>(&self, service: S) -> Layered<<L as Layer<S>>::Service, S>where
L: Layer<S>,
Layered].