HIGH xpath injectionadonisjsjwt tokens

Xpath Injection in Adonisjs with Jwt Tokens

Xpath Injection in Adonisjs with Jwt Tokens — 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 AdonisJS, this often arises when authentication or role checks rely on XML-based identity stores or when XPath is built dynamically using request parameters, query values, or headers. Combining this with JWT tokens increases risk because tokens frequently carry user claims (such as username, roles, or groups) that may be used to construct or filter XPath expressions. If these claims are embedded directly into XPath logic without validation or escaping, an attacker can manipulate the token payload (e.g., by altering role claims) to change the XPath logic, bypassing intended filters or extracting additional data.

Consider an AdonisJS application that uses JWTs to determine user permissions and builds an XPath query against an XML user store to retrieve user details. A developer might write code that reads the username claim from the token and directly interpolates it into an XPath expression. An attacker who can influence the token—by using a weak signing key, exploiting a misconfigured issuer, or leveraging an insecure token acceptance flow—can inject malicious predicates into the XPath. For example, a token with username=admin' or '1'='1 could transform an intended lookup like //user[username='admin'] into //user[username='admin' or '1'='1'], returning all user nodes and enabling privilege escalation or data exposure.

Because middleBrick scans unauthenticated attack surfaces, it can detect endpoints where JWT tokens influence XPath construction without proper input validation. The scanner’s Input Validation and Property Authorization checks highlight places where untrusted data reaches XPath evaluations, and the LLM/AI Security module can flag patterns where token claims are used in security-sensitive queries. This combination makes the attack path more accessible: an attacker does not need to compromise the signing key outright; they only need to supply a token with a crafted payload if the application trusts client-controlled claims or lacks strict schema validation.

Real-world examples include XPath expressions built with template literals in JavaScript/TypeScript that concatenate claims directly, such as //user[username='${usernameFromToken}']. Without canonicalization, escaping, or strict type checks, this opens the door to classic XPath injection techniques like predicate manipulation or node traversal abuse. The OWASP API Top 10 category ‘2023:5:Broken Function Level Authorization’ and related data exposure risks align closely with this pattern, especially when sensitive XML resources are involved.

Jwt Tokens-Specific Remediation in Adonisjs — concrete code fixes

Remediation focuses on strict validation, canonicalization, and avoiding direct interpolation of token claims into XPath expressions. Treat JWT claims as untrusted input, even when they are signed, and enforce schema validation before use. Prefer parameterized or compiled XPath APIs where available, and apply principle of least privilege to data accessible via XPath queries.

Below are concrete, realistic examples for AdonisJS that demonstrate secure handling of JWT tokens and construction of XPath queries.

Secure JWT verification and claim validation

Always verify the token signature, issuer, audience, and expiration using a well-maintained library. Then validate claims against a strict schema.

import { base64urlDecode } from 'oslo/encoding'
import { createHmac } from 'crypto'
import { JwtPayload, decode as decodeJwt } from 'jose/jwt/decode'

interface UserClaims {
  sub: string
  username: string
  roles: string[]
}

function verifyAndValidateJwt(token: string, expectedIssuer: string, audience: string, publicKey: string): UserClaims {
  // Decode header to inspect algorithm and kid if needed
  const { protectedHeader, payload } = decodeJwt(token) as { protectedHeader: any; payload: Record }
  // Perform full verification with Jose or similar robust library
  const jwt = new jose.GeneralVerify(token, publicKey, { type: 'json', issuer: expectedIssuer, audience })
  const claims = await jwt.payload()

  // Strict claim checks
  if (!claims.username || typeof claims.username !== 'string' || !claims.roles || !Array.isArray(claims.roles)) {
    throw new Error('Invalid claims schema')
  }
  return claims
}

Avoid XPath injection by using parameterized approaches or safe builders

If you must work with XPath, use a library that supports compiled expressions or explicit parameter binding rather than string concatenation. If only native APIs are available, rigorously escape and whitelist values.

import { DOMParser } from 'xmldom'
import xpath from 'xpath'

// Assume xmlDoc is obtained from a trusted source, not user-controlled
function findUserByUsernameSafe(xmlDoc: Document, username: string): any[] {
  // Whitelist characters for username (alphanumeric and underscore)
  if (!/^[A-Za-z0-9_]+$/.test(username)) {
    throw new Error('Invalid username format')
  }
  // Use xpath.select with a precompiled expression where possible
  // Here we construct a safe expression using a variable binding pattern supported by xpath library
  const select = xpath.useNamespaces({ 'x': 'http://example.com/ns' })
  const nodes = xpath.select(`//x:user[x:username="${xpath.escape(username)}"]`, xmlDoc)
  return nodes
}

In this example, xpath.escape ensures that any special characters in the username are safely escaped within the string literal context of the XPath expression. Whitelisting further reduces injection surface. For stronger guarantees, prefer XPath implementations that support variable binding or compiled expressions, which separate structure from values entirely.

Additionally, apply the principle of least privilege: restrict the XML documents and node sets accessible via XPath to the minimum necessary for the operation. Combine this with role checks derived from the validated JWT claims, but ensure those checks are performed in a canonical, non-XPath-sensitive context (e.g., using an authorization service or policy engine) rather than encoding logic into the query itself.

middleBrick’s scans can help identify endpoints where JWT claims influence XPath logic without proper validation. Use the CLI (middlebrick scan <url>) or GitHub Action to detect these patterns in CI/CD, and refer to the findings to guide secure coding practices and input handling improvements.

Frequently Asked Questions

Can a JWT token with a manipulated claim directly cause XPath Injection in AdonisJS?
Yes, if the application uses JWT claims directly in XPath expressions without validation or escaping, manipulated claims can alter the XPath logic and enable injection.
Does middleBrick fix XPath Injection or JWT-related vulnerabilities automatically?
No, middleBrick detects and reports these issues with remediation guidance. Developers must apply fixes such as input validation, claim schema checks, and safe XPath construction.