Skip to main content

IndexRustTutorial

Axum Authentication, Validation and Security Basics

Part 13 of Rust for web developers: add users to an Axum API with Argon2 password hashing, session tokens, the validator crate, body limits and CORS.

By LearnWebCraft Team31 min readBeginner

Part 13 of 15 · Rust for web developers

At the end of part 12, linkbox stored its links in PostgreSQL and survived restarts. It also let anyone on the internet delete every link in it. There was no idea of a user, the validation was a hand-written check() function with two if statements, and a frontend running on another origin couldn't call it from a browser at all.

This part fixes all of that. By the end, linkbox will have:

  • users who register with an email and password, with the password hashed using Argon2id
  • login that hands out a random session token, and logout that actually revokes it
  • an AuthUser extractor, so a handler requires a login just by asking for one in its arguments
  • links that belong to a user, where only the owner can change or delete them
  • declarative validation with the validator crate, with per-field errors a frontend can show
  • a request body size limit, and CORS that lets your own frontend in and nobody else's

I'll also measure a timing leak in the login route and fix it, because it's the kind of bug that looks fine in every test you'd think to write.

Everything here ran on Rust 1.100.0, Axum 0.8.9, SQLx 0.9.1, argon2 0.6.0 and validator 0.21.0 against PostgreSQL 18.7. Every output is real.

A note before we start: security code is where copying from a tutorial is most dangerous, this one included. I'll explain why each choice is made, so you can judge it for your own app instead of trusting it.

Sessions or JWTs

The first decision is what a client sends to prove who it is. There are two common answers.

A session token is a long random string. The server stores it (or a hash of it) in the database next to a user id and an expiry time. On every request, the server looks the token up. If the row is there and hasn't expired, the request belongs to that user. Logging out deletes the row.

A JWT is a signed JSON document that says "this is user 42, valid until Friday". The server checks the signature and trusts the contents, with no database lookup. That's the appeal. The cost shows up when you want to log someone out, or ban an account, or react to a stolen token: the token is valid until it expires, because nothing on the server knows about it. Teams work around that with short expiries plus refresh tokens, or with a denylist in the database, and at that point they're doing a database lookup again.

For a single API with one database, sessions are simpler and easier to get right. The lookup is one indexed query on a primary key, which costs well under a millisecond next to everything else a request does. So linkbox uses opaque session tokens sent in an Authorization: Bearer header. If you later split linkbox into services that need to check identity without sharing a database, that's when a JWT earns its complexity.

I'm also using a header rather than a cookie on purpose. Cookies are sent by the browser automatically, which is convenient and is also exactly what makes cross-site request forgery possible. A bearer token only goes where your frontend code puts it. The trade is that your frontend has to store the token somewhere, and that needs its own care. I'll come back to that at the end.

New dependencies

Fig. 1bash
cargo add argon2@0.6 rand@0.10 sha2@0.11 hex@0.4
cargo add validator@0.21 --features derive

argon2 hashes passwords. rand generates session tokens. sha2 and hex hash tokens before they go into the database. validator replaces our check() function.

The CORS layer is part of tower-http, which we already have. It just needs its feature turned on:

Fig. 2toml
tower-http = { version = "0.7.1", features = ["trace", "timeout", "compression-gzip", "cors"] }

The migration

Users, sessions, and an owner for each link:

Fig. 3bash
sqlx migrate add users_and_sessions
Fig. 4sql
CREATE TABLE users (
    id             BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    email          TEXT NOT NULL UNIQUE,
    password_hash  TEXT NOT NULL,
    created_at     TIMESTAMPTZ NOT NULL DEFAULT now()
);

CREATE TABLE sessions (
    token_hash  TEXT PRIMARY KEY,
    user_id     BIGINT NOT NULL REFERENCES users (id) ON DELETE CASCADE,
    expires_at  TIMESTAMPTZ NOT NULL
);

ALTER TABLE links ADD COLUMN user_id BIGINT REFERENCES users (id) ON DELETE CASCADE;

ALTER TABLE links DROP CONSTRAINT links_url_key;
ALTER TABLE links ADD CONSTRAINT links_user_url_key UNIQUE (user_id, url);
Fig. 5text
$ sqlx migrate run
Applied 20261201000001/migrate users and sessions (21.410964ms)

A few details matter here.

ON DELETE CASCADE means deleting a user deletes their sessions and links. Without it, Postgres would refuse to delete a user who has any.

links.user_id is nullable, because linkbox already has links in it from part 12 and none of them have an owner. A migration that adds NOT NULL to a table with rows in it fails, unless you give it a default or fill the column first. Those old links stay readable, and since no user owns them, nobody can edit or delete them. That's fine for a tutorial. In a real app you'd decide what to do with them before running the migration.

In part 12, URLs were unique across the whole table. Now that links belong to people, two users should both be able to save the Rust homepage, so the constraint moves to the pair (user_id, url). Postgres named the old one links_url_key automatically, and I give the new one a name myself, because the error-handling code is about to look constraint names up.

Hashing passwords with Argon2

Never store a password. Store something that lets you check a password later without being able to recover it. That's a password hash, and it needs two properties a normal hash like SHA-256 doesn't have.

