HIGH xss cross site scriptingadonisjsmutual tls

Xss Cross Site Scripting in Adonisjs with Mutual Tls

Xss Cross Site Scripting in Adonisjs with Mutual Tls

Cross-site scripting (XSS) in an AdonisJS application that uses mutual TLS (mTLS) does not mean mTLS "causes" XSS. Instead, the combination exposes and amplifies risk because mTLS is often used to protect sensitive internal APIs and admin surfaces where the impact of XSS is higher. mTLS ensures the client presenting a certificate is known to the server; it does not validate or sanitize the data that authenticated client sends. If an authenticated, mTLS‑verified client submits a request containing malicious script—via query parameters, JSON bodies, or form fields—and that data is reflected into HTML responses without escaping, reflected XSS occurs. Because mTLS environments commonly serve admin dashboards or internal tools, the browser context may hold elevated privileges, increasing the blast radius.

AdonisJS does not provide automatic escaping for HTML responses; developers must explicitly escape output when injecting dynamic values into HTML, JavaScript strings, or attributes. Typical routes or controllers that render user-controlled data directly into templates are vulnerable. For example, returning res.send(`Hello, ${userInput}`) where userInput originates from a request (even one backed by mTLS) can lead to script execution. Stored XSS is also possible if untrusted data is saved and later rendered in admin views. The presence of mTLS may give a false sense of security, leading developers to skip input validation and output encoding, which is why the XSS attack surface remains significant despite strong transport-layer authentication.

With OpenAPI/Swagger spec analysis (2.0, 3.0, 3.1) and full $ref resolution, middleBrick cross-references spec definitions with runtime findings to highlight where user-supplied data enters the API surface. In an mTLS‑protected API, unchecked parameters can still lead to XSS when responses are consumed by browsers or admin tools. Prioritized findings include severity, a clear description, and remediation guidance, helping teams address the root cause: missing output encoding and insufficient input validation, not the presence of mTLS itself.

Mutual Tls-Specific Remediation in Adonisjs — concrete code fixes

Remediation focuses on secure handling of user input and strict output encoding. mTLS should be treated as an authentication mechanism, not a sanitization layer. Always validate and sanitize incoming data, and escape all dynamic content before embedding it in HTML, JavaScript, or CSS.

  • Validate and sanitize inputs using libraries like validator or AdonisJS sanitizers. Reject or transform unexpected characters and encodings.
  • Escape output based on context: HTML body, attribute, JavaScript, and URL require different escaping rules.
  • Use Content Security Policy (CSP) headers to reduce the impact of any potential injection.
  • Ensure mTLS client certificates are validated correctly and do not bypass authorization checks.

AdonisJS route examples: safe handling with mTLS

Safe controller method with escaping and validation:

// Safe handling in an AdonisJS controller
const { schema, rules } = use('@ioc:Adonis/Core/Validator')
const HttpContext = use('HttpContext')

export default class UserController {
  async showProfile({ request, response }) {
    // Validate incoming query/string inputs
    const validatedData = await request.validate({
      schema: schema.create({
        name: schema.string.optional([ rules.escape ]), // escapes HTML chars
        bio: schema.string.optional([ rules.sanitize ])  // strips dangerous chars
      })
    })

    // Simulate fetching user (mTLS has already authenticated the client)
    const user = {
      name: validatedData.name || 'Anonymous',
      bio: validatedData.bio || ''
    }

    // Explicitly escape when rendering into HTML
    response.send(`
      <h1>Profile</h1>
      <p>Name: ${this.escapeHtml(user.name)}</p>
      <p>Bio: ${this.escapeHtml(user.bio)}</p>
    `)
  }

  escapeHtml(str) {
    const div = document.createElement('div')
    div.textContent = str
    return div.innerHTML
  }
}

Setting CSP headers in AdonisJS middleware to mitigate impact:

// start/hooks.ts or a dedicated middleware file
import { Exception } from '@poppinss/utils'

export const cspMiddleware = async (ctx, next) => {
  ctx.response.header(
    'Content-Security-Policy',
    "default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data:;"
  )
  await next()
}

Example of unsafe pattern to avoid:

// UNSAFE: directly injecting user input into HTML response
const userInput = request.input('comment')
res.send(`<div>${userInput}</div>`) // No escaping — reflected XSS possible

By combining proper validation, context-aware escaping, and security headers, XSS risk is significantly reduced even in mTLS‑protected endpoints. middleBrick can scan such APIs to surface missing escapes and validation gaps, with findings mapped to OWASP API Top 10 and compliance frameworks.

Related CWEs: inputValidation

CWE IDNameSeverity
CWE-20Improper Input Validation HIGH
CWE-22Path Traversal HIGH
CWE-74Injection CRITICAL
CWE-77Command Injection CRITICAL
CWE-78OS Command Injection CRITICAL
CWE-79Cross-site Scripting (XSS) HIGH
CWE-89SQL Injection CRITICAL
CWE-90LDAP Injection HIGH
CWE-91XML Injection HIGH
CWE-94Code Injection CRITICAL

Frequently Asked Questions

Does mutual TLS prevent XSS in AdonisJS APIs?
No. Mutual TLS authenticates the client but does not validate or sanitize input. XSS is prevented by input validation, output encoding, and CSP — not by transport-layer authentication.
How can middleBrick help detect XSS in mTLS‑protected APIs?
middleBrick scans the unauthenticated attack surface and checks for missing output encoding and improper handling of user-controlled data, providing severity-ranked findings and remediation guidance mapped to frameworks like OWASP API Top 10.