HIGH sql injectionactixbearer tokens

Sql Injection in Actix with Bearer Tokens

Sql Injection in Actix with Bearer Tokens — how this specific combination creates or exposes the vulnerability

SQL Injection remains a top concern in web APIs, including Actix-based Rust services that rely on bearer tokens for authentication. When bearer tokens are used to identify a user but are not validated for content or length, they can be inadvertently concatenated into SQL strings, creating injection paths if the token value is used directly in query construction. For example, an endpoint that extracts the token from the Authorization header and uses it to build dynamic SQL without parameterization can allow an attacker-controlled token to alter query structure.

Consider an Actix handler that reads a bearer token and uses it to select user-specific data:

let token = req.headers().get("Authorization")?.to_str()?; // e.g., Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyIjoidXNlcjEifQ.sign
let query = format!("SELECT * FROM profiles WHERE user_id = '{}'", token); // Unsafe string interpolation
let result = sqlx::query(&query).fetch_one(&pool).await?;

If the token is attacker-controlled (e.g., a forged token like ' OR 1=1 --), the resulting SQL becomes:

SELECT * FROM profiles WHERE user_id = '' OR 1=1 --'

This demonstrates how an authorization header can be weaponized to bypass intended access controls and expose all rows. Even when tokens are validated by an identity provider, the API must treat all external input—including headers—as untrusted. The risk is compounded if the token is long-lived or improperly scoped, increasing the impact of a successful injection (information disclosure, data modification, or privilege escalation).

Additionally, if the API dynamically builds queries using string formatting for table or column names derived from token metadata (such as tenant identifiers), the injection surface extends beyond literal values to schema objects. This aligns with the BOLA/IDOR and Input Validation checks in middleBrick’s 12 parallel scans, which flag unsafe string usage and missing parameterization. An attacker may probe for such patterns by sending crafted bearer tokens and observing error messages or anomalous behavior, which middleBrick’s unauthenticated scanning can detect through runtime analysis without credentials.

Bearer Tokens-Specific Remediation in Actix — concrete code fixes

Remediation centers on strict separation of code and data by using parameterized queries and avoiding any direct interpolation of header values into SQL. Never embed bearer token values or any other external input into SQL strings. Instead, bind token values as parameters and validate their format before use.

Correct usage with sqlx in Actix:

use actix_web::{web, HttpRequest, Result};
use sqlx::PgPool;

async fn get_profile(req: HttpRequest, pool: web::Data<PgPool>) -> Result<impl actix_web::Responder> {
    // Extract bearer token; this is external input and must not be directly interpolated.
    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::ErrorBadRequest("Invalid header encoding"))?;
    let token = auth_str.strip_prefix("Bearer ").unwrap_or(auth_str); // Remove "Bearer " prefix if present

    // Validate token format (e.g., length, allowed characters) before using it as a parameter.
    if token.len() < 10 {
        return Err(actix_web::error::ErrorBadRequest("Invalid token"));
    }

    // Use parameterized query: token is passed as a bound value, not string concatenation.
    let profile = sqlx::query_as!(
    Profile,
    "SELECT id, user_id, email FROM profiles WHERE user_id = $1",
    token
    )
    .fetch_optional(pool.as_ref())
    .await?;

    match profile {
        Some(p) => Ok(web::Json(p)),
        None => Err(actix_web::error::ErrorNotFound("Profile not found")),
    }
}

In this example, token is never inserted into the SQL string; it is supplied as a bound parameter ($1), ensuring that even if the token contains SQL metacharacters, they are treated as data. This directly mitigates SQL Injection risks and aligns with OWASP API Top 10 A03:2023 Injection. middleBrick’s scans will flag any endpoint that concatenates headers into queries and provide prioritized findings with severity and remediation guidance.

Additional hardening steps include validating token structure (e.g., rejecting tokens with comment sequences or unexpected characters) and applying consistent input validation across all endpoints. If you use the middleBrick CLI (middlebrick scan <url>) or GitHub Action, you can integrate these checks into your CI/CD pipeline to fail builds when unsafe patterns are detected. The Dashboard helps track improvements over time, and the Pro plan supports continuous monitoring with configurable alerts.

Related CWEs: inputValidation

CWE IDNameSeverity
CWE-20Improper Input Validation HIGH
CWE-22Path Traversal HIGH
CWE-74Injection CRITICAL
CWE-77Command Injection CRITICAL
CWE-78OS Command Injection CRITICAL
CWE-79Cross-site Scripting (XSS) HIGH
CWE-89SQL Injection CRITICAL
CWE-90LDAP Injection HIGH
CWE-91XML Injection HIGH
CWE-94Code Injection CRITICAL

Frequently Asked Questions

Can middleBrick detect SQL Injection risks in Actix APIs that use bearer tokens?
Yes. middleBrick runs unauthenticated black-box scans that include Input Validation and BOLA/IDOR checks, identifying unsafe string usage and missing parameterization regardless of authentication requirements.
Does middleBrick provide specific guidance for fixing SQL Injection in Actix?
Yes. Each finding includes severity, a clear description, and remediation guidance, such as using parameterized queries and avoiding concatenation of headers into SQL strings.