Skip to main content

RequireScopes

Struct RequireScopes 

Source
pub struct RequireScopes { /* private fields */ }
Available on crate feature tower only.
Expand description

A route-level scope requirement: a tower::Layer for the routes (or services) that need more than the authentication layer in front of them requires — say, a write scope on the routes that write. It adds no key cache and no validation of its own: it reads the credential that layer accepted from the request’s extensions and checks it against its scopes (all-of, the same matching as the validator’s own check, AuthorizedToken::require_scopes).

Place it INSIDE (behind) an authentication layer — the axum AuthLayer or an HttpAuthLayer, which both mark every request they pass:

The request…Answer
carries an OAuth token with every scopeserved
carries an OAuth token missing one403, with the layer’s refusal body and a challenge naming the layer’s scopes followed by these (crate::refusal_for_scopes’s, for the same scopes)
carries a static token403 the same way — a static token has no scopes — unless static_token_bypasses_scopes
carries no credential (an optional layer passed it through)the layer’s own 401 and challenge
passed an allow_unauthenticated layer with no credential401 with crate::DEFAULT_STATIC_CHALLENGE, logged at error
passed NO authentication layer (mounted outside it)500, empty body, logged at error — never served

An empty requirement serves every request the layer let through (a 500 without a layer all the same). Nothing in the credential or the scopes reaches the response beyond the challenge; refusals are logged under oauth_resource_server::http_layer (403 at info, with the required and present scopes).

The credential judged is the innermost Credential a layer accepted. A layer checks static tokens first, so a request presenting both a static token and an OAuth token (in two sources) is judged by the static token.

The same type is oauth_resource_server::axum::RequireScopes. Under axum, the layer’s refusal body comes from its on_reject; behind an HttpAuthLayer, from its on_reject when the response body types match, else ResBody::default().

§Examples

Behind an HttpAuthLayer, on any tower stack:

use std::sync::Arc;

use http::{Request, Response};
use oauth_resource_server::OAuthValidator;
use oauth_resource_server::http_layer::{HttpAuthLayer, RequireScopes};
use tower::{ServiceBuilder, service_fn};

let writes = ServiceBuilder::new()
    // Outermost first: authenticate, then require the write scope.
    .layer(HttpAuthLayer::builder().oauth(oauth).build().unwrap())
    .layer(RequireScopes::new(["docs:write"]))
    .service(service_fn(|_request: Request<String>| async {
        Ok::<_, std::convert::Infallible>(Response::new(String::from("written")))
    }));

Under axum (feature axum, as oauth_resource_server::axum::RequireScopes), .route_layer(RequireScopes::new(["docs:write"])) on the routes that need it, before (so inside) .route_layer(auth).

§Panics

RequireScopes::new panics when a scope is not an RFC 6749 §3.3 scope-token (empty, or holding a space, ", \, a control or non-ASCII character): no token can carry one, so the route could never be reached. Use it for scopes written as literals in code; for scopes read from configuration use RequireScopes::try_new, which returns the error instead.

Implementations§

Source§

impl RequireScopes

Source

pub fn new(scopes: impl IntoIterator<Item = impl Into<String>>) -> Self

Require every scope in scopes (deduplicated). For literals in code; see RequireScopes::try_new for scopes from configuration.

§Panics

When a scope is not an RFC 6749 §3.3 scope-token; see the type’s docs.

Source

pub fn try_new( scopes: impl IntoIterator<Item = impl Into<String>>, ) -> Result<Self, InvalidScope>

RequireScopes::new for scopes read from configuration: the same requirement, or the first scope that is not a scope-token.

§Errors

InvalidScope, naming the offending scope.

§Examples
use oauth_resource_server::http_layer::RequireScopes;

assert!(RequireScopes::try_new(["docs:write"]).is_ok());
let err = RequireScopes::try_new(["docs:write", "two words"]).unwrap_err();
assert_eq!(err.scope(), "two words");
Source

pub fn static_token_bypasses_scopes(self) -> Self

Let a static token through instead of refusing it with 403.

§Security

A static token then reaches these routes whatever they require — the static token is treated as holding every scope. Use it only where the static token is meant to be a full-access key.

Source

pub fn scopes(&self) -> &[String]

The scopes required, deduplicated, in the order given.

Trait Implementations§

Source§

impl Clone for RequireScopes

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for RequireScopes

Source§

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

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

impl<S> Layer<S> for RequireScopes

Source§

type Service = RequireScopesService<S>

The wrapped service
Source§

fn layer(&self, inner: S) -> Self::Service

Wrap the given service with the middleware, returning a new service that has been decorated with the middleware.

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

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> FromRef<T> for T
where T: Clone,

Source§

fn from_ref(input: &T) -> T

Converts to this type from a reference to the input type.
Source§

impl<T> Instrument for T

Source§

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

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

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> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
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.
Source§

impl<T> WithSubscriber for T

Source§

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

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

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