Repository navigation
fix(nextcloud-talk): bound concurrent pre-auth webhook reads - #138278
masatohoshino wants to merge 6 commits into
Conversation
|
🦞👀 Pull request received. I will update this pull request when review starts. ClawSweeper review completeClawSweeper finished reviewing this revision. The review result is being finalized. |
|
Codex review: blocked before merge. Reviewed September 4, 2026, 2:00 PM ET / 18:00 UTC. ClawSweeper reviewWhat this changesThis PR caps concurrent unauthenticated Nextcloud Talk webhook body reads at 64 and returns HTTP 503 when the listener is full. Regression provenancePossible regression — probable (reviewed change; failure trace). No predecessor PR is attributed. Merge readiness⛔ Blocked before merge - 8 items remain Keep open. The capacity proof is strong, but the prior P1 remains: a pipelined overflow rejection can close a connection before an earlier signed delivery finishes durable admission and sends its required 200 response. The new 503 outcome also has no verified Nextcloud redelivery contract. Priority: P1 Review scores
Verification
How this fits togetherNextcloud Talk receives signed events through a standalone HTTP listener, which reads and authenticates the request before sending accepted events to durable inbound storage. The limiter sits before body reading, while durable acknowledgment happens later in the same request. flowchart LR
Sender[Nextcloud webhook sender] --> Headers[Header and backend checks]
Headers --> Budget[Pre-auth capacity budget]
Budget -->|available| Verify[Read body and verify signature]
Budget -->|full| Reject[503 and connection close]
Verify -->|valid| Durable[Durable inbound admission]
Durable --> Ack[HTTP 200 acknowledgment]
Decision needed
Why: The existing ordering owner is core-internal, while direct core imports from the plugin violate the extension boundary; choosing and exposing a supported generic seam is maintainer-owned API direction. Before merge
Findings
Agent review detailsSecurityNone. PR surfaceSource +52, Tests +203, Docs +1. Total +256 across 3 files. View PR surface stats
Review metrics
Merge-risk optionsMaintainer options:
Technical reviewBest possible solution: Expose a narrow generic Plugin SDK connection-ordering seam, use it around the complete standalone listener dispatch, and add a raw keep-alive valid-then-overflow regression proving the earlier durable 200 is delivered before closure. Do we have a high-confidence way to reproduce the issue? Yes—source-reproducible: an existing lifecycle boundary test demonstrates that a rejection behind an unfinished earlier response produces no wire output without response-aware ordering, and this PR adds that rejection trigger to the standalone listener. Is this the best way to solve the issue? No. The limiter addresses the unbounded-read problem, but the standalone dispatch bypasses the canonical ordering owner; a narrow generic Plugin SDK seam is the maintainable repair. Full review comments:
Overall correctness: patch is incorrect AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning high; reviewed against b6a4d0dad430. LabelsLabel changes:
Label justifications:
EvidenceWhat I checked:
Likely related people:
Rating scale
Overall follows the weaker of proof and patch quality. Workflow
HistoryReview history (4 earlier review cycles)
|
sylvesterkaczmarek
left a comment
There was a problem hiding this comment.
Bounding the unauthenticated body-read phase is the right control; the failed-auth limiter cannot help requests that never finish a body and therefore never reach signature verification. Acquiring immediately before readBody and releasing only after rejection teardown preserves the actual scarce resource, not just handler entry. The measured cost is also stated correctly: a valid signed delivery can receive 503 while the pre-auth budget is saturated. I would keep that behaviour explicit in operator docs because retryability depends on Nextcloud’s sender semantics, which this PR does not prove.
The Nextcloud Talk channel runs its own HTTP listener and reads the request body before verifying the signature. Each read is bounded to 64 KiB and 5 s, but there was no application-level cap on how many ran at once, so any client that can reach the port could occupy those reads by opening connections and uploading slowly. No credentials are needed: the signature is not checked until after the read, and the checks that do run first are not authentication. The failed-auth rate limiter cannot cover this. It decides from attempts recorded by recordFailure, which is only reached once a read completes and its signature turns out invalid, so a caller that never finishes a body is never counted. Bound the concurrency with the shared createWebhookInFlightLimiter, one budget of 64 per listener. Excess requests are refused with 503 rather than 429: this handler already depends on the sender retrying a 5xx, answering 500 on admission failure so the delivery stays retryable, and it records no such expectation for 429, so a refusal the sender may not redeliver would turn a capacity limit into silent message loss. The 413 and 408 answers move inside the guarded block so a rejected request keeps its slot until the response has been delivered, which the shared rejection lifecycle bounds at one second. Measured with 512 held connections: the base admits all 512 and holds the next request's read for the full 5 s budget, while a correctly signed delivery sent during saturation still returns 200. On this change admission stops at 64, the next request is refused in 3 ms, and the signed delivery is refused with 503 — the disclosed cost — then admitted again once the held connections finish.
0c5f912 to
4e88c59
Compare
|
Applied — the
The last two sentences go past making the behavior visible, on purpose: the bound is not configurable, so an operator who sees this On retryability, the repository's own statement is the comment at Two other corrections since your review:
@clawsweeper — on the two Before-merge items:
|
|
Closing as superseded by current main. The original problem — unbounded concurrent pre-authentication webhook body reads — is now addressed on main with the shared webhook in-flight limiter. The current listener also runs requests through the repository's connection-ordering owner rather than this PR's standalone rejection path, which was the remaining P1 concern in the review. Given that the needed behavior has landed through a different implementation, continuing to repair this older branch would duplicate current main rather than improve it. |
Related: the SMS channel's equivalent
change — prior art for the shape, not a
prerequisite.
Scope: one production file (
extensions/nextcloud-talk/src/monitor.ts), one existing testfile, and one bullet in
docs/channels/nextcloud-talk.mdrecording the new503outcome.What Problem This Solves
The Nextcloud Talk channel runs its own HTTP listener —
createNextcloudTalkWebhookServercalls
node:http'screateServer(monitor.ts:119,149), started bymonitor-runtime.ts:96,135on the operator-configured host and port — and reads the requestbody before verifying the signature. Each read is bounded to 64 KiB and 5 s
(
monitor.ts:18,21,96-105), but nothing capped how many ran at once, so any client that canreach the port and satisfy the pre-read checks below could occupy those reads by uploading
slowly.
It takes an unauthenticated but protocol-shaped request:
POSTto the configured path, aJSON content type,
x-nextcloud-talk-signatureandx-nextcloud-talk-randommerelypresent — neither is validated at this stage — and, where the account declares a backend
URL, an
x-nextcloud-talk-backendmatching it. None of these authenticate the caller: thefirst two are unchecked until after the read, and the third is a value to know rather than a
secret to prove.
What is claimed here is the absence of a bound, not observed starvation. The capture below
holds 512 unauthenticated reads: the base admits all 512, and a correctly signed delivery sent
while they are held still returns
200and reaches the spool. So the listener keeps servingwith 512 reads open, and this PR does not claim otherwise. What it claims is that no
application-level cap exists — 512 is the number the harness opened, not a limit the code
imposed.
Why This Change Was Made
Nothing before the read bounds repetition.
isBackendAllowedis() => trueunless abackend URL is declared (
monitor-runtime.ts:101-107). The failed-auth rate limiter cannothelp by construction:
createAuthRateLimiter(src/gateway/auth-rate-limit.ts:183) answerscheck()fromentry.attempts, appended to only byrecordFailure, whichverifyWebhookSignaturereaches only after a read completes with a bad signature(
monitor.ts:73-94,recordFailureat:88). A caller that never finishes a body is nevercounted.
This patch changes
monitor.tsto bound the concurrency withcreateWebhookInFlightLimiter(
src/plugin-sdk/webhook-request-guards.ts:125), exported to plugins sincee1ec51b1a4a, anancestor of this base:
createNextcloudTalkWebhookServerand acquired withone fixed key. The limiter counts per key in a map owned by the instance
(
webhook-request-guards.ts:131-155), so one instance plus one key is one budget for thelistener;
503throughsendHttpRequestRejection— that refusal reachesits own sender before its connection closes;
finallyaround the read and signature check, before the spool, which isdownstream of authentication;
413and408answers moved inside that block. Left in the outercatchthey wouldrun after the new
finally, freeing the slot mid-teardown. The teardown is the helper'sordering:
sendHttpRequestRejectionawaitsrejection.closed(
src/infra/http-request-lifecycle.ts:286), resolved on the socket'scloseaftersetTimeout(rejection.destroy, REJECTION_CLOSE_TIMEOUT_MS)— one second (:10,:173).503, not429is a local retryability decision. This file answers500on admissionfailure and says why at
monitor.ts:197-198— "Nextcloud retries only a few times ... appendfailure must remain retryable". This is an analogy, not protocol evidence: that comment is
about an append failure, not about a capacity refusal, and it is the repository's own statement
about the sender rather than a measurement. What it establishes is which status class this file
already treats as worth retrying; there is no corresponding statement for
429. Whether adeployed Nextcloud redelivers a refused webhook is unverified either way.
503is a new user-visible outcome for thischannel, so accepting it on that basis is a maintainer product call; the operator-facing half is
recorded in
docs/channels/nextcloud-talk.md("a 503 here reports load rather than amisconfiguration ... Whether Nextcloud redelivers a refused webhook depends on its own sender
behavior").
64 is a new effective cap for this listener. It bounds how many requests are inside the
guarded region at once, and that region is wider than the read alone: it runs from just before
readBodythrough signature verification to thefinally. So the cap is on unauthenticatedwork in flight, not only on bytes being read. The value is taken from
PRE_AUTH_MAX_IN_FLIGHT(extensions/sms/src/webhook.ts:31, passed asmaxInFlightPerKeyat
:115), where the other standalone listener bounds its own pre-authentication reads —prior art for the number, not a shared policy, and nothing here couples the two. It caps
concurrent admitted
readBodyoperations, each of which may buffer up to the 64 KiBpre-authentication limit. Whether 64 suits a bot webhook receiving one delivery per chat
event is a judgement rather than a measurement; no traffic data is offered for it, and it is
a one-constant change to revise.
Out of scope. The listener keeps its own
node:httpserver rather than registering throughregisterWebhookTargetWithPluginRoute; the failed-auth limiter keeps its semantics; no otherchannel is touched.
User Impact
At most 64 requests occupy the guarded region at once — the budget applies after the method,
header and backend checks, and covers everything from just before the body read to the end of
signature verification. A request arriving while it is full is answered
503, which is a newoutcome here: a delivery that would previously have entered the read can now be refused before
it. That refusal is final for that request; what may succeed later is a redelivery, once a slot
has freed.
413and408keep their existing responses. Cases 2 and 4 below show a validdelivery returning
200after the budget was filled and drained, on the413path and on thesignature-rejection path; case 3 shows the route still serving after a timed-out read, which is
liveness rather than proof that that request returned its slot. No operator-configurable option
is added; the default behavior is what changes.
Three shapes occupy the budget: slow uploads, each holding a slot for as long as its read runs,
up to 5 s — the original defect; oversized bodies, rejected on crossing the 64 KiB cap and then
holding their slot for the rejection's teardown, which the shared lifecycle bounds at one
second; and completed bodies still inside signature verification, which is a synchronous HMAC
and therefore brief, but is inside the region rather than after it.
Evidence
Four cases in the channel's existing wire test file,
extensions/nextcloud-talk/src/monitor.replay.test.ts, undercreateNextcloudTalkWebhookServer pre-authentication concurrency. They drive the realcreateNextcloudTalkWebhookServeron a loopback port over raw sockets, so the status line andconnection outcome are observed independently of
fetch. Fixtures carry what the pre-readchecks need; the requests that occupy the budget carry a placeholder signature (never examined
in cases 1 and 3, whose reads never complete, and in case 2, whose reads end at the 64 KiB cap
before verification; deliberately invalid in case 4), and every
delivery asserted to return
200carries a real signature from the channel's fixture helper.answers 503 on the wire once the pre-auth read budget is full— 64 readers held at aninjected barrier, then one more request asserted on the wire: status line,
connection: close, JSON body, server-side close, unadvanced counter;returns an over-limit body's slot, so later deliveries still land— 64 oversized requestsissued together, each answered
413; past the rejection grace a valid signed delivery gets200. That200shows at least one slot came back, not that all 64 did — one free slotserves one delivery. What covers the other 63 is that all 64 are asserted to receive their
413, that answer is giveninside the guarded region, and the release is an unconditional
finallyon that path, soeach of the 64 released on its own. The hold itself is bounded by a wall-clock grace inside a
shared owner, and asserting it is still held would mean racing that clock on the runner, so
this case deliberately asserts only the deterministic half;
answers a stalled upload with 408 on the wire and does not wedge the route— a requestdeclaring 4096 bytes and sending one is answered
408after the 5 s read timeout, and adelivery 1500 ms later gets
200. This holds one request against a budget of 64, so that200shows the route still serves; it does not establish that the timed-out requestreturned its slot, since 63 were free regardless. The release ordering for that block is
what case 2 covers — both branches are the same
rejectWebhookRequestcall in the sameposition, inside the same
finally;releases the slot a rejected signature took, so later deliveries still land— 64 reads areadmitted and parked at an injected barrier, the barrier is opened, each completes and is then
rejected by signature verification, and a valid delivery afterwards returns
200. As in case2, that
200shows at least one slot; the other 63 rest on all 64 taking the sameunconditional release.
Reverting
monitor.tsto the base givesTests 1 failed | 15 passed (16): case 1 fails, sinceit asserts a
503that exists only with the budget. Cases 2-4 pass either way — they guard thenew mechanism against leaking slots or wedging the route rather than demonstrating the defect.
Behavior addressed: the listener applies no application-level cap on concurrent
pre-authentication body reads.
Real environment tested: Linux, Node v24.18.0. A standalone probe — not part of this diff;
the in-tree reproducer is the regression above — starts the real listener on a loopback port and
drives it over real TCP. It opens 512 connections carrying the four headers the pre-read checks
require and a
Content-Lengthfor the real payload, writes one byte on each and stops, thensends one more request, sends a correctly signed delivery while saturated, writes the remaining
bytes on all 512, and sends the signed delivery again.
admittedToSpoolcounts calls into thelistener's
onWebhookhandler — the point past authentication where a delivery is accepted — andeach arm runs its own process, so the counters start at zero on both sides.
reachedBodyReadcounts requests whosebody produced at least one chunk, so it measures the 512 holders only: the extra request sends
headers and no body, and therefore never advances the counter on either arm. Whether it was
admitted is read from its own answer instead — a
408after the full 5 s read budget means itentered the read; a
503in under a millisecond means it did not.Exact steps or command run after this patch:
Both arms run the same script in their own checkout.
monitor.ts-blobisgit hash-objectofthe file the process actually loaded, so each side is identifiable independently of the branch
name. The script is not in this diff and is not fetchable from it, so a reviewer cannot re-run
this command: the reproduction anyone can run is the committed wire test above, which asserts
the same boundary on the same listener. The probe is here because it reaches 512 connections and
the real production reader on both arms, which the test file does not.
Before evidence: base
7167fb6f195, blobc4c245a234c, which equalsgit rev-parse 7167fb6f195:extensions/nextcloud-talk/src/monitor.ts.All 512 are admitted. The extra request is admitted too:
408after 5001 ms is thepre-authentication read timeout (
PREAUTH_WEBHOOK_BODY_TIMEOUT_MS,monitor.ts:21) firing,which only happens inside the read it entered.
Evidence after fix: head
802c408b5fe, blob76fc3634a58.Observed result after fix:
reachedBodyReadstops at exactly the bound — 512 → 64 — and theextra request is answered
503in under a millisecond instead of entering a read and timing outafter 5001 ms. The
while saturatedline is the cost this PR imposes, measured rather than argued: a correctly signed delivery that
returns
200on the base is refused with503on the branch. The line after it shows thecapacity is not leaked — once the held connections finish, a subsequent identical signed
delivery is admitted. The refused request itself is over; the listener does not retry it.
What was not tested: no deployed Nextcloud server, so its handling of the refusal is not
demonstrated — whether it redelivers a refused webhook is its own sender behavior, and the docs
bullet says so rather than asserting it. No claim is made that deliveries stop arriving at
today's scale; see the note above.
Known risk, deferred: this listener does not serialise responses through
runHttpConnectionRequest(src/infra/http-request-lifecycle.ts:75), so on a pipelinedconnection a refusal that closes the socket can cut a response owed to an earlier request. The
existing
413and408answers already close the socket the same way; the new503adds onemore occasion. It holds for the other standalone listeners too, so the fix is a shared seam
rather than a change here, and a local attempt at it broke the channel's existing suite. Not
carried in this PR; happy to open an issue for it.
All file and line references are against base
7167fb6f1959e9ecb9381e33c4c0a36b6865459a.