Skip to content

fix(mentions): the handle regex was safe because of a character class 850 lines away - #1206

Merged
lilyshen0722 merged 3 commits into
mainfrom
fix/human-mention-handle-regex-escape
Oct 23, 2026
Merged

lilyshen0722 merged 3 commits into
mainfrom
fix/human-mention-handle-regex-escape

Conversation

@lilyshen0722

@lilyshen0722 lilyshen0722 commented Aug 25, 2026 •

Copy link
Copy Markdown
Contributor

Defect

The human mention lookup interpolated extracted handles into a regular expression. The current extractor excludes regex metacharacters, but widening it later could silently route a mention to the wrong user.

Fix

Escape the handle at the matcher itself, using the service's existing escapeRegExp helper. The matcher is exported so its literal matching contract can be tested with metacharacters that the current extractor does not yet allow.

Rebased onto current main for TASK-345.

Verification

  • agentMentionService.handleMatcher.test.js: 8/8 pass on Node 22. The pre-fix implementation fails the five metacharacter cases.
  • Changed source ESLint: zero errors.
  • Exact head: cc5111a37999b71f6fb261d5ccfa79de49cdedc4.

@lilyshen0722 lilyshen0722 left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Gate: approve on substance, two doc-level fixes before merge.

Verified your claim exactly. Isolated worktree at e5b7cce0, Node 22 (the import graph reaches jsonwebtoken → jws → jwa → buffer-equal-constant-time, which throws on Node 26):

  • as shipped: 8/8 pass
  • handleMatcher reverted to the pre-fix raw `^${username}$`: 5 failed, 3 passed, and the 3 survivors are exactly the reachable-input cases (anchoring/prefix, case-insensitivity, a_b-c literals). The 5 failures are dot, alternation, quantifier, unbalanced bracket, wildcard.

Then reverted the worktree edit and removed it.


1. The insert orphans resolveHumanMentionUserIds's docstring (backend/services/agentMentionService.ts).

handleMatcher + its new JSDoc landed between the existing docstring and the function it documents. Two adjacent JSDoc blocks now sit above handleMatcher, and resolveHumanMentionUserIds is left undocumented.

The stranded block is not incidental — it carries the precondition prose this PR exists to localize:

Handles are extracted from [a-z0-9_-], but anchoring keeps a prefix such as @casey from following casey-admin too.

A PR whose thesis is "a precondition maintained in another function is one edit away from not holding" has moved a docstring away from its function. Fix: hoist handleMatcher + its doc above the resolveHumanMentionUserIds docstring.

2. Off-by-one in the test header (backend/__tests__/unit/services/agentMentionService.handleMatcher.test.js:34).

Comment says "The four below are unreachable through extractMentions today"; five tests follow. Your pod message says 5 of 8 — the message is right, the comment is wrong.


Not verified: that the commit adding this lookup also widened the extractMentions character class (asserted in the new JSDoc, taken as given). Nothing outside this file was exercised — enqueueMentions end-to-end is untested here, which is consistent with your own reachability argument.

samxu01 pushed a commit that referenced this pull request Aug 25, 2026
@sprint-review retracted both numbers they had given me: "roughly a fifth of
~23 observations" needing three reads, and the "four of five three-read PRs
came back CLEAN" split. Neither reproduces, and every PR in the sample is warm
now, so the population that would settle them no longer exists.

What survives is individually-named and still checkable — #1168 and #1206
needed three reads out of a batch of fifteen, #809 needed three, #1215
resolved on the first — plus the qualitative finding that read count did not
track CLEAN/DIRTY.

Stating no rate is the deliberate choice, not a gap. This entry's own rule is
"loop until the value is not UNKNOWN", and a frequency is exactly what tempts
the next reader to budget a fixed number of reads — which is the bug the
bullet exists to prevent. A number that cannot be re-derived is worse than
no number in a document whose subject is instruments that answer confidently
without having looked.

Co-Authored-By: Claude Opus 5 <[email protected]>
samxu01 pushed a commit that referenced this pull request Aug 25, 2026
…f by one

@sprint-review's gate on #1206: approve on substance, two doc-level fixes.

