Repository navigation
fix(agent-message): validate [[upload:X]] directives against File collection - #413
Closed
lilyshen0722 wants to merge 9 commits into
Closed
lilyshen0722 wants to merge 9 commits into
lilyshen0722 wants to merge 9 commits into
Conversation
…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).
… 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.
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.
…) 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.
3 tasks
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.'
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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 callingcommonly_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 thispodId:File.fileName(canonical, the storage key) ORFile.originalName(tolerance for agents that put the human name first).[[upload:...]]directive in the body").$inlookup batches all directives in the message — flat cost regardless of count.Why the two notes are worth distinguishing
commonly_attach_file; operator should check workspace for the file and re-attach.Same severity, very different remediation path.
Empirical repro (from smoke 2026-05-20)
[[upload:smoke-postmortem-2026-05-20-v2.md]]GET /api/pods/6a0da39bae757028b39f87a6/files→[]GET /api/uploads/smoke-postmortem-2026-05-20-v2.md→ 404smoke-postmortem-2026-05-20-v2.mdas phantom.Test plan
backend/__tests__/unit/services/agentMessageService.phantom-directive.test.jscovers 6 cases:fileName→ no footeroriginalName→ no footer🤖 Generated with Claude Code