Auth Bypass in Rocket with Bearer Tokens
Auth Bypass in Rocket with Bearer Tokens — how this specific combination creates or exposes the vulnerability
Auth bypass in Rocket applications using Bearer tokens can occur when token validation is incomplete or when authorization checks are decoupled from authentication. Rocket is a web framework for Rust that encourages strong routing and guards, but developers must explicitly enforce authentication and authorization on each protected route. A common pattern is to use a request guard that extracts a Bearer token from the Authorization header and validates it before proceeding. If a route declares a guard for extraction but omits a corresponding guard for authorization, or if the validation logic accepts tokens without verifying scope, audience, or signature rigorously, an authenticated context can be falsely established.
Consider a route defined with #[get("/admin")] and a request guard that calls auth_bearer(headers) to extract a token. If auth_bearer only checks the presence of a well-formed token and returns a user ID without verifying revocation status or permissions, an attacker who obtains a valid token (or crafts one if signing is weak) can access admin endpoints despite lacking privileges. Misconfigured token introspection or local validation that does not match the resource server’s expectations can lead to Insecure Direct Object References (IDOR) when the token identifies a subject but does not enforce per-object authorization. The unauthenticated attack surface tested by middleBrick can expose these gaps by probing endpoints that rely on Bearer tokens without enforcing strict scope checks, resulting in an authentication bypass where access controls are assumed but not verified.
Additionally, tokens with overly broad scopes or missing binding to the intended resource enable privilege escalation across horizontal or vertical authorization boundaries. For example, a token issued for read-only profiles might be reused to invoke administrative routes if the server does not validate scope per route. MiddleBrick’s checks for Authentication and Authorization (BOLA/IDOR, BFLA/Privilege Escalation) run in parallel to identify whether endpoints correctly enforce token-based permissions, flagging cases where a Bearer token grants access without validating context, ownership, or scope. These findings map to OWASP API Top 10 A01:2023 — Broken Object Level Authorization and map to compliance considerations in SOC2 and GDPR where access control integrity is required.
Bearer Tokens-Specific Remediation in Rocket — concrete code fixes
To remediate auth bypass with Bearer tokens in Rocket, enforce strict token validation and per-route authorization using request guards that verify claims, scope, and revocation. Below are concrete code examples using the Rocket framework with the rocket::http::Status and rocket::request::Request guards.
use rocket::http::Status;
use rocket::request::{self, Request, FromRequest};
use rocket::serde::json::Json;
use jsonwebtoken::{decode, Algorithm, DecodingKey, Validation, TokenData};
#[derive(Debug)]
pub struct TokenAuth {
pub sub: String,
pub scopes: Vec<String>,
}
#[rocket::async_trait]
impl<'_> FromRequest<'> for TokenAuth {
type Error = Status;
async fn from_request(req: &'req Request<'>) -> request::Outcome<Self, Self::Error> {
let auth_header = req.headers().get_one("Authorization");
let token = match auth_header {
Some(h) if h.starts_with("Bearer ") => &h[7..],
_ => return request::Outcome::Error((Status::Unauthorized, "Missing or malformed Authorization header".to_string())),
};
let validation = Validation::new(Algorithm::HS256);
let token_data: TokenData<Claims> = match decode(
token,
&DecodingKey::from_secret(SECRET_KEY.as_ref()),
&validation,
) {
Ok(data) => data,
Err(_) => return request::Outcome::Error((Status::Unauthorized, "Invalid token".to_string())),
};
// Ensure token is not revoked and scopes are sufficient for the route
if is_revoked(&token_data.claims.jti) {
return request::Outcome::Error((Status::Unauthorized, "Token revoked".to_string()));
}
request::Outcome::Success(TokenAuth {
sub: token_data.claims.sub,
scopes: token_data.claims.scopes,
})
}
}
// Example admin route requiring a specific scope
#[rocket::get("/admin")]
async fn admin_endpoint(auth: TokenAuth) -> Result<Json<AdminData>, Status> {
if !auth.scopes.contains("admin:read".to_string()) {
return Err(Status::Forbidden);
}
// Perform admin action with subject-based ownership checks
let data = fetch_admin_data(&auth.sub).map_err(|_| Status::InternalServerError)?;
Ok(Json(data))
}
// Helper to check token revocation (e.g., against a Redis cache)
fn is_revoked(jti: &str) -> bool {
// Check revocation store; return true if revoked
false
}
In this example, the TokenAuth request guard validates the Bearer token signature, checks revocation, and ensures the token includes required scopes before allowing access. Each route can then enforce additional authorization, such as verifying ownership of resources to prevent IDOR. middleBrick’s scans can verify that such guards are present and that endpoint behavior aligns with declared token requirements, reducing the risk of auth bypass.
For broader protection, apply consistent validation across all routes, use short-lived tokens with refresh rotation, bind tokens to the intended audience and issuer, and log suspicious validation failures. The Pro plan’s continuous monitoring can help detect regressions by tracking security scores over time, while the CLI allows you to integrate scans into local development and the GitHub Action can fail builds if risk scores drop below your chosen threshold.
Related CWEs: authentication
| CWE ID | Name | Severity |
|---|---|---|
| CWE-287 | Improper Authentication | CRITICAL |
| CWE-306 | Missing Authentication for Critical Function | CRITICAL |
| CWE-307 | Brute Force | HIGH |
| CWE-308 | Single-Factor Authentication | MEDIUM |
| CWE-309 | Use of Password System for Primary Authentication | MEDIUM |
| CWE-347 | Improper Verification of Cryptographic Signature | HIGH |
| CWE-384 | Session Fixation | HIGH |
| CWE-521 | Weak Password Requirements | MEDIUM |
| CWE-613 | Insufficient Session Expiration | MEDIUM |
| CWE-640 | Weak Password Recovery | HIGH |