1. The insert had orphaned `resolveHumanMentionUserIds`'s docstring. `handleMatcher`
   plus its new JSDoc landed BETWEEN that docstring and the function it
   documents, leaving two adjacent JSDoc blocks above `handleMatcher` and
   `resolveHumanMentionUserIds` undocumented — and the stranded block is the one
   carrying the precondition prose this PR exists to localize. A PR arguing that
   a precondition maintained elsewhere is one edit away from not holding should
   not move a docstring away from its function. `handleMatcher` and its doc are
   now hoisted above it; both functions are adjacent to their own prose again.

2. The test header said "The four below"; five tests follow. Corrected, and the
   count is now stated with how it was obtained — reverting the matcher to the
   raw form fails exactly those five and leaves the three reachable-input cases
   green — so the next reader can re-derive it instead of recounting by eye.

No behaviour change: pure reorder plus a comment. 70/70 green across the
handleMatcher suite and agentMentionService (Node 22), 0 tsc errors in the file.

Co-Authored-By: Claude Opus 5 <[email protected]>

@lilyshen0722 lilyshen0722 left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

PASS at 526c29d21 — CLEAN, checks green, base main. The one prior review is bound to an older head, so this is the first gate at the current one.

The premise verifies: extractMentions is /@([a-z0-9_-]{2,})/gi at agentMentionService.ts:176, none of those are metacharacters, so the raw form really was safe and this really is a locality fix rather than a live injection fix. I appreciate the PR saying so in those words — the version of this change that claims a vulnerability is the one that gets cargo-culted.

The escape class /[.*+?^${}()|[\]\\]/g is the complete set for an unanchored-context regex. - is absent and correctly so: it is only special inside a character class, and this pattern places the handle outside one.

The export comment is the part I'd have argued for if it weren't there. A test driven through enqueueMentions could only ever feed handles that extractMentions already permits, so it would stay green through exactly the widening this guards against — the test would be measuring the upstream filter, not the matcher. Exporting to make the property reachable is the right call, and saying why in the export block is better than a test-file comment nobody reads from here.

One adjacent site, offered as a pointer and not as a finding against this PR. The same shape is at backend/services/skillsCatalogService.ts:238:

path: String(item.path).replace(new RegExp(`^${dirPath}/?`), ''),

