HIGH api key exposuresailsbearer tokens

Api Key Exposure in Sails with Bearer Tokens

Api Key Exposure in Sails with Bearer Tokens — how this specific combination creates or exposes the vulnerability

When a Sails.js application uses Bearer Tokens for authentication, the risk of Api Key Exposure typically arises from insecure handling, transport, or storage practices rather than the token type itself. Bearer Tokens are simple credentials: whoever presents the token is assumed to be the owner. Because of this, if a token is leaked—through logs, error messages, client-side code, or insecure transport—it can be used by any attacker to impersonate the associated identity.

In Sails, developers often configure policies to check for tokens in the Authorization header using the format Authorization: Bearer <token>. If these tokens are generated with insufficient entropy, stored in client-side JavaScript or browser local storage, or transmitted over non-TLS connections, they become susceptible to exposure. For example, if a Sails backend accidentally includes the token in a server-side error stack trace that is returned to the client, an attacker who sees the error can reuse the token.

Another common exposure scenario involves misconfigured CORS or reverse proxy setups in front of Sails. If CORS headers are too permissive or if the proxy forwards the Authorization header to unintended origins, third-party scripts or malicious sites may read or relay the token. Similarly, logging middleware in Sails that prints incoming request headers—including the Authorization header—without sanitization can lead to tokens being written to log files that are accessible to unauthorized users or external logging services.

Additionally, if a Sails application embeds Bearer Tokens in frontend templates or bundles them with JavaScript assets that are publicly served, the tokens can be harvested by automated crawlers scanning for patterns that resemble tokens, such as long base64-like strings. Even when HTTPS is used, failing to set the Secure and HttpOnly flags for cookies that carry tokens (if used in that context), or not rotating tokens regularly, increases the window of opportunity for exposure.

Because middleBrick tests unauthenticated attack surfaces, it can detect scenarios where an API endpoint returns sensitive headers, exposes tokens in error responses, or lacks transport security. Findings from such scans can highlight whether Authorization headers are reflected in responses or whether TLS is consistently enforced, helping teams identify and reduce the window of Api Key Exposure involving Bearer Tokens in Sails.

Bearer Tokens-Specific Remediation in Sails — concrete code fixes

To reduce the risk of exposing Bearer Tokens in a Sails application, focus on secure generation, transmission, storage, and handling practices. Below are concrete remediation steps with code examples tailored to Sails v1.x.

1. Secure Token Generation

Ensure tokens are generated using a cryptographically strong random source. Avoid predictable values or low-entropy strings.

// Example: generating a secure random token using Node.js crypto module
const crypto = require('crypto');

function generateBearerToken(length = 64) {
  return crypto.randomBytes(length).toString('hex');
}

// Usage in a user login route (e.g., api/controllers/AuthController.js)
login: async function (req, res) {
  const { email, password } = req.body;
  const user = await User.findOne({ email });
  if (!user || user.password !== hashPassword(password)) {
    return res.unauthorized('Invalid credentials');
  }
  const token = generateBearerToken();
  // Store token securely server-side, e.g., in a Redis cache or database with user association
  await TokenService.storeToken(user.id, token);
  return res.ok({ token });
}

2. Transmit Tokens Only Over TLS and Validate Host

Always serve APIs over HTTPS and enforce strict transport security. In production, use a reverse proxy or load balancer to terminate TLS, but ensure headers are not stripped insecurely.

Configure Sails to trust the proxy correctly in config/http.js to avoid header spoofing:

// config/http.js
module.exports.http = {
  trustProxy: true, // Only enable if behind a trusted reverse proxy
  secure: true,     // Enforce secure (HTTPS) requests in production
};

3. Avoid Logging Sensitive Headers

Ensure request and response logging in Sails does not include the Authorization header. Customize the logger or disable header logging in production.

// Example: custom logging policy in config/log.js
module.exports.log = {
  level: 'info',
  // Exclude sensitive headers from being logged
  excludeHeaders: ['authorization', 'cookie'],
};

4. Store Tokens Securely on the Client

If the frontend is a single-page application, store Bearer Tokens in memory or in secure, HttpOnly cookies (with SameSite and Secure flags) rather than in local storage to reduce exposure via XSS.

When using cookies, configure them explicitly in Sails responses:

// Example: setting a secure cookie with a Bearer Token (or session reference)
res.setCookie('token', token, {
  httpOnly: true,
  secure: true,      // Only sent over HTTPS
  sameSite: 'strict',
  path: '/',
  maxAge: 1000 * 60 * 60 * 24, // 24 hours
});

5. Implement Token Rotation and Revocation

Use short-lived tokens and provide a mechanism to revoke compromised tokens. Maintain a server-side denylist or rely on a session store with expiration.

// Example: token validation policy (api/policies/bearer-auth.js)
module.exports.bearerAuth = async function (req, res, proceed) {
  const authHeader = req.headers('authorization');
  if (!authHeader || !authHeader.startsWith('Bearer ')) {
    return res.unauthorized('Authorization header missing or invalid format');
  }
  const token = authHeader.split(' ')[1];
  const isValid = await TokenService.validateToken(token); // checks expiry and denylist
  if (!isValid) {
    return res.unauthorized('Invalid or expired token');
  }
  return proceed();
};

6. Enforce CORS Strictly

Limit CORS origins to trusted domains and avoid wildcard origins when using credentials or tokens.

// config/cors.js
module.exports.cors = {
  origin: ['https://app.example.com'],
  credentials: true,
  exposedHeaders: [],
  methods: ['GET', 'POST', 'PUT', 'DELETE'],
};

Frequently Asked Questions

Can Bearer Tokens be safely stored in local storage in a Sails-powered single-page application?
No. Storing Bearer Tokens in local storage increases the risk of exposure via cross-site scripting (XSS). Prefer in-memory storage or secure, HttpOnly cookies with appropriate flags to reduce client-side exposure.
How does middleBrick help detect Api Key Exposure involving Bearer Tokens in Sails applications?
middleBrick scans the unauthenticated attack surface of your API and can identify whether Authorization headers containing Bearer Tokens are inadvertently reflected in responses, exposed in error messages, or transmitted without TLS, providing findings and remediation guidance.