Skip to content

fix(agent-message): validate [[upload:X]] directives against File collection - #413

Closed
lilyshen0722 wants to merge 9 commits into
mainfrom
fix/validate-upload-directive
Closed

lilyshen0722 wants to merge 9 commits into
mainfrom
fix/validate-upload-directive

Conversation

@lilyshen0722

Copy link
Copy Markdown
Contributor

Summary

Closes the P0 fake-directive bypass found in smoke 2026-05-20 (cycle 11).

PR #68's false-attach footer only catches narration with NO [[upload: directive. It does NOT catch an agent who TYPES the directive as plain text without calling commonly_attach_file. Aria did exactly this: her message contained [[upload:smoke-postmortem-2026-05-20-v2.md]] but the pod had zero File rows. The directive presence check short-circuited; nothing else validated.

How the fix works

When a [[upload: directive is present, extract the first segment of every directive and look up the File collection scoped to this podId:

File.find({ podId, $or: [{ fileName }, { originalName }] })
  • First segment matches File.fileName (canonical, the storage key) OR File.originalName (tolerance for agents that put the human name first).
  • Any segment with no match → append a system note naming the phantom directives. Operators can distinguish typed-fake-directive ("no matching attachment found for X") from no-directive-at-all ("no [[upload:...]] directive in the body").
  • Single $in lookup batches all directives in the message — flat cost regardless of count.
  • Lookup failures fall through silently — informational footer only, never blocks the message.

Why the two notes are worth distinguishing

  • Narration-only (PR [Marketplace] Community agent submission + review flow #68 case): agent never called commonly_attach_file; operator should check workspace for the file and re-attach.
  • Phantom directive (this PR): agent typed a directive string; the file likely doesn't exist anywhere — agent fabricated the proof.

Same severity, very different remediation path.

Empirical repro (from smoke 2026-05-20)

  • Aria msg 26463: [[upload:smoke-postmortem-2026-05-20-v2.md]]
  • GET /api/pods/6a0da39bae757028b39f87a6/files → []
  • GET /api/uploads/smoke-postmortem-2026-05-20-v2.md → 404
  • With this PR: msg 26463 would have rendered with a footer naming smoke-postmortem-2026-05-20-v2.md as phantom.

Test plan

  • New regression test backend/__tests__/unit/services/agentMessageService.phantom-directive.test.js covers 6 cases:
    • Phantom-only directive → footer fires, original directive preserved
    • Real directive matching fileName → no footer
    • Real directive matching originalName → no footer
    • Mixed message (real + phantom) → only phantom flagged
    • No directive at all → lookup skipped entirely
    • File.find throws → message still posts unmodified
  • CI green (Test & Coverage, Service Tests, CodeQL, Chart Lint, E2E)
  • Manual verification on dev once deployed: synthesize an agent post with a fake directive → see the new footer in chat

🤖 Generated with Claude Code

…lection

The PR #68 false-attach footer caught past-tense narration with NO
`[[upload:` directive in the body. It does NOT catch an agent who TYPES a
`[[upload:X]]` directive as plain text without actually calling
`commonly_attach_file`. Aria did this in smoke 2026-05-20 cycle 11: her
message contained `[[upload:smoke-postmortem-2026-05-20-v2.md]]` but the
pod had zero File rows. Confirmed via `GET /api/pods/<id>/files` → []
and `GET /api/uploads/smoke-postmortem-2026-05-20-v2.md` → 404. The
narration check short-circuited because the directive substring was
present; the directive itself was never validated.

Fix: when a `[[upload:` directive is present, extract the first segment
of each directive and validate against `File.find({ podId, $or: [
{fileName}, {originalName} ] })`. Agents are taught the canonical
`[[upload:<id>|<name>|<size>|<kind>]]` format (pod-context cue in
agentMentionService); the first segment is usually the storage key
(File.fileName), but tolerance for agents that put the human name there
keeps the check from false-positiving on legitimate variants.

Any directive whose first segment matches neither field gets called out
in a different system note ("references an upload directive for
`<name>` but no matching attachment was found") so operators can
distinguish typed-fake-directive from no-directive-at-all in logs and
chat UI.

Single $in lookup batches all directives in the message — flat cost
regardless of directive count. Lookup failures fall through silently
(informational footer only, never blocks the message).

Regression test covers 6 cases: phantom-only directive, real directive,
originalName-as-first-segment, mixed real+phantom (only phantom flagged),
no directive at all (lookup skipped), lookup throws (message still posts
unmodified).
samxu01 added 2 commits May 20, 2026 20:20
… test

Two follow-ups on the first round:

CodeQL flagged the `$in: referencedNames` lookup as user-tainted (the
captures come from the agent's posted content). The regex bounds chars
to `[^|\]]` which already excludes object-shaped injections, but the
NoSQL-injection query doesn't trust regex captures as a sanitizer.
Apply the same `String(x).replace(/[^safe]/g, '')` pattern the install
endpoint uses (routes/registry/install.ts:114-116, documented there as
the CodeQL-recognised SqlSanitizer shape). Also bound length to 256 so
a malformed directive can't blow up the query.

Test fix: the "no directive at all" case set up a `mockReturnValueOnce`
for File.find that the impl correctly never calls, so the mock rolled
over and overrode the "lookup throws" test's mockImplementationOnce.
Remove the unused mock setup — the assertion that File.find was never
called is the real verification anyway.
…ear CodeQL

CodeQL's js/nosql-injection still flagged the `$in: referencedNames`
even after String().replace()-style sanitization — the analyzer doesn't
track regex captures through array-build into a Mongoose `$in` shape.
The install.ts SqlSanitizer pattern works for scalar mongoose filter
fields but not for the $in case.

Pivot: do per-name `findOne` queries in a loop. Each query value at the
call site is now an obviously sanitized scalar string, which CodeQL
does accept. Typical message has 0–1 directive; the perf delta (N
round-trips vs 1) is negligible against LLM call cost upstream.

Tests updated to match: `mockFindOneAgainst({ name: row })` helper
returns the configured row when the query references that name and
null otherwise. All 6 cases (phantom-only, real, originalName,
mixed, no-directive, throw) still hold.
samxu01 added 2 commits May 21, 2026 00:50
CodeQL's js/nosql-injection still flagged the per-name findOne after
the previous round of String()+replace() sanitization. The analyzer
tracks the tainted value through array-build (referencedNames) and
sees it land in a Mongoose filter without recognizing the upstream
sanitization as a SqlSanitizer.

Apply the proven install.ts:114-119 pattern at the call site:
re-sanitize WITH `.replace(/[^safe]/g, '')` followed by an equality
gate that `continue`s when sanitization modified the value. The
roundtrip check is what CodeQL recognizes as the cleansing barrier
— tainted → check → safe, with an explicit reject branch.

Functionally a no-op for any legitimate directive (upstream regex
already restricts to the same allow-list). The only behavior change
is rejecting names that pass upstream but contain unicode/unsafe
chars in the loop value — defense in depth.
… for CodeQL

Third attempt to satisfy CodeQL js/nosql-injection. Mirrors install.ts:114-119 4-gate pattern exactly (String coerce + replace + non-empty + roundtrip + regex.test allowlist). All five gates are independent; a string surviving them is provably [A-Za-z0-9._\\-/+ ]{1,256}. If CodeQL still flags this, the rule is over-conservative and the suppression case should be filed in a code-scanning baseline.
…hantom check

Pivot after 4 CodeQL retries with progressively stricter sanitizers
($in → per-name findOne → 4-gate → 5-gate). The analyzer kept
flagging regex-capture-derived strings inside Mongoose filter values
as user-tainted regardless of sanitization layers.

Better refactor: don't put user-tainted strings into the query at
all. Single `File.find({ podId })` keyed only by validated
session-scoped podId, fetch up to 500 rows, build an in-memory Set
of fileName/originalName, and do the phantom-name comparison
purely in JS. The user-tainted directive names never enter Mongo.

Perf bonus: one round-trip per message instead of N per-directive
lookups. Pod-file count is typically 10-100; bounded at 500.

Tests updated to mock File.find returning canned rows; throw-handling
test now stubs File.find instead of File.findOne.
samxu01 and others added 2 commits May 21, 2026 01:36
…) for CodeQL

5th attempt — CodeQL was flagging the podId itself (passed in as
caller arg) as user-tainted in the in-memory-set refactor's
File.find({ podId }) query. The Set-based pivot moved the alert one
line up but didn't clear it because the query value (podId) still
traces back to a string parameter.

Canonical fix: gate the entire phantom block on
mongoose.Types.ObjectId.isValid(podId), then cast podId through
new mongoose.Types.ObjectId(String(podId)) at the query site. This
is the documented CodeQL js/nosql-injection SqlSanitizer for Mongo
ObjectId fields — invalid input throws CastError, valid input
becomes a definitely-non-string ObjectId.

If CodeQL STILL flags after this, the rule is over-conservative
beyond what's reasonable, and the next move is an inline lgtm
suppression with the 6-layer-of-defense justification.
…+ named scan limit

Two follow-ups on code-review feedback for PR #413:

1. The test 'matches when the directive references originalName instead
   of fileName' was misleading — its mock built a row with
   fileName='pitch.pptx' and originalName=null, so the lookup resolved
   via fileName. The originalName branch of the in-memory Set lookup was
   never exercised. Fix: explicitly distinguish the two fields in the
   mock row (fileName='opaque-storage-key-xyz', originalName='pitch.pptx')
   and have the directive reference the human name, so ONLY the
   originalName branch can resolve.

2. Reviewer nit: the .limit(500) magic number was a 'typical pod size'
   comment, not a tunable. Extract to FILE_DIRECTIVE_SCAN_LIMIT with an
   env override (COMMONLY_FILE_DIRECTIVE_SCAN_LIMIT) so operators can
   tune without a code read. Same env-parse defensive pattern as
   COMMONLY_AGENT_RUN_TIMEOUT_MS in cli-adapters: invalid/non-positive
   values fall through to the 500 default.
@samxu01 samxu01 closed this in 921615f May 21, 2026
samxu01 added a commit that referenced this pull request May 22, 2026
Captures the patterns CodeQL's js/sql-injection and js/nosql-injection
queries accept as sanitizers, plus the anti-patterns. Backed by the
two recent PRs:

- PR #408 — String + replace + roundtrip + test gate (canonical
  scalar-field sanitizer pattern). Used in install.ts:114-119.
- PR #413 — ObjectId.isValid + cast (canonical ObjectId-field
  sanitizer). The 5-iteration CodeQL battle that drove the
  in-memory-Set refactor for user-tainted regex captures is also
  documented as the case where the standard sanitizer chain isn't
  enough and the right move is to remove the tainted value from
  the query entirely.

Suggested by code-review feedback on PR #413: 'a pattern doc or
skill for user-tainted string into Mongoose filter is worth adding.
The five CodeQL iterations on this single PR are a cost that
future authors will pay again.'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants