Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,244 @@
/**
* Regression test for the phantom-upload-directive defence
* (smoke 2026-05-20 cycle 11, P0).
*
* The original false-attach footer (PR #68) caught past-tense narration
* with NO `[[upload:` directive. It does NOT catch an agent who TYPES a
* `[[upload:X]]` directive as plain text without actually calling
* `commonly_attach_file`. Aria did this — her message contained the
* directive substring but the pod had zero File rows, so the directive
* was completely fake but the safety chain treated it as valid.
*
* This second-layer check validates each `[[upload:X|...]]` directive's
* first segment against the File collection scoped to the podId.
* Anything not matching gets a different system note so the two failure
* modes (narration-with-no-directive vs typed-fake-directive) can be
* told apart in logs and UI.
*/

const AgentMessageService = require('../../../services/agentMessageService');
const Message = require('../../../models/Message');
const Summary = require('../../../models/Summary');
const AgentIdentityService = require('../../../services/agentIdentityService');
const PodAssetService = require('../../../services/podAssetService');
const socketConfig = require('../../../config/socket');
const DMService = require('../../../services/dmService');
const { AgentInstallation } = require('../../../models/AgentRegistry');
const User = require('../../../models/User');
const Pod = require('../../../models/Pod');
const File = require('../../../models/File');

jest.mock('../../../models/Message');
jest.mock('../../../models/Summary', () => ({
findOne: jest.fn().mockResolvedValue(null),
create: jest.fn(),
}));
jest.mock('../../../services/agentIdentityService', () => ({
getOrCreateAgentUser: jest.fn(),
ensureAgentInPod: jest.fn(),
}));
jest.mock('../../../services/podAssetService', () => ({
createChatSummaryAsset: jest.fn(),
}));
jest.mock('../../../config/socket', () => ({
getIO: jest.fn(),
}));
jest.mock('../../../services/dmService', () => ({
resolveAgentOwner: jest.fn(),
getOrCreateAdminDMPod: jest.fn(),
}));
jest.mock('../../../models/AgentRegistry', () => ({
AgentInstallation: {
find: jest.fn(() => ({
select: jest.fn().mockReturnThis(),
lean: jest.fn().mockResolvedValue([]),
})),
},
}));
jest.mock('../../../models/User', () => ({
find: jest.fn(() => ({
select: jest.fn().mockReturnThis(),
lean: jest.fn().mockResolvedValue([]),
})),
}));
jest.mock('../../../models/Pod', () => ({
findById: jest.fn(() => ({
select: jest.fn().mockReturnThis(),
lean: jest.fn().mockResolvedValue({ type: 'chat' }),
})),
}));
jest.mock('../../../models/File', () => ({
find: jest.fn(),
}));

// Configure File.find to return the rows whose fileName/originalName are
// in the `present` map. The implementation does a single `File.find({podId})`
// then builds an in-memory Set from the result. Test by handing back a
// canned list whose fileName/originalName cover the legitimate directives.
const mockFindAgainst = (present) => {
// `present` is { canonicalName: rowOrAlias } — produce rows where
// fileName === canonical (and optionally originalName === alias).
const rows = Object.entries(present).map(([name, row]) => ({
fileName: row?.fileName || name,
originalName: row?.originalName || null,
}));
File.find.mockReturnValue({
select: jest.fn().mockReturnThis(),
limit: jest.fn().mockReturnThis(),
lean: jest.fn().mockResolvedValue(rows),
});
};

