HIGH broken access controlaxumrust

Broken Access Control in Axum (Rust)

Broken Access Control in Axum with Rust — how this specific combination creates or exposes the vulnerability

Broken Access Control occurs when API endpoints do not properly enforce authorization checks, allowing one user to access or modify another user's resources. In Axum with Rust, this commonly arises because route handlers are plain functions; if developers forget to add per-route authorization checks or incorrectly trust path parameters, authenticated users can act on other users' data. Axum does not enforce authorization at the framework level, so it is the developer's responsibility to validate that the requesting user is allowed to access a given resource.

Consider a typical REST pattern using path parameters like /users/{user_id}/profile. If the handler reads user_id from the path and returns profile data without verifying that the authenticated user matches that ID, this is a classic BOLA/IDOR flaw. An authenticated attacker can simply change the numeric ID in the request to enumerate other profiles. Because Axum routes map cleanly to these parameters, misconfigured extractors and missing guards make this class of vulnerability easy to introduce.

Middleware or extractors can centralize some checks, but if they are not applied consistently across all protected routes, gaps remain. For example, an extractor that resolves a JWT and attaches user claims to the request is helpful, but each handler must still compare those claims to the resource being accessed. In Rust, type safety helps, yet it does not prevent logical mistakes like using the wrong user identifier or omitting a check for admin-override logic that may inadvertently expose admin-only endpoints to non-admin actors.

Real-world attack patterns mirror the OWASP API Top 10 Broken Access Control category and commonly map to SSRF when internal endpoints are accidentally exposed, or to privilege escalation when role checks are missing. For instance, an endpoint intended for user profile reads might also reveal sensitive account settings if a role guard is not enforced. Because Axum relies on explicit routing and handler composition, inconsistent middleware application or incomplete per-operation checks directly create access control weaknesses.

Tools like middleBrick scan these scenarios by checking whether authorization is validated at the endpoint level and whether path parameters align with authenticated subject claims. They test unauthenticated and authenticated-as-one-user accesses to see if data from another user is returned, and they verify that admin routes are not reachable by standard users. These scans complement manual review by surfacing mismatches between declared routes and actual enforcement in Rust code.

Rust-Specific Remediation in Axum — concrete code fixes

Remediation centers on consistently applying authorization checks in handlers and ensuring path parameters cannot be abused to reference other users' resources. Below are concrete Axum examples that demonstrate secure patterns.

First, define a shared extractor for the authenticated subject that validates the JWT and ensures the user ID is present:

use axum::{async_trait, extract::FromRequest, http::Request, response::IntoResponse};
use jsonwebtoken::{decode, Algorithm, DecodingKey, Validation};
use serde::{Deserialize, Serialize};

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Claims {
    pub sub: String,
    pub roles: Vec,
}

pub struct AuthUser {
    pub user_id: String,
    pub roles: Vec,
}

#[async_trait]
impl FromRequest<S> for AuthUser
where
    S: Send + Sync,
{
    type Rejection = (StatusCode, String);

    async fn from_request(req: Request<S>) -> Result<Self, Self::Rejection> {
        let token = req.headers()
            .get("authorization")
            .and_then(|v| v.to_str().ok())
            .and_then(|s| s.strip_prefix("Bearer "))
            .ok_or_else(|| (StatusCode::UNAUTHORIZED, "Missing or invalid token".to_string()))?;

        let key = DecodingKey::from_secret("your-secret".as_ref());
        let token_data = decode::

Next, enforce ownership checks in handlers by comparing the authenticated user ID to the resource ID, and reject mismatches:

use axum::{routing::get, Router};
use std::net::SocketAddr;

async fn get_profile(
    AuthUser { user_id, roles }: AuthUser,
    Path(requested_id): Path<String>,
) -> Result<impl IntoResponse, (StatusCode, String)> {
    if user_id != requested_id && !roles.contains("admin") {
        return Err((StatusCode::FORBIDDEN, "Access denied".to_string()));
    }
    // Fetch and return the profile for requested_id
    Ok((StatusCode::OK, format!("Profile for {}", requested_id)))
}

#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/users/:user_id/profile", get(get_profile));

    let addr = SocketAddr::from(([127, 0, 0, 1], 3000));
    axum::Server::bind(&addr).serve(app.into_make_service()).await.unwrap();
}

For admin routes, apply a role guard explicitly and avoid broad wildcards:

async fn admin_stats() -> Result<impl IntoResponse, (StatusCode, String)> {
    // Only allow users with the admin role
    let AuthUser { roles, .. } = AuthUser::from_request(...).await?;
    if !roles.contains("admin") {
        return Err((StatusCode::FORBIDDEN, "Admin access required".to_string()));
    }
    // Safe admin logic
    Ok(StatusCode::OK)
}

Use tower layers or axum middleware to centralize common authorization logic, but ensure each route that accesses user-specific data still validates the subject against the resource identifier. This approach mitigates BOLA/IDOR and prevents privilege escalation via missing role checks.

Frequently Asked Questions

Why does Axum not prevent Broken Access Control by default?
Axum is a low-level web framework that does not enforce authorization; it provides routing and extraction primitives. Developers must explicitly implement per-route checks and ensure path parameters or query inputs are validated against the authenticated subject.
How can middleBrick help detect these issues in Rust Axum APIs?
middleBrick scans unauthenticated attack surfaces and tests authenticated scenarios (where supported) to identify missing authorization checks, path parameter confusion, and privilege escalation risks, including mappings to OWASP API Top 10 for Axum-based services.