HIGH email injectionadonisjsapi keys

Email Injection in Adonisjs with Api Keys

Email Injection in Adonisjs with Api Keys — how this combination creates or exposes the vulnerability

Email injection in AdonisJS when API keys are used for authentication can occur when user-controlled input is passed into email-related functions without proper validation or escaping. AdonisJS typically uses nodemailer under the hood to send emails, and if developer code directly interpolates user-supplied data into email headers or body content, an attacker can inject additional headers or malformed content. This is a classic injection vector against the Email Sending security check in middleBrick, which tests whether inputs are validated and encoded before being used by the mail subsystem.

When API keys are involved, they are often handled as environment variables or configuration values that authenticate the outbound mail service (for example, using an SMTP provider). If an API key is logged, exposed in error messages, or if the application uses the key to authorize requests that also accept user input for email composition, the combination increases the risk of information leakage or misuse. For instance, an attacker might supply a crafted email address or header value to trigger verbose errors that reveal the API key or service configuration. middleBrick’s Email Injection and Data Exposure checks look for such patterns by analyzing the unauthenticated attack surface and correlating runtime findings with the OpenAPI spec where endpoints accept email-related payloads.

Consider an endpoint that accepts a JSON body with recipient, subject, and message fields, and then uses a mailer utility that includes the API key for SMTP authentication. If the recipient field is not validated, an attacker can provide a value like [email protected]\r\nCC: [email protected], which may cause the mailer to add an unintended CC header. If the application also exposes configuration details in stack traces (e.g., via a debug route or error page), the API key used for SMTP may be disclosed. middleBrick’s checks for Input Validation and Data Exposure are designed to detect missing sanitization and inadvertent exposure of sensitive configuration, including API keys that may appear in logs or responses.

An example of vulnerable code might look like:

import { Mail } from '@ioc:Adonis/Addons/Mail';

export async function sendContactEmail({ request }) {
  const { name, email, message } = request.body();
  // user input directly used in headers/content without strict schema validation
  await Mail.send((message) => {
    message
      .from('[email protected]')
      .to(email)
      .subject(name)
      .htmlView('contact/email', { message });
  });
}

In this snippet, the email and name fields are used without validation, and if an error occurs during sending, internal paths or configuration (including API keys from environment) might be exposed through detailed error pages. middleBrick’s LLM/AI Security checks are not applicable here because this scenario does not involve LLM endpoints, but the scan’s Email Injection and Data Exposure findings highlight the need for input sanitization and safe error handling.

Api Keys-Specific Remediation in Adonisjs — concrete code fixes

To remediate email injection and protect API keys in AdonisJS, validate and sanitize all user input used in email headers and bodies, and ensure API keys are never exposed in logs, responses, or error messages. Use schema validation to enforce strict types and patterns for email fields, and configure mailers to read SMTP credentials from environment variables without exposing them through application code or error payloads.

Below is a secure example using AdonisJS mail with explicit validation and safe handling of API-related configuration:

import Mail from '@ioc:Adonis/Addons/Mail';
import { schema, rules } from '@ioc:Adonis/Core/Validator';

const emailSchema = schema.create({
  email: schema.string({}, [rules.email(), rules.normalizeEmail()]),
  name: schema.string({}, [rules.minLength(2), rules.maxLength(120)]),
  message: schema.string({}, [rules.minLength(10), rules.maxLength(2000)]),
});

export async function sendContactEmail({ request }) {
  const payload = await request.validate({ schema: emailSchema });

  await Mail.send((message) => {
    message
      .from('[email protected]')
      .to(payload.email)
      .subject('Contact form submission')
      .htmlView('contact/email', { message: payload.message });
  });
}

In this version, the email field is normalized and validated, preventing newline characters that could facilitate injection. The API key used for SMTP authentication should be stored in .env and referenced via Env.get('SMTP_KEY') in your mail configuration, never echoed or returned to the client. For example, your config/mail.ts might include:

import { Env } from '@ioc:Adonis/Core/Env';

export default {
  connection: 'smtp',
  smtp: {
    host: Env.get('SMTP_HOST'),
    port: Env.get('SMTP_PORT'),
    username: Env.get('SMTP_USER'),
    password: Env.get('SMTP_KEY'), // API key kept out of code and logs
    secure: true,
  },
};

Additionally, ensure error handling does not leak sensitive information. Use generic error messages for users and log detailed issues server-side without exposing API keys. middleBrick’s Data Exposure and Encryption checks help verify that configurations and keys are not inadvertently surfaced in responses or logs.

Frequently Asked Questions

How does middleBrick detect email injection risks in AdonisJS APIs that use API keys?
middleBrick runs unauthenticated black-box scans with 12 parallel security checks, including Input Validation and Data Exposure, to identify missing sanitization and inadvertent exposure of sensitive configuration such as API keys in email-related flows.
Can the middleBrick CLI be used to scan an AdonisJS API for email injection and API key exposure?
Yes; you can run the CLI with the command middlebrick scan to perform a scan from the terminal and receive JSON or text output with prioritized findings and remediation guidance.