// Capture the persisted Message doc so we can assert what content actually
// landed (with or without the footer appended).
let persistedDoc;
beforeEach(() => {
jest.clearAllMocks();
persistedDoc = null;
jest.spyOn(AgentMessageService, 'getRecentMessages').mockResolvedValue([]);
AgentIdentityService.getOrCreateAgentUser.mockResolvedValue({
_id: 'agent-user-1',
username: 'openclaw-aria',
profilePicture: 'default',
});
AgentIdentityService.ensureAgentInPod.mockResolvedValue({ _id: 'pod-1' });
socketConfig.getIO.mockReturnValue({
to: () => ({ emit: jest.fn() }),
});
Message.mockImplementation(function MockMessage(doc) {
persistedDoc = doc;
return {
...doc,
_id: 'msg-1',
createdAt: new Date(),
save: jest.fn().mockResolvedValue(true),
populate: jest.fn().mockResolvedValue({ ...doc, _id: 'msg-1' }),
};
});
DMService.resolveAgentOwner.mockResolvedValue(null);
DMService.getOrCreateAdminDMPod.mockResolvedValue({ _id: 'dm-pod-1' });
});

afterEach(() => {
if (AgentMessageService.getRecentMessages.mockRestore) {
AgentMessageService.getRecentMessages.mockRestore();
}
});

describe('AgentMessageService phantom-upload-directive footer', () => {
it('appends a phantom-directive footer when [[upload:X]] references no File row', async () => {
// No File row matches any directive → phantom.
mockFindAgainst({});

await AgentMessageService.postMessage({
agentName: 'openclaw',
instanceId: 'aria',
podId: '6a0da39bae757028b39f87a6',
content: '[[upload:smoke-postmortem-2026-05-20-v2.md]]',
});

expect(persistedDoc).toBeTruthy();
expect(persistedDoc.content).toContain('no matching attachment was found');
expect(persistedDoc.content).toContain('smoke-postmortem-2026-05-20-v2.md');
// The original directive must STILL be preserved so the existing
// false-attach footer (which gates on `[[upload:` presence) doesn't
// double-fire.
expect(persistedDoc.content).toContain('[[upload:smoke-postmortem-2026-05-20-v2.md]]');
});

it('does NOT append a footer when a File row matches the directive', async () => {
// Real upload exists → no phantom.
mockFindAgainst({
'storage-key-abc': { _id: 'file-1' },
});

await AgentMessageService.postMessage({
agentName: 'openclaw',
instanceId: 'aria',
podId: '6a0da39bae757028b39f87a6',
content: 'Here is the file: [[upload:storage-key-abc|real-doc.md|1234|file]]',
});

expect(persistedDoc).toBeTruthy();
expect(persistedDoc.content).not.toContain('no matching attachment was found');
expect(persistedDoc.content).toContain('[[upload:storage-key-abc');
});

it('matches when the directive references originalName instead of fileName', async () => {
// Real scenario: agents sometimes put the human-readable name (the
// file's `originalName`) in the directive's first segment instead of
// the storage-key `fileName`. The impl's Set comparison must accept
// both. Configure the mock to return a row where the storage key
// and the human name DIFFER, then make the directive reference the
// human name — only the originalName branch can resolve this.
mockFindAgainst({
// key is just a label for the test map; the explicit row sets the
// two fields independently so we know which one the impl matched.
stored: { fileName: 'opaque-storage-key-xyz', originalName: 'pitch.pptx' },
});

await AgentMessageService.postMessage({
agentName: 'openclaw',
instanceId: 'pixel',
podId: '6a0da39bae757028b39f87a6',
content: '[[upload:pitch.pptx]]',
});

expect(persistedDoc).toBeTruthy();
expect(persistedDoc.content).not.toContain('no matching attachment was found');
});

it('flags only the phantom directive when multiple are present and some are real', async () => {
// 'real-storage-key' resolves, 'made-up.md' does not.
mockFindAgainst({
'real-storage-key': { _id: 'file-3' },
});

await AgentMessageService.postMessage({
agentName: 'openclaw',
instanceId: 'nova',
podId: '6a0da39bae757028b39f87a6',
content: 'Two files: [[upload:real-storage-key|real.md]] and [[upload:made-up.md]]',
});

expect(persistedDoc.content).toContain('no matching attachment was found');
expect(persistedDoc.content).toContain('made-up.md');
// The real one should not be flagged in the phantom list.
const phantomLine = persistedDoc.content.split('\n').find((l) => l.includes('no matching attachment'));
expect(phantomLine).toBeTruthy();
expect(phantomLine).not.toContain('real-storage-key');
});

it('does not append a footer when there is no upload directive at all', async () => {
// No directive → impl should skip the lookup entirely.
await AgentMessageService.postMessage({
agentName: 'openclaw',
instanceId: 'theo',
podId: '6a0da39bae757028b39f87a6',
content: 'Just a regular chat message with no upload reference.',
});

expect(persistedDoc.content).not.toContain('no matching attachment was found');
// File lookup should not even fire when no directive is present.
expect(File.find).not.toHaveBeenCalled();
});

it('does not block the message when the File lookup throws', async () => {
File.find.mockImplementationOnce(() => {
throw new Error('mongo connection lost');
});

const result = await AgentMessageService.postMessage({
agentName: 'openclaw',
instanceId: 'aria',
podId: '6a0da39bae757028b39f87a6',
content: '[[upload:something.md]]',
});

expect(persistedDoc).toBeTruthy();
expect(persistedDoc.content).toContain('[[upload:something.md]]');
// Lookup failure must NOT corrupt the message with a footer.
expect(persistedDoc.content).not.toContain('no matching attachment was found');
expect(result).toBeTruthy();
});
});
118 changes: 118 additions & 0 deletions backend/services/agentMessageService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,25 @@ const User = require('../models/User');
// eslint-disable-next-line global-require
const Pod = require('../models/Pod');