It needs a salt, a random value stored with each hash, so two users with the same password get different hashes and an attacker can't use a precomputed table.

And it needs to be slow. SHA-256 is designed to be fast, and a single graphics card can try billions of guesses a second against it. A password hash is designed to take a noticeable amount of time and memory per guess, which barely matters for one login and matters enormously for someone guessing millions of passwords from a stolen database.

Argon2id is the current recommendation from OWASP for new applications, and the argon2 crate's defaults use the parameters OWASP lists as a minimum: 19 MiB of memory, 2 iterations, 1 degree of parallelism. Here's hashing and verifying:

Fig. 6rust
use argon2::{
    Argon2,
    password_hash::{PasswordHasher, PasswordVerifier, phc::PasswordHash},
};

/// Hash a password with Argon2id. Slow on purpose, so it runs off the async threads.
pub async fn hash_password(password: String) -> Result<String, AppError> {
    tokio::task::spawn_blocking(move || {
        Argon2::default()
            .hash_password(password.as_bytes())
            .map(|hash| hash.to_string())
            .map_err(|e| AppError::Internal(e.to_string()))
    })
    .await
    .map_err(|e| AppError::Internal(e.to_string()))?
}

/// Check a password against a stored hash.
pub async fn verify_password(password: String, hash: String) -> Result<bool, AppError> {
    tokio::task::spawn_blocking(move || {
        let parsed = PasswordHash::new(&hash).map_err(|e| AppError::Internal(e.to_string()))?;
        Ok(Argon2::default()
            .verify_password(password.as_bytes(), &parsed)
            .is_ok())
    })
    .await
    .map_err(|e| AppError::Internal(e.to_string()))?
}

In argon2 0.6, hash_password generates the salt for you from the operating system's random number generator. Older versions and older tutorials make you create a SaltString first and pass it in. If you see that, it's the same thing done by hand.

The spawn_blocking is the part that's specific to async Rust. In part 9 I showed that a CPU-heavy function called directly inside an async handler blocks one of Tokio's worker threads, and every other request scheduled on that thread waits. Argon2 is CPU-heavy by design. spawn_blocking moves it onto a separate thread pool meant for this kind of work, and the handler awaits the result. The double ? handling deals with two different failures: the outer one is the blocking task itself panicking, and the inner one is the hash failing.

How slow is it? Registering a user took 0.43 seconds in a debug build, almost all of it Argon2. In a release build, a login with a wrong password took 18 milliseconds. Debug builds of Rust are slow at exactly this kind of tight number crunching, so don't judge your hashing cost by cargo run.

Here's what ends up in the database:

Fig. 7text
 id |      email      |              password_hash
----+-----------------+------------------------------------------
  1 | ana@example.com | $argon2id$v=19$m=19456,t=2,p=1$XmhGdSJk0
  3 | bo@example.com  | $argon2id$v=19$m=19456,t=2,p=1$ys9XI2RUh

I cut the hashes to 40 characters. The full value is a PHC string: the algorithm, its version, the parameters, the salt and the hash, all in one. Because the parameters are stored with each hash, you can raise them later for new passwords, and old ones still verify with the settings they were made with.

You might wonder why the ids are 1 and 3. I'll get to that in a minute.

Register

Fig. 8rust
async fn register(
    State(state): State<AppState>,
    ValidJson(creds): ValidJson<Credentials>,
) -> Result<(StatusCode, Json<User>), AppError> {
    let email = creds.email.trim().to_lowercase();
    let password_hash = hash_password(creds.password).await?;
    let user = state.create_user(&email, &password_hash).await?;
    tracing::info!(user_id = user.id, "user registered");
    Ok((StatusCode::CREATED, Json(user)))
}

ValidJson is new, and I'll cover it in the validation section. For now, read it as "parse the JSON body, then check the rules on Credentials".

The email gets lowercased before it's stored. Without that, ana@example.com and ANA@example.com would be two different accounts, which is confusing at best. (Technically, the part before the @ can be case-sensitive. In practice, no mail provider you'll meet treats it that way, and every site you use lowercases it.)

create_user is one INSERT ... RETURNING id, email, created_at. It returns a User, and User has no password hash field at all:

Fig. 9rust
/// A user as the API shows it. There is deliberately no password hash here.
#[derive(Debug, Serialize)]
pub struct User {
    pub id: i64,
    pub email: String,
    pub created_at: DateTime<Utc>,
}

That's the safest way to keep hashes out of responses. If the field doesn't exist on the type you serialize, no future handler can leak it by accident.

Fig. 10text
$ curl -i -X POST http://127.0.0.1:3000/auth/register -H content-type: application/json -d {"email":"ana@example.com","password":"correct horse battery"}
HTTP/1.1 201 Created
content-type: application/json
x-response-time: 466.89ms
vary: accept-encoding
vary: origin
content-length: 77

{"id":1,"email":"ana@example.com","created_at":"2026-12-01T07:16:45.448455Z"}

Registering the same address again, in capitals:

Fig. 11text
$ curl -X POST http://127.0.0.1:3000/auth/register -H content-type: application/json -d {"email":"ANA@example.com","password":"another long one"}
{"error":{"code":"conflict","message":"that email is already registered"}}

