HIGH log injectionactixfirestore

Log Injection in Actix with Firestore

Log Injection in Actix with Firestore — how this specific combination creates or exposes the vulnerability

Log injection occurs when untrusted input is written directly into application logs without validation or sanitization. In an Actix web service that uses Google Cloud Firestore as a backend, risk arises when request data—such as user IDs, query parameters, or authentication tokens—are included in log statements without escaping newlines or control characters.

Consider an Actix handler that retrieves a document by ID and logs the operation:

async fn get_document(req: HttpRequest, firestore: web::Data) -> impl Responder {
    let doc_id = req.match_info().get("id").unwrap_or("");
    info!(target: "api", "Fetching document id={}", doc_id);
    match firestore.get_document(doc_id).await {
        Ok(doc) => HttpResponse::Ok().json(doc),
        Err(_) => HttpResponse::NotFound().finish(),
    }
}

If doc_id contains a newline (e.g., abc%0A%20%20malicious), the log line can be poisoned. Many logging frameworks interpret newlines as record separators, so the injected content may appear as a separate log entry. In structured JSON logging, a newline in a field can break parsers or split one logical event into multiple entries, complicating correlation and analysis.

In Firestore-backed Actix services, additional risk comes from logging queries or paths that include user-controlled values. For example, constructing a log message with a Firestore document path that contains line breaks or braces can distort log context:

let doc_path = format!("projects/{}/databases/(default)/documents/users/{}", project_id, user_id);
warn!(target: "firestore", "Access attempt path={}", doc_path);

If user_id includes carriage returns or brackets, it may interfere with log aggregation tools or create misleading entries that appear to reference non-existent paths. This can obscure real security events, such as privilege escalation attempts or malformed token usage.

Another scenario involves logging LLM-related operations if your service integrates AI features. For instance, logging system prompts or model outputs without filtering could inadvertently expose sensitive patterns or facilitate prompt injection artifacts in logs. middleBrick’s LLM/AI Security checks specifically test for system prompt leakage and output PII, which is complementary to ensuring logs do not become an injection vector.

Finally, Firestore security rules and audit logs should be monitored independently of application logs. Relying solely on application-side logging for security events—especially when user input shapes those logs—can create blind spots. Using middleware to normalize and sanitize log data before export helps reduce the attack surface presented by log injection in this stack.

Firestore-Specific Remediation in Actix — concrete code fixes

Remediation focuses on input validation, structured logging, and safe string handling. Never trust IDs, query parameters, or document paths. Sanitize before logging.

1. Validate and sanitize document IDs before using them in logs. Reject or encode control characters:

fn sanitize_id(input: &str) -> String {
    // Remove or replace newlines, carriage returns, and other control chars
    input.chars().filter(|c| !c.is_control()).collect()
}

Use this function when constructing log messages:

async fn get_document_safe(req: HttpRequest, firestore: web::Data) -> impl Responder {
    let raw_id = req.match_info().get("id").unwrap_or("");
    let doc_id = sanitize_id(raw_id);
    info!(target: "api", "Fetching document id={}", doc_id);
    // proceed with Firestore call using raw_id if needed, but log the sanitized version
}

2. Use structured logging with explicit field types to avoid delimiter ambiguity. For JSON logs, ensure string fields do not contain unescaped newlines:

use serde_json::json;
async fn get_document_structured(req: HttpRequest, firestore: web::Data) -> impl Responder {
    let raw_id = req.match_info().get("id").unwrap_or("");
    let log_entry = json!({
        "event": "fetch_document",
        "document_id": sanitize_id(raw_id),
        "timestamp": chrono::Utc::now().to_rfc3339(),
    });
    info!(target: "api", "{}", log_entry.to_string());
    // Firestore call omitted for brevity
    HttpResponse::Ok().finish()
}

3. When logging Firestore paths, avoid concatenating user input directly. Instead, use predefined path templates and parameterize safely:

async fn access_user_document(req: HttpRequest, firestore: web::Data) -> impl Responder {
    let user_id = req.match_info().get("user_id").unwrap_or("");
    let safe_user_id = sanitize_id(user_id);
    let doc_ref = firestore.client().document(&format!("users/{}", safe_user_id));
    // Use doc_ref for Firestore operations; log only safe references
    info!(target: "firestore", "Accessing user document ref={}", doc_ref);
    HttpResponse::Ok().finish()
}

4. For applications that also incorporate LLM endpoints, apply the same discipline to prompts and responses. middleBrick’s MCP Server can be used from IDEs to scan API endpoints, including those that involve AI interactions, ensuring log-friendly output and input validation across the stack.

5. Complement runtime protections with CI/CD checks. The middleBrick GitHub Action can enforce security thresholds before deployment, reducing the likelihood that vulnerable logging patterns reach production. This is especially valuable when new endpoints or log statements are added.

Frequently Asked Questions

How can I test if my Actix logs are vulnerable to injection via Firestore document IDs?
Send a request with encoded newline or carriage return in the document ID (e.g., /documents/abc%0A) and inspect raw logs. If the log line splits or changes structure, injection is possible. Use sanitization and structured JSON logging to confirm mitigation.
Does using Firestore structured logging eliminate log injection risks in Actix?
Structured logging reduces delimiter-related issues but does not eliminate injection if untrusted data is written into fields that are later concatenated or interpreted by log shippers. Always sanitize inputs and avoid embedding raw user-controlled strings in log fields.