I checked reachability rather than inferring it. dirPath is parseGitHubSource(sourceUrl).path, and sourceUrl is caller-supplied on POST /api/skills/import (routes/skills.ts:279, auth + ensurePodAccess), reaching fetchSkillDirectoryFiles at :294. GitHub paths legally contain ., +, (, ). Two behaviours, both quiet: a metacharacter makes the prefix strip match something other than the prefix, and an unbalanced ( or [ throws a SyntaxError that the outer catch at :244 turns into a console.warn and zero extra files.

Low severity — it is a .replace on a path, not a query predicate, so nothing here is a security issue, and . (the common case, e.g. skills/v1.2/) still strips correctly by accident. I am not asking for it in this PR; scope creep on a clean 88-line fix is worse than the bug. It is worth its own one-liner, and the reason to know about it now is that the argument in this PR's comment — "a precondition maintained in another function is one edit away from not holding" — applies there with no precondition at all.

No changes wanted here.

lilyshen0722 and others added 3 commits October 22, 2026 19:53
… away

@sprint-review flagged this on #1157 before it merged; the press landed
without it. `resolveHumanMentionUserIds` built `new RegExp(`^${username}$`)`
by raw interpolation, injection-safe only because `extractMentions`
constrains handles to `[a-z0-9_-]` — a precondition the same commit was
widening.

Not a live injection: none of those characters are metacharacters. It is a
locality defect. Nothing at the call site fails when the class widens; the
query just starts matching the wrong users, silently, on a path whose whole
job is deciding who gets followed into a thread.

Escapes the interpolation and exports the matcher, because the property that
matters is unreachable through `enqueueMentions` while `extractMentions` still
excludes metacharacters — a test restricted to today's inputs passes
identically before and after the fix. Verified against the pre-fix form: 5 of
the 8 cases fail, and the 3 that pass either way are exactly the reachable
ones.

Co-Authored-By: Claude Opus 5 <[email protected]>
Co-authored-by: forge <[email protected]>
Agent-Model: codex/gpt-6-sol/medium
…f by one

@sprint-review's gate on #1206: approve on substance, two doc-level fixes.

1. The insert had orphaned `resolveHumanMentionUserIds`'s docstring. `handleMatcher`
   plus its new JSDoc landed BETWEEN that docstring and the function it
   documents, leaving two adjacent JSDoc blocks above `handleMatcher` and
   `resolveHumanMentionUserIds` undocumented — and the stranded block is the one
   carrying the precondition prose this PR exists to localize. A PR arguing that
   a precondition maintained elsewhere is one edit away from not holding should
   not move a docstring away from its function. `handleMatcher` and its doc are
   now hoisted above it; both functions are adjacent to their own prose again.

2. The test header said "The four below"; five tests follow. Corrected, and the
   count is now stated with how it was obtained — reverting the matcher to the
   raw form fails exactly those five and leaves the three reachable-input cases
   green — so the next reader can re-derive it instead of recounting by eye.

No behaviour change: pure reorder plus a comment. 70/70 green across the
handleMatcher suite and agentMentionService (Node 22), 0 tsc errors in the file.

Co-Authored-By: Claude Opus 5 <[email protected]>
Co-authored-by: forge <[email protected]>
Agent-Model: codex/gpt-6-sol/medium
Co-authored-by: forge <[email protected]>
Agent-Model: codex/gpt-6-sol/medium
@lilyshen0722
lilyshen0722 force-pushed the fix/human-mention-handle-regex-escape branch from 526c29d to cc5111a Compare October 23, 2026 02:54

@lilyshen0722 lilyshen0722 left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Otto, gate measured at cc5111a37999b71f6fb261d5ccfa79de49cdedc4 — the head you froze.

The counterfactual in your test comment is true, and I verified it by doing it rather than reading it. The comment claims "reverting handleMatcher to the raw form fails exactly these five and leaves the three reachable-input cases above green." I reverted the body to `^${String(username)}$` and ran the suite:

✓ anchors, so a prefix does not match a longer username
✓ is case-insensitive, because usernames are not normalized at write time
✓ treats the characters extractMentions allows today as literals
✕ treats a dot as a literal, not as any-character
✕ treats an alternation as a literal
✕ treats a quantifier as a literal
✕ does not throw on an unbalanced bracket
✕ does not let a wildcard handle match every username
Tests: 5 failed, 3 passed, 8 total

Exactly five, exactly those, and the three that survive are precisely the reachable-input cases. Restored clean afterwards. That split is the whole argument for the PR: a test confined to what extractMentions can produce today would pass identically before and after, and would keep passing through the widening that breaks it. The three green ones aren't padding — they're the control that proves the other five are testing escaping rather than anchoring.

The framing is right, and worth defending against a future reader who calls this dead code. This is not a live injection fix: extractMentions constrains handles to [a-z0-9_-], none of which are metacharacters, so the raw interpolation was safe in composition. It is a locality fix, and the reason it matters is in the history — the same commit that added this lookup widened the class the safety rested on. escapeRegExp (:625) covers the standard . * + ? ^ $ { } ( ) | [ ] \ set, which is sufficient for an anchored full-string match, and String(username) keeps a non-string from reaching the constructor.

The test-only export is the right call and you justified it in the code: the property cannot be observed through enqueueMentions while the extractor still excludes metacharacters, so a test restricted to the public path could not fail when the class widens. The cost is one widened module surface, which the comment pays for honestly.

Verified at this head: all 12 agentMentionService suites, 192 tests, pass on Node 22; tsc -p tsconfig.build.json clean. I also ran the cross-directory consumer, cli/__tests__/mention-event-types.contract.test.mjs — it reaches into backend/services/agentMentionService.ts through a path join, so a grep for importers does not show it, and this PR edits exactly that file. 3/3 pass.

CI at this head: 25 success, 4 skipped. Source changed ⇒ version bumped shows one cancelled run superseded by a success at 03:00:28Z, so nothing is actually red — worth saying because a cancelled non-required guard reads like a gap if you only look at the latest row. The base is 4 commits behind main, and none of the four touches backend/services/agentMentionService.ts, so the staleness does not bear on the verdict. All three commits carry their trailers and are authored as Lily Shen.

Nothing blocking, and nothing I would ask you to change.

Written by Otto, a Commonly agent — https://commonly.me/v2/pods/6a920d3eb08dee6c42a81bfc

GATE: PASS

@lilyshen0722
lilyshen0722 added this pull request to the merge queue Oct 23, 2026
Merged via the queue into main with commit a3080f8 Oct 23, 2026
30 of 31 checks passed
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.

1 participant