All files / src/middleware rate-limiter.ts

84.14% Statements 69/82
82.85% Branches 29/35
90.9% Functions 10/11
83.75% Lines 67/80

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268                          9x               9x               9x     9x 9x           29x   5x                                 5x           9x 7x 3x 3x               6x               15x 15x 7x       8x 8x 1x     7x                               12x 12x     12x 7x       7x       12x     12x 11x     12x                             12x 12x 12x                             9x   29x   29x   16x 1x 1x       15x       15x   8x 2x 2x         6x 6x 6x           6x   6x 1x 1x   1x 1x               1x     5x 5x       7x 1x 1x     6x 6x 6x   6x   6x                               6x             9x       11x           2x          
/**
 * Rate Limiting Middleware
 *
 * Protects the MCP server from excessive anonymous requests.
 * Authenticated users are NOT rate limited to avoid impacting legitimate usage.
 *
 * Design principles:
 * - Per-IP rate limiting for anonymous requests (enabled by default)
 * - Authenticated users skip rate limiting (they've proven who they are)
 * - Standard rate limit headers (X-RateLimit-*)
 */
 
import { Request, Response, NextFunction, RequestHandler } from "express";
import {
  RATE_LIMIT_IP_ENABLED,
  RATE_LIMIT_IP_WINDOW_MS,
  RATE_LIMIT_IP_MAX_REQUESTS,
  RATE_LIMIT_SESSION_ENABLED,
  RATE_LIMIT_SESSION_WINDOW_MS,
  RATE_LIMIT_SESSION_MAX_REQUESTS,
} from "../config";
import { logger } from "../logger";
 
interface RateLimitEntry {
  count: number;
  resetAt: number;
}
 
// In-memory storage for rate limit tracking
const rateLimitStore = new Map<string, RateLimitEntry>();
 
// Cleanup interval (run every minute)
const CLEANUP_INTERVAL_MS = 60000;
let cleanupInterval: ReturnType<typeof setInterval> | null = null;
 
/**
 * Start the cleanup interval for expired entries
 */
function startCleanup(): void {
  if (cleanupInterval) return;
 
  cleanupInterval = setInterval(() => {
    const now = Date.now();
    let cleaned = 0;
 
    for (const [key, entry] of rateLimitStore.entries()) {
      if (entry.resetAt <= now) {
        rateLimitStore.delete(key);
        cleaned++;
      }
    }
 
    if (cleaned > 0) {
      logger.debug(`Rate limiter cleanup: removed ${cleaned} expired entries`);
    }
  }, CLEANUP_INTERVAL_MS);
 
  // Don't prevent process exit
  cleanupInterval.unref();
}
 
/**
 * Stop the cleanup interval
 */
export function stopCleanup(): void {
  if (cleanupInterval) {
    clearInterval(cleanupInterval);
    cleanupInterval = null;
  }
}
 
/**
 * Get the IP address from a request
 */
function getIpAddress(req: Request): string {
  return req.ip ?? req.socket.remoteAddress ?? "unknown";
}
 
/**
 * Check if request is authenticated (has valid session)
 */
function isAuthenticated(req: Request, res: Response): boolean {
  // Check for OAuth session ID set by auth middleware
  const oauthSessionId = res.locals.oauthSessionId as string | undefined;
  if (oauthSessionId) {
    return true;
  }
 
  // Check for MCP session ID header (indicates active session)
  const mcpSessionId = req.headers["mcp-session-id"] as string | undefined;
  if (mcpSessionId) {
    return true;
  }
 
  return false;
}
 
/**
 * Check and update rate limit for a key
 */
function checkRateLimit(
  key: string,
  windowMs: number,
  maxRequests: number
): {
  allowed: boolean;
  remaining: number;
  resetAt: number;
  total: number;
} {
  const now = Date.now();
  let entry = rateLimitStore.get(key);
 
  // Create or reset entry if expired
  if (!entry || entry.resetAt <= now) {
    entry = {
      count: 0,
      resetAt: now + windowMs,
    };
    rateLimitStore.set(key, entry);
  }
 
  // Check if limit exceeded
  const allowed = entry.count < maxRequests;
 
  // Increment count if allowed
  if (allowed) {
    entry.count++;
  }
 
  return {
    allowed,
    remaining: Math.max(0, maxRequests - entry.count),
    resetAt: entry.resetAt,
    total: maxRequests,
  };
}
 
