Rust Playbook

Course › Week 5 · Axum microservice › Day 5 · lesson 33 of 42 · 25 min reading + 45 min practice

Middleware

Tracing, timeouts, CORS, an API key check and graceful shutdown.

tower-httpmiddlewaregraceful shutdown

On this page
  1. 1. Log every request
  2. 2. A timeout for every request
  3. 3. Your own middleware: an API key
  4. 4. CORS, only if a browser calls
  5. 5. The order of layers, and a clean shutdown
  6. The same middleware in Laravel
  7. Practice
  8. Remember

Laravel middleware wraps a request: auth:sanctum runs before the controller, TrimStrings changes the request, and a middleware can answer early without calling $next($request) at all. axum uses the same idea, from the tower crate. A middleware is a layer around the router; .layer(…) adds one around everything above it.

tower-http is the ready-made set, like the middleware Laravel ships with. Today: logging, timeouts and CORS from there, an API key check written by hand, and a shutdown that does not cut requests off mid-way.

1. Log every request

TraceLayer::new_for_http() logs each request through tracing, the logger from the config and logging lesson. It logs at debug level, so the EnvFilter default turns on debug for tower_http only: info,tower_http=debug.

src/main.rs
use axum::Router;
use axum::http::StatusCode;
use axum::routing::{get, post};
use tokio::net::TcpListener;
use tower_http::trace::TraceLayer;
use tracing_subscriber::EnvFilter;

async fn health() -> &'static str {
    "ok"
}

async fn store() -> (StatusCode, &'static str) {
    (StatusCode::ACCEPTED, "queued")
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    tracing_subscriber::fmt()
        .with_env_filter(
            EnvFilter::try_from_default_env()
                .unwrap_or_else(|_| EnvFilter::new("info,tower_http=debug")),
        )
        .with_writer(std::io::stderr)
        .with_ansi(false)
        .without_time()
        .init();

    let app = Router::new()
        .route("/health", get(health))
        .route("/batches", post(store))
        .layer(TraceLayer::new_for_http());

    let listener = TcpListener::bind("127.0.0.1:3000").await?;
    axum::serve(listener, app)
        .with_graceful_shutdown(async {
            let _ = tokio::signal::ctrl_c().await;
        })
        .await?;
    Ok(())
}
$ curl -si http://127.0.0.1:3000/health
HTTP/1.1 200 OK
content-type: text/plain; charset=utf-8
content-length: 2

ok
$ curl -si -X POST http://127.0.0.1:3000/batches
HTTP/1.1 202 Accepted
content-type: text/plain; charset=utf-8
content-length: 6

queued
the server’s log (stderr), after Ctrl-C
DEBUG request{method=GET uri=/health version=HTTP/1.1}: tower_http::trace::on_request: started processing request
DEBUG request{method=GET uri=/health version=HTTP/1.1}: tower_http::trace::on_response: finished processing request latency=0 ms status=200
DEBUG request{method=GET uri=/health version=HTTP/1.1}: tower_http::trace::on_eos: end of stream stream_duration=0 ms
DEBUG request{method=POST uri=/batches version=HTTP/1.1}: tower_http::trace::on_request: started processing request
DEBUG request{method=POST uri=/batches version=HTTP/1.1}: tower_http::trace::on_response: finished processing request latency=0 ms status=202
DEBUG request{method=POST uri=/batches version=HTTP/1.1}: tower_http::trace::on_eos: end of stream stream_duration=0 ms

Three lines per request, inside a span with the method and the path: started, finished with the status and the time it took, and end of stream once the body has been sent. latency=0 ms is real; these handlers do nothing.

The span fields come for free in every line a handler logs too, so RUST_LOG=info,tower_http=debug is the switch between quiet production logs and “show me every request”.

2. A timeout for every request

Laravel has max_execution_time and the web server’s timeout; axum has none by default, so a handler stuck on a slow query holds its connection forever. TimeoutLayer answers in its place after a limit. The rest of the program is in section 5; these are the lines that matter:

src/main.rs (part)
async fn slow() -> &'static str {
    tokio::time::sleep(Duration::from_secs(3)).await;
    "done"
}

// in main, around the routes:
        .layer(TimeoutLayer::with_status_code(
            StatusCode::REQUEST_TIMEOUT,
            Duration::from_secs(1),
        ))
$ curl -si http://127.0.0.1:3000/slow
HTTP/1.1 408 Request Timeout
access-control-allow-origin: https://admin.nordic.test
content-length: 0
the server’s log (stderr), after Ctrl-C
 INFO evaluations: listening on 127.0.0.1:3000
