HIGH cryptographic failuressailsapi keys

Cryptographic Failures in Sails with Api Keys

Cryptographic Failures in Sails with Api Keys — how this specific combination creates or exposes the vulnerability

Cryptographic failures occur when applications fail to protect sensitive data in transit or at rest. In Sails.js, combining weak cryptographic practices with improper handling of API keys can expose secrets and enable account compromise or service abuse. API keys are long-lived credentials often embedded in configuration files, environment variables, or request headers. When transmitted or stored without strong cryptography, they become high-value targets for attackers.

In Sails, a common pattern is to pass API keys via headers (e.g., x-api-key) or query parameters. If these requests are sent over unencrypted HTTP, the keys are exposed in clear text to anyone on the network. Even when HTTPS is used, implementation errors such as missing HTTP Strict Transport Security (HSTS), weak cipher suites, or improper certificate validation can weaken the cryptographic protection. Additionally, logging API keys—intentionally or inadvertently—creates persistent secrets in log files, which may be accessible to unauthorized parties.

OWASP API Security Top 10 lists cryptographic failures as a primary concern. For API keys in Sails, this maps to the Cryptographic Failures category. Attackers can exploit these weaknesses to intercept traffic (man-in-the-middle), replay captured requests, or use exposed keys to call downstream services on behalf of the application. The risk is compounded when API keys have broad permissions, as is typical in microservice architectures. Unlike tokens designed for short lifetimes, API keys often persist for months or years, increasing the window of exposure.

middleBrick scans for these issues by checking whether API keys are transmitted over unencrypted channels, whether secure transmission headers are present, and whether sensitive data appears in logs or error messages. The scanner also detects whether responses inadvertently include API keys or cryptographic artifacts, which can lead to unintended data exposure. These checks are part of the Data Exposure and Encryption categories in the 12 parallel security checks, ensuring that cryptographic failures related to API keys are identified early in development.

Api Keys-Specific Remediation in Sails — concrete code fixes

Remediation focuses on ensuring API keys are always transmitted and stored using strong cryptography, and that their exposure surface is minimized. In Sails, enforce HTTPS across the application, avoid logging keys, and use environment variables for configuration.

1. Enforce HTTPS and secure headers

Configure Sails to require HTTPS and set security headers. In config/http.js, enable the secure flag for cookies and ensure HSTS is active in production.

// config/http.js
module.exports.http = {
  secure: true, // Ensures cookies are only sent over HTTPS
  hsts: {
    enabled: true,
    maxAge: 31536000,
    includeSubDomains: true
  },
  middleware: {
    order: ['startRequestTimer', 'cookieParser', 'session', 'bodyParser', 'compress', 'poweredBy', 'httpHeaders', 'csrf', 'www', 'favicon', '404', '500']
  }
};

2. Pass API keys securely via headers

Always use headers rather than query parameters for API keys. Query strings are often logged in server and proxy logs. In your controller or service, read the key from the request header and validate it against a stored secret.

// api/controllers/ExternalController.js
module.exports = {
  callExternalService: async function (req, res) {
    const apiKey = req.header('x-api-key');
    if (!apiKey) {
      return res.status(401).json({ error: 'Missing API key' });
    }
    // Validate format (example: simple regex pattern)
    if (!/^ak_live_[a-zA-Z0-9]{32}$/.test(apiKey)) {
      return res.status(403).json({ error: 'Invalid API key' });
    }
    // Use the key to call an external API securely
    try {
      const response = await sails.helpers.externalApi.call(apiKey);
      return res.ok(response);
    } catch (err) {
      return res.serverError(err);
    }
  }
};

3. Use environment variables and avoid logging

Store API keys in environment variables and access them via process.env. Never hardcode keys in models or controllers. Also, ensure that logs do not capture sensitive headers.

// config/env/production.js
module.exports = {
  api: {
    key: process.env.EXTERNAL_API_KEY
  }
};

// services/externalApi.js
module.exports = {
  call: async function (apiKey) {
    const axios = require('axios');
    return axios.get('https://api.external.com/data', {
      headers: { 'x-api-key': apiKey },
      timeout: 5000
    });
  }
};

4. Validate and rotate keys

Implement validation logic to ensure keys conform to expected patterns and rotate them periodically. Use middleware to check key scope and revocation status where applicable.

// api/policies/validateApiKey.js
module.exports = async function (req, res, next) {
  const key = req.header('x-api-key');
  if (!key) return res.status(401).send('Unauthorized');
  // Example: check against a list of valid keys from a secure store
  const isValid = await sails.helpers.validateKey(key);
  if (!isValid) return res.status(403).send('Forbidden');
  return next();
};

Frequently Asked Questions

How does middleBrick detect cryptographic failures related to API keys?
middleBrick checks whether API keys are transmitted over unencrypted protocols, whether secure headers like HSTS are set, and whether keys appear in logs or error responses.
Can API keys be safely passed via query parameters in Sails?
No. Query parameters are often logged in server and proxy logs, increasing exposure risk. Always use headers such as x-api-key and enforce HTTPS to protect API keys.