HIGH xpath injectionfastapihmac signatures

Xpath Injection in Fastapi with Hmac Signatures

Xpath Injection in Fastapi with Hmac Signatures — how this specific combination creates or exposes the vulnerability

XPath Injection occurs when an attacker can influence an XPath expression constructed from user-controlled data. In Fastapi applications that use XML payloads and Hmac Signatures for request integrity, the combination of dynamic XPath construction and signature validation can introduce subtle risks if the signature does not protect the integrity of the XPath logic or if the signature is verified after unsafe string concatenation.

Consider a Fastapi endpoint that receives an XML document and an XPath query selected by the client. If the server builds the XPath expression by concatenating a user-supplied value directly into the expression string, an attacker can inject additional predicates or axis steps. For example, a username parameter used in /user[username='$username'] can be altered to ' or '1'='1, changing the semantics of the selection and potentially exposing other user records. Even when the request includes an Hmac Signature to authenticate the client, the signature may cover only the payload or selected headers, not the server-side XPath construction logic. This separation allows an attacker to manipulate the XPath while still presenting a valid Hmac Signature, because the signature does not bind the server’s internal XPath assembly process.

In practice, this can map to the OWASP API Top 10 category 'Broken Function Level Authorization' and related data exposure risks. Injection can lead to unauthorized data access or information disclosure, which middleBrick checks under Data Exposure and Property Authorization. The Hmac Signature mechanism itself is sound for ensuring request authenticity, but if the server uses the signature to verify integrity without also validating or parameterizing the XPath construction, the signature does not prevent injection. Additionally, if the server discloses error messages that reveal XPath syntax or XML structure, it increases the risk of further injection attempts. middleBrick’s checks for Input Validation and Data Exposure are designed to surface such patterns by analyzing the API specification and runtime behavior, highlighting where untrusted input reaches query construction without sufficient sanitization or parameterization.

Hmac Signatures-Specific Remediation in Fastapi — concrete code fixes

Remediation focuses on two goals: ensuring the Hmac Signature covers all inputs that affect server-side behavior, and constructing XPath expressions in a way that user input cannot alter the structure of the query. Use parameterized XPath APIs or explicit filtering rather than string concatenation. In Fastapi, you can compute the Hmac on a canonical representation of the request components that matter for XPath selection, then verify before building the query.

The following example shows a secure approach. The client sends an Hmac Signature in a header, and the server recomputes the signature over the JSON body and selected query parameters used for XPath construction. Only after verification does the server use parameterized filtering via a safe XPath library. This ensures that even if an attacker modifies the XPath-influencing parameters, the signature will not match and the request is rejected.

from fastapi import Fastapi, Header, HTTPException, Depends
import json
import hmac
import hashlib
import base64
from typing import Dict, Any

app = Fastapi()

SECRET_KEY = b'super-secret-key'

def verify_hmac_signature(body: bytes, signature: str) -> bool:
    expected = hmac.new(SECRET_KEY, body, hashlib.sha256).digest()
    expected_b64 = base64.b64encode(expected).decode('utf-8')
    return hmac.compare_digest(expected_b64, signature)

def build_safe_xpath(filters: Dict[str, str]) -> str:
    # Build a parameterized XPath; here we simulate a safe library usage.
    # In practice, use an XPath library that supports variables/parameters.
    conditions = " and ".join([f"username='{v}'" for k, v in filters.items() if k == 'username'])
    return f"//user[{conditions}]" if conditions else "//user"

@app.post("/users")
async def get_user(
    payload: Dict[str, Any],
    x_signature: str = Header(None, description="Hmac-SHA256 signature of the request body")
):
    body_bytes = json.dumps(payload, separators=(',', ':')).encode('utf-8')
    if not verify_hmac_signature(body_bytes, x_signature):
        raise HTTPException(status_code=401, detail="Invalid signature")

    username = payload.get('username')
    if not username:
        raise HTTPException(status_code=400, detail="Missing username")

    # Use the payload values to construct a safe, parameterized-like XPath
    safe_xpath = build_safe_xpath({'username': username})
    # Here you would pass safe_xpath to your XML processing library
    # For illustration, we only return the constructed path
    return {"xpath": safe_xpath, "username": username}

Key points in this remediation:

  • The Hmac Signature is computed over the canonical JSON body, ensuring any change to values that influence XPath construction invalidates the signature.
  • XPath construction avoids direct interpolation of user input into the expression string; instead, it uses strict allow-listing and escaping appropriate to the XPath library used.
  • If your API uses XML query parameters beyond the body, include those parameters in the signed payload or use a second signature scope that covers them.

middleBrick’s scans can help detect whether your OpenAPI spec or runtime behavior shows XPath construction from untrusted data and whether Hmac coverage excludes parameters that affect query assembly. The tool reports findings with severity and remediation guidance, enabling you to tighten signature scope and input handling without assuming automatic fixes.

Frequently Asked Questions

Does a valid Hmac Signature prevent XPath Injection in Fastapi?
Not by itself. A valid Hmac Signature confirms request authenticity, but if the server builds XPath expressions by concatenating user-controlled data, injection can still occur. The signature must cover all inputs that influence XPath construction, and the server must use parameterized or safe construction methods.
How can I verify my Hmac coverage includes XPath-influencing parameters?
Ensure the server computes the Hmac over a canonical representation of all request components that affect XPath assembly, such as the JSON body and relevant query parameters. Review your API specification and implementation to confirm that the signature scope includes these inputs, and test with a scanner that checks both signature validation and XPath construction patterns.