DEBUG request{method=GET uri=/slow version=HTTP/1.1}: tower_http::trace::on_request: started processing request
DEBUG request{method=GET uri=/slow version=HTTP/1.1}: tower_http::trace::on_response: finished processing request latency=1000 ms status=408
 INFO evaluations: SIGINT received
 INFO evaluations: stopped

408 after one second (latency=1001 ms in the log). When the timeout fires, the handler’s future is dropped, so its work stops at the next .await, like the timeout from the async lesson.

Keep the service’s limit below the caller’s. Laravel’s Http::timeout(10) gives up at ten seconds; a service that answers 408 at eight gives Laravel a clear answer instead of a connection error.

3. Your own middleware: an API key

A middleware written by hand is an async function. It takes extractors like a handler, then the Request and Next last. next.run(request).await is $next($request): it calls the handler and returns its response. Returning a response without calling it answers early, here with 401 and the body Laravel’s auth middleware gives.

src/main.rs (part)
async fn require_api_key(
    State(state): State<AppState>,
    headers: HeaderMap,
    request: Request,
    next: Next,
) -> Response {
    match headers.get("x-api-key") {
        Some(key) if key.as_bytes() == state.api_key.as_bytes() => next.run(request).await,
        _ => (
            StatusCode::UNAUTHORIZED,
            Json(Message {
                message: "Unauthenticated.",
            }),
        )
            .into_response(),
    }
}

// in main:
        .route("/batches", post(store))
        .route_layer(middleware::from_fn_with_state(
            state.clone(),
            require_api_key,
        ))
        .route("/health", get(health))

from_fn_with_state turns the function into a layer and gives it the state. It takes its own copy of AppState, which is why state.clone(): with_state at the end takes the other.

route_layer applies only to routes added before it. /health comes after, so a load balancer can check it without a key. This is Route::middleware('auth')->group(…) written by position.

$ curl -si -X POST http://127.0.0.1:3000/batches
HTTP/1.1 401 Unauthorized
content-type: application/json
access-control-allow-origin: https://admin.nordic.test
content-length: 30

{"message":"Unauthenticated."}
$ curl -si -X POST -H 'x-api-key: 9f2c4e1ab7d05e38' http://127.0.0.1:3000/batches
HTTP/1.1 202 Accepted
content-type: text/plain; charset=utf-8
access-control-allow-origin: https://admin.nordic.test
content-length: 6

queued
$ curl -si http://127.0.0.1:3000/health
HTTP/1.1 200 OK
content-type: text/plain; charset=utf-8
access-control-allow-origin: https://admin.nordic.test
content-length: 2

ok
the server’s log (stderr), after Ctrl-C
 INFO evaluations: listening on 127.0.0.1:3000
DEBUG request{method=POST uri=/batches version=HTTP/1.1}: tower_http::trace::on_request: started processing request
DEBUG request{method=POST uri=/batches version=HTTP/1.1}: tower_http::trace::on_response: finished processing request latency=0 ms status=401
DEBUG request{method=POST uri=/batches version=HTTP/1.1}: tower_http::trace::on_eos: end of stream stream_duration=0 ms
DEBUG request{method=POST uri=/batches version=HTTP/1.1}: tower_http::trace::on_request: started processing request
DEBUG request{method=POST uri=/batches version=HTTP/1.1}: tower_http::trace::on_response: finished processing request latency=0 ms status=202
DEBUG request{method=POST uri=/batches version=HTTP/1.1}: tower_http::trace::on_eos: end of stream stream_duration=0 ms
DEBUG request{method=GET uri=/health version=HTTP/1.1}: tower_http::trace::on_request: started processing request
DEBUG request{method=GET uri=/health version=HTTP/1.1}: tower_http::trace::on_response: finished processing request latency=0 ms status=200
DEBUG request{method=GET uri=/health version=HTTP/1.1}: tower_http::trace::on_eos: end of stream stream_duration=0 ms
 INFO evaluations: SIGINT received
 INFO evaluations: stopped

The key comes from SERVICE_API_KEY, read once at startup into AppState, never from a constant in the code. The same value goes into Laravel’s .env for the client side; the build day sets both.

One weakness: == stops at the first byte that differs, so in theory an attacker who can time millions of requests learns the key byte by byte. Laravel compares secrets with hash_equals for this reason. The practice part below fixes it.

4. CORS, only if a browser calls

