HIGH auth bypassactixbasic auth

Auth Bypass in Actix with Basic Auth

Auth Bypass in Actix with Basic Auth — how this specific combination creates or exposes the vulnerability

Auth Bypass in Actix with Basic Auth occurs when authentication is implemented in a way that does not properly protect or validate credentials on each request. Basic Auth encodes credentials in Base64 but does not encrypt them; without TLS, credentials are easily exposed. In Actix, developers may mistakenly assume that checking for a valid Authorization header once is sufficient across the application lifecycle. This can lead to bypasses if the application reuses identity context, fails to enforce authentication on certain routes, or mishandles header parsing.

When middleware or guards are not consistently applied, an attacker can access protected endpoints by omitting or manipulating the Authorization header. For example, if a route is mistakenly marked as public or if role checks are performed only at initialization, unauthenticated access becomes possible. Additionally, if the server does not reject requests with malformed or missing credentials, an attacker may rely on default or guest permissions to interact with admin or sensitive endpoints.

Another vector specific to Actix arises from how extractors interact with guards. If an extractor for credentials is implemented but not enforced by a guard on all sensitive handlers, a user can reach those handlers through an unguarded path. This misalignment between extraction and authorization constitutes an Auth Bypass. The risk is compounded when combined with other findings such as missing rate limiting or insufficient input validation, which may allow automated probing of unprotected routes.

middleBrick scans such misconfigurations by sending unauthenticated requests to endpoints that should require credentials, checking whether access is granted without valid Basic Auth headers. It inspects whether authentication is enforced at the handler level, whether credentials are validated on every request, and whether any routes expose sensitive functionality without protection. The tool also cross-references findings with the OpenAPI specification when available, validating whether declared security requirements match runtime behavior, helping identify gaps between documented and actual authentication coverage.

Basic Auth-Specific Remediation in Actix — concrete code fixes

To remediate Auth Bypass with Basic Auth in Actix, enforce authentication on every sensitive route and validate credentials on each request. Use Actix's built-in extractors and guards consistently, and avoid relying on global state to track authentication. Below are concrete, working examples.

Secure Basic Auth extractor

Define a custom extractor that validates the Authorization header on every call. This example decodes the Base64 payload and checks against a hardcoded credential set; in production, validate against a secure store.

use actix_web::{dev::ServiceRequest, Error, HttpMessage, HttpRequest};
use actix_web::http::header::AUTHORIZATION;
use actix_web::web::Bytes;
use base64::prelude::*;
use futures_util::future::{ok, Either, FutureResult};
use std::future::Future;

pub struct BasicAuth {
    pub user: String,
    pub pass: String,
}

pub fn basic_auth(req: &HttpRequest, body: &Bytes) -> Result {
    let auth_header = req.headers().get(AUTHORIZATION)
        .ok_or_else(|| actix_web::error::ErrorUnauthorized("Missing Authorization header"))?;
    let auth_str = auth_header.to_str().map_err(|_| actix_web::error::ErrorUnauthorized("Invalid header"))?;
    if !auth_str.starts_with("Basic ") {
        return Err(actix_web::error::ErrorUnauthorized("Invalid scheme"));
    }
    let encoded = auth_str.trim_start_matches("Basic ");
    let decoded = BASE64_STANDARD.decode(encoded).map_err(|_| actix_web::error::ErrorUnauthorized("Invalid encoding"))?;
    let credentials = String::from_utf8(decoded).map_err(|_| actix_web::error::ErrorUnauthorized("Invalid credentials"))?;
    let parts: Vec<&str> = credentials.splitn(2, ':').collect();
    if parts.len() != 2 {
        return Err(actix_web::error::ErrorUnauthorized("Invalid format"));
    }
    Ok(BasicAuth {
        user: parts[0].to_string(),
        pass: parts[1].to_string(),
    })
}

// Example guard that enforces authentication
pub fn require_auth(req: &ServiceRequest) -> Result<(), (Error, ServiceRequest)> {
    let (req, pl) = req.into_parts();
    let body = actix_web::web::Bytes::from(pl.body.as_ref().unwrap_or(&vec![]).to_vec());
    basic_auth(&req, &body).map(|_| {
        let req = actix_web::dev::ServiceRequest::from_parts(req, pl);
        Ok(req)
    }).map_err(|e| (e, actix_web::dev::ServiceRequest::from_parts(req, pl)))}

Applying the guard to routes

Use the guard on each handler that requires authentication. Do not mark handlers as public unless explicitly intended.

use actix_web::{web, App, HttpResponse, HttpServer, Responder};

async fn admin_panel() -> impl Responder {
    HttpResponse::Ok().body("Admin area — access granted with valid auth")
}

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    HttpServer::new(|| {
        App::new()
            .route("/admin", web::get().to(admin_panel).guard(require_auth))
    })
    .bind("127.0.0.1:8080")?
    .run()
    .await
}

Transport security and credential handling

Always serve Basic Auth over TLS to prevent credential interception. Avoid hardcoding credentials in source code; use environment variables or a secure vault. Combine with additional checks such as role validation and logging to detect abuse. Do not rely on obscurity or IP-based restrictions as a substitute for proper authentication.

When using the middleBrick CLI (middlebrick scan <url>) or the GitHub Action, you can verify that these protections are in place by confirming that authenticated checks are enforced on sensitive endpoints and that unauthenticated access is rejected. The Pro plan’s continuous monitoring can help detect regressions in authentication enforcement over time.

Related CWEs: authentication

CWE IDNameSeverity
CWE-287Improper Authentication CRITICAL
CWE-306Missing Authentication for Critical Function CRITICAL
CWE-307Brute Force HIGH
CWE-308Single-Factor Authentication MEDIUM
CWE-309Use of Password System for Primary Authentication MEDIUM
CWE-347Improper Verification of Cryptographic Signature HIGH
CWE-384Session Fixation HIGH
CWE-521Weak Password Requirements MEDIUM
CWE-613Insufficient Session Expiration MEDIUM
CWE-640Weak Password Recovery HIGH

Frequently Asked Questions

Can an attacker bypass Basic Auth in Actix if the Authorization header is missing but the endpoint is public?
Yes; if an endpoint intended to require Basic Auth is not guarded or the check is omitted, an attacker can access it without credentials. Always enforce authentication via guards and extractors on every sensitive route.
Does using Basic Auth over HTTPS prevent all bypass risks in Actix?
No. While HTTPS protects credentials in transit, bypass risks remain if authentication is not consistently enforced, routes are misconfigured as public, or role checks are incomplete. Validate credentials on every request and apply middleware/guards uniformly.