HIGH email injectionchijwt tokens

Email Injection in Chi with Jwt Tokens

Email Injection in Chi with Jwt Tokens — how this specific combination creates or exposes the vulnerability

Email Injection in the Chi web framework occurs when user-controlled input is directly interpolated into email-related operations such as headers, recipient lists, or message bodies without proper validation or encoding. When this pattern exists in an API that issues or validates JWT tokens, the risk expands into authentication and authorization workflows. For example, an endpoint that accepts a user-supplied email address to construct a password-reset link or a token delivery message may embed the email value into SMTP headers or into a JWT claim that is later reflected in an email body. If the input is not sanitized, an attacker can inject newline characters or additional headers, causing the application to send messages to unintended recipients, execute unintended commands in the mail subsystem, or forge authentication-related notifications.

In a JWT-centric design, the combination is particularly sensitive because JWT tokens often carry identity information such as email in claims. If an API endpoint accepts an email parameter, builds a JWT with that email, and then uses the same email in an SMTP operation, an attacker can supply crafted input like attacker@example.com\r\nCc: victim@example.com. Depending on how the server-side mail library processes headers, this can lead to email spoofing, header injection, or unauthorized message relay. Because JWT tokens are commonly used for stateless authentication and session management, any tampering or leakage of identity-related claims can undermine trust in the token flow. middleBrick detects this class of issue in its Email Injection checks, testing how user input propagates through both the Chi application logic and any associated mail delivery paths.

Moreover, because Chi routes often bind path parameters, query strings, and JSON bodies directly into handler arguments, developers may inadvertently pass raw values into mail functions while also encoding them into JWTs for downstream verification. The scanner exercises combinations such as registering a new user, capturing the email input, and observing whether injected control characters alter the behavior of SMTP interactions or token usage. Findings include missing input sanitization, lack of strict type constraints on email fields, and improper separation between data and header boundaries. These patterns are surfaced with severity and remediation guidance in the per-category breakdown provided by middleBrick, which references the OWASP API Top 10 and common secure coding practices for handling identity data.

Jwt Tokens-Specific Remediation in Chi — concrete code fixes

To remediate Email Injection risks in Chi when working with JWT tokens, enforce strict validation and canonicalization of email inputs before using them in both JWT claims and mail operations. Treat email addresses as structured data: parse and normalize them using a dedicated library, and reject any input that does not conform to a precise pattern. Avoid string concatenation for constructing email headers or JWT payloads; instead, use typed structures and serialization functions that guarantee safe encoding. The following Chi handler demonstrates a secure approach where the email is validated, used to build a JWT, and then safely passed to a mail function that treats the address purely as data.

open Ring.Conn
open JWT
open Crypto.JWT

type Email = Email of string

let parseEmail (s: string) : Result Email string =
  if System.Text.RegularExpressions.Regex.IsMatch(s, "^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$")
  then Ok (Email s)
  else Error "Invalid email format"

let createToken (secret: string) (Email email: Email) : Result string string =
  let claims = [ Claims.sub email; Claims.claim "email" email ]
  let key = Key.fromString secret
  issue key claims
  |> Result.map (Jwt.encode >> Compact.serialize)

let sendVerificationEmail (Email email: Email) token =
  // Use a mail library that accepts structured recipients and headers
  let mail =
    { To = [ email ]
      Subject = "Verify your account"
      Body = sprintf "Please verify using token: %s" token }
  Mail.sendSmtp mail

let registerHandler (req: Request) =
  match req |> readJsonOpt<| { email: string } > with
  | None -> Results.badRequest "Missing email"
  | Some data -
> match parseEmail data.email with
    | Error msg -> Results.badRequest msg
    | Ok email -
> match createToken "your-256-bit-secret" email with
      | Error msg -> Results.internalError msg
      | Ok token -
> do
          sendVerificationEmail email token
          Results.ok "Registration acknowledged"

This pattern ensures that the email value is canonicalized early, preventing newline or header characters from reaching JWT or SMTP layers. The token is constructed from the validated email claim, and the mail function receives a clean, structured recipient list. In production, combine this with runtime monitoring and periodic scans using middleBrick, which can verify that no raw user input is directly interpolated into headers or claims. The CLI tool (middlebrick scan <url>) and the Web Dashboard make it easy to track these fixes over time, while the Pro plan can enforce continuous monitoring and CI/CD integration through GitHub Actions to prevent regressions.

Frequently Asked Questions

How does middleBrick detect Email Injection when JWT tokens are involved?
middleBrick tests unauthenticated endpoints that accept email inputs, then traces whether the value is reflected in JWT claims, used in mail operations, or returned in API responses. It checks for missing sanitization and header separation issues by injecting controlled newline and header sequences.
Can the GitHub Action fail builds if an Email Injection is found in Chi endpoints with JWT tokens?
Yes. By configuring the GitHub Action with a risk-score threshold, any scan finding a high-severity issue such as Email Injection will cause the build to fail, enforcing remediation before merge.