HIGH open redirectrestifyapi keys

Open Redirect in Restify with Api Keys

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

An open redirect in a Restify service that uses Api Keys occurs when an endpoint accepts a user-controlled redirect target (typically via a query parameter such as next or redirect_uri) and uses that value in a response that instructs the client to navigate elsewhere. If the endpoint also relies on Api Keys for identification rather than strong authentication, the redirect can be leveraged in phishing or token disclosure scenarios. For example, an endpoint like /login?api_key=KEY&next=https://evil.com may validate the Api Key and then perform a 302 redirect to the provided next URL. Because the Api Key is tied to the client application, an attacker who can trick a user into using a crafted link might be able to redirect the user’s authenticated session to a malicious site while the Api Key remains valid for the duration of the interaction.

From a scanning perspective, middleBrick performs unauthenticated checks against such endpoints, including the BFLA/Privilege Escalation and Input Validation test suites. It examines whether the API accepts a redirect target, whether the supplied target is validated against an allowlist, and whether the Api Key is exposed in redirects or logs. Without proper validation, an API can inadvertently assist phishing campaigns or enable cross-site request forgery-like abuse where the Api Key is used as a credential but the redirect undermines the trust boundary. The presence of Api Keys does not inherently prevent open redirects; it changes the threat model by tying the redirect to a specific client credential that may be reused across sessions.

In practice, this combination is risky when the redirect logic does not enforce strict allowlisting and does not require additional user consent or context-bound tokens. Even if the Api Key identifies the calling application, the application must still ensure that the redirect target is safe and consistent with the intended user flow. middleBrick’s checks for Property Authorization and System Prompt Leakage (in products that interface with LLM endpoints) are not directly relevant here, but the scanner will flag missing input validation and missing rate limiting as contributing factors that increase the likelihood of abuse.

Api Keys-Specific Remediation in Restify — concrete code fixes

To remediate open redirect issues in Restify when using Api Keys, validate and restrict redirect targets and ensure Api Key usage does not leak into unsafe flows. Below are concrete, working examples that demonstrate a safe approach.

1. Validate redirect target against an allowlist

Do not trust user-supplied URLs. Compare the provided redirect target against a strict list of permitted origins or paths.

const restify = require('restify');

const server = restify.createServer();
const ALLOWED_REDIRECT_HOSTS = new Set(['https://app.example.com', 'https://myapp.example.com']);

server.get('/login', (req, res, next) => {
  const { api_key, next: redirectTarget } = req.query;

  // Validate Api Key presence (pseudocode; integrate with your auth scheme)
  if (!isValidApiKey(api_key)) {
    return res.send(401, { error: 'invalid_api_key' });
  }

  // Validate redirect target
  let targetUrl;
  try {
    targetUrl = new URL(redirectTarget);
  } catch (err) {
    return res.send(400, { error: 'invalid_redirect' });
  }

  if (!ALLOWED_REDIRECT_HOSTS.has(targetUrl.origin)) {
    return res.send(400, { error: 'redirect_not_allowed' });
  }

  // Safe redirect with a one-time token or short-lived session cookie instead of raw user input
  const safeToken = generateSessionTokenForUser(api_key);
  res.setHeader('Set-Cookie', `session=${safeToken}; Path=/; HttpOnly; Secure; SameSite=Lax`);
  return res.redirect(302, targetUrl.pathname + targetUrl.search);
});

function isValidApiKey(key) {
  // Replace with your key verification logic (e.g., lookup in a store)
  return typeof key === 'string' && key.length > 0;
}

function generateSessionTokenForUser(api_key) {
  // Generate a short-lived, server-side session token
  return 'sess_' + api_key.slice(-8) + '_' + Date.now();
}

2. Use a server-side redirect map instead of raw user input

Replace open redirects with a server-controlled mapping so the client receives only safe, known paths.

server.get('/auth/callback', (req, res, next) => {
  const { api_key, provider, state } = req.query;

  if (!isValidApiKey(api_key)) {
    return res.send(401, { error: 'invalid_api_key' });
  }

  // Map provider to a safe destination
  const destinations = {
    sso: '/dashboard/sso',
    payment: '/dashboard/payment',
  };

  const destination = destinations[provider];
  if (!destination) {
    return res.send(400, { error: 'invalid_provider' });
  }

  // Optionally validate state for CSRF protection
  if (!state || !isValidState(state, api_key)) {
    return res.send(400, { error: 'invalid_state' });
  }

  return res.redirect(302, destination + (state ? '?state=' + encodeURIComponent(state) : ''));
});

function isValidState(state, api_key) {
  // Implement state verification (e.g., HMAC with api_key as key)
  return true; // simplified
}

These examples ensure that Api Key validation occurs before any redirect decision, and that redirect targets are never directly reflected from user input. middleBrick’s CLI can be used to confirm that such patterns are present and that no open redirect vectors remain. To scan your service from the terminal, use: middlebrick scan <url>. For CI/CD enforcement, the GitHub Action can fail builds when findings related to open redirects or weak validation are detected, helping maintain secure deployment gates.

Frequently Asked Questions

Does using Api Keys prevent open redirects in Restify?
No. Api Keys identify callers but do not validate redirect targets. Without strict allowlisting of redirect destinations, open redirect vulnerabilities remain possible even when Api Keys are required.
How can I test my Restify endpoints for open redirects using middleBrick?
Run middleBrick’s unauthenticated scan against your endpoint with a crafted redirect parameter (e.g., ?next=https://evil.com). The scanner reports whether user-controlled redirect targets are reflected without validation and maps findings to relevant checks such as Input Validation and BFLA/Privilege Escalation.