Repository navigation
app/: bound the work strangers' GitHub App installations and anonymous requests can cause (sc-9144, sc-9124) - #162
Open
ndbroadbent wants to merge 7 commits into
Open
ndbroadbent wants to merge 7 commits into
ndbroadbent wants to merge 7 commits into
Conversation
…s requests can cause (sc-9144, sc-9124) The GitHub App is public, so anyone can install it and make GitHub send its webhook. - /webhooks/github refuses a missing or malformed signature before reading the body, and a wrong one before parsing it. - Deliveries are rate limited in the cache store (VISUALCI_GITHUB_WEBHOOKS_*): per installation (600/min claimed, 60/min unclaimed), all unclaimed installations together (600/min) and everything (6000/min). Over the limit, a claimed installation gets a 429 (GitHub's delivery log keeps it for redelivery) and an unclaimed one a 202, dropped and logged once a minute. `installation` deliveries count only in the total, so onboarding is never dropped. - Unclaimed installations' membership changes recheck nobody; an installation delivery looks its repositories up in one query and asks GitHub whether the installation exists only when a project changes. - RecheckAccess is debounced (30 s, at most 2 min) over an access_rechecks queue, so a burst of membership deliveries lists every linked repository's collaborators once. /status reports oldest_access_recheck_seconds; the hourly sync clears the queue. - forge::calls counts every request's GitHub calls through the app's HTTP client: 5 per request, 22 for a sign-in, 10 for linking a repository. Logged per request; under APP_ENV=testing a request over budget answers 500, so a handler that loops over a GitHub list fails CI. Jobs count their own. - A sign-in reads at most one page of installations and 20 pages of repositories (10 per installation); a GitLab sign-in at most 20 pages. The unused installation_repositories pager is gone. - OAuth client registrations: 20/hour per address, 1000/day in total. Sign-in start and callback: 60/min per address. Repository picks: 20/hour per person. /status reuses its numbers for 10 s per process.
…s through the queue, picker search past the cap, cached installation tokens (sc-9144, sc-9124) - A claimed installation's delivery over its rate limit is kept (deferred_webhooks, verified payloads only) and acted on at the allowed rate by DrainDeferredWebhooks, capped at 50 MB per installation and 500 MB in total (past a cap: an error in the log and a 202). /status reports oldest_deferred_webhook_seconds. Unclaimed ones are still dropped. - RedeliverFailedWebhooks, every 10 minutes: reads the App's delivery log for the last day (at most 10 pages), and redelivers each failed delivery of a claimed installation once (webhook_redeliveries), at most 50 a run, with VISUALCI_WEBHOOK_REDELIVERY_HEARTBEAT_URL/_TOKEN. - Picks: up to 500 at once, 500 an hour per person and 2,000 a day per organization, refused with the time to try again; ImportRepositories makes 20 projects a run, 15 s apart; validation in one query. - Picker: installations[].listed and .total; for an installation the sign-in didn't list completely, a search asks GitHub once as the person (their sign-in token, encrypted in the cache), 30 a minute per person. - Installation tokens cached encrypted until 5 minutes before expiry, forgotten on a 401.
ndbroadbent
force-pushed
the
app-abuse-hardening
branch
from
December 4, 2026 01:47
54ecd3a to
30afdd3
Compare
…44, sc-9124) - admit() never accepts a delivery whose counts can't be read; a refused delivery gives its earlier counts back. - Claims by plan: paid installations count against nothing shared (600/min, 50 MB kept); free ones 120/min, 5 MB each and 50 MB together, and the shared total; the total covers unclaimed and free traffic only. - A claimed delivery over the storage cap gets a 503 (redelivered later), never a 202. - Redelivery: a high-water mark, up to 100 pages; partial runs fail the heartbeat; paid first, oldest first, 10 per installation; refused redeliveries recorded and retried up to 3 times; the run goes on. - Drain: rows claimed per run (claimed_until), runs capped at 240 s, blocked installations left out in SQL, and live deliveries kept behind an installation's kept ones so they're acted on in order. - OAuth registrations: trailing-slash paths limited (hosts.rs too), IPv6 by /64, a cap on never-used clients that deletes the oldest instead of a daily total. - Picks: limits checked and recorded under per-org and per-person advisory locks. - Nits: kept GitHub token forgotten on sign-out; claimed deliveries deduplicated by X-GitHub-Delivery; in-flight body bytes capped per process; no Instant subtraction in log_dropped; /status lock not held across the query and failures cached 2 s; defer's cap check atomic; import batches recheck the admin role; retry times with the date when not today; the drain rechecks claims.
…-9124) - Redelivery: failed deliveries are recorded in webhook_redeliveries as the log is read and drained across runs (paid first, oldest first, 10 per installation, 50 a run); the mark moves only once a scan reaches the old one, and a partial run resumes from its cursor. A redelivered delivery whose new attempt fails is pending again with a doubling backoff, given up with an error after 5 tries or 72 hours. - Body budget taken per megabyte as bytes arrive, with a 1 MB/s minimum rate; requests from outside GitHub's hook addresses (GET /meta, refreshed hourly; /status github_hook_addresses_seconds) share an 8 MB budget. - /status: a drop guard clears the asking flag, which also expires after 15 s; no answer older than 60 s. - OAuth: IPv6 /48 limit too; only unused clients over a day old are deleted, warn when they are. - defer() counts bytes in deferred_webhook_bytes, locking only the installation's row. - The drain counts an attempt when it claims a row. - A claim's plan comes only from the organization the installation is set up for. - Dedupe inserts the GUID first, released when acting on it fails.
…count refilling on a slow CI machine doesn't fail it
…c-9124) - Dedupe claims have a state: processing (taken over after 2 minutes, answered 409 meanwhile) and done (the only duplicate), so a request cut off or a worker gone mid-way can't make a retry look handled. - Redelivery queue: paid stored on each row and ordered first in SQL; unclaimed installations' failures not recorded; at most 100 waiting per free installation; a free installation's own full store answers 507, never recorded. - OAuth: 5 registrations a day per address or /64 (15 per /48), unused-client cap 100,000, a 150,000 ceiling past which the oldest go whatever their age, and a once-a-minute warning while registrations get 429s. - GitHub's hook addresses read within five minutes of starting; a cache error counts as outside. - A rejected resume cursor is cleared and the log read again from the newest. - The counters' overshoot comment names the in-flight body bound.
…sc-9124) - OAuth registrations counted per address (or /64) and redirect URI host, 50 a day, so a hosted platform's users sharing its addresses get their own count; 500 a day per address across hosts, 3x per /48; counts given back on a refusal. - A free installation with a paid organization's projects linked through it answers 503 past its store's cap (redelivered), and its failures go first without the free queue cap; its rate limits stay its own organization's. - The drain acts on a kept delivery for at most 90 s, under the 120 s takeover; a timeout releases the claim. - Claims carry a random owner token; only the owner finishes or releases one. - design.md: a free installation keeps at most 100 failures waiting, and its 507s aren't redelivered.
This branch has not been deployed
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.
Two CLI fixes, one version bump (0.2.24 → 0.2.25).
sc-9174: an upload with identical files fails on R2 429
WeasyPrint's build of 42 files held 14 identical
.txtfiles. The server answers an upload URL for every snapshot whose file it lacks, and identical files share one content-addressed key, so the CLI PUT the same key up to 14 times in parallel. R2 lets one client write an object about once a second, and the retries from #128 (6 tries, 0.5 s → 8 s, no jitter) retried in lockstep, so the upload failed.add_snapshotsuploads each distinct SHA-256 once per run, across registration batches too. Every snapshot is still registered by name with its hash; the others point at the same blob. The registration request sends each snapshot once, as before; it's the upload list that asked for the same SHA twice, and that's deduplicated now.put_blobinstead of adding a second layer. 429, 5xx and dropped connections still get 6 tries with exponential backoff (orRetry-After, at most 30 s), plus up to 50% random jitter so parallel uploads don't retry together.uploading out/sample-03.txt: the store refused it 6 times, the last with 429 Too Many Requests(an inline snapshot shows asname (from path)). The presigned URL no longer goes into the log.POST /snapshots(app/src/http/api/builds.rs) would cover them; I left app/ alone here.sc-9164: PDF fingerprints change every run when font subsets carry a timestamp
fontTools stamps the time it saves each subset into
head.modified, which changeshead.checkSumAdjustmentand the directory checksum forhead. So every run of WeasyPrint, fpdf2 and similar tools got new fingerprints.visualci-core::pdf): font programs under a font descriptor'sFontFile2orFontFile3are decompressed (Flate etc. via lopdf), thennormalize_sfntzeroeshead.modified,head.checkSumAdjustmentand theheadtable-directory checksum before hashing. It parses the sfnt table directory and findsheadby tag. It skips the font, leaving it to be hashed as it is, unless the version is 0x00010000,trueorOTTO, the whole directory fits the data, theheadrecord exists, the table holds at least 36 bytes in range (checked arithmetic) and the magic number is 0x5F0F3CF5. No indexing can panic. CFF (Type1C), Type 1FontFileand collections are hashed as before. A font program the normalisation doesn't change hashes exactly as before: the referenced-stream path feedsRplus the stream's digest, the same asfeed.pdf::fingerprint_without_font_programs), it lists them under "same drawing, embedded fonts differ" with a note that this is usually a subsetter's timestamp, and suggestsSOURCE_DATE_EPOCH. It doesn't list every page as differing. It still exits 1, because those PDFs would still re-render each run.SOURCE_DATE_EPOCH. skills/ is regenerated and the plugin is bumped to 0.1.54.Deploy impact (fingerprints are shared with the renderer)
ALGORITHMstaysvci-pdf-1. I reworded its doc comment: bump it when a change could let PDFs that draw differently match. This change only makes fewer bytes count, so an old fingerprint can equal a new one only for PDFs that draw the same. Bumping would have re-rendered every PDF; this way only the affected ones re-render.headtable. That's most PDFs with embedded TrueType subsets (WeasyPrint, Chrome/Skia, fpdf2, ReportLab TTF).checkSumAdjustmentis never zero, so these get a new fingerprint once, whether or not their font had a timestamp. PDFs with only CFF/Type 1 or non-embedded fonts keep their fingerprints.rendersis keyed by project, source fingerprint and renderer), so they upload, render and get charged rendered-page credits once. Their manifest groups (sc-8868) hash fingerprints, so those groups show as needed and are re-checked once. After that, timestamp-only runs match and stop re-rendering.base.image == head.imageor the pixel fingerprint), so a re-render of the same drawing compares unchanged. Nothing shows as changed and nothing needs re-approving. The text-snapshot "variant" lookup uses text fingerprints, not PDF ones.document_fingerprintfrom the samefingerprint_bytes, so the CLI 0.2.25 and the renderer agree on any file.blobs.pdf_fingerprintis written only where it's NULL, so blobs already rendered keep the old value. That only matters when a PDF is registered by hash alone without a fingerprint (current CLIs always send one), and the worst case is one extra render.Security review fixes (review of 30afdd3)
when_uncounted). A claimed installation's delivery is kept for later; if the database is down, keeping it fails with a 5xx, which GitHub logs as failed and the redelivery job picks up. An unclaimed installation's delivery is dropped with a 202.Bucket::give_back, through thelaravel-rust-cachecrate, since 0.1.4'slaravel::rate_limitdoesn't exportBucket). The drain therefore doesn't spend a second token.webhook_redelivery_marks) and pages back to it, at most 100 pages and 24 hours.partial, and its heartbeat is a failure.webhook_redeliveriesand the run continues. Later runs retry it first, up to 3 tries in all.claimed_until, 5 minutes, through a conditional UPDATE), and a row another run holds blocks its installation for this run. A crashed run's claim expires, so the delivery is retried rather than lost. I chose this overDELETE … RETURNINGbecause a crash then would lose the delivery.has_deferred), so they're acted on in order.hosts.rsis_oauth_server_pathnow trims trailing slashes too, so/oauth/register/is the MCP host's path and is limited.VISUALCI_OAUTH_UNUSED_CLIENTS, 5,000): a registration past the cap deletes the oldest unused clients first (registered over 10 minutes ago, with no authorization code pending), so new MCP clients can always register. It refuses only while every unused client is newer than that. Concurrent registrations can overshoot the cap by however many arrive at once, and the next registration corrects it.pg_advisory_xact_lockper organization, then per person (always in that order). The job is dispatched after the commit.Nits:
X-GitHub-Delivery(webhook_deliveries_seen, kept 3 days, pruned by the redelivery job), live and in the drain. Unclaimed ones aren't recorded: they're inconsequential, and recording them would cost a write each.Content-Lengthrounded up, or 25 MB without one). A request that waits more than 5 s gets a 503.log_droppedkeeps anOption<Instant>, so there's no subtraction that could panic./statusholds its lock only to read or write the cached value. While one request queries the database, others get the last answer. A failure is cached for 2 s.defer()checks the caps and inserts under an advisory transaction lock, so it's atomic with no overshoot.import_batchstops a pick (with an error saying why) when the person is no longer an admin of the organization.Review-fix tests:
Re-review fixes (review of 975bfb5)
webhook_redeliverieswith its GUID, installation, the first and last attempt IDs seen, and a state (pending,redelivered,succeeded,given_uporskipped). Runs drain thependingones across runs: paid installations first, oldest first, 10 per installation and 50 per run, and the rest wait. The mark moves only once a scan has read back to the old mark. A run that stops at its page cap saves its cursor and the newest ID it started from (webhook_redelivery_marks), and the next run resumes there. Within a scan, an older failed attempt of a GUID that already got a 2xx isn't recorded. A success read in an earlier run can't be seen that way, so that delivery may be redelivered once; the GUID dedupe then makes it a no-op.pendingagain, with a backoff of 10 minutes doubling each time. After 5 tries it's given up with an error log, as are entries older than 72 hours (how long GitHub keeps them). An ask GitHub refuses is recorded, retried with the same backoff, and the run continues.GET /metahooks, refreshed hourly byRefreshGithubHookAddressesinto the cache store;/statusreportsgithub_hook_addresses_seconds. The check usesrequest.ip()as the trusted proxies resolve it, and while the list isn't known yet every address counts as GitHub's./statuscan't get stuck on a stale answer. A drop guard clears the "someone is asking" flag however the request ends, and the flag also expires after 15 s. No answer older than 60 s is ever served.deferred_webhook_bytes(per installation, free, total), updated in the same transaction. Only the installation's own row is locked (FOR UPDATE), so its cap holds exactly. Thefreeandtotalrows are read without a lock and incremented atomically, so deliveries for different installations never wait on each other. Those two caps can overshoot by the deliveries being kept at that moment, at most 25 MB each.org:deletedeletes organizations), so the kept token is forgotten on sign-out and otherwise expires within 8 hours.Re-review tests:
pendingbehind a backoff, is redelivered again, and is given up after 5 tries.Third-pass fixes (review of 7cac487)
webhook_deliveries_seennow has a state andstarted_at. A delivery is claimed asprocessingand set todoneafter success; onlydonecounts as a duplicate (200). Another delivery of a GUID that's stillprocessinggets a 409, which isn't a 2xx, so GitHub's log keeps it as failed for the redelivery job. A claim stillprocessingafter 2 minutes (past the 30 s request limit) was abandoned (a request cut off, a panic, a worker gone), and the next delivery takes it over. If acting on it fails, the claim is released. In the drain, a delivery another request is acting on waits with its installation until the next run, and the attempt isn't counted.paid(the claim tier at recording time), and the drain query orders bypaid DESC, first_attempt_idbefore itsLIMIT.VISUALCI_OAUTH_UNUSED_CLIENTS_CEILING): above it, the oldest unused clients are deleted whatever their age./metarefresh is scheduled every five minutes but only fetches when the list is missing or an hour old, so a new server has it within five minutes of starting. I chose that over a boot hook, which would make every test boot call GitHub. A cache read error now counts as "outside" (the 8 MB budget).Third-pass tests:
processingclaim is taken over and acted on once; a live one gets 409 and is never answered as a duplicate.Fourth-pass fixes (review of 747626b)
VISUALCI_OAUTH_REGISTRATIONS_PER_REDIRECT_HOST). Hosted platforms like claude.ai's connectors register their users' clients from shared egress addresses with their own callback host, so they get a count of their own, and one attacker can't fill another platform's.VISUALCI_OAUTH_REGISTRATIONS_PER_ADDRESS), and 1,500 per IPv6 /48.finish_deliveryandrelease_deliveryact only on a claim their caller still owns, so a late release can't undo a newer takeover.docs/design.md(limits): a free installation keeps at most 100 failures waiting, and its 507s aren't redelivered.Fourth-pass tests:
Tests
identical_files_are_uploaded_once: 20 identical files throughadd_snapshotsagainst a fake API and store → registered 20, exactly 1 PUT.an_upload_the_store_refuses_once_succeeds_on_a_retry: a 429, then success → 2 PUTs.an_upload_the_store_keeps_refusing_fails_naming_the_file: persistent 429 → 6 PUTs, and the error namessample-00.txt, "6 times" and 429.ignores_the_time_a_font_subset_was_saved: a synthetic TrueType subset (generated in the test, with real table checksums andcheckSumAdjustment) in a minimal PDF as Flate-compressedFontFile2. Two copies that differ only inhead.modifiedand the two checksums get the same document and page fingerprints.a_font_with_other_glyphs_still_changes_the_fingerprint: differentglyfbytes → different fingerprint, and the fonts-left-out fingerprint still matches (the compare-runs case).malformed_fonts_are_left_alone_without_panicking: empty data, a truncated header, directory or head table, a numTables that overruns, overflowing or out-of-range head offsets, a head that's too short, a bad magic number. Each is left unchanged, and the PDFs embedding them still fingerprint as drawn.Gates on the build pool:
cargo fmt --all --check,cargo clippy --locked --workspace --all-targets -- -D warnings,cargo test --locked --workspace --exclude visualci-app(all pass), andnode scripts/skills.mjs --check. No app/ code changed.