HIGH email injectionexpressbearer tokens

Email Injection in Express with Bearer Tokens

Email Injection in Express with Bearer Tokens — how this specific combination creates or exposes the vulnerability

Email Injection in Express applications using Bearer Tokens typically arises when user-controlled data is reflected into email headers or message bodies without proper validation, and the API relies on Bearer Token authentication for access control. In this setup, an attacker who obtains or guesses a valid Bearer Token might interact with an endpoint that processes email-related parameters (e.g., to, cc, from, or subject). If the server constructs email messages by directly concatenating these inputs into SMTP commands or template strings, newline characters (\n or \r\n) can break out of intended header boundaries.

Consider an Express route that sends a password reset email using a token-based API. If the route accepts a JSON payload with an email address and does not sanitize line breaks, an authenticated user with a valid Bearer Token could supply a value such as [email protected]\r\nCC: [email protected]. Poorly composed email logic may then forward the message to the injected address, enabling email spoofing, phishing, or information disclosure. This becomes more impactful when combined with Bearer Token misuse or leakage, because the token grants the attacker authenticated access to the endpoint, bypassing unauthenticated restrictions.

Moreover, if the same API exposes an unauthenticated or weakly protected endpoint that internally uses Bearer Token validation patterns (for example, checking tokens in headers but not enforcing strict scope or origin checks), an attacker might probe for IDOR or BOLA issues. In such cases, crafted email parameters could leak sensitive information or trigger unintended side effects. The combination of Bearer Token handling and unchecked email inputs exemplifies a broken access control and injection risk mapped to OWASP API Top 10 categories such as Broken Object Level Authorization and Injection.

middleBrick scans identify these patterns by correlating authentication mechanisms like Bearer Tokens with input validation and email-specific checks. The scanner runs active prompt injection tests and output scanning for PII or secrets, which helps surface logic flaws where authenticated interactions affect email workflows. Findings include severity ratings and remediation guidance, helping teams understand how improper input handling and token usage intersect to create exploitable paths.

Bearer Tokens-Specific Remediation in Express — concrete code fixes

To secure Express APIs that use Bearer Tokens and handle email-related inputs, apply strict validation, avoid direct concatenation of user data into email headers, and enforce principle of least privilege. Below are concrete code examples demonstrating secure practices.

1. Validate and sanitize email inputs
Use a robust validation library and normalize addresses before use. Never directly insert user input into email headers.

const express = require('express');
const nodemailer = require('nodemailer');
const validator = require('validator');

const app = express();
app.use(express.json());

app.post('/request-reset', (req, res) => {
  const { email } = req.body;
  const token = req.headers.authorization?.split(' ')[1]; // Bearer Token extraction

  if (!token) {
    return res.status(401).json({ error: 'Missing Bearer Token' });
  }

  if (!validator.isEmail(email)) {
    return res.status(400).json({ error: 'Invalid email address' });
  }

  const safeEmail = validator.normalizeEmail(email, { gmail_remove_dots: false });

  // Use transporter with secure service-specific config
  const transporter = nodemailer.createTransport({
    service: 'sendgrid',
    auth: {
      user: process.env.SENDGRID_USER,
      pass: process.env.SENDGRID_PASS,
    },
  });

  const mailOptions = {
    from: '[email protected]',
    to: safeEmail,
    subject: 'Password Reset Request',
    text: `You requested a reset. Use this token: ${token}`,
  };

  transporter.sendMail(mailOptions, (err, info) => {
    if (err) {
      return res.status(500).json({ error: 'Failed to send email' });
    }
    res.json({ message: 'Reset email sent', info: info.messageId });
  });
});

2. Enforce Bearer Token validation and scope checks
Verify tokens using a trusted library and confirm required scopes before processing sensitive operations.

const jwt = require('jsonwebtoken');

function verifyBearer(req, res, next) {
  const authHeader = req.headers.authorization;
  if (!authHeader || !authHeader.startsWith('Bearer ')) {
    return res.status(401).json({ error: 'Unauthorized' });
  }
  const token = authHeader.substring(7);
  try {
    const decoded = jwt.verify(token, process.env.JWT_SECRET);
    // Example scope check for email actions
    if (!decoded.scopes || !decoded.scopes.includes('email:write')) {
      return res.status(403).json({ error: 'Insufficient scope' });
    }
    req.user = decoded;
    next();
  } catch (err) {
    return res.status(401).json({ error: 'Invalid token' });
  }
}

app.post('/send-email', verifyBearer, (req, res) => {
  // Proceed with email logic after token and scope validation
  res.json({ message: 'Authorized' });
});

3. Use parameterized templates and header separation
Leverage template engines or dedicated mail libraries that separate headers from content, preventing injection via newlines.

const emailTemplate = (to, subject, body) => ({
  to: to,
  subject: subject,
  html: body,
});

app.post('/notify', verifyBearer, (req, res) => {
  const { recipient, subject, body } = req.body;
  if (!validator.isEmail(recipient)) {
    return res.status(400).json({ error: 'Invalid recipient' });
  }

  const mailOptions = emailTemplate(
    validator.normalizeEmail(recipient),
    subject.substring(0, 50), // limit length
    body
  );

  // send mail as shown earlier
  res.json({ message: 'Notification prepared safely' });
});

These measures reduce the risk of Email Injection when Bearer Tokens are used for authentication. They also align with middleware practices that enforce input validation, token verification, and least-privilege access. With proper implementation, endpoints remain robust against authenticated email manipulation attempts.

Frequently Asked Questions

How does middleBrick detect Email Injection risks in authenticated Express APIs?
middleBrick runs parallel security checks including Input Validation and Authentication. It analyzes OpenAPI specs for email-related parameters and tests authenticated endpoints using Bearer Tokens to detect improper handling of newline characters and header injection patterns.
Can the free plan be used to scan an Express API for Email Injection vulnerabilities?
Yes. The free plan provides 3 scans per month, allowing you to submit an Express API URL and receive a security risk score with findings related to Email Injection, Bearer Token usage, and input validation.