HIGH api key exposurefeathersjssession cookies

Api Key Exposure in Feathersjs with Session Cookies

Api Key Exposure in Feathersjs with Session Cookies — how this specific combination creates or exposes the vulnerability

FeathersJS is a framework for creating JavaScript APIs with a service-oriented architecture. When session cookies are used for stateful authentication, developers may inadvertently expose API keys through insecure handling of session data and related endpoints. This combination can lead to sensitive information being included in logs, responses, or error messages, and can facilitate information leakage if session management is not strictly isolated from key management.

One common pattern is storing an API key in the session object after authentication, for example during an OAuth flow or service integration. If the session is serialized into responses, transmitted in URLs, or written to server-side logs without redaction, the API key can be exposed to unauthorized parties. For instance, a developer might attach the key to the session for downstream service calls:

// Example: attaching an API key to the session in a FeathersJS hook
app.hooks({
  after: {
    create: [context => {
      if (context.result && context.result.apiKey) {
        context.params.session.apiKey = context.result.apiKey;
      }
      return context;
    }]
  }
});

If context.params.session is later serialized into a response (e.g., via an error stack trace, debug endpoint, or insecurely rendered template), the key can be exposed. Additionally, if the session store is not properly isolated between services, an attacker who compromises one service might enumerate or infer API keys linked to other services via shared session identifiers.

Another vector involves CORS and cookie handling. If FeathersJS is configured to allow credentials across origins without strict validation, an attacker can leverage cross-origin requests to trick the server into including session cookies—and thus any attached API keys—in responses to malicious origins. Misconfigured cors options can therefore amplify exposure:

// Example: insecure CORS configuration that may expose session cookies
const corsConfig = {
  origin: '*',
  credentials: true
};
app.use(cors(corsConfig));

Furthermore, if error handling inadvertently includes session contents in stack traces or HTTP responses (for example, returning a 500 with detailed session data), API keys stored in the session become exposed through standard error channels. This is particularly risky when combined with logging mechanisms that do not filter sensitive fields.

Insecure deserialization of session data can also play a role. If an attacker can tamper with or replay session cookies, and the server trusts the contents without validation, they may be able to inject or extract API keys stored in the session. This underscores the need to treat session data as untrusted input and to validate and sanitize any values derived from it.

Session Cookies-Specific Remediation in Feathersjs — concrete code fixes

To mitigate exposure, treat session cookies as untrusted and ensure API keys are never stored in or derived from session data that may be serialized, logged, or exposed. Use short-lived tokens for service-to-service authentication instead of baking keys into sessions.

First, avoid attaching API keys to the session. If you must store sensitive material, use environment variables or a secure secrets manager, and reference them by identifier rather than by value:

// Secure approach: do not store API keys in session
app.hooks({
  after: {
    create: [context => {
      // Use a session identifier only; fetch key from secure store at call time
      const serviceId = context.params.session.serviceId;
      context.params.apiKey = await getApiKeyFromVault(serviceId);
      return context;
    }]
  }
});

Second, enforce strict CORS settings to prevent credentials from being sent cross-origin unintentionally:

// Secure CORS configuration
const corsConfig = {
  origin: 'https://your-trusted-domain.com',
  credentials: true
};
app.use(cors(corsConfig));

Third, ensure session cookies are marked as HttpOnly, Secure, and have SameSite=Strict or Lax to reduce exposure via client-side scripts or cross-origin requests:

// Secure cookie settings in FeathersJS
const sessionMiddleware = require('express-session');
app.use(sessionMiddleware({
  name: 'api_sid',
  secret: process.env.SESSION_SECRET,
  cookie: {
    httpOnly: true,
    secure: process.env.NODE_ENV === 'production',
    sameSite: 'strict',
    maxAge: 24 * 60 * 60 * 1000
  },
  resave: false,
  saveUninitialized: false
}));

Fourth, sanitize and redact any session-related data before logging or error reporting. Use a custom error formatter that strips sensitive fields:

// Redact session data in errors
app.use((err, req, res, next) => {
  if (req && req.params && req.params.session) {
    const safeSession = { ...req.params.session };
    delete safeSession.apiKey;
    delete safeSession.token;
    err.public = { session: safeSession };
  }
  next(err);
});

Fifth, validate and scope session contents on each request. Do not trust deserialized session values; re-derive or re-fetch sensitive identifiers from a trusted source:

// Validate session content before use
app.hooks({
  before: {
    all: [context => {
      const { session } = context.params;
      if (!session || typeof session.userId !== 'number') {
        throw new Error('Invalid session');
      }
      // Re-fetch service credentials from secure store, not session
      context.params.serviceId = session.serviceId;
      return context;
    }]
  }
});

Finally, prefer token-based authentication for API-to-API communication and reserve session cookies for browser-based sessions. This reduces the surface area where API keys might leak through session serialization or client-side handling.

middleBrick capabilities relevant to this scenario

middleBrick can scan a FeathersJS endpoint to detect insecure session handling and accidental API key exposure as part of its Data Exposure and Unsafe Consumption checks. Using the CLI, you can run a quick black-box scan without credentials:

middlebrick scan https://api.example.com

The scan completes in 5–15 seconds and produces a prioritized finding with remediation guidance. If you integrate middleBrick into your development workflow, the GitHub Action can enforce a minimum security score before merging, and the MCP Server allows you to initiate scans directly from your IDE while you code.

Note that middleBrick detects and reports issues—it does not fix or block. Use its findings to adjust hooks, tighten CORS, and remove sensitive data from session objects.

Frequently Asked Questions

Can session cookies alone cause API key exposure in FeathersJS?
Session cookies do not inherently expose API keys; exposure occurs when API keys are stored in session data that is serialized, logged, or transmitted insecurely. Mitigate by avoiding storage of keys in sessions and enforcing HttpOnly, Secure, and SameSite cookie attributes.
Does middleBrick fix the exposed API key findings it reports?
middleBrick detects and reports findings with remediation guidance; it does not automatically fix, patch, or block. Developers must apply the recommended changes, such as removing keys from session objects and tightening cookie settings.