HIGH integrity failuresflaskapi keys

Integrity Failures in Flask with Api Keys

Integrity Failures in Flask with Api Keys — how this specific combination creates or exposes the vulnerability

An integrity failure occurs when an API does not sufficiently verify that a request has not been tampered with in transit or by an untrusted component. In Flask applications that rely on API keys for authorization, integrity failures often stem from treating the key as proof of authenticity without also proving that the request itself is authentic and unmodified.

Consider a Flask route that expects an API key in a header:

from flask import Flask, request, jsonify

app = Flask(__name__)

VALID_KEYS = {"sk_live_abc123", "sk_test_xyz789"}

@app.route("/admin/export")
def admin_export():
    key = request.headers.get("X-API-Key")
    if key not in VALID_KEYS:
        return jsonify({"error": "forbidden"}), 403
    # Proceed with sensitive operation
    return jsonify({"status": "export started"})

If the API key is transmitted over HTTP or is stored and compared in an unsafe way (e.g., using a plain substring check or logging the key), an attacker can intercept or manipulate the request. Integrity failures in this context include:

  • Transmission without integrity protection: API keys sent over unencrypted channels can be captured and reused (e.g., via passive sniffing or insecure reverse proxies), enabling request tampering or replay.
  • Key leakage in logs or error messages: Including the key in logs or returning it inadvertently in error responses can expose secrets that an attacker can use to forge authenticated requests.
  • Lack of request signing: When the API key is used only as a bearer token without additional integrity protection (such as signing the request payload), an attacker who can influence any part of the request (headers, query parameters, or body) may be able to modify the intent of the operation while still presenting a valid key.
  • Insecure storage on the client side: Keys embedded in JavaScript or mobile app binaries can be extracted and reused to impersonate legitimate clients.

These weaknesses map to common findings in the BOLA/IDOR and Property Authorization checks, and they can enable privilege escalation or data exposure when combined with other flaws. For example, an attacker who steals an API key might exploit a BOLA flaw to access or modify resources belonging to other users, or abuse insufficient input validation to inject malicious commands. The LLM/AI Security checks do not directly test integrity of key transmission, but they do verify that endpoints handling keys do not leak system prompts or expose keys in model outputs.

middleBrick scans such endpoints in black-box mode, identifying whether API keys are transmitted insecurely, logged improperly, or accepted without integrity verification. The scan provides a security risk score and prioritized findings with remediation guidance, helping teams detect integrity-related weaknesses without requiring internal architecture details.

Api Keys-Specific Remediation in Flask — concrete code fixes

Remediation focuses on ensuring integrity of requests that carry API keys, protecting keys in transit and at rest, and avoiding unsafe handling patterns.

1. Enforce HTTPS for all API traffic

Ensure the application is served exclusively over TLS so that API keys cannot be observed in transit. In production, terminate TLS at the load balancer or WSGI server and configure Flask to require secure cookies and strict transport security.

2. Use HMAC request signing instead of bare API keys

Rather than sending the API key as a simple bearer token, have the client sign the request with a shared secret. The server verifies the signature before processing the request. This prevents tampering with headers, query parameters, or body.

import hmac
import hashlib
import time

def verify_signed_request(request, secret):
    timestamp = request.headers.get("X-Timestamp")
    signature = request.headers.get("X-Signature")
    if not timestamp or not signature:
        return False
    # Reject old requests to prevent replay
    if abs(time.time() - int(timestamp)) > 300:
        return False
    payload = f"{timestamp}{request.method}{request.path}{request.get_data(as_text=True)}"
    expected = hmac.new(secret.encode(), payload.encode(), hashlib.sha256).hexdigest()
    return hmac.compare_digest(expected, signature)

@app.route("/admin/export", methods=["POST"])
def admin_export_signed():
    if not verify_signed_request(request, "{{shared_secret}}"):
        return jsonify({"error": "invalid signature"}), 403
    return jsonify({"status": "export started"})

3. Avoid logging or exposing API keys

Ensure request logs do not capture header values that contain API keys. Sanitize inputs and outputs, and never return keys in JSON responses or error messages.

@app.before_request
def strip_keys_from_logs():
    # Remove sensitive headers from request context used by logging
    request.sanitized_headers = {k: v for k, v in request.headers if k.lower() != "x-api-key"}

4. Rotate keys and scope them to least privilege

Use distinct keys per integration and scope them to specific endpoints or operations. Rotate keys regularly and revoke compromised keys immediately.

5. Combine with additional integrity checks

Use CSRF protection for browser-based consumers and validate all inputs rigorously to prevent injection or parameter tampering that could leverage a stolen key.

Using the CLI, you can scan your Flask endpoints to detect insecure key handling:

middlebrick scan https://api.example.com/openapi.json

For teams integrating security into development workflows, the GitHub Action can fail builds when risk scores exceed your defined threshold, while the MCP Server enables scanning APIs directly from AI coding assistants within your IDE. The Dashboard lets you track these scores and findings over time.

Frequently Asked Questions

Can API key headers be safely logged if masked partially?
Partial masking reduces accidental exposure but does not prevent reconstruction or leakage in structured logs. Avoid logging API keys entirely; instead log request IDs and use key identifiers without the secret.
Is sending API keys in query strings acceptable over HTTPS?
No. Query strings may be logged in server logs, browser history, and proxy logs, and can be exposed via referrer headers. Use headers with strong integrity protections instead.