Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Authentication

Api::Principal is who is calling. authenticate finds the principal from the credentials that the request presented:

/// The principal that an API key names. Nobody without a key. 401 for a key that nobody holds.
fn caller_of_key(req: &api::Request) -> Result<Option<String>, api::ApiError> {
    let key = api::server::credentials(req).into_iter().map(|api::server::Credential::ApiKey(key)| key).next();
    match key {
        Some("secret") => Ok(Some("ann".to_owned())),
        Some(_) => Err(api::ApiError::new(api::http::StatusCode::UNAUTHORIZED, "unknown key")),
        None => Ok(None),
    }
}

fn authenticated() -> axum::Router {
    api::Server::new(Server).authenticate(|req: &api::Request| std::future::ready(caller_of_key(req))).into_axum()
}

find answers None for nobody. When your Api names a Principal, a server without authenticate does not compile. Layers added after authenticate read the principal from the request’s extensions:

Whether the server finds who is calling: Anonymous until Server::authenticate, then Authenticated.

An Api whose Principal is () builds into a service as it is. Any other Principal needs Server::authenticate: without it into_service does not compile. Each operation then takes what its security asks for:

The operation’s securityctx.principalWhen authenticate found nobody
none (security: [])()the handler runs
an empty alternative ([{}, {apiKey: []}])Option<Principal>the handler runs with None
credentials requiredPrincipal401 in the error schema

Every 401 of an operation carries WWW-Authenticate with a challenge for its http schemes (Bearer, Basic), also one that your handler returns. An apiKey or mutualTLS scheme has no HTTP authentication scheme to name in a challenge (RFC 9110 section 11.6.1), so a 401 for one carries none.

server::credentials(req) gives one Credential variant per security scheme that the operation matched. A scheme added to the description is then a compile error until you handle it.

Request context

Values that outer tower layers attach also reach authenticate. So does the address of the client:

/// Who is calling: the layer in front of the router and the client's address.
fn find_caller(req: &api::Request) -> Result<Option<String>, api::ApiError> {
    let principal = req
        .extensions()
        .get::<Principal>()
        .ok_or_else(|| api::ApiError::new(api::http::StatusCode::UNAUTHORIZED, "no principal"))?;
    let peer = api::peer(req.extensions())
        .ok_or_else(|| api::ApiError::new(api::http::StatusCode::UNAUTHORIZED, "no peer"))?;
    Ok(Some(format!("{} from {peer}", principal.0)))
}

Recipes maps the claims of a JWT or session layer that you already run to the principal.

Signatures over the body

Some schemes sign the body: webhooks (X-Hub-Signature-256, Stripe-Signature) and Matrix federation (X-Matrix). The layer that checks the signature reads the body with api::read_body(&mut req).await. The operation decodes the same bytes and reads nothing again:

/// A signature over the body, as webhooks (`X-Hub-Signature-256`) and Matrix (`X-Matrix`) send. Here the signature is
/// the body's length, a stand-in for an HMAC. The filter owns the request, so it reads the body itself. The operation
/// then decodes the same bytes and reads nothing again.
async fn verify(mut req: api::Request) -> Result<api::Request, api::ApiError> {
    let len = api::read_body(&mut req).await?.len();
    let ok = req.headers().get("x-signature").and_then(|v| v.to_str().ok()) == Some(len.to_string().as_str());
    if ok { Ok(req) } else { Err(api::ApiError::new(api::http::StatusCode::UNAUTHORIZED, "bad signature")) }
}
        let service = api::Server::new(Catalog::default())
            .operation_layer(tower::filter::AsyncFilterLayer::new(verify))
            .into_service();

A layer that does not call read_body runs before the body is read. So a refused request costs no body read. A client signs in its transport: the request is final there, body included. reqwest-middleware and tower layers work too.

Scopes and roles

Scopes and roles are typed. There is one server::Scope variant per name in the description. Match them exhaustively. A permission added to the description is then a compile error until you map it:

/// Checks the permissions the operation requires: every request runs through it.
fn permitted(req: &api::Request) -> Result<(), api::ApiError> {
    let token = server::credentials(req).into_iter().map(|Credential::Pat(t)| t.to_owned()).next();
    let held = |s: Scope| {
        let t = token.as_deref().unwrap_or("");
        match s {
            Scope::IssuesRead => t.split('+').any(|p| p == "read"),
            Scope::IssuesWrite => t.split('+').any(|p| p == "write"),
        }
    };
    if server::scopes_held(req, held) {
        Ok(())
    } else {
        Err(api::ApiError::new(api::http::StatusCode::FORBIDDEN, "missing permission"))
    }
}

Client certificates

A mutualTLS alternative is never satisfied on its own. A layer that trusts the certificate your TLS terminator verified adds api::ClientCertificateVerified to the request’s extensions.