/**
 * Set rate limit headers on response
 */
function setRateLimitHeaders(
  res: Response,
  info: { remaining: number; resetAt: number; total: number }
): void {
  res.set("X-RateLimit-Limit", info.total.toString());
  res.set("X-RateLimit-Remaining", info.remaining.toString());
  res.set("X-RateLimit-Reset", Math.ceil(info.resetAt / 1000).toString());
}
 
/**
 * Express middleware for rate limiting
 *
 * Behavior:
 * - Authenticated requests: NOT rate limited (trusted users)
 * - Anonymous requests: Rate limited by IP address
 *
 * When rate limit is exceeded, returns HTTP 429 with:
 * - Retry-After header
 * - JSON error body with details
 * - Standard rate limit headers
 */
export function rateLimiterMiddleware(): RequestHandler {
  // Start cleanup on first use
  startCleanup();
 
  return (req: Request, res: Response, next: NextFunction): void => {
    // Skip health check endpoint (monitoring should always work)
    if (req.path === "/health") {
      next();
      return;
    }
 
    // Check if user is authenticated
    const authenticated = isAuthenticated(req, res);
 
    // Authenticated users skip rate limiting by default
    // (they've proven who they are and shouldn't suffer security measures)
    if (authenticated) {
      // Only apply session rate limit if explicitly enabled
      if (!RATE_LIMIT_SESSION_ENABLED) {
        next();
        return;
      }
 
      // Apply per-session rate limiting (optional)
      const sessionId =
        (res.locals.oauthSessionId as string) || (req.headers["mcp-session-id"] as string);
      const key = `session:${sessionId}`;
      const info = checkRateLimit(
        key,
        RATE_LIMIT_SESSION_WINDOW_MS,
        RATE_LIMIT_SESSION_MAX_REQUESTS
      );
 
      setRateLimitHeaders(res, info);
 
      if (!info.allowed) {
        const retryAfter = Math.ceil((info.resetAt - Date.now()) / 1000);
        logger.warn(`Session rate limit exceeded for ${sessionId}`);
 
        res.set("Retry-After", retryAfter.toString());
        res.status(429).json({
          error: "Too Many Requests",
          message: "Session rate limit exceeded. Please slow down your requests.",
          retryAfter,
          limit: info.total,
          remaining: info.remaining,
          resetAt: new Date(info.resetAt).toISOString(),
        });
        return;
      }
 
      next();
      return;
    }
 
    // Anonymous request - apply IP-based rate limiting
    if (!RATE_LIMIT_IP_ENABLED) {
      next();
      return;
    }
 
    const ip = getIpAddress(req);
    const key = `ip:${ip}`;
    const info = checkRateLimit(key, RATE_LIMIT_IP_WINDOW_MS, RATE_LIMIT_IP_MAX_REQUESTS);
 
    setRateLimitHeaders(res, info);
 
    Iif (!info.allowed) {
      const retryAfter = Math.ceil((info.resetAt - Date.now()) / 1000);
      logger.warn(`IP rate limit exceeded for ${ip}`);
 
      res.set("Retry-After", retryAfter.toString());
      res.status(429).json({
        error: "Too Many Requests",
        message: "Rate limit exceeded. Please authenticate or slow down your requests.",
        retryAfter,
        limit: info.total,
        remaining: info.remaining,
        resetAt: new Date(info.resetAt).toISOString(),
      });
      return;
    }
 
    next();
  };
}
 
/**
 * Get current rate limit stats (for debugging/monitoring)
 */
export function getRateLimitStats(): {
  totalEntries: number;
  entries: Array<{ key: string; count: number; resetAt: Date }>;
} {
  const entries = Array.from(rateLimitStore.entries()).map(([key, entry]) => ({
    key,
    count: entry.count,
    resetAt: new Date(entry.resetAt),
  }));
 
  return {
    totalEntries: rateLimitStore.size,
    entries,
  };
}