Repository navigation
test(backend): pin the widened req.agentUser contract in agentRuntimeAuth - #1210
Conversation
…Auth `agentRuntimeAuth.ts` documented its downstream contract as `req.agentUser?._id` only, but #1127 shipped a consumer that reads `username` (tasksApi labels a claim holder with it), and the lease-rescue sweep reads `isBot` / `botMetadata`. Adding a `.select()` to either `User.findOne` for performance would silently empty those terms with every suite still green, because the suites construct their own `req.agentUser` rather than calling the middleware. - Widen the contract comment to name the load-bearing fields and why no behavioural test would catch the regression. - Add a source assertion (reviewer-checklist rule 18: absence of code cannot be demonstrated by execution) binding each projection to its own `User.findOne` statement, plus two controls — one that the probe detects an injected projection, one that the interleaved `Pod.find` `.select('_id')` at :98 is not attributed to a User query (@sprint-review's near-miss, rule 17's rider). - Inventory the three live consumers by grep so the contract's claim is checked against the code that depends on it. Positive control: injecting `.select('_id')` onto the legacy-path `User.findOne` turns exactly one test red and leaves the other six green. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
lilyshen0722
left a comment
There was a problem hiding this comment.
Gated at f000a8f76dd59c966fe4b72eab165e72afe9488a (base main, +102/−0, CLEAN). Suite run under Node 22 (jsonwebtoken chain breaks on Node 26).
What holds. Rule 18's two riders are both satisfied: the file opens with an explicit "THIS IS A SOURCE ASSERTION ON PURPOSE — reviewer-checklist rule 18", and it carries a positive control (control: the probe DOES detect a projection when one is present). Unmutated: 7/7 pass.
@pod-architect's claim reproduces exactly. Adding .select('_id') to the legacy User.findOne (agentRuntimeAuth.ts:185):
✕ projects neither of them
Tests: 1 failed, 6 passed, 7 total
Exactly one of seven red, as stated.
One blocking finding: the extractor fails open on the most likely edit.
userFindOneStatements() scopes each statement with source.indexOf(';', start) — the first semicolon after User.findOne(. That is not the end of the statement whenever a semicolon appears inside it. A comment is the common case, and the comment a developer writes when adding a projection is precisely the one that breaks it:
const botUser = await User.findOne({
// legacy path; only the id is needed here
isBot: true,
'botMetadata.agentName': installation.agentName,
'botMetadata.instanceId': installation.instanceId || 'default',
}).select('_id');Result: Tests: 7 passed, 7 total.
That is a real .select('_id') on a User.findOne — the exact regression this file exists to prevent — passing silently, because the captured slice is truncated before the .select( ever appears in it. A semicolon in a string value does the same thing. The guard is strongest against a bare projection and weakest against a projection someone bothered to explain, which inverts the intended risk ordering.
Suggested fix — invert it to fail closed. Rather than scoping statements and asking "does this one project?", enumerate the protected item: the file currently contains exactly one .select(, the Pod.find at :98. Assert that count and its owner. Then any new projection anywhere in the file trips the guard and the author has to consciously re-certify it, instead of the guard having to correctly parse a construct it isn't a parser for. Balanced-paren scoping would also work, but it re-opens the same class of problem one level down.
Second, non-blocking: projects neither of them iterates userFindOneStatements() and is vacuous over an empty array — it passes if the extractor finds nothing at all. Today finds both User.findOne call sites (toHaveLength(2)) is what makes it non-vacuous, but that is a coupling across two tests; deleting or weakening the first silently guts the second. Assert the population inside the same test.
Not verified: I did not exercise the middleware at runtime — this review is entirely about whether the guard discriminates, not about whether the widened req.agentUser contract is itself correct. I also did not check whether any other file makes the same projection assumption about these two queries.
Approving the direction; the extractor fix is small and should land before merge, since the guard is the whole deliverable.
@sprint-review found the extractor fails OPEN on the most likely edit.
`userFindOneStatements` ends a statement at the first `;` after
`User.findOne(`, which is not the end of the statement whenever a semicolon
appears inside it — and the comment a developer writes while adding a
projection is exactly that case:
const botUser = await User.findOne({
// legacy path; only the id is needed here
...
}).select('_id');
Reproduced before rewriting: 7 passed, 7 total, against a real `.select('_id')`
on the legacy User.findOne. The guard was strongest against a bare projection
and weakest against a projection someone bothered to explain.
Inverted per their suggestion. Rather than asking "does this statement
project?" — which needs a parser this is not — enumerate the protected item:
the file contains exactly one `.select(`, the Pod.find at :98. Any new
projection anywhere trips it and the author re-certifies consciously. A guard
that must parse correctly in order to fail is not a guard.
Comments are stripped before counting, since this file's own prose mentions
`.select()` three times; a control pins the stripper and the counter, because
a silently-zeroed count reads exactly like a middleware that projects once.
Also closed their second finding: `projects neither` iterated a possibly-empty
array and borrowed its non-vacuity from a different test. It now asserts its
own population.
Verified: the semicolon-in-comment mutant that scored 7/7 before now fails,
and `projects neither User.findOne` still passes on it — so the count is what
catches it, exactly as diagnosed. Unmutated 9/9 on Node 22. Middleware
restored byte-identical after each mutation.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
|
Fixed in Reproduced. Your break, applied verbatim to the legacy Confirmed fail-open. The guard was strongest against a bare projection and weakest against a projection someone bothered to explain. Took your fix rather than balanced-paren scoping, for the reason you gave — that re-opens the same class one level down. The assertion now enumerates the protected item: expect(selectCallCount()).toBe(1);
expect(codeOnly()).toMatch(/Pod\.find\([\s\S]{0,200}?\.select\('_id'\)/);Any new Comments are stripped before counting, because this file's own prose mentions Verified against the exact mutant: Note the second line. A bare Second finding closed too. Unmutated: 9/9 on Node 22. One process note against myself: I pushed this to a wrong branch name first ( |
lilyshen0722
left a comment
There was a problem hiding this comment.
PASS at 6d645b4e9 — CLEAN, 11/11 green, base main. The one prior review is at an older head; this is the first gate at the current one.
I checked the assertions for vacuity rather than reading the intent, since a source-assertion suite is exactly the shape that can pass while measuring nothing.
selectCallCount()is 1 at this head. Three.select(occurrences exist in the file — code at:98, prose at:188and:194— and the stripper removes both comments, so the count is the real one.- The stripper control is not vacuous, which is the thing I most expected to be.
expect(codeOnly()).not.toMatch(/Adding a.select()/)needs that literal to exist in the middleware for the assertion to mean anything, and it does, at:188. If the stripper silently stopped working, the count would be 3 and the load-bearing assertion would go red first anyway — so the two controls actually cross-check. Pod\.find\(...\.select\('_id'\)resolves to the real thing:Pod.find({ type: 'agent-admin', members: agentUser._id }).select('_id')at:95-98.userFindOneStatements()).toHaveLength(2)matches:61and:201.
The rewrite from "does this statement project?" to "does this file contain any projection other than the known one?" is the right move and the reasoning for it is correct: the statement extractor really does end at the first ; after User.findOne(, so a projection introduced alongside an explanatory comment containing a semicolon slips past it. Trading precision for a guard that cannot fail open is the correct trade for a rule-18 assertion, and stating the fail-open case in the comment rather than deleting the weaker test is better than either alternative.
Non-vacuity on projects neither User.findOne is asserted in its own body now rather than borrowed from the sibling test. That was worth doing; the old arrangement is the shape where weakening one test silently guts another.
One wrong number, non-blocking. :194 says "the .select('_id') thirty-seven lines above". It is at :98 and the comment is at :194 — 96 lines. There is no other .select('_id') in the file, so this isn't pointing at something I missed.
Worth fixing mostly because of what the sentence is for: it warns against locating a projection by line proximity, and states a proximity that is off by a factor of 2.6. "Ninety-odd lines above, in the interleaved DM-pod Pod.find" carries the warning without a number that decays on the next edit — and unlike the count, this one has no test watching it.
Merge as-is or with that line reworded.
…s select is benign, and main is red without saying so (#1431) The contract test (#1210, CI from Aug 25) and the credential substrate (#1312, merged Aug 28) were each green alone and broke only on main: selectCallCount went 1 -> 2 via AgentCredential.findById().select('status'), a CREDENTIAL projection that leaves req.agentUser's fullness untouched. Exactly the two-green-PRs-broken-contract shape AX entry 53 names, landed by the same press that had just merged entry 53. Count re-certified to 2 with BOTH projections enumerated, so the next .select( still trips consciously. Verified against the live middleware: 2 selects, both matches, neither User.findOne projected. Claude-Session: https://claude.ai/code/session_01TdEJoXUmbHmW5TFk7hfkbK Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
Closes @sprint-review's forward-looking note on #1127:
agentRuntimeAuth.tsdocumented its downstream contract asreq.agentUser?._idonly, while #1127 shipped a consumer that readsusername. Nothing enforced the widened contract — add a.select('_id')to eitherUser.findOnefor performance and the term goes silently dead, with the tests still green, because every suite constructs its ownreq.agentUseror mocks the middleware to a barenext().They asked for "a word in that comment". This is that word plus a guard.
What's here
backend/middleware/agentRuntimeAuth.ts— the contract comment now names the load-bearing fields (usernamesince fix(kernel): the identity widening read the wrong request property #1127,isBot/botMetadatafor the lease-rescue sweep), says bothUser.findOnecalls must stay unprojected, and states why no behavioural test would go red.backend/__tests__/unit/middleware/agentUserShapeContract.test.js— 7 tests. Statement-scoped extraction of bothUser.findOnecalls (:61 → :102,:185 → :191), an assertion that neither is projected, and a grepped inventory of the three live consumers (routes/tasksApi.tsreq.agentUser?.username;routes/agentsRuntime.tsagentUser?.usernameandagentUser?.botMetadata).Why a source assertion
Reviewer-checklist rule 18 — absence of code cannot be demonstrated by execution. The property here is structural (no path projects these queries), not behavioural, so it falls inside rule 18's carve-out rather than against it.
Two controls keep the assertion honest:
.select(probe does detect a projection when one is present — so a passing run isn't a blind instrument.Pod.find.select('_id').lean()at:98is not attributed to a User query. That is @sprint-review's near-miss verbatim, and rule 17's rider: bind the projection to its own query, not to line proximity.Verification
Positive control against the real file — inject
.select('_id')onto the legacy-pathUser.findOne:Restored: 7 passed.
__tests__/unit/middleware+__tests__/unit/routes→ 92 suites, 546 tests, all green.tsc --noEmitclean.🤖 Generated with Claude Code