That 409 comes from the UNIQUE constraint on email, through the From<sqlx::Error> conversion we wrote in part 12. Now there are two unique constraints the app can hit, so the conversion checks which one fired:

Fig. 12rust
impl From<sqlx::Error> for AppError {
    fn from(err: sqlx::Error) -> Self {
        if let sqlx::Error::Database(db) = &err
            && db.is_unique_violation()
        {
            return match db.constraint() {
                Some("users_email_key") => AppError::Conflict("that email is already registered"),
                _ => AppError::Conflict("you already saved a link with that url"),
            };
        }
        AppError::Database(err)
    }
}

users_email_key is the name Postgres generated for the UNIQUE on email. Conflict now holds a &'static str with the message, instead of one hard-coded message.

And this is why the ids are 1 and 3. The duplicate insert asked the identity column for a new id, got 2, and then failed on the constraint. Postgres never hands out the same identity value twice, even if the insert that took it rolls back, so 2 is gone and Bo got 3. This was exercise 4 in part 12. Gaps in ids are normal, and nothing should depend on ids being consecutive.

There's a cost to this route worth knowing about: a 409 for a registered email tells anyone who asks that the email has an account. Most sites accept that on the sign-up form, because the alternative (always saying "check your email") needs an email-sending system. Login is different, and that's where it matters.

Login, and a timing leak

The login route needs to answer one question without telling an attacker anything extra. "Wrong password" and "no such user" must look identical. The obvious part of that is the error message. Both cases return the same thing:

Fig. 13text
$ curl -i -X POST http://127.0.0.1:3000/auth/login -H content-type: application/json -d {"email":"ana@example.com","password":"wrong password"}
HTTP/1.1 401 Unauthorized
content-type: application/json
www-authenticate: Bearer
x-response-time: 424.39ms
vary: accept-encoding
vary: origin
content-length: 74

{"error":{"code":"bad_credentials","message":"invalid email or password"}}
$ curl -X POST http://127.0.0.1:3000/auth/login -H content-type: application/json -d {"email":"nobody@example.com","password":"wrong password"}
{"error":{"code":"bad_credentials","message":"invalid email or password"}}

The less obvious part is time. Here's the version of login most people write first:

Fig. 14rust
let Some((user_id, hash)) = state.user_for_login(&email).await? else {
    return Err(AppError::BadCredentials);
};
if !verify_password(creds.password, hash).await? {
    return Err(AppError::BadCredentials);
}

It looks correct, and every test you'd write for it passes. I built it and timed three attempts each against a real account and a made-up one:

Fig. 15text
wrong password: 0.477939s
unknown email:  0.002311s
wrong password: 0.452426s
unknown email:  0.002016s
wrong password: 0.440049s
unknown email:  0.001999s

When the email exists, the server spends time running Argon2. When it doesn't, the server returns almost immediately. The response bodies are identical, and the timing still tells you which emails have accounts. Anyone with a list of addresses can find out which ones are registered, then focus their password guessing on those.

The fix is to always run Argon2. When the user doesn't exist, verify the password against a real hash of a password nobody has:

Fig. 16rust
/// A real hash of a password nobody has, checked when the email doesn't exist,
/// so a failed login takes the same time either way.
static DUMMY_HASH: LazyLock<String> = LazyLock::new(|| {
    Argon2::default()
        .hash_password(b"not a real password")
        .expect("hashing a constant works")
        .to_string()
});

async fn login(
    State(state): State<AppState>,
    ValidJson(creds): ValidJson<Credentials>,
) -> Result<Json<Value>, AppError> {
    let email = creds.email.trim().to_lowercase();
    let found = state.user_for_login(&email).await?;
    let (user_id, hash) = match found {
        Some((id, hash)) => (Some(id), hash),
        None => (None, DUMMY_HASH.clone()),
    };
    let password_ok = verify_password(creds.password, hash).await?;
    let Some(user_id) = user_id.filter(|_| password_ok) else {
        return Err(AppError::BadCredentials);
    };

    let token = new_token();
    let expires_at = Utc::now() + Duration::days(SESSION_DAYS);
    state
        .create_session(&hash_token(&token), user_id, expires_at)
        .await?;
    Ok(Json(json!({ "token": token, "expires_at": expires_at })))
}

LazyLock is from the standard library. It computes the value the first time something reads it, then keeps it for the life of the process. It's the Rust version of a module-level constant in Node that's computed on import, except it's lazy and thread-safe.

user_id.filter(|_| password_ok) keeps the id only if the password matched. If there was no user, it was None already. Either way, let ... else returns the same error.

The same measurement with this version:

Fig. 17text
wrong password: 0.426271s
unknown email:  0.445705s
wrong password: 0.425284s
unknown email:  0.429511s
wrong password: 0.433961s
unknown email:  0.423465s

And in a release build:

Fig. 18text
wrong password: 0.018223s
unknown email:  0.018739s
wrong password: 0.018015s
unknown email:  0.018445s