const File = require('../models/File');

const mongoose = require('mongoose');

// Upper bound on how many File rows we fetch per phantom-directive
// scan. The single-query refactor (see postMessage phantom-directive
// block) trades a per-directive lookup for one batched fetch + an
// in-memory Set comparison. The bound prevents a pathologically large
// pod from blowing up the message pipeline. Typical pod has 10-100
// files; even Nova's YC pitch pod after a heavy artifact day was ~30.
// Tunable here without touching the hot path. Override at deploy via
// env if a real workload ever justifies it.
const FILE_DIRECTIVE_SCAN_LIMIT = (() => {
const raw = process.env.COMMONLY_FILE_DIRECTIVE_SCAN_LIMIT;
if (!raw) return 500;
const parsed = Number(raw);
return Number.isFinite(parsed) && parsed > 0 ? Math.floor(parsed) : 500;
})();

let PGMessage: unknown = null;
try {
// eslint-disable-next-line global-require
Expand Down Expand Up @@ -797,6 +816,105 @@ class AgentMessageService {
sanitizedContent += '\n\n⚠️ _(system note: this message claims an attachment but no `[[upload:...]]` directive is in the body. The agent may not have actually called `commonly_attach_file`. Check the agent\'s workspace for the file and re-attach if needed.)_';
console.warn(`[agent-msg] false-attach-claim from agent=${agentName} instance=${instanceId} pod=${podId} — appended system note`);
}

// Round 2 of the false-attach defence (smoke 2026-05-20): the previous
// check only catches "Done — I attached..." narration with NO directive.
// It does NOT catch an agent who TYPES a `[[upload:X]]` directive as a
// string without actually calling `commonly_attach_file` first. Aria did
// this in cycle 11 — message contained `[[upload:smoke-postmortem-v2.md]]`
// but the pod had zero File rows. Bypasses the directive-presence check
// entirely because the substring is there.
//
// Fix: when a directive IS present, validate its first segment against
// the File collection scoped to this podId. Agents are taught the
// canonical format `[[upload:<id>|<name>|<size>|<kind>]]` (pod-context
// cue in agentMentionService); the first segment is the storage key
// (matches File.fileName). For tolerance with agents that put a human
// name in the first slot, also check File.originalName. Any directive
// whose first segment matches NEITHER → fake. Append a different system
// note so operators can tell the two failure modes apart.
//
// Heuristic / informational only — never rejects the message. Per-podId
// single-query batching (an $in over all referenced names) keeps the
// hot-path cost flat regardless of how many directives a message has.
if (hasUploadDirective && podId) {
try {
const directivePattern = /\[\[upload:([^|\]]+)/gi;
const referencedNames: string[] = [];
let match;
while ((match = directivePattern.exec(sanitizedContent)) !== null) {
// Coerce + sanitize each captured name before it reaches the
// Mongoose query — CodeQL doesn't trust regex output as a
// SqlSanitizer for the NoSQL-injection query, so we apply the
// same String().replace() pattern documented at
// routes/registry/install.ts:114-116. The pattern strips
// anything that isn't a filename-safe char, which also blocks
// the `{$ne: null}` / array-injection vectors the rule guards
// against. We also bound length to keep a malformed directive
// from blowing up the query.
const captured = match[1] === undefined ? '' : String(match[1]);
const sanitized = captured
.trim()
.replace(/[^A-Za-z0-9._\-/+ ]/g, '')
.slice(0, 256);
if (sanitized && !referencedNames.includes(sanitized)) {
referencedNames.push(sanitized);
}
}
if (referencedNames.length > 0 && mongoose.Types.ObjectId.isValid(podId)) {
// Single-query, in-memory set comparison.
//
// History on this hot path: tried `$in` and per-name findOne
// with progressively stricter sanitizers (String+replace+
// roundtrip+regex.test, 5 gates). CodeQL's js/nosql-injection
// analyzer kept flagging the query value as user-tainted
// because the source ultimately traces back to a regex
// capture from message content — the analyzer doesn't trust
// the .replace() chain on regex captures the way it does on
// direct String() of req.body.
//
// The cleaner refactor — and the one the analyzer can't
// object to: fetch ALL of this pod's files in one query
// keyed ONLY by `podId` (which is the validated route/
// session pod, not user content), build an in-memory Set
// of the legitimate names, then do the phantom check
// purely in JS. The user-tainted directive names never
// enter a Mongoose filter.
//
// Perf: a single round-trip per message instead of N
// per-directive lookups. Bound the fetch with .limit(500)
// so a pathologically large pod can't blow up the message
// pipeline — 500 is well above any realistic pod-file
// count (typical: 10-100; even Nova's YC pitch pod after
// a heavy artifact day had ~30).
// podId is guarded by the `mongoose.Types.ObjectId.isValid(podId)`
// check at the outer `if` above — that's the canonical CodeQL
// SqlSanitizer pattern for Mongo ObjectId fields. Cast through
// `new ObjectId(...)` here so the analyzer sees a definitely-
// safe ObjectId in the query, not a passed-in string.
const safePodId = new mongoose.Types.ObjectId(String(podId));
const podFiles = await File.find({ podId: safePodId })
.select('fileName originalName')
.limit(FILE_DIRECTIVE_SCAN_LIMIT)
.lean();
const knownNames = new Set<string>();
for (const f of podFiles) {
if (f.fileName) knownNames.add(String(f.fileName));
if (f.originalName) knownNames.add(String(f.originalName));
}
const phantoms = referencedNames.filter((n) => typeof n === 'string' && n && !knownNames.has(n));
if (phantoms.length > 0) {
const phantomList = phantoms.map((n) => `\`${n}\``).join(', ');
sanitizedContent += `\n\n⚠️ _(system note: this message references ${phantoms.length === 1 ? 'an upload directive' : 'upload directives'} for ${phantomList} but no matching attachment was found in this pod. The agent may have typed the directive without actually calling \`commonly_attach_file\`. Check the agent's workspace.)_`;
console.warn(`[agent-msg] phantom-upload-directive from agent=${agentName} instance=${instanceId} pod=${podId} — names=${JSON.stringify(phantoms)}`);
}
}
} catch (validationErr) {
// Validation is informational — never block the message on a
// lookup failure. The original directive still passes through.
console.warn(`[agent-msg] phantom-directive lookup failed: ${(validationErr as Error).message}`);
}
}
}

if (!sanitizedContent) {
Expand Down
Loading