HIGH zip slipactixbasic auth

Zip Slip in Actix with Basic Auth

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

Zip Slip is a path traversal vulnerability that occurs when an API constructs file paths from user-supplied input without proper validation. In Actix, a Rust web framework, this often manifests through route parameters or query values used to build filesystem paths, such as extracting archives or serving files. When Basic Auth is used, the presence of an Authorization header can change how requests are processed, but it does not reduce the risk if the application treats authenticated requests as trusted.

Specifically, in Actix with Basic Auth, a developer might check credentials early in a handler or middleware and then proceed to use unchecked user input to access files. Because Basic Auth is often perceived as a gatekeeper, developers may incorrectly assume that once authentication passes, the request path is safe. This misconception can lead to skipping path sanitization for authenticated requests, making the endpoint vulnerable to Zip Slip when handling filenames from archives, uploads, or dynamically generated resources.

During a middleBrick scan that includes OpenAPI/Swagger spec analysis, the tool cross-references the declared authentication scheme (e.g., securitySchemes with type: http and scheme: basic) with runtime behavior. If the spec indicates Basic Auth protection but the runtime logic does not enforce path validation for authenticated calls, middleBrick flags this as a high-severity finding. The scanner tests unauthenticated attack surfaces as well as authenticated-style inputs to detect whether path traversal is possible when credentials are supplied.

Real-world examples of this pattern include handlers that extract a filename parameter from a request and join it with a base directory using Rust's std::path::Path without normalization. An attacker can supply paths such as ../../../etc/passwd or archive traversal sequences to escape the intended directory. middleBrick detects these patterns and maps them to OWASP API Top 10 and related frameworks, providing remediation guidance that emphasizes strict input validation regardless of authentication state.

Basic Auth-Specific Remediation in Actix — concrete code fixes

To mitigate Zip Slip in Actix when Basic Auth is used, ensure that all user-controlled path components are validated, sanitized, and resolved against a strict base directory. Authentication should be treated as a separate concern from path safety. Below are concrete, syntactically correct examples that demonstrate secure handling in Actix with Basic Auth.

First, use middleware to validate and normalize paths before they reach business logic. Combine authentication checks with path canonicalization to prevent directory traversal regardless of auth status.

use actix_web::{web, App, HttpResponse, HttpServer, Responder};
use actix_web::http::header::HeaderValue;
use actix_web::middleware::from_fn;
use std::path::{Path, PathBuf};

async fn validate_path(path: &str) -> Result {
    let base = Path::new("/safe/base/directory");
    let requested = Path::new(path);
    // Prevent traversal: ensure the normalized path starts with the base
    let full = base.join(requested).canonicalize()
        .map_err(|_| actix_web::error::ErrorBadRequest("Invalid path"))?;
    if full.starts_with(base) {
        Ok(full)
    } else {
        Err(actix_web::error::ErrorBadRequest("Path traversal detected"))
    }
}

async fn basic_auth_middleware(req: actix_web::dev::ServiceRequest) -> Result {
    if let Some(auth_header) = req.headers().get("Authorization") {
        if let Ok(auth_str) = auth_header.to_str() {
            if auth_str.starts_with("Basic ") {
                // In real use, decode and validate credentials against a secure store
                return Ok(req);
            }
        }
    }
    Err(actix_web::error::ErrorUnauthorized("Missing or invalid Basic Auth"))
}

async fn download_file(path: web::Path) -> impl Responder {
    match validate_path(&path).await {
        Ok(full_path) => HttpResponse::Ok()
            .content_type("application/octet-stream")
            .body(full_path.to_string_lossy().into_owned()),
        Err(e) => HttpResponse::BadRequest().body(e.to_string()),
    }
}

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    HttpServer::new(|| {
        App::new()
            .wrap(from_fn(basic_auth_middleware))
            .route("/files/{path}", web::get().to(download_file))
    })
    .bind("127.0.0.1:8080")?
    .run()
    .await
}

In this example, the validate_path function ensures that any user-supplied path is joined with a fixed base directory and canonicalized. The middleware performs Basic Auth checks but does not grant implicit trust in the path. This separation of concerns prevents Zip Slip regardless of authentication outcome. middleBrick can verify that such validation is present and report findings when path sanitization is missing or inconsistent across authenticated routes.

Additionally, prefer using crates like sanitize-filename or custom allowlists for filenames when accepting uploads or generating archives. Avoid concatenating raw user input into filesystem paths, and always resolve paths with canonicalize before access. These practices reduce the attack surface and align with secure coding guidance referenced in middleBrick findings.

Frequently Asked Questions

Can Basic Auth alone prevent Zip Slip in Actix APIs?
No. Basic Auth handles identity verification but does not protect against path traversal. Zip Slip depends on how paths are constructed and validated, so you must sanitize and canonicalize all user input regardless of authentication.
How does middleBrick detect Zip Slip risks in Actix APIs with Basic Auth?
middleBrick scans the OpenAPI/Swagger spec to identify Basic Auth requirements and runtime tests to check whether user-controlled path parameters are properly validated and confined. It flags cases where authentication is present but path traversal protections are missing or inconsistently applied.