HIGH llm data leakageexpresshmac signatures

Llm Data Leakage in Express with Hmac Signatures

Llm Data Leakage in Express with Hmac Signatures — how this specific combination creates or exposes the vulnerability

When an Express API uses HMAC signatures to verify request integrity but inadvertently exposes data in error paths or logs, it can lead to LLM data leakage. This occurs when application behavior differs based on signature validity, allowing an unauthenticated attacker to probe endpoints and infer sensitive information through side channels. middleBrick’s LLM/AI Security checks specifically test for system prompt leakage and output exposure, which can be relevant when LLM integrations are present in an Express service.

Consider an Express route that verifies an HMAC signature and, upon failure, returns detailed debug information that includes model names, prompt templates, or internal identifiers. If the response is returned to an LLM agent or logged in a way that becomes part of training data, sensitive implementation details may be extracted. An attacker can send modified requests with invalid HMACs and analyze differences in responses, leading to extraction of system prompts or operational logic. This is especially risky when the Express app serves as a gateway to an LLM endpoint, because the leaked data may include instructions or context intended only for the model.

Using middleBrick’s active prompt injection testing, an attacker can attempt to extract system prompts even when the Express layer uses HMAC for request authentication. If the Express API does not uniformly handle invalid signatures and instead exposes stack traces, validation errors, or conditional logic branches, these responses may reveal whether a signature was valid and provide clues about the underlying codebase. The LLM/data leakage risk increases when the API returns different content types or structures depending on signature verification, enabling inference attacks that violate confidentiality expectations.

Real-world examples include an Express service that returns HTTP 200 with a JSON body containing debug: true and prompt_template: "Answer user queries about billing using model {{model_name}}" when HMAC verification fails, versus a generic 401 response when it succeeds. An attacker can iterate through guesses or use automated probes to map these differences. middleBrick’s Output Scanning checks for PII, API keys, and executable code in LLM responses, which can detect accidental inclusion of sensitive data that should never be exposed through any channel, including error paths influenced by signature checks.

Additionally, improper handling of HMAC verification in Express can lead to Insecure Direct Object References (IDOR) or BOLA when combined with weak access controls. If signature validation is bypassed or incorrectly implemented, an attacker might access resources they should not, and any LLM-integrated response that includes object identifiers or data references may leak relationships between resources. This aligns with the BOLA/IDOR checks in middleBrick, which test whether object-level authorization is consistently enforced regardless of authentication or signature validity.

Hmac Signatures-Specific Remediation in Express — concrete code fixes

To mitigate LLM data leakage risks when using HMAC signatures in Express, ensure consistent error handling, avoid leaking validation state, and enforce strict input and output sanitation. The following examples demonstrate secure patterns.

First, use a constant-time comparison to prevent timing attacks and ensure that validation failures do not reveal which part of the HMAC check failed.

const crypto = require('crypto');

function verifyHmac(req, secret) {
  const received = req.headers['x-hmac-signature'];
  const payload = JSON.stringify(req.body);
  const expected = crypto.createHmac('sha256', secret).update(payload).digest('hex');
  // Use timing-safe comparison
  return crypto.timingSafeEqual(Buffer.from(received), Buffer.from(expected));
}

app.post('/api/data', (req, res) => {
  const isValid = verifyHmac(req, process.env.HMAC_SECRET);
  // Always respond with the same structure and status regardless of signature validity
  if (!isValid) {
    return res.status(401).json({ error: 'Unauthorized' });
  }
  // Proceed with business logic
  res.json({ result: 'success' });
});

Second, avoid returning detailed errors or debug information in production. Use centralized error handling to ensure uniform responses.

app.use((err, req, res, next) => {
  // Log the full error internally for debugging
  console.error(err);
  // Return a generic response to the client
  res.status(500).json({ error: 'Internal server error' });
});

app.post('/api/data', (req, res) => {
  try {
    if (!verifyHmac(req, process.env.HMAC_SECRET)) {
      throw new Error('Invalid signature');
    }
    // Business logic that may involve LLM calls
    const result = callLlmModel(req.body);
    res.json({ result });
  } catch (err) {
    next(err);
  }
});

Third, ensure that any LLM responses are scanned before being returned or logged. With the Pro plan, continuous monitoring and GitHub Action integration can enforce security gates in CI/CD pipelines, reducing the risk of accidental data exposure during development. For teams using the CLI, running middlebrick scan https://your-express-api.com regularly helps detect misconfigurations that could lead to LLM data leakage.

Finally, apply the principle of least privilege and scope HMAC secrets to specific endpoints. Rotate secrets periodically and audit logs for anomalies. These practices complement the security checks provided by middleBrick’s scans, which map findings to frameworks such as OWASP API Top 10 and PCI-DSS, helping you maintain compliance while protecting against LLM-related data exposure.

Related CWEs: llmSecurity

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

Frequently Asked Questions

How can I test my Express API for LLM data leakage using middleBrick?
Run a scan with the CLI: middlebrick scan https://your-express-api.com. The scan includes LLM/AI Security checks that detect system prompt leakage and unsafe output exposure.
Does middleBrick provide automated fixes for HMAC-related data leakage?
middleBrick detects and reports findings with remediation guidance, but it does not automatically fix code. Use the provided guidance to adjust error handling and HMAC verification in your Express application.