MEDIUM log injectionfeathersjsfirestore

Log Injection in Feathersjs with Firestore

Log Injection in Feathersjs with Firestore — how this specific combination creates or exposes the vulnerability

Log injection occurs when an attacker can control or influence data that is written to application logs. In a Feathersjs application that uses Firestore as the data store, this typically arises when request data that is not sanitized is included in structured log entries. Because Feathersjs services are often event-driven and may directly serialize Firestore documents into log output, newlines or other control characters in Firestore fields can lead to log forging or log injection.

Consider a Feathersjs service that creates a document in Firestore and then logs the created payload. If a field such as message or displayName contains newline characters (e.g., %0A%0Aevil: true), the log entry may appear to contain multiple logical log records. This can confuse log-based monitoring systems and obscure the origin of events. An example Firestore write in Feathersjs might look like:

const app = require('@feathersjs/feathers')();
const memory = require('@feathersjs/adapter-memory');
const { Firestore } = require('@google-cloud/firestore');
const { FirestoreService } = require('feathers-google-firestore');

app.configure(memory());
const firestore = new Firestore();
app.use('messages', new FirestoreService({
  name: 'messages',
  firestore
}));

app.service('messages').on('created', (context) => {
  console.log('Message created:', JSON.stringify(context.result));
});

If a client submits a message with text: "hello\nmalicious: injected", the resulting log line can be split into multiple lines. This may cause log parsers to misinterpret the structure of events, making it harder to distinguish legitimate entries from injected content. In security-focused logging, this behavior is undesirable because it can reduce the reliability of audits and incident response.

Another vector specific to Feathersjs hooks involves logging within hook logic. If a custom hook logs user-controlled input without normalization, it can be used to inject additional log lines. For example:

app.hooks({
  before: {
    create: [async context => {
      const { text } = context.data;
      console.log('Incoming create payload:', text);
    }]
  }
});

When text contains newline characters, the console output becomes multi-line. While console outputs themselves may not be directly exploitable, downstream log aggregation systems can parse these entries incorrectly, leading to gaps in traceability. This is especially relevant when correlating logs across services, as injection can break expected patterns used for alerting.

Log injection in this stack does not directly enable code execution, but it can facilitate log forging, hide related events, and complicate automated analysis. Because Feathersjs encourages lightweight service definitions and Firestore documents often carry user-generated content, developers must treat log entries as structured but potentially untrusted output. Mitigations should focus on sanitization before logging and structured formats that resist injection.

Firestore-Specific Remediation in Feathersjs — concrete code fixes

Remediation focuses on ensuring that any data written to logs is normalized and that structured logging does not rely on raw user input. For Firestore-backed Feathersjs services, you should sanitize fields that may contain newlines or control characters before logging them. Below are concrete code examples that demonstrate safe practices.

One approach is to sanitize string fields before logging by replacing newlines and trimming whitespace. This can be implemented as a Feathersjs hook:

function sanitizeLogData(context) {
  const data = context.data || {};
  const sanitize = (obj) => {
    for (const key of Object.keys(obj)) {
      if (typeof obj[key] === 'string') {
        obj[key] = obj[key].replace(/[\r\n]+/g, ' ');
      }
    }
    return obj;
  };
  sanitize(data);
  if (context.result) {
    context.result = JSON.parse(JSON.stringify(context.result).replace(/[\r\n]+/g, ' '));
  }
  return context;
}

app.service('messages').hooks({
  after: {
    create: [sanitizeLogData],
    update: [sanitizeLogData],
    patch: [sanitizeLogData]
  }
});

This hook removes carriage returns and line feeds from string fields in both the payload and the Firestore result before any logging occurs. By normalizing newlines to spaces, you prevent log splitting while preserving the readability of the logged content.

For structured logging, prefer explicit field selection and JSON serialization instead of relying on implicit stringification of Firestore documents. For example:

app.service('messages').on('created', (context) => {
  const safeEntry = {
    id: context.result.id,
    text: typeof context.result.text === 'string' ? context.result.text.trim() : context.result.text,
    createdAt: context.result.createdAt.toISOString ? context.result.createdAt.toISOString() : String(context.result.createdAt)
  };
  console.log('MessageCreated', JSON.stringify(safeEntry));
});

This pattern ensures that only intended fields are logged and that newline characters are handled explicitly. It also avoids leaking internal Firestore metadata that could be affected by formatting quirks.

Additionally, if you use the CLI tool middlebrick to scan this service, it can surface log injection risks among other findings. The dashboard and JSON reports help you track such issues across versions. For teams that want automated checks in CI/CD, adding the GitHub Action can fail builds when risk scores drop below a chosen threshold, encouraging consistent remediation.

When integrating with AI coding assistants via the MCP Server, you can request code snippets that include log-safe patterns. This helps maintain secure logging habits across the codebase. Ultimately, combining input validation, structured logging, and periodic scans reduces the likelihood of log injection affecting auditability in Feathersjs applications backed by Firestore.

Frequently Asked Questions

Can log injection in Feathersjs with Firestore lead to remote code execution?
No. Log injection in this stack typically enables log forging or obfuscation rather than remote code execution. The primary risk is reduced log integrity and difficulty in correlating events.
How can I detect log injection vulnerabilities in my Feathersjs + Firestore service?
Use the middleBrick CLI to scan your API endpoints. The scanner includes checks for improper logging and input handling, and the dashboard provides prioritized findings with remediation guidance.