Skip to main content

OAuth2ClientCredentials

Struct OAuth2ClientCredentials 

Source
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 before expires_in elapses, 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 Debug output.

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

Source

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

Source

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.

Source

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.

Source

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.

Source

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://.

Source

pub fn with_tls_config(self, tls: ClientConfig) -> OAuth2ClientCredentials

Available on crate feature 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).

Source

pub fn with_scopes<I, S>(self, scopes: I) -> OAuth2ClientCredentials
where I: IntoIterator<Item = S>, S: Into<String>,

Sets the scopes to request (joined with spaces per RFC 6749 §3.3).

Source

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).

Source

pub fn with_extra_param( self, key: impl Into<String>, value: impl Into<String>, ) -> OAuth2ClientCredentials

Adds an extra form parameter to the token request.

Source

pub const fn with_auth_style( self, style: TokenEndpointAuthStyle, ) -> OAuth2ClientCredentials

Sets how client credentials are presented (default: TokenEndpointAuthStyle::Basic).

Source

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.

Source

pub const fn with_request_timeout( self, timeout: Duration, ) -> OAuth2ClientCredentials

Sets the token-request timeout (default 30 s).

Source

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

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
Source§

impl TokenProvider for OAuth2ClientCredentials

Source§

fn access_token( &self, ) -> Pin<Box<dyn Future<Output = Result<String, ClientError>> + Send + '_>>

Returns a currently-valid access token. Read more
Source§

fn invalidate(&self, token: &str)

Tells the provider the agent rejected token (HTTP 401), so it should not hand that token out again. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<'a, T, E> AsTaggedExplicit<'a, E> for T
where T: 'a,

§

fn explicit(self, class: Class, tag: u32) -> TaggedParser<'a, Explicit, Self, E>

§

impl<'a, T, E> AsTaggedImplicit<'a, E> for T
where T: 'a,

§

fn implicit( self, class: Class, constructed: bool, tag: u32, ) -> TaggedParser<'a, Implicit, Self, E>

Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
§

impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

§

impl<T> FutureExt for T

§

fn with_context(self, otel_cx: Context) -> WithContext<Self> ⓘ

Attaches the provided Context to this type, returning a WithContext wrapper. Read more
§

fn with_current_context(self) -> WithContext<Self> ⓘ

Attaches the current Context to this type, returning a WithContext wrapper. Read more
§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self> ⓘ

Instruments this type with the provided [Span], returning an Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self> ⓘ

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ

Converts 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 more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
where F: FnOnce(&Self) -> bool,

Converts 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

§

fn into_request(self) -> Request<T>

Wrap the input message T in a tonic::Request
§

impl<L> LayerExt<L> for L

§

fn named_layer<S>(&self, service: S) -> Layered<<L as Layer<S>>::Service, S>
where L: Layer<S>,

Applies the layer to a service and wraps it in [Layered].
§

impl<T> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> ⓘ
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a [WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self> ⓘ

Attaches the current default Subscriber to this type, returning a [WithDispatch] wrapper. Read more