HIGH prompt injectionactixhmac signatures

Prompt Injection in Actix with Hmac Signatures

Prompt Injection in Actix with Hmac Signatures — how this specific combination creates or exposes the vulnerability

When an Actix web service uses Hmac Signatures to authenticate requests, the assumption is that only trusted callers can invoke the endpoint. If the service also forwards user-controlled data to an LLM endpoint without strict validation, an authenticated request can become a vector for Prompt Injection. The attacker crafts a request with a valid Hmac Signature but places malicious instructions or data within parameters that reach the LLM. Because the server trusts the signature, it proceeds to call the LLM and may expose system prompts or allow instruction override through carefully designed inputs.

Consider an API that accepts a user query, appends it to a system prompt, and sends the combined text to an LLM. If the user query is not sanitized and the Hmac verification only checks the presence and correctness of the signature, an attacker can supply query text designed to jailbreak the model, such as asking the model to ignore prior instructions or reveal its system prompt. The valid Hmac Signature makes the request appear legitimate, but the content exploits the integration point between Actix and the LLM. This is especially relevant when the endpoint is unauthenticated from the LLM provider’s perspective (unauthenticated LLM endpoint), increasing the risk of unauthorized behavior or data exfiltration.

In a real scenario, an attacker might send a POST with JSON body containing a malicious prompt and a valid Hmac header. The Actix handler processes the signature, deserializes the body, and forwards the user-supplied fields to the LLM. Without output scanning for PII, API keys, or executable code, the LLM response might leak sensitive information or reveal internal logic. Because middleBrick’s active prompt injection testing includes system prompt extraction and instruction override probes, such integrations can be assessed without credentials, highlighting how a valid Hmac Signature does not prevent malicious content from influencing the model.

Additionally, if the Actix service uses tool_calls or function_call patterns, an attacker might embed instructions that cause the model to invoke functions in unintended ways. Excessive agency detection is designed to identify these patterns, but only if the service integrates such analysis. Without it, the combination of Hmac Signatures and LLM calls creates a blind spot where trusted transport masks harmful intent. Proper input validation and output scanning are essential to mitigate this class of risk.

middleBrick’s LLM/AI Security checks highlight these concerns by testing for system prompt leakage and output exposure. Even though Hmac Signatures protect the channel, they do not sanitize the content passed to the model. Integrating continuous monitoring and automated scans in the CI/CD pipeline using the GitHub Action can help detect regressions early, ensuring that new endpoints or model integrations do not inadvertently expose injection surfaces.

Hmac Signatures-Specific Remediation in Actix — concrete code fixes

To reduce Prompt Injection risk in Actix when using Hmac Signatures, validate and sanitize all user-supplied data before it reaches the LLM. Do not rely on the signature alone to ensure safety; treat the LLM call as an untrusted downstream component. Below are concrete remediation steps and code examples.

  • Verify the Hmac Signature and then explicitly filter or escape content used in prompts. For example, reject inputs that contain known jailbreak patterns or that attempt to inject instruction overrides.
  • Use strict schema validation for incoming JSON, ensuring that fields passed to the LLM conform to expected formats and do not contain unexpected keys that could alter behavior.
  • Implement output scanning for PII, API keys, and executable code before returning LLM responses to clients. This reduces the impact of accidental exposure through crafted inputs.
  • When using tool_calls or function_call, validate the function name and parameters against an allowlist to prevent unauthorized function invocation.

Example Actix handler with Hmac verification and input sanitization in Rust:

use actix_web::{post, web, HttpResponse, Responder};
use hmac::{Hmac, Mac};
use sha2::Sha256;
use serde::{Deserialize, Serialize};

// Type alias for HMAC-SHA256
 type HmacSha256 = Hmac<Sha256>;

#[derive(Deserialize)]
struct LlamaRequest {
    user_query: String,
    // other fields ...
}

#[derive(Serialize)]
struct LlamaResponse {
    content: String,
}

// Allowed set of functions if using tool_calls
const ALLOWED_FUNCTIONS: &[&str] = &["get_status", "search"];

fn verify_hmac(secret: &[u8], body: &[u8], received: &str) -> bool {
    let mut mac = HmacSha256::new_from_slice(secret).expect("HMAC can take key of any size");
    mac.update(body);
    match mac.verify_slice(received.as_bytes()) {
        Ok(_) => true,
        Err(_) => false,
    }
}

fn sanitize_query(input: &str) -> Option<String> {
    // Basic rejection of common jailbreak patterns; extend as needed
    let lower = input.to_lowercase();
    if lower.contains("ignore previous instructions") || lower.contains("system prompt") {
        return None;
    }
    Some(input.trim().to_string())
}

#[post("/chat")]
async fn chat(
    body: web::Json<LlamaRequest>,
    headers: actix_web::http::HeaderMap,
) -> impl Responder {
    let raw_body = match serde_json::to_vec(&body) {
        Ok(b) => b,
        Err(_) => return HttpResponse::BadRequest().finish(),
    };

    // Extract HMAC from header
    let received = match headers.get("X-Hub-Signature-256") {
        Some(h) => match h.to_str() {
            Ok(s) => s.trim_start_matches("sha256="),
            Err(_) => return HttpResponse::Unauthorized().finish(),
        },
        None => return HttpResponse::Unauthorized().finish(),
    };

    let secret = include_bytes!("../hmac_secret.key");
    if !verify_hmac(secret, &raw_body, received) {
        return HttpResponse::Unauthorized().finish();
    }

    // Input validation and sanitization
    let user_query = match sanitize_query(&body.user_query) {
        Some(q) => q,
        None => return HttpResponse::BadRequest().body("Invalid input"),
    };

    // Example: construct safe prompt
    let system_prompt = "You are a helpful assistant.";
    let prompt = format!("{}\nUser: {}", system_prompt, user_query);

    // Here you would call the LLM endpoint, ensuring it is either authenticated or
    // unauthenticated scanning is accounted for in your security posture.
    // For illustration, we return a sanitized response.
    let response = LlamaResponse { content: prompt };
    HttpResponse::Ok().json(response)
}

In this example, the handler verifies the Hmac Signature using a constant-time comparison, then explicitly sanitizes the user query to reject known jailbreak patterns. The sanitized prompt is constructed from a fixed system prompt and the cleaned user input. If tool_calls are used, validate function names against ALLOWED_FUNCTIONS before forwarding. Coupling this with continuous scanning via the middleBrick GitHub Action ensures that future changes do not reintroduce injection risks.

For teams using the Web Dashboard or CLI (middlebrick scan), schedule regular scans of the Actix endpoints to detect new findings. The CLI can be integrated into pre-commit hooks or CI to fail builds when risk scores degrade. These practices complement code-level fixes by providing ongoing visibility into the security posture of your API surface.

Related CWEs: llmSecurity

CWE IDNameSeverity
CWE-754Improper Check for Unusual or Exceptional Conditions MEDIUM

Frequently Asked Questions

Does a valid Hmac Signature guarantee the safety of LLM inputs in Actix?
No. Hmac Signatures authenticate the request but do not sanitize content. User data reaching the LLM must still be validated and screened for injection patterns.
Can middleBrick detect Prompt Injection in Actix endpoints protected by Hmac Signatures?
Yes. middleBrick’s active prompt injection testing sends probes including system prompt extraction and instruction override. These checks run against the live endpoint and can surface vulnerabilities even when Hmac Signatures are used, without requiring credentials.