HIGH api key exposurefeathersjsbasic auth

Api Key Exposure in Feathersjs with Basic Auth

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

FeathersJS is a popular Node.js framework for building REST and real-time APIs. When Basic Authentication is used without additional protections, developers risk unintentionally exposing API keys or other sensitive values that are embedded in client-side code, JavaScript bundles, or HTTP requests. This occurs because Basic Auth sends credentials as base64-encoded strings in the Authorization header (e.g., Authorization: Basic base64(username:password)), which is not encrypted unless TLS is enforced. If an API key is also passed in headers, query parameters, or within JavaScript that runs in the browser, an attacker who can observe or intercept traffic may correlate the Basic Auth context with the exposed key.

In Feathers, services are often configured with hooks and custom transports. A common pattern is to read an API key from environment variables and attach it to data or headers for downstream services. If this key is inadvertently included in responses, logs, or error messages, and Basic Auth is used for client authentication, the combination can amplify information leakage. For example, a misconfigured hook might forward the API key in an HTTP header to a third-party endpoint without validating whether the client is authorized to use that key. Because Basic Auth does not inherently scope permissions to the key itself, an attacker who compromises or observes a single request might infer relationships between users and backend service keys.

Another exposure pathway arises during unauthenticated or improperly configured endpoints. Feathers allows services to be declared with authentication: false, which can be useful for public APIs. However, if such endpoints proxy requests that include API keys in headers or query strings, and Basic Auth is used elsewhere in the app, an attacker may test whether these public endpoints reflect or leak the key. Additionally, if CORS is permissive and credentials are included, browsers may send Authorization headers to origins that should not receive them, increasing the risk of cross-origin exposure.

During a scan, tools like middleBrick assess whether API keys are exposed through unintended channels when Basic Auth is in use. Checks include verifying that sensitive values are not present in error responses, logs, or client-side JavaScript, and that transport-layer encryption is enforced. The scanner also examines whether Authorization headers are transmitted over non-TLS connections and whether endpoints that accept Basic Auth also expose keys through query parameters or insecure redirects.

Real-world attack patterns include man-in-the-middle scenarios where TLS is not enforced, leading to interception of Basic Auth credentials and associated headers. Another pattern involves insecure logging or debugging routes that echo headers, inadvertently including API keys. OWASP API Security Top 10 categories such as Broken Object Level Authorization and Security Misconfiguration are relevant when these exposures occur in Feathers services.

To illustrate a typical Feathers service with Basic Auth, consider the following configuration. This example sets up an authentication hook and a custom header provider, but it must be reviewed to ensure API keys are not propagated unintentionally.

// src/hooks/authentication.js
const { AuthenticationError } = require('@feathersjs/errors');
const basicAuth = require('feathers-authentication').strategies.basic;

module.exports = function (app) {
  const auth = new feathersAuthentication({
    entity: 'user',
    service: 'users',
    secret: process.env.JWT_SECRET,
    strategies: ['local', 'basic'],
  });

  app.configure(auth);
};

// src/services/orders/orders.hooks.js
const headers = (hook) => {
  // Example of attaching a static API key to outgoing requests
  if (hook.method === 'create' && hook.data && hook.data.external) {
    hook.headers = hook.headers || {};
    hook.headers['x-api-key'] = process.env.EXTERNAL_API_KEY;
  }
  return hook;
};

module.exports = {
  before: {
    all: [],
    find: [verifyToken], // custom verify
    get: [],
    create: [headers],
    update: [notImplemented],
    patch: [notImplemented],
    remove: [notImplemented],
  },
};

In this setup, EXTERNAL_API_KEY is read from the environment and added to headers for certain operations. If an endpoint using this hook also permits Basic Auth and does not restrict which clients can trigger it, the key may be exposed through logs or error traces. Ensuring that such hooks are only invoked by authenticated and authorized contexts, and that keys are not included in responses, is essential.

middleBrick scans for these risks by analyzing endpoint configurations, hook implementations, and runtime behavior where accessible. It checks whether API keys appear in responses, whether Basic Auth is transmitted without TLS, and whether public endpoints inadvertently reference sensitive values. The scanner maps findings to frameworks such as OWASP API Top 10 and provides remediation guidance to help developers isolate keys from authentication flows.

Basic Auth-Specific Remediation in Feathersjs — concrete code fixes

Remediation focuses on ensuring that Basic Auth is used only over TLS, that API keys are never returned to clients, and that hooks and services are scoped to prevent unintended propagation of sensitive values. The following examples demonstrate secure configurations.

First, enforce HTTPS in your Feathers application to protect credentials in transit. This can be done at the server or proxy level, but within Feathers you can add a hook that rejects insecure requests.

// src/hooks/require-https.js
module.exports = function () {
  return (hook) => {
    if (process.env.NODE_ENV === 'production' && !hook.params.secure) {
      throw new Error('HTTPS required');
    }
    return hook;
  };
};

// In your app configuration
app.configure({
  middleware: {
    hooks: {
      all: [requireRequireHttps()],
    },
  },
});

Second, avoid attaching API keys to hooks that may be invoked for public or unauthenticated requests. Scope sensitive hooks to authenticated operations only and ensure they do not leak keys in responses or logs.

// src/services/orders/orders.hooks.js
const headers = (hook) => {
  // Only add API key for authenticated create operations
  if (
    hook.method === 'create' &&
    hook.params.user && // authenticated user present
    hook.data &&
    hook.data.external
  ) {
    hook.headers = hook.headers || {};
    hook.headers['x-api-key'] = process.env.EXTERNAL_API_KEY;
    // Ensure the key is not echoed back
    delete hook.result;
  }
  return Promise.resolve(hook);
};

module.exports = {
  before: {
    create: [headers],
  },
};

Third, configure authentication hooks to validate the presence and correctness of credentials without exposing internal values. Use established libraries and avoid manually handling base64 decoding in business logic.

// src/hooks/authentication.js
const auth = new feathersAuthentication({
  entity: 'user',
  service: 'users',
  secret: process.env.JWT_SECRET,
  strategies: ['basic'],
  usernameField: 'email',
  passwordField: 'password',
});

app.configure(auth);

Fourth, apply role-based access controls to ensure that even authenticated users can only invoke services appropriate to their permissions. This reduces the impact of any key exposure.

// src/services/orders/orders.class.js
class OrdersService {
  setup(app) {
    this.app = app;
  }

  async create(data, params) {
    if (!params.user || !params.user.can('manage:orders')) {
      throw new errors.NotAuthenticated('Access denied');
    }
    // Proceed with order creation
    return { id: Date.now(), ...data };
  }
}

Finally, audit your services to confirm that no endpoint returns headers containing API keys and that Basic Auth is not used in contexts where TLS cannot be guaranteed. Use tools like middleBrick to validate these controls and receive prioritized remediation steps.

By combining transport security, careful hook design, and strict authorization checks, you can mitigate the risk of API key exposure while using Basic Auth in Feathers applications.

Frequently Asked Questions

Can Basic Auth alone protect API keys in FeathersJS?
No. Basic Auth provides identity verification but does not prevent exposure of API keys if they are included in responses, logs, or error messages. Use TLS, scope hooks, and avoid propagating keys to clients.
How does middleBrick help detect API key exposure with Basic Auth?
middleBrick scans unauthenticated endpoints and checks whether API keys appear in responses, headers, or logs when Basic Auth is in use. It flags insecure configurations and maps findings to frameworks such as OWASP API Top 10.