Laravel calls this service from PHP, server to server. No browser is involved, so CORS does not apply and you need no CORS layer. Add one only if JavaScript in a browser calls the service directly. Then name the origins; CorsLayer::permissive() allows any site to call it with the visitor’s browser.

src/main.rs (part)
    let cors = CorsLayer::new()
        .allow_origin(HeaderValue::from_static("https://admin.nordic.test"))
        .allow_methods([Method::GET, Method::POST])
        .allow_headers([CONTENT_TYPE, HeaderName::from_static("x-api-key")]);

A browser sends an OPTIONS request first, the preflight, and sends the real request only if the answer allows it:

$ curl -si -X OPTIONS -H 'Origin: https://admin.nordic.test' -H 'Access-Control-Request-Method: POST' -H 'Access-Control-Request-Headers: x-api-key' http://127.0.0.1:3000/batches
HTTP/1.1 200 OK
access-control-allow-methods: GET,POST
access-control-allow-headers: content-type,x-api-key
access-control-allow-origin: https://admin.nordic.test
allow: POST
content-length: 0
the server’s log (stderr), after Ctrl-C
 INFO evaluations: listening on 127.0.0.1:3000
DEBUG request{method=OPTIONS uri=/batches version=HTTP/1.1}: tower_http::trace::on_request: started processing request
DEBUG request{method=OPTIONS uri=/batches version=HTTP/1.1}: tower_http::trace::on_response: finished processing request latency=0 ms status=200
 INFO evaluations: SIGINT received
 INFO evaluations: stopped

The CORS layer answered the preflight itself, without a key: the browser sends none on a preflight, so the API key check must not see it. That is the order question, next.

5. The order of layers, and a clean shutdown

Each .layer wraps everything above it, so the last one added runs first. Here a request passes TraceLayer, then CORS, then the timeout, then (on /batches) the API key check, then the handler. That order is chosen: the trace sees every answer, the 401s and 408s included; CORS answers preflights before the key check; and the timeout covers the key check too.

The other new piece is shutdown_signal. A deploy (systemd, Docker, Kubernetes, Forge) stops the old process with SIGTERM, not Ctrl-C. with_graceful_shutdown then stops accepting connections and waits for requests in progress to finish, so a deploy does not cut off a Laravel request halfway. tokio::select! from the async lesson waits for whichever signal comes first.

src/main.rs
use std::env;
use std::time::Duration;

use axum::extract::{Request, State};
use axum::http::header::CONTENT_TYPE;
use axum::http::{HeaderMap, HeaderName, HeaderValue, Method, StatusCode};
use axum::middleware::{self, Next};
use axum::response::{IntoResponse, Response};
use axum::routing::{get, post};
use axum::{Json, Router};
use serde::Serialize;
use tokio::net::TcpListener;
use tokio::signal::unix::{SignalKind, signal};
use tower_http::cors::CorsLayer;
use tower_http::timeout::TimeoutLayer;
use tower_http::trace::TraceLayer;
use tracing::info;
use tracing_subscriber::EnvFilter;

#[derive(Clone)]
struct AppState {
    api_key: String,
}

#[derive(Serialize)]
struct Message {
    message: &'static str,
}

async fn health() -> &'static str {
    "ok"
}

async fn store() -> (StatusCode, &'static str) {
    (StatusCode::ACCEPTED, "queued")
}

/// Stands in for a handler stuck on a slow database or API.
async fn slow() -> &'static str {
    tokio::time::sleep(Duration::from_secs(3)).await;
    "done"
}

async fn require_api_key(
    State(state): State<AppState>,
    headers: HeaderMap,
    request: Request,
    next: Next,
) -> Response {
    match headers.get("x-api-key") {
        Some(key) if key.as_bytes() == state.api_key.as_bytes() => next.run(request).await,
        _ => (
            StatusCode::UNAUTHORIZED,
            Json(Message {
                message: "Unauthenticated.",
            }),
        )
            .into_response(),
    }
}