The two paths are now indistinguishable from outside. (The first pair of requests in that run took 43 and 61 milliseconds, slower than the rest for both kinds, because the process had only just started. That includes LazyLock computing the dummy hash, which happens once per process, so it can't be used to tell accounts apart.)

Session tokens

A successful login returns a token:

Fig. 19text
$ curl -X POST http://127.0.0.1:3000/auth/login -H content-type: application/json -d {"email":"ana@example.com","password":"correct horse battery"}
{"expires_at":"2026-12-08T07:16:50.754408527Z","token":"5659537c13e9ae98c438e715074358b1cd0e7687abc4200a661184abb390327b"}

Two small functions do the work:

Fig. 20rust
/// A new random session token: 32 bytes from a secure generator, as hex.
fn new_token() -> String {
    let bytes: [u8; 32] = rand::random();
    hex::encode(bytes)
}

/// Tokens are stored hashed, so a leaked database doesn't leak working tokens.
fn hash_token(token: &str) -> String {
    hex::encode(Sha256::digest(token.as_bytes()))
}

rand::random() uses rand's thread-local generator, which is seeded from the operating system and is cryptographically secure. Thirty-two random bytes is 256 bits, far past anything guessable. Don't build tokens from timestamps, user ids, or Math.random()-style generators. The whole security of a session rests on the token being unpredictable.

The server stores the SHA-256 of the token, never the token itself. If someone gets a copy of the sessions table, from a backup or a SQL injection somewhere else, they have hashes, and a hash isn't a working token. Here's the table after Ana logged out and Bo was still logged in:

Fig. 21text
    token_hash    | user_id |          expires_at
------------------+---------+-------------------------------
 db5dbe4b43cc5c73 |       3 | 2026-12-08 07:16:51.243374+00

You might ask why SHA-256 is fine here when I just spent a whole section saying it's wrong for passwords. It's about how much guessing the hash has to resist. A password comes from a human, and humans pick from a small space, so the hash has to make each guess expensive. A token is 256 random bits. Nobody can guess it no matter how fast the hash is, so a fast hash is fine, and it keeps the lookup on every request cheap.

Sessions last seven days. The expiry is enforced in the query that checks a token:

Fig. 22rust
/// The user a session token belongs to, if it exists and hasn't expired.
pub async fn session_user(&self, token_hash: &str) -> Result<Option<i64>, sqlx::Error> {
    sqlx::query_scalar!(
        "SELECT user_id FROM sessions WHERE token_hash = $1 AND expires_at > now()",
        token_hash,
    )
    .fetch_optional(&self.pool)
    .await
}

query_scalar! is for queries that return one column. It gives you that column's value directly instead of a row struct. Expired rows stay in the table until something deletes them. A scheduled DELETE FROM sessions WHERE expires_at < now() once a day takes care of that, and it's an exercise at the end.

An extractor for logged-in users

Here's the part I like most about doing auth in Axum. In Express, you'd write middleware that sets req.user, then remember to apply it to the right routes, and every handler trusts that req.user is there. In Axum, a handler declares that it needs a logged-in user by taking one as an argument:

Fig. 23rust
async fn create(
    State(state): State<AppState>,
    user: AuthUser,
    ValidJson(input): ValidJson<NewLink>,
) -> Result<(StatusCode, AppJson<Link>), AppError> {
    let link = state.insert(user.id, input).await?;
    tracing::info!(id = link.id, user_id = user.id, "link created");
    Ok((StatusCode::CREATED, AppJson(link)))
}

If the request doesn't have a valid token, the handler never runs. And you can't forget to protect a route that uses user.id, because without the AuthUser argument there's no user.id to use. The type system turns "did I remember the auth middleware" into a compile error.

AuthUser is a struct with a FromRequestParts implementation:

Fig. 24rust
/// A logged-in user. Add this to a handler's arguments to require a login.
pub struct AuthUser {
    pub id: i64,
    token_hash: String,
}

impl FromRequestParts<AppState> for AuthUser {
    type Rejection = AppError;

    async fn from_request_parts(parts: &mut Parts, state: &AppState) -> Result<Self, AppError> {
        let token = parts
            .headers
            .get(AUTHORIZATION)
            .and_then(|value| value.to_str().ok())
            .and_then(|value| value.strip_prefix("Bearer "))
            .ok_or(AppError::Unauthorized)?;
        let token_hash = hash_token(token);
        let id = state
            .session_user(&token_hash)
            .await?
            .ok_or(AppError::Unauthorized)?;
        Ok(AuthUser { id, token_hash })
    }
}

FromRequestParts is the trait behind Path, Query and State: extractors that only need the request's headers, URI and method, not its body. Implementing it for AppState specifically (rather than for any state type) lets it call state.session_user. The chain of and_then calls reads the header, rejects anything that isn't valid text, and strips the Bearer prefix. Any step that fails turns into Unauthorized.

token_hash is private, so code outside the auth module can read user.id but can't see the token. The logout handler is inside the module and uses it.

The 401 response also gets a www-authenticate: Bearer header, which is what the HTTP spec says a 401 should include. I added that in IntoResponse for AppError:

Fig. 25rust
if status == StatusCode::UNAUTHORIZED {
    response
        .headers_mut()
        .insert("www-authenticate", "Bearer".parse().unwrap());
}

Trying it with no token, a valid token and a made-up one:

Fig. 26text
$ curl -i http://127.0.0.1:3000/auth/me
HTTP/1.1 401 Unauthorized
content-type: application/json
www-authenticate: Bearer
x-response-time: 0.08ms
vary: accept-encoding
vary: origin
content-length: 75

{"error":{"code":"unauthorized","message":"you need to log in to do that"}}
$ curl http://127.0.0.1:3000/auth/me -H authorization: Bearer 5659537c13e9ae98c438e715074358b1cd0e7687abc4200a661184abb390327b
{"id":1,"email":"ana@example.com","created_at":"2026-12-01T07:16:45.448455Z"}
$ curl http://127.0.0.1:3000/auth/me -H authorization: Bearer 0000
{"error":{"code":"unauthorized","message":"you need to log in to do that"}}

Extractor order matters

Axum runs extractors in the order they appear in the handler's arguments, and only the last one may read the body. That's why user: AuthUser comes before ValidJson(input) in create. It also has a nice side effect, which I found by accident. I sent a 70 KB body to POST /links without a token, expecting the body size limit to reject it:

Fig. 27text
HTTP/1.1 401 Unauthorized
content-type: application/json
www-authenticate: Bearer
x-response-time: 0.84ms

{"error":{"code":"unauthorized","message":"you need to log in to do that"}}

The auth check ran first and rejected the request before the server read the body at all. Anonymous clients can't make the server buffer anything on protected routes. Put cheap checks first.

AuthUser tells us who's asking. The queries decide what they're allowed to touch:

Fig. 28rust
/// Delete a link, but only if `user_id` owns it.
pub async fn remove(&self, user_id: i64, id: i64) -> Result<bool, sqlx::Error> {
    let result = sqlx::query!(
        "DELETE FROM links WHERE id = $1 AND user_id = $2",
        id,
        user_id
    )
    .execute(&self.pool)
    .await?;
    Ok(result.rows_affected() == 1)
}

replace works the same way, with WHERE id = $1 AND user_id = $2 on the UPDATE. The ownership check is in the same statement as the change, so there's no gap between checking and acting where something else could happen. Doing it as two steps (load the link, compare owners in Rust, then update) works too, but it's more code and more chances to get it wrong.

Ana saves a link. Ana can't save it twice, but Bo can save the same URL, thanks to the new (user_id, url) constraint:

Fig. 29text
$ curl -X POST http://127.0.0.1:3000/links -H content-type: application/json -H authorization: Bearer 5659...327b -d {"url":"https://www.rust-lang.org/learn","title":"Learn Rust","tags":["rust"]}
{"id":5,"url":"https://www.rust-lang.org/learn","title":"Learn Rust","tags":["rust"],"created_at":"2026-12-01T07:16:51.418404Z"}
$ curl -X POST http://127.0.0.1:3000/links -H content-type: application/json -H authorization: Bearer 5659...327b -d {"url":"https://www.rust-lang.org/learn","title":"Again"}
{"error":{"code":"conflict","message":"you already saved a link with that url"}}
$ curl -X POST http://127.0.0.1:3000/links -H content-type: application/json -H authorization: Bearer 50c6...a764 -d {"url":"https://www.rust-lang.org/learn","title":"Bo saves it too"}
{"id":7,"url":"https://www.rust-lang.org/learn","title":"Bo saves it too","tags":[],"created_at":"2026-12-01T07:16:51.451480Z"}

(I shortened the tokens in these commands to keep the lines readable.)

Then Bo tries to delete and overwrite Ana's link:

Fig. 30text
$ curl -i -X DELETE http://127.0.0.1:3000/links/5 -H authorization: Bearer 50c6...a764
HTTP/1.1 404 Not Found
content-type: application/json
x-response-time: 1.66ms

{"error":{"code":"not_found","message":"link 5 not found"}}
$ curl -X PUT http://127.0.0.1:3000/links/5 -H content-type: application/json -H authorization: Bearer 50c6...a764 -d {"url":"https://evil.example","title":"Hijacked"}
{"error":{"code":"not_found","message":"link 5 not found"}}
$ curl http://127.0.0.1:3000/links/5
{"id":5,"url":"https://www.rust-lang.org/learn","title":"Learn Rust","tags":["rust"],"created_at":"2026-12-01T07:16:51.418404Z"}

Ana's link is untouched. Notice the status is 404, not 403. A 403 would confirm that link 5 exists and belongs to someone else. For linkbox it hardly matters, because links are publicly readable, but for private data like invoices or messages, "not found" is the right answer to "that's not yours", and it's what the query naturally gives you anyway.

Reading stays public in this version: GET /links and GET /links/{id} don't take an AuthUser. Making links private, so each user only sees their own, is one AuthUser argument and one WHERE user_id = $1 away, and it's an exercise.

Logout

Fig. 31rust
async fn logout(State(state): State<AppState>, user: AuthUser) -> Result<StatusCode, AppError> {
    state.delete_session(&user.token_hash).await?;
    Ok(StatusCode::NO_CONTENT)
}
Fig. 32text
$ curl -i -X POST http://127.0.0.1:3000/auth/logout -H authorization: Bearer 5659...327b
HTTP/1.1 204 No Content
x-response-time: 2.71ms
vary: origin

$ curl http://127.0.0.1:3000/auth/me -H authorization: Bearer 5659...327b
{"error":{"code":"unauthorized","message":"you need to log in to do that"}}

The token stops working the moment the row is gone. This is the thing a plain JWT can't do, and it's why I chose sessions.

Validation with the validator crate

In part 11, validation was a function:

Fig. 33rust
fn check(input: &NewLink) -> Result<(), AppError> {
    if input.title.trim().is_empty() {
        return Err(AppError::Validation("title must not be empty".into()));
    }
    // ...
}

It worked, but it stopped at the first problem, it was easy to forget to call, and every new rule meant more if statements. The validator crate lets you write the rules on the struct, like class-validator decorators in NestJS or a Zod schema:

Fig. 34rust
use validator::{Validate, ValidationError};

/// What a client sends to create or replace a link.
#[derive(Debug, Deserialize, Validate)]
pub struct NewLink {
    #[validate(url, custom(function = "http_or_https"))]
    pub url: String,
    #[validate(length(min = 1, max = 200))]
    pub title: String,
    #[serde(default)]
    #[validate(length(max = 10, message = "at most 10 tags"))]
    pub tags: Vec<String>,
}

fn http_or_https(url: &str) -> Result<(), ValidationError> {
    if url.starts_with("http://") || url.starts_with("https://") {
        Ok(())
    } else {
        Err(ValidationError::new("scheme")
            .with_message("must start with http:// or https://".into()))
    }
}

/// Email and password, for registering and logging in.
#[derive(Deserialize, Validate)]
pub struct Credentials {
    #[validate(email)]
    pub email: String,
    #[validate(length(min = 8, max = 128))]
    pub password: String,
}

url checks that the string parses as a URL. It accepts ftp:// and mailto: too, so the custom http_or_https function adds the rule linkbox actually wants. length on a String counts characters, and on a Vec it counts items. The password has a maximum as well as a minimum, because Argon2 hashing a multi-megabyte "password" is a cheap way for someone to burn your CPU.

Deriving Validate gives the struct a .validate() method that checks every rule and collects every failure into a ValidationErrors value. To run it automatically, I wrote one more extractor. It does what AppJson does, then validates:

Fig. 35rust
/// Like `AppJson`, but also runs the type's validation rules.
pub struct ValidJson<T>(pub T);

impl<S, T> FromRequest<S> for ValidJson<T>
where
    S: Send + Sync,
    T: DeserializeOwned + Validate,
{
    type Rejection = AppError;

    async fn from_request(req: Request, state: &S) -> Result<Self, Self::Rejection> {
        let AppJson(value) = AppJson::<T>::from_request(req, state).await?;
        value.validate()?;
        Ok(ValidJson(value))
    }
}

FromRequest, unlike FromRequestParts, gets the whole request including the body, which is why it has to be the last argument. This one is generic over any state type S, because it doesn't use the state. The ? on value.validate() works because AppError::Validation now holds a ValidationErrors with #[from]:

Fig. 36rust
#[error("some fields are invalid")]
Validation(#[from] ValidationErrors),

ValidationErrors implements Serialize, so the error response includes it under a fields key:

Fig. 37rust
let mut error = json!({ "code": code, "message": message });
if let AppError::Validation(errors) = &self {
    error["fields"] = json!(errors);
}

Now a handler that takes ValidJson<NewLink> can't receive an invalid link. As with AuthUser, there's nothing to remember to call. Here's a request that breaks three rules at once:

Fig. 38text
$ curl -X POST http://127.0.0.1:3000/links -H content-type: application/json -H authorization: Bearer 5659...327b -d {"url":"ftp://example.com","title":"","tags":["a","b","c","d","e","f","g","h","i","j","k"]}
{"error":{"code":"invalid_input","fields":{"tags":[{"code":"length","message":"at most 10 tags","params":{"max":10,"value":["a","b","c","d","e","f","g","h","i","j","k"]}}],"title":[{"code":"length","message":null,"params":{"max":200,"min":1,"value":""}}],"url":[{"code":"scheme","message":"must start with http:// or https://","params":{"value":"ftp://example.com"}}]},"message":"some fields are invalid"}}

Every field that failed is listed, with a machine-readable code, the rule's parameters, and a message where I gave one. A frontend can put each error next to the right input. A value that isn't a URL at all fails both URL rules:

Fig. 39text
$ curl -X POST http://127.0.0.1:3000/links -H content-type: application/json -H authorization: Bearer 5659...327b -d {"url":"not a url","title":"Rust"}
{"error":{"code":"invalid_input","fields":{"url":[{"code":"url","message":null,"params":{"value":"not a url"}},{"code":"scheme","message":"must start with http:// or https://","params":{"value":"not a url"}}]},"message":"some fields are invalid"}}

And registration:

Fig. 40text
$ curl -X POST http://127.0.0.1:3000/auth/register -H content-type: application/json -d {"email":"not-an-email","password":"short"}
{"error":{"code":"invalid_input","fields":{"email":[{"code":"email","message":null,"params":{"value":"not-an-email"}}],"password":[{"code":"length","message":null,"params":{"max":128,"min":8,"value":"short"}}]},"message":"some fields are invalid"}}

One thing to notice there: the response echoes the rejected value in params.value, and for the password field, that's the password the user typed. It's going back to the same person who sent it, over the same connection, so it isn't a leak to a third party. But if you log error responses, or if a proxy does, you'd be logging passwords. In a real app I'd strip params from the response for sensitive fields, or not echo values at all. It's another exercise.

Validation is about the shape of the input. It isn't a substitute for the database constraints. The UNIQUE and NOT NULL rules in the migration still have the final say, and the 409 for a duplicate email comes from Postgres, not from validator, because only the database can know whether an email is taken at the moment of the insert.

Limiting the request body

Axum's Json extractor already limits bodies to 2 MB by default. linkbox's biggest legitimate request is a link with a 200-character title and ten tags, which is well under 1 KB. Accepting 2 MB means accepting a lot of memory use per request that's never needed, so I lowered it:

Fig. 41rust
.layer(DefaultBodyLimit::max(64 * 1024))

DefaultBodyLimit doesn't reject anything itself. It sets the limit that body extractors like Json use when they read. With a 70 KB body and a valid token:

Fig. 42text
HTTP/1.1 413 Payload Too Large
content-type: application/json
x-response-time: 1.02ms

{"error":{"code":"invalid_json","message":"Failed to buffer the request body: length limit exceeded"}}

The status is right, but invalid_json is the wrong code. The JSON wasn't invalid, it was never read. That came from our AppError::Json arm, which uses the rejection's status but always says invalid_json. A frontend switching on code would show the wrong message. One more match arm fixes it, with a guard that checks the status:

Fig. 43rust
AppError::Json(rejection) if rejection.status() == StatusCode::PAYLOAD_TOO_LARGE => {
    (StatusCode::PAYLOAD_TOO_LARGE, "too_large")
}
AppError::Json(rejection) => (rejection.status(), "invalid_json"),
Fig. 44text
HTTP/1.1 413 Payload Too Large
content-type: application/json
x-response-time: 1.61ms
vary: accept-encoding
vary: origin
content-length: 99

{"error":{"code":"too_large","message":"Failed to buffer the request body: length limit exceeded"}}

Match arms are checked in order, so the guarded arm has to come first.

CORS

Say your frontend runs on http://localhost:5173 (Vite's default) and the API on http://localhost:3000. Those are different origins, because the port is part of the origin. When the frontend calls the API with fetch, the browser checks whether the API allows it. For anything more than a simple GET, and a request with an Authorization header or a JSON body counts, the browser first sends a preflight: an OPTIONS request asking "may this origin send a POST with these headers?" If the response doesn't say yes, the browser blocks the real request.

tower-http has a CorsLayer that answers those preflights and adds the right headers to normal responses:

Fig. 45rust
/// Only these origins may call the API from a browser.
fn cors(allowed_origins: Vec<HeaderValue>) -> CorsLayer {
    CorsLayer::new()
        .allow_origin(allowed_origins)
        .allow_methods([Method::GET, Method::POST, Method::PUT, Method::DELETE])
        .allow_headers([AUTHORIZATION, CONTENT_TYPE])
        .max_age(Duration::from_secs(60 * 60))
}

The allowed origins come from an environment variable, because they're different in development and production:

Fig. 46rust
let origins = std::env::var("CORS_ORIGINS").unwrap_or_else(|_| "http://localhost:5173".into());
let allowed_origins = origins
    .split(',')
    .map(|origin| origin.trim().parse())
    .collect::<Result<Vec<_>, _>>()
    .context("CORS_ORIGINS must be a comma-separated list of origins")?;

Parsing happens at startup, so a typo in the variable stops the server with a clear message instead of failing on the first request. collect into a Result<Vec<_>, _> is the trick from part 5: it stops at the first error, or gives you the whole list.

app() now takes the list as an argument, and the layer goes near the outside of the stack so it sees preflight requests before anything else:

Fig. 47rust
pub fn app(state: AppState, allowed_origins: Vec<HeaderValue>) -> Router {
    Router::new()
        .route("/health", get(health))
        .nest("/auth", auth::router())
        .nest("/links", routes::links::router())
        .fallback(not_found)
        .with_state(state)
        .layer(DefaultBodyLimit::max(64 * 1024))
        .layer(middleware::from_fn(response_time))
        .layer(CompressionLayer::new())
        .layer(TimeoutLayer::with_status_code(
            StatusCode::REQUEST_TIMEOUT,
            Duration::from_secs(10),
        ))
        .layer(cors(allowed_origins))
        .layer(TraceLayer::new_for_http())
}

A preflight from the allowed origin:

Fig. 48text
$ curl -i -X OPTIONS http://127.0.0.1:3000/links -H origin: http://localhost:5173 -H access-control-request-method: POST -H access-control-request-headers: authorization, content-type
HTTP/1.1 200 OK
vary: origin
access-control-allow-methods: GET,POST,PUT,DELETE
access-control-allow-headers: authorization,content-type
access-control-max-age: 3600
access-control-allow-origin: http://localhost:5173
allow: GET,HEAD,POST
content-length: 0

The browser sees access-control-allow-origin matching its own origin and sends the real request. max-age lets it remember that answer for an hour instead of preflighting every call.

The same preflight from somewhere else:

Fig. 49text
$ curl -i -X OPTIONS http://127.0.0.1:3000/links -H origin: https://evil.example -H access-control-request-method: POST
HTTP/1.1 200 OK
vary: origin
access-control-allow-methods: GET,POST,PUT,DELETE
access-control-allow-headers: authorization,content-type
access-control-max-age: 3600
allow: GET,HEAD,POST
content-length: 0

That's still a 200, which surprised me the first time. The difference is the missing access-control-allow-origin header. CORS doesn't work by the server refusing requests. It works by the server telling the browser what's allowed, and the browser enforcing it. With no matching origin in the response, the browser blocks the call and the page's JavaScript gets a network error.

Normal responses to an allowed origin get the header too, along with vary: origin, which tells caches that the response depends on the Origin header:

Fig. 50text
$ curl -i http://127.0.0.1:3000/links/5 -H origin: http://localhost:5173
HTTP/1.1 200 OK
content-type: application/json
x-response-time: 1.05ms
vary: accept-encoding
vary: origin
access-control-allow-origin: http://localhost:5173
content-length: 128

The thing to understand about CORS is what it doesn't do. It isn't authentication and it isn't a firewall. Every curl command in this article ignored it completely, because curl isn't a browser. CORS protects your users: it stops a page on some other site from using a visitor's browser to call your API. It doesn't stop anyone from calling your API directly. That's what the AuthUser extractor is for.

You'll see CorsLayer::permissive() and allow_origin(Any) in a lot of examples. They let every origin in. That's sometimes fine for a truly public, read-only API. For anything with logins, list the origins you mean.

Updating the offline query data

The new queries mean the .sqlx folder from part 12 is out of date. Running prepare again:

Fig. 51text
$ cargo sqlx prepare
    Checking linkbox v0.1.0 (/w/linkbox)
    Finished `dev` profile [unoptimized + debuginfo] target(s) in 15.13s
query data written to .sqlx in the current directory; please check this into version control
$ ls .sqlx | wc -l
11

Eleven queries, up from five. SQLX_OFFLINE=true cargo check passes with no database, which matters for the Docker build in part 15.

What this doesn't cover

This part covers the basics, and it would be dishonest to call linkbox production-ready. Here's what a real deployment still needs, roughly in the order I'd add it.

HTTPS comes first. Bearer tokens and passwords in plain HTTP can be read by anyone on the network path. In production, the API runs behind something that terminates TLS, which we'll set up in part 15.

Next is rate limiting on login and register. Argon2 makes each guess slow, but nothing stops someone from sending thousands of login attempts. A per-IP and per-email limit on /auth/login is the next thing I'd add. The tower_governor crate does this as a Tower layer.

Then there's where the frontend keeps the token. If it's in localStorage, any script that runs on your page (including one injected through a cross-site scripting bug) can read it. An HttpOnly cookie can't be read by scripts, but brings back cross-site request forgery, which then needs SameSite cookies or CSRF tokens. There's no option with zero trade-offs. For a browser-only app on one domain, an HttpOnly, Secure, SameSite=Lax cookie is the common choice.

Email verification and password reset are missing too. Both need to send email and both need their own single-use tokens, which work very much like the session tokens here.

And finally, expired sessions should be cleaned up, and you probably want to limit how many sessions one user can have.

Express and Axum side by side

Express Axum
bcrypt or argon2 npm package argon2 crate, inside spawn_blocking
Middleware sets req.user AuthUser extractor in the handler's arguments
Forget the middleware and req.user is undefined Forget AuthUser and there's no user.id to use
crypto.randomBytes(32).toString("hex") hex::encode(rand::random::<[u8; 32]>())
express-session with a store A sessions table and one query
Zod or class-validator validator with #[derive(Validate)]
zod.safeParse(req.body) in each handler ValidJson<T> extractor
express.json({ limit: "64kb" }) DefaultBodyLimit::max(64 * 1024)
cors({ origin: [...] }) CorsLayer::new().allow_origin(...)
helmet() for security headers tower-http SetResponseHeader layers, one per header

The last row is the one place where Node has a convenience Rust doesn't match out of the box. There's no single crate that's as widely used as helmet, so you add the headers you want yourself.

Exercises

  1. Make links private. GET /links and GET /links/{id} should take an AuthUser and only return the caller's own links. What should GET /links/5 return to Bo now?
  2. Add a DELETE /auth/sessions route that logs the user out everywhere, by deleting all of their sessions. Then add a GET /auth/sessions that lists them (with expiry times, but obviously not the hashes).
  3. Write a background task, started in main with tokio::spawn, that deletes expired sessions once an hour. Use tokio::time::interval from part 9.
  4. Change IntoResponse for AppError so validation errors never echo params.value for a field named password. Check the response for a short password before and after.
  5. Add a POST /auth/password route that changes the password. It should require the current password, and it should delete every other session of that user. Why is that second part important?
  6. Remove the DUMMY_HASH and time the login route yourself with curl -w "%{time_total}". Then put it back.

Next up: testing

linkbox has grown a lot over four parts, and so far I've tested all of it by hand with curl. That doesn't scale, and it won't catch the day someone removes the AND user_id = $2 from a query.

Part 14 adds real tests. We'll call the router directly with tower::ServiceExt::oneshot, without starting a server or opening a port, use #[sqlx::test] to give every test its own fresh database with migrations applied, and write tests for exactly the things this part got right: the 401s, the 404 for someone else's link, the validation errors and the timing-safe login.