Hallucination Attacks in Feathersjs with Mongodb
Hallucination Attacks in Feathersjs with Mongodb — how this specific combination creates or exposes the vulnerability
FeathersJS is a framework for real-time APIs that typically sits over a database adapter such as Mongoose for MongoDB. A hallucination attack in this context occurs when an API returns fabricated or misleading data, or allows an attacker to influence the query in a way that produces unintended, false results. With MongoDB, this can arise from permissive query construction, missing input validation, or misconfigured service hooks that allow field selection or filtering to be overridden by the client.
When a FeathersJS service for MongoDB does not explicitly restrict which fields can be queried or how filters are applied, an attacker can inject query parameters that cause the service to return sensitive records or to interpret empty filters as broad matches. For example, if a service exposes filtering on nested fields without validating the structure of the object, an attacker can supply keys that do not meaningfully constrain the query, effectively bypassing intended access controls. This can lead to data exposure where the API appears to return only a subset of data but actually returns documents the caller should not see.
Additionally, without strict validation, an attacker can provide values that trigger unexpected type coercion in MongoDB queries. A string supplied where an ObjectId is expected may still match a document depending on MongoDB’s comparison rules, leading to matches that the developer did not intend. In FeathersJS, if the service does not normalize or validate identifiers before passing them to the MongoDB adapter, this can result in an information leak or unauthorized access across related resources.
Another vector involves the use of $where or other JavaScript evaluation constructs in MongoDB if the adapter or service code inadvertently allows raw expressions from client input. Although modern MongoDB drivers discourage this, if a FeathersJS service builds queries by directly concatenating user input into the filter object, it can open paths for injection that affect query logic and cause hallucinated results.
Hallucination attacks in this combination are particularly concerning because the API surface appears normal and authenticated, yet the underlying query logic is malleable. The absence of strict schema enforcement on queries, combined with the flexibility of MongoDB’s query language, means that an attacker can probe the API with crafted parameters to observe inconsistent or fabricated behavior, revealing data that should remain protected.
Mongodb-Specific Remediation in Feathersjs — concrete code fixes
Remediation focuses on strict input validation, explicit field selection, and canonical query building. Use FeathersJS hooks to sanitize and constrain queries before they reach the MongoDB adapter.
// Example FeathersJS hook to sanitize query parameters
const { sanitizeQuery } = require('feathers-hooks-common');
function restrictQueryFields (context) {
const { query } = context.params;
// Allow only safe top-level fields
const allowedFields = ['$limit', '$skip', 'slug', 'status'];
const sanitized = {};
allowedFields.forEach(key => {
if (Object.prototype.hasOwnProperty.call(query, key)) {
sanitized[key] = query[key];
}
});
// Ensure no MongoDB operator injection via unexpected keys
const mongoOperators = ['$where', '$eval', '$function'];
for (const key of Object.keys(query)) {
if (mongoOperators.some(op => key.startsWith(op))) {
delete sanitized[key];
}
}
context.params.query = sanitized;
return context;
}
// Use ObjectId validation for IDs
const { ObjectId } = require('mongodb');
function validateId (context) {
const { id } = context.params;
if (id && !ObjectId.isValid(id)) {
throw new Error('Invalid ObjectId');
}
return context;
}
module.exports = {
before: {
all: [sanitizeQuery, validateId],
find: []
},
after: {
all: [],
find: []
},
error: {
all: [],
find: []
}
};
In your service definition, explicitly define the Model and ensure that the adapter uses strict schema validation where possible. Configure the Mongoose adapter (if used) to lean queries and project only required fields to avoid returning extra data that could be leveraged in a hallucination attack.
const mongoose = require('mongoose');
const feathers = require('feathers');
const mongodb = require('feathers-mongodb');
const app = feathers();
const conn = mongoose.createConnection('mongodb://localhost:27017/mydb');
const PostSchema = new mongoose.Schema({
title: { type: String, required: true },
content: String,
slug: { type: String, required: true, unique: true },
status: { type: String, enum: ['draft', 'published'], default: 'draft' }
});
const PostModel = conn.model('Post', PostSchema);
app.use('/posts', mongodb({
Model: PostModel,
paginate: {
default: 10,
max: 25
},
// Use projection to limit returned fields
async create (data) {
// Ensure only expected fields are used
return {
title: data.title,
content: data.content,
slug: data.slug,
status: data.status || 'draft'
};
}
}));
// Apply hooks globally
app.service('posts').hooks({
before: {
all: [
require('./hooks/sanitize-query'),
require('feathers-hooks-common').disableRemove()
],
find: [require('feathers-hooks-common').hashPassword()]
}
});
For production, combine these hooks with runtime scanning to detect anomalous query patterns. Do not rely solely on client-supplied filters; enforce allowlists for sort fields and populate paths. When using ObjectId parameters, validate format before passing to the MongoDB adapter to prevent type confusion. These measures reduce the attack surface that enables hallucination attacks in the FeathersJS and MongoDB stack.
Related CWEs: llmSecurity
| CWE ID | Name | Severity |
|---|---|---|
| CWE-754 | Improper Check for Unusual or Exceptional Conditions | MEDIUM |