HIGH sql injectionactixbasic auth

Sql Injection in Actix with Basic Auth

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

SQL Injection in Actix applications that rely on HTTP Basic Authentication can occur when user-controlled input from authentication credentials or related request parameters is concatenated into SQL queries without proper validation or parameterization. Basic Auth transmits credentials as a base64-encoded string in the Authorization header; while the encoding itself is not a security boundary, the decoded username and password can be mishandled by application code that builds SQL statements using string interpolation or concatenation.

Consider an Actix handler that extracts the username and password from Basic Auth headers and uses them to query a database for permissions or session data. If the code does not use prepared statements or an ORM with parameter binding, an attacker can supply crafted credentials such as admin' -- as the username. When these values are interpolated into a query like SELECT * FROM users WHERE username = '{username}' AND password = '{password}', the SQL syntax can be altered to bypass authentication or extract data. This pattern is common in custom authentication logic and can expose the unauthenticated attack surface that middleBrick scans, testing endpoints that should require credentials but instead reflect SQL errors or data leaks in responses.

Certain API designs exacerbate the risk. For example, if Actix endpoints expose user data based on identifiers derived from authenticated user claims (e.g., a user ID taken from a decoded JWT or session derived from Basic Auth), and those identifiers are used in dynamic SQL, the combination of weak authentication handling and unsafe query construction can lead to Authentication Bypass or unauthorized data access. middleBrick’s checks for Authentication and BOLA/IDOR can surface endpoints where authentication does not properly scope data access, while Input Validation checks detect signs of SQL Injection via unexpected payloads in credentials or related headers.

Real-world exploit patterns mirror classic SQL Injection techniques mapped to the OWASP API Top 10, such as using tautologies (username = ' OR '1'='1) or union-based extraction in credential fields. Because Basic Auth credentials are often reused across services, leaked error messages or inconsistent responses can reveal database structure or allow account takeover. The scanner’s tests for Data Exposure and Input Validation help identify endpoints where SQL errors are returned or sensitive data appears in responses, indicating improper query handling.

To illustrate, an unsafe Actix handler might look like this in Rust, demonstrating the risk when strings are passed directly to a SQL query builder:

// UNSAFE: string concatenation used to build SQL
async fn unsafe_login(user: String, pass: String) -> String {
    let query = format!("SELECT id, role FROM users WHERE username = '{}' AND password = '{}'", user, pass);
    // execute query …
    query
}

In this scenario, if user is supplied via Basic Auth and contains SQL metacharacters, the endpoint is vulnerable. middleBrick’s scans do not rely on internal architecture but focus on observable behavior, testing whether authentication vectors influence SQL-related behavior in ways that indicate injection risk.

Basic Auth-Specific Remediation in Actix — concrete code fixes

Remediation centers on eliminating string concatenation for SQL and ensuring credentials are treated as data, not executable syntax. Use parameterized queries or a type-safe query builder so that user input from Basic Auth (username and password) is never directly interpolated. In Actix, this means handling the Authorization header with a parsing helper, validating and hashing credentials server-side, and interacting with the database via prepared statements.

Below is a safe Actix example using sqlx with parameterized queries. The handler extracts Basic Auth, decodes the credentials, and passes them as bind parameters:

use actix_web::{web, HttpRequest, HttpResponse};
use base64::prelude::*;
use sqlx::postgres::PgPool;

async fn safe_login(
    req: HttpRequest,
    pool: web::Data,
) -> HttpResponse {
    let auth_header = match req.headers().get("authorization") {
        Some(h) => h.to_str().unwrap_or(""),
        None => return HttpResponse::Unauthorized().finish(),
    };
    if !auth_header.starts_with("Basic ") {
        return HttpResponse::Unauthorized().finish();
    }
    let encoded = auth_header.trim_start_matches("Basic ");
    let decoded = match BASE64_STANDARD.decode(encoded) {
        Ok(d) => d,
        Err(_) => return HttpResponse::Unauthorized().finish(),
    };
    let creds = match String::from_utf8(decoded) {
        Ok(s) => s,
        Err(_) => return HttpResponse::Unauthorized().finish(),
    };
    let parts: Vec<&str> = creds.splitn(2, ':').collect();
    if parts.len() != 2 {
        return HttpResponse::Unauthorized().finish();
    }
    let (username, password) = (parts[0].trim(), parts[1].trim());

    // Parameterized query prevents SQL Injection
    let user_record = sqlx::query!( 
        "SELECT id, role FROM users WHERE username = $1 AND password = $2",
        username,
        password
    )
    .fetch_optional(pool.get_ref())
    .await;

    match user_record {
        Ok(Some(rec)) => HttpResponse::Ok().json(rec),
        Ok(None) => HttpResponse::Unauthorized().finish(),
        Err(_) => HttpResponse::InternalServerError().finish(),
    }
}

Key practices include validating header format, using a constant-time comparison for credentials when possible, and storing passwords as hashes rather than plaintext. middleBrick’s Authentication and Input Validation checks can confirm that endpoints requiring Basic Auth do not reflect raw credentials in errors and that SQL-related inputs are properly parameterized.

For continuous assurance, the Pro plan’s GitHub Action can be configured to fail builds if risk scores degrade, integrating API security checks into CI/CD pipelines. This helps catch regressions where authentication logic or SQL handling changes inadvertently reintroduce SQL Injection risks. The CLI tool (middlebrick scan <url>) allows quick local verification, while the Web Dashboard tracks how remediation impacts your security score over time.

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 in Actix APIs that use Basic Auth?
Yes. middleBrick tests unauthenticated attack surfaces and can identify SQL Injection indicators such as error-based responses or data exposure when credentials are manipulated. It checks Authentication and Input Validation to highlight risky query patterns.
Does middleBrick provide automatic fixes for SQL Injection found in Actix endpoints?
No. middleBrick detects and reports findings with remediation guidance, but it does not fix, patch, or block code. Developers should apply parameterized queries and review authentication handling to address SQL Injection.