HIGH open redirectnestjsapi keys

Open Redirect in Nestjs with Api Keys

Open Redirect in Nestjs with Api Keys — how this specific combination creates or exposes the vulnerability

An open redirect occurs when an application redirects a user to an arbitrary URL supplied in the request. In NestJS applications that rely on API keys for access control, this risk can appear when a redirect parameter is accepted from the client without strict validation and the API key is used to authorize access to the redirect flow. Even when authentication is enforced via an API key, an attacker can craft a URL such as /auth/login?api_key=VALID_KEY&next=https://evil.com. If the route handler uses the API key only to decide whether the request is allowed and then follows the next parameter without verifying its value, the valid API key becomes a mechanism that helps the attacker bypass casual checks while the application performs the redirect on behalf of a trusted source.

Because middleBrick scans unauthenticated attack surfaces, it can detect open redirect patterns even when API keys are present, provided the endpoint exposes a redirect parameter and does not validate it. The presence of an API key does not mitigate a missing validation or a lack of allowlisting. In NestJS, common causes include using raw query parameters in res.redirect(), failing to parse and sanitize the target, or trusting HTTP referrer headers to decide the destination. Attackers may combine these weaknesses with social engineering, embedding malicious links in emails or documentation that appear to originate from a trusted domain protected by an API key.

Another relevant pattern is when API keys are passed in headers or query strings and the endpoint unconditionally redirects based on a dynamic location derived from request data. For example, a handler might read a target field from the request body after verifying the key, then forward the client to that target. middleBrick’s checks for input validation and authentication will highlight whether the redirect destination is constrained to a safe set of values or whether it accepts arbitrary external URLs. This combination of permissive routing and key-based access control can unintentionally signal to clients that the redirect is safe because a key was presented, while the real issue is an incomplete validation chain.

Api Keys-Specific Remediation in Nestjs — concrete code fixes

Remediation focuses on strict validation, allowlisting, and avoiding dynamic redirects based on untrusted input, even when an API key is present. Below are concrete examples for a NestJS controller that uses API keys via a custom guard and query parameters.

Example 1: Allowlisted destinations with a record map

import { Controller, Get, Query, Redirect, Req } from '@nestjs/common';

const ALLOWED_REDIRECTS: Record = {
  dashboard: 'https://app.example.com/dashboard',
  settings: 'https://app.example.com/settings',
  profile: 'https://app.example.com/profile',
};

@Controller('auth')
export class AuthController {
  @Get('login')
  @Redirect()
  login(
    @Query('api_key') apiKey: string,
    @Query('target') targetKey: string,
  ) {
    // API key validation would happen earlier in the guard; assume verified
    const resolved = ALLOWED_REDIRECTS[targetKey];
    if (!resolved) {
      // Fallback to a safe default
      return { url: 'https://app.example.com/home' };
    }
    return { url: resolved };
  }
}

Example 2: Validate against a protocol+host allowlist

import { Controller, Get, Query, Redirect, Req, BadRequestException } from '@nestjs/common';
import { URL } from 'url';

const ALLOWED_ORIGINS = new Set(['https://app.example.com', 'https://staging.example.com']);

@Controller('auth')
export class AuthController {
  @Get('redirect')
  @Redirect()
  redirectUser(
    @Query('api_key') apiKey: string,
    @Query('url') urlParam: string,
  ) {
    let target: URL;
    try {
      target = new URL(urlParam);
    } catch {
      throw new BadRequestException('Invalid URL');
    }

    if (!ALLOWED_ORIGINS.has(target.origin)) {
      throw new BadRequestException('Redirect target not allowed');
    }

    // Additional sanity checks: ensure path is safe, no unexpected fragments
    return { url: target.toString() };
  }
}

Example 3: Using a whitelist regex for safe paths

import { Controller, Get, Query, Redirect, BadRequestException } from '@nestjs/common';

const SAFE_PATH_REGEX = /^\/dashboard|\/settings|\/profile$/;

@Controller('auth')
export class AuthController {
  @Get('redirect')
  @Redirect()
  redirectWithPatternCheck(
    @Query('api_key') apiKey: string,
    @Query('path') path: string,
  ) {
    if (!SAFE_PATH_REGEX.test(path)) {
      throw new BadRequestException('Path not allowed');
    }
    // Ensure path is still relative to prevent open redirect via hostname manipulation
    return { url: path };
  }
}

In all examples, the API key is treated as an authentication factor and does not influence the validation of the redirect target. middleBrick can highlight whether your endpoints validate destinations correctly and whether they inadvertently trust user-supplied URLs. By combining API key protection with strict allowlists and input validation, you reduce the risk of open redirect while preserving legitimate post-login navigation flows.

Frequently Asked Questions

Does using an API key prevent open redirect vulnerabilities in NestJS?
No. An API key can authenticate the request but does not validate the redirect destination. Without strict allowlisting or pattern checks, an attacker can supply a malicious URL and leverage the API key to pass casual checks.
How does middleBrick detect open redirect risks in endpoints that require API keys?
middleBrick tests the unauthenticated attack surface and can flag endpoints that accept redirect parameters without validating or restricting their values. API key presence is noted, but the scanner focuses on whether validation and safe routing controls are missing.