/// Finishes when the process is asked to stop: Ctrl-C in a terminal (SIGINT),
/// or SIGTERM from systemd, Docker, Kubernetes or Forge during a deploy.
async fn shutdown_signal() {
    let mut terminate = match signal(SignalKind::terminate()) {
        Ok(stream) => stream,
        Err(error) => {
            tracing::error!(%error, "cannot listen for SIGTERM");
            return;
        }
    };
    tokio::select! {
        _ = tokio::signal::ctrl_c() => info!("SIGINT received"),
        _ = terminate.recv() => info!("SIGTERM received"),
    }
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    tracing_subscriber::fmt()
        .with_env_filter(
            EnvFilter::try_from_default_env()
                .unwrap_or_else(|_| EnvFilter::new("info,tower_http=debug")),
        )
        .with_writer(std::io::stderr)
        .with_ansi(false)
        .without_time()
        .init();

    let state = AppState {
        api_key: env::var("SERVICE_API_KEY")?,
    };
    let cors = CorsLayer::new()
        .allow_origin(HeaderValue::from_static("https://admin.nordic.test"))
        .allow_methods([Method::GET, Method::POST])
        .allow_headers([CONTENT_TYPE, HeaderName::from_static("x-api-key")]);

    let app = Router::new()
        .route("/batches", post(store))
        .route_layer(middleware::from_fn_with_state(
            state.clone(),
            require_api_key,
        ))
        .route("/health", get(health))
        .route("/slow", get(slow))
        .layer(TimeoutLayer::with_status_code(
            StatusCode::REQUEST_TIMEOUT,
            Duration::from_secs(1),
        ))
        .layer(cors)
        .layer(TraceLayer::new_for_http())
        .with_state(state);

    let listener = TcpListener::bind("127.0.0.1:3000").await?;
    info!("listening on 127.0.0.1:3000");
    axum::serve(listener, app)
        .with_graceful_shutdown(shutdown_signal())
        .await?;
    info!("stopped");
    Ok(())
}
$ curl -si -X POST -H 'x-api-key: 9f2c4e1ab7d05e38' http://127.0.0.1:3000/batches
HTTP/1.1 202 Accepted
content-type: text/plain; charset=utf-8
access-control-allow-origin: https://admin.nordic.test
content-length: 6

queued
the server’s log (stderr), after Ctrl-C
 INFO evaluations: listening on 127.0.0.1:3000
DEBUG request{method=POST uri=/batches version=HTTP/1.1}: tower_http::trace::on_request: started processing request
DEBUG request{method=POST uri=/batches version=HTTP/1.1}: tower_http::trace::on_response: finished processing request latency=0 ms status=202
DEBUG request{method=POST uri=/batches version=HTTP/1.1}: tower_http::trace::on_eos: end of stream stream_duration=0 ms
 INFO evaluations: SIGINT received
 INFO evaluations: stopped

The checker that produced this output stops the server with Ctrl-C, so the log says SIGINT received; on a deploy it says SIGTERM. Either way stopped comes last, after the requests in progress.

If the SIGTERM listener cannot be installed, shutdown_signal logs the error and returns, which shuts the server down at once. A server that cannot be stopped cleanly should say so at startup, not at the next deploy.

The same middleware in Laravel

app/Http/Middleware/RequireApiKey.php
<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class RequireApiKey
{
    public function handle(Request $request, Closure $next): Response
    {
        $key = (string) $request->header('X-Api-Key', '');

        if (! hash_equals((string) config('services.batch.key'), $key)) {
            return response()->json(['message' => 'Unauthenticated.'], 401);
        }

        return $next($request);
    }
}

The shape is the same: look at the request, then either answer or call $next. The difference is where it is attached. Laravel registers middleware by name and applies it in route files or groups; axum applies it by position in the router, so what you read in main is the full order, with nothing registered elsewhere.

Practicetower-http’s docs, and a constant-time key check

Skim the tower-http docs for the layers it has. CompressionLayer, RequestIdLayer and SetSensitiveHeadersLayer are the ones a service like this one adds next.

Exercise: compare the key in constant time

Add subtle = "2.6.1" and compare the key with ConstantTimeEq::ct_eq, which looks at every byte whatever their values. It returns a Choice, not a bool; bool::from(…) converts it.

Show the new check
src/main.rs (part)
use subtle::ConstantTimeEq;

fn key_matches(sent: &[u8], expected: &[u8]) -> bool {
    bool::from(sent.ct_eq(expected))
}

// in require_api_key:
//     Some(key) if key_matches(key.as_bytes(), state.api_key.as_bytes()) => next.run(request).await,

ct_eq on slices of different lengths returns false at once, so the time still reveals the key’s length. A key of fixed length, like the 16 hex characters here, gives nothing away.

Remember

  • The last .layer runs first; route_layer covers only the routes added before it.
  • Stop on SIGTERM as well as Ctrl-C, and let requests in progress finish.

Tomorrow: build the service. Laravel posts a batch of evaluations, the service answers 202 at once, analyses them in the background, and Laravel polls for the result.