Token Leakage in Feathersjs with Basic Auth
Token Leakage in Feathersjs with Basic Auth — how this specific combination creates or exposes the vulnerability
FeathersJS is a framework for real-time web applications that commonly exposes REST and WebSocket endpoints. When Basic Authentication is used without additional protections, tokens or session identifiers can unintentionally leak through logs, error messages, or misconfigured transports. This occurs because Basic Auth typically encodes credentials in headers, and if the application echoes headers, logs requests verbatim, or exposes detailed errors over WebSockets, an authenticated or unauthenticated attacker may observe sensitive material.
Consider a Feathers service that accepts Basic Auth via a custom header or standard Authorization header. If the server implementation attaches the decoded credentials to the connection object and later serializes that object for debugging or telemetry, fragments of the token or user context may appear in logs or client responses. For example, a naive hook that copies headers into the connection metadata might look like this:
// Example of risky header propagation in a Feathers before hook
module.exports = function (options = {}) {
return async context => {
const { headers } = context;
// Attaching raw headers to context can expose tokens if logged later
context.connectionMeta = { headers };
return context;
};
};
If context.connectionMeta is ever included in logs or transmitted over an insecure channel, any bearer token or session identifier attached to the request may be exposed. Additionally, misconfigured transports can amplify leakage: if the Feathers app enables both HTTP and WebSockets and shares state between them without clearing sensitive fields, a token used for one transport might be reflected in another.
Another vector involves unauthenticated LLM endpoints or verbose error handling that reveals stack traces including header contents. middleBrick’s LLM/AI Security checks specifically scan for such exposure patterns, including system prompt leakage and unsafe output handling. In a Feathers service, failing to sanitize responses and error objects can inadvertently surface authentication artifacts, especially when combined with verbose logging or introspection features.
Operational telemetry compounds this: if your monitoring or dashboard integrations ingest logs that include Authorization headers, the token path extends beyond the application into third-party systems. middleBrick’s Data Exposure checks help identify whether runtime findings align with spec definitions, ensuring that $ref-resolved OpenAPI schemas do not encourage unsafe header propagation or storage.
Basic Auth-Specific Remediation in Feathersjs — concrete code fixes
Remediation focuses on ensuring credentials and any derived tokens never propagate beyond the authentication step. Avoid attaching raw headers or decoded credentials to shared contexts, and enforce strict separation between authenticated execution and logging or serialization pathways.
1. Do not copy headers into context or connection metadata. Instead, immediately derive a minimal identity and discard the raw credentials.
// Safer Feathers before hook for Basic Auth
module.exports = function (options = {}) {
return async context => {
const authHeader = context.headers.authorization || '';
const token = extractTokenFromBasic(authHeader); // custom safe extractor
if (!token) {
throw new Error('Unauthorized');
}
// Set only what you need for authorization checks
context.params.authenticated = true;
context.params.userId = lookupUserId(token);
// Explicitly avoid copying raw headers
delete context.headers.authorization;
return context;
};
};
function extractTokenFromBasic(header) {
if (!header.startsWith('Basic ')) return null;
const base64 = header.slice('Basic '.length);
// Decode and parse without retaining the original header
const decoded = Buffer.from(base64, 'base64').toString('utf8');
const [user, pass] = decoded.split(':');
// Validate user/pass and issue a scoped token or session id
return verifyCredentials(user, pass);
}
2. Configure transports independently and avoid sharing mutable state. If your Feathers app supports both REST and WebSockets, ensure that each transport maintains its own clean context and does not reuse objects that may contain residual credentials.
// Transport-specific setup to limit cross-channel leakage
const feathers = express();
const socket = require('socket.io');
// REST service with strict header handling
feathers.use('/api', authService);
// WebSocket transport with isolated context
const io = socket(server);
io.on('connection', socket => {
socket.on('authenticate', credentials => {
// Perform auth without echoing raw headers
if (verifySocketToken(credentials.token)) {
socket.data.userId = credentials.userId;
}
});
});
3. Harden error handling to prevent verbose disclosures. Override default error formats to strip headers and sensitive fields before transmission.
// Feathers error handler that removes sensitive data
module.exports = function () {
return function errorHandler(err, context) {
// Remove headers from any error context
if (context && context.headers) {
delete context.headers.authorization;
}
// Return generic messages to the client
return {
name: err.name,
message: err.message,
code: err.code || 400
};
};
};
4. Use middleware to enforce rate limiting and input validation, reducing the likelihood of token leakage via abuse or injection. Combine these with continuous scanning via the middleBrick GitHub Action to fail builds if risky patterns appear in your API definitions.
// Example integration with validation and rate limiting
const validation = require('feathers-hooks-common').validateSchema;
const rateLimit = require('feathers-ratelimit');
app.configure(rateLimit({
window: 60 * 1000,
max: 30
}));
app.use('/api', validation({
type: 'json',
schema: { type: 'object', properties: { token: { type: 'string' } } }
}));
These steps reduce the attack surface by ensuring that tokens are not stored in logs, contexts, or error objects. middleBrick’s CLI can be used to scan endpoints from the terminal, while the Pro plan’s continuous monitoring and GitHub Action provide automated checks that align with frameworks such as OWASP API Top 10 and PCI-DSS.