Repository navigation
fix(docs): keep cleanup off prefixes being re-uploaded and the token out of the build - #236
Conversation
…out of the build Cleanup aged a prefix by its _publish.json, which a same-commit re-upload keeps until its last put, so a concurrent cleanup could delete a prefix mid-upload. Every upload now writes an _uploading.json marker first, cleanup treats the newer of the two as the prefix's last activity, and it re-reads that immediately before each delete. The publish build also no longer receives the job token. A step before the content checkout fetches the release schedule into a file, and the build reads it through DOCS_RELEASE_SCHEDULE_FILE. Assisted-by: AI
DOCS-1351 Clear the pre-public batch: fake AWS key, internal identifiers, flip-day checklist and hardening items
Low/Info batch. https://github.com/coder/security-assessments/issues/386 Before the repository goes public (§A):
Hardening, after the flip:
Split into separate issues as work starts. |
|
/coder-agents-review |
|
The latest updates on your projects. Learn more about Vercel for GitHub.
1 Skipped Deployment
|
Jesswinters
left a comment
There was a problem hiding this comment.
Approving: I found no blockers. Cleanup now checks the _uploading.json marker, the marker is written and awaited before any object upload (a failed marker put fails the upload), and every time comparison fails closed: a missing index, an invalid uploadedAt or a missing marker all keep the prefix. Moving the schedule fetch into its own step before the content checkout removes github.token from the build step's environment, and adding DOCS_RELEASE_SCHEDULE_FILE to the sync task's turbo env is needed under strict env mode.
The most useful follow-ups are inline. The cleanup tests never reach the delete loop, so removing the new gate still passes them. The final re-read happens before the object listing, which leaves the race window wider than the PR body says. Separately, docs-pr-preview.yml still hands github.token to a build of PR content.
Checks I ran on 4e09e65: scripts/publish/*.test.mjs 94 of 94, apps/docs pnpm test 267 of 267, packages/docs-build 107 of 107, oxlint and oxfmt clean on the changed files, and actionlint with shellcheck clean on the workflows. The new upload tests fail against main for the right reasons, but the new cleanup tests fail there only because the lastActivity export is missing. CI is green.
This PR and #228 both add a constant after OBJECTS_KEY in upload.mjs and both append tests to upload.test.mjs, so whichever lands second has a small conflict to resolve (keep both).
Generated by Coder Agents on behalf of @Jesswinters.
| assert.equal(await lastActivity(orphan, fakeListing({})), undefined); | ||
| }); | ||
|
|
||
| test("an in-place re-upload that started after the age check keeps its prefix from being deleted", async () => { |
There was a problem hiding this comment.
Should fix: these tests call lastActivity and stillDeletable directly, but nothing covers the code that uses them: listPrefixes and the delete loop in the cleanup.mjs main block. As a check, I copied scripts/publish, removed the stillDeletable gate from the delete loop and put listPrefixes back to reading only _publish.json. All 10 cleanup tests still passed. This test's name says the prefix is kept from being deleted, yet no delete runs in it.
AGENTS.md asks for a security invariant to be tested by showing the failure itself. One way: move the main block into an exported runCleanup({ items, listPage, delPage, now, graceMs, dryRun }) with seams like uploadDir already has. Then test two cases: a fake store whose _uploading.json turns fresh between the listing and the re-read, asserting that delPage is never called for that prefix, and a listing that already sees a fresh marker.
There was a problem hiding this comment.
Done in f47af9c. The main block is now an exported runCleanup({ items, listPage, delPage, now, graceMs, dryRun, log, retry }), and the tests drive it against a fake store with an onList hook. Two of them are the cases you described: a marker that is already fresh at listing time, and one that turns fresh while cleanup lists the prefix's objects, after the listing that chose it; both assert delPage is never called. Two more cover a marker that turns fresh between a rate-limited delete and its retry, and an index that vanishes before the delete, plus a happy-path delete and a dry run. Mutation check: removing the re-read fails four of the new tests, moving it back before the object listing fails three, and moving it outside the retry closure fails the retry test. Because of your optional point, the listing now reads _publish.json only by design, so the pre-delete re-read is the one gate and the tests pin that gate rather than the listing.
| // Last gate before a destructive call: planCleanup already filtered on | ||
| // the shape, so this can only fail if that filter is ever loosened. | ||
| assertArchivePrefix(prefix); | ||
| if (!(await stillDeletable({ prefix, listPage, now: new Date(), graceMs }))) { |
There was a problem hiding this comment.
Should fix: stillDeletable runs before lines 151 to 157 page through every object under the prefix, and del only runs after that. Each listWithRetry page can wait up to five minutes when the store rate-limits, and cleanup runs during batches, when rate limiting is most likely. So the window is the last re-read, then the whole listing with retries, then the delete, not just the moment before del that the PR body describes.
If a re-upload writes its marker inside that window, it loses every object it has rewritten so far. The keys are the same because of addRandomSuffix: false. It then writes _publish.json, and verify only spot-checks a few keys.
Suggested fix: collect the URLs first and call stillDeletable right before del. Better still, call it inside the withBlobRetry closure, so that a delete retried after a 429 checks again.
There was a problem hiding this comment.
Done in f47af9c. Cleanup collects the URLs first, then calls keepReason (the renamed stillDeletable) inside the withBlobRetry closure right before delPage, so a delete retried after a 429 re-reads too. a re-upload that starts while cleanup lists the prefix's objects keeps the prefix fails with the re-read before the listing, and a delete retried after a 429 re-checks the prefix first fails with it outside the closure. The PR body now describes the window as the gap between that read and the store acting on the delete.
| const prefixes = await listPrefixes(token); | ||
| const listPage = (options) => listWithRetry({ ...options, token }); | ||
| const prefixes = await listPrefixes(token, listPage); | ||
| const graceMs = 7 * 24 * 60 * 60 * 1000; |
There was a problem hiding this comment.
Follow-up, not caused by this PR: the grace period counts from the upload time, but apps/docs/README.md (Cleanup) says a prefix is deleted only after it "has stayed unreferenced for at least seven days". I checked with a scratch planCleanup call. When release/2.36 moves from P1 (uploaded 30 days ago) to P2, P1 can be deleted as soon as the manifest write lands, which the same publish's cleanup step will do within minutes.
It gets worse with a concurrent publish: its cleanup can delete P1 while this publish's smoke check is still running, and if smoke then fails, the restore step points the manifest back at a deleted prefix. That's the same kind of cleanup-versus-publish race this PR hardens, so it may be worth an issue that records when each prefix was first seen unreferenced.
There was a problem hiding this comment.
Agreed, and out of scope here: the grace period counts from upload time, not from when the prefix was first seen unreferenced, and the smoke-failure restore makes it worse. This will be tracked in a separate issue rather than in this PR.
| // the shape, so this can only fail if that filter is ever loosened. | ||
| assertArchivePrefix(prefix); | ||
| if (!(await stillDeletable({ prefix, listPage, now: new Date(), graceMs }))) { | ||
| console.log(`cleanup: ${prefix} saw upload activity since it was listed; skipping`); |
There was a problem hiding this comment.
Nit: this message ("saw upload activity since it was listed") is also printed when the index has disappeared, for example because a concurrent cleanup already deleted it, so it can point an operator the wrong way. Also, the QA section says this line shows when a prefix is skipped. A prefix whose fresh marker is already visible at listing time never reaches doomed, so it logs nothing.
There was a problem hiding this comment.
Fixed in f47af9c. keepReason returns the reason, and the log is now either cleanup: <prefix> saw upload activity at <time>; skipping or cleanup: <prefix> its _publish.json is gone; skipping, with a test for each. Since the listing no longer filters on the marker, every candidate reaches that check, and I rewrote the QA line to say which messages appear and that a prefix inside the grace period is never a candidate and logs nothing.
| } | ||
|
|
||
| async function listPrefixes(token, listPage) { | ||
| // versions/<id>/<sha>/... : fold twice to enumerate prefixes, then read the |
There was a problem hiding this comment.
Nit: this comment still says the listing reads "the upload time from each prefix's _publish.json object", but it now uses the newer of _publish.json and _uploading.json. Also, the new JSDoc blocks at lines 77 to 82 and 93 to 95 explain reasoning the PR body already covers, and AGENTS.md asks for comments of at most one short line, so they could be cut to the @param types plus one line.
There was a problem hiding this comment.
Fixed in f47af9c. The listing comment now says it ages each prefix by its _publish.json, which is true again after the optional change, and the JSDoc on lastActivity, keepReason and runCleanup is down to the types plus one line.
| const indexBlob = page.blobs[0]; | ||
| if (!indexBlob) { | ||
| const prefix = shaFolder.replace(/\/$/, ""); | ||
| const uploadedAt = await lastActivity(prefix, listPage); |
There was a problem hiding this comment.
Optional: listPrefixes now makes two list calls per prefix instead of one, including every tag prefix (hundreds after a backfill). Tags are never deleted, and line 147 re-reads both objects before any delete anyway. Looking up the marker only for prefixes that pass planCleanup would save list calls during exactly the batches where they compete with uploads for the rate limit.
There was a problem hiding this comment.
Done in f47af9c. The listing reads only _publish.json again, one list call per prefix, and the marker is read only for candidates that pass planCleanup, in the pre-delete re-read. That keeps the race-safety story to a single gate: the re-read inside the retried delete is what decides, and the listing is just a pre-filter.
| } | ||
| const schedule = await writeReleaseSchedule({ | ||
| outFile: out, | ||
| token: process.env.DOCS_GITHUB_TOKEN || undefined, |
There was a problem hiding this comment.
Nit: process.env.DOCS_GITHUB_TOKEN || undefined quietly falls back to an anonymous request if the step's env ever loses the token. The PR body rules out anonymous requests because of the shared-IP rate limit. need("DOCS_GITHUB_TOKEN") from ./env.mjs would fail closed, as the other publish scripts do.
There was a problem hiding this comment.
Fixed in f47af9c: release-schedule.mjs uses need("DOCS_GITHUB_TOKEN"), and running it without the variable now throws DOCS_GITHUB_TOKEN must be set.
| assert.equal(liveArchivePrefix({ items, plan: { kind: "line", id: "2.35" } }), undefined); | ||
| }); | ||
|
|
||
| test("the upload marker is written before any object, so a cleanup sweep sees the prefix as in flight", async () => { |
There was a problem hiding this comment.
Nit: with concurrency: 1 and a fake put that resolves at once, keys[0] === marker would still pass if the marker put stopped being awaited (for example Promise.all([markerPut, ...workers])), because each worker awaits its file read before calling blobPut. Holding the marker put open with a deferred promise, and asserting that no object put starts until it resolves, would test the ordering the PR relies on.
There was a problem hiding this comment.
Fixed in f47af9c. The test holds the marker put on a deferred promise with concurrency: 4, waits, asserts the only put started is the marker, then releases it and checks the index is last. Turning the marker put into Promise.all([markerPut, ...workers]) makes it fail.
| const fixtureCorpus = !single && !process.env.DOCS_REPO; | ||
| // A schedule fetched earlier by a step that held the token, so the build that | ||
| // compiles the corpus never needs one. | ||
| const scheduleFile = process.env.DOCS_RELEASE_SCHEDULE_FILE; |
There was a problem hiding this comment.
Should fix, docs outside the diff: ARCHITECTURE.md:203 still says "The sync fetches the schedule once per build". In a publish, a separate step now fetches it and the sync reads DOCS_RELEASE_SCHEDULE_FILE. In apps/docs/README.md, line 460 still says only _publish.json and _objects.json keep a 60-second TTL, which _uploading.json now does too, and the Cleanup section (around line 319) doesn't mention the marker. AGENTS.md wants invariants like "marker first, cleanup uses the newer time" and "the build step holds no token" in ARCHITECTURE.md or the README.
There was a problem hiding this comment.
Fixed in 385b156. ARCHITECTURE.md's release-schedule section now says a separate step fetches the schedule before the content checkout and the sync reads DOCS_RELEASE_SCHEDULE_FILE, and records that there is no token in the build step's environment. The apps/docs README lists _uploading.json with the 60-second TTL objects, and the Cleanup section records marker first and index last, the newer-of-two rule, the pre-delete re-read inside the retried delete, and the two skip messages.
| # job's token, and the build reads the result from a file. | ||
| working-directory: engine/apps/docs | ||
| env: | ||
| DOCS_GITHUB_TOKEN: ${{ github.token }} |
There was a problem hiding this comment.
Follow-up: docs-pr-preview.yml:141 still passes DOCS_GITHUB_TOKEN: ${{ github.token }} to the step that builds pull-request content, and that job grants pull-requests: write, a broader token than the contents: read this PR removes here. The required reviewers on docs-preview reduce the risk but don't remove it. The same pattern would work there: fetch the schedule before the content checkout and point DOCS_RELEASE_SCHEDULE_FILE at it (apps/offlinedocs/scripts/sync-docs.mjs:71 would need the same file preference). Or list it under "Not done".
Small wording point: on a hosted runner, a step with code execution and passwordless sudo can still read runner memory, so "no token in the build step's environment" is more accurate than "no longer has any token".
There was a problem hiding this comment.
Left docs-pr-preview.yml alone here, because that workflow belongs to another open change, and added it to the PR body's "Not done" list with the pattern you described, including the apps/offlinedocs sync change. I also changed the wording to "no token in the build step's environment" in the PR body and in ARCHITECTURE.md.
The re-read that keeps a prefix being re-uploaded from deletion ran before cleanup paged through the prefix's objects, so the real window was that whole listing, with rate-limit waits of up to five minutes per page, plus the delete. A re-upload that wrote its marker inside it would lose every object it had rewritten. Cleanup now lists the objects first and re-reads the index and the marker inside the retried delete closure, so a delete retried after a 429 checks again too. The main block moves into an exported runCleanup with list and delete seams, so the tests drive the delete loop against a fake store: a marker that is fresh at listing time, one that turns fresh while the objects are listed, one that turns fresh between a rate-limited delete and its retry, and an index that vanishes. The skip log now says which of those it was. The listing ages prefixes by the index alone, since the pre-delete re-read is what decides, which halves the list calls per prefix during the batches that compete with uploads. The marker-ordering upload test now holds the marker put open and asserts no object put starts until it resolves, and the release-schedule fetch requires its token instead of quietly going anonymous. Assisted-by: AI
ARCHITECTURE.md still said the sync fetches the release schedule itself, and the README's TTL and cleanup notes predated the upload marker. Write down the invariants the code now relies on: every upload writes its marker first and its index last, cleanup decides on the newer of the two re-read just before each delete, and there is no token in the build step's environment. Assisted-by: AI
Merge order
Independent, but it edits
upload.mjsand its tests, which two other open PRs also touch (the artifact-path validation and the redirects size cap), andpublish-version.ymlnear the build step. The edits are in separate functions and steps, so whichever merges later rebases. If the artifact-path PR lands first, its rule against underscore-prefixed root files already covers the new_uploading.jsonname.Summary
Two publish-pipeline items from the pre-public hardening batch. Cleanup could delete a prefix while a same-commit re-upload was filling it, and the build step that compiles untrusted content was handed the job's GitHub token only to lift the rate limit on one public API call.
Fix
Cleanup judged a prefix's age by
_publish.json, whichupload.mjswrites last and which a re-upload of the same commit leaves in place until its final put. An orphan older than seven days that the reconciler re-dispatched could therefore still look old while its objects were being rewritten, and a concurrent publish's cleanup could delete them. Nowupload.mjswrites a small_uploading.jsonmarker before any object, andcleanup.mjstakes the newer of the two as the prefix's last activity. The listing ages candidates by the index alone; what decides is a re-read of both, made after the candidate's objects have been listed and inside the retried delete closure, so a delete retried after a 429 checks again. A prefix with no index is still skipped as in flight, and one whose index vanished before its delete is skipped with its own log line. The remaining window is the gap between that last read and the store acting on the delete. The marker is one more small object per prefix, and it goes away with the prefix.The token change moves the release-schedule fetch into its own step before the content checkout, the only step that sees
github.token. It writes the schedule to a file in the runner's temp directory, and the build reads it through a newDOCS_RELEASE_SCHEDULE_FILEvariable thatsync-docs.mjsprefers over fetching. There is no token in the build step's environment. I did not go anonymous because GitHub-hosted runners share addresses and the anonymous limit is small, and a failed fetch fails the publish.Not done: the read-only token for
manifest showin the republish, historical-sync and reconcile workflows. No read-scoped token exists today, andreadManifestItemscalls the Vercel API with the same token the writes use, so it needs a new secret and probably a read path in the manifest package. That is a decision for Nick.Also not done:
docs-pr-preview.ymlstill passesDOCS_GITHUB_TOKEN: ${{ github.token }}to the step that builds pull-request content, under a job that grantspull-requests: write. The same pattern (fetch the schedule before the content checkout, pointDOCS_RELEASE_SCHEDULE_FILEat it, and teachapps/offlinedocs/scripts/sync-docs.mjsthe same file preference) applies there, but that workflow belongs to a separate open change, so it is left to that one.Review feedback applied in f47af9c and 385b156.
QA
There is nothing to see on the site. In a publish run, the build job should show a
Fetch the release schedulestep before the content checkout, and theuploadstep should show the marker being written first. When thecleanupstep skips a deletion candidate, it logs eithersaw upload activity at <time>orits _publish.json is gone; a prefix younger than the grace period is never a candidate and logs nothing.Pages to compare
Testing
New cleanup tests drive
runCleanupagainst a fake store: an idle orphan is deleted in full, a dry run deletes nothing, anddelPageis never called for a prefix whose marker is fresh at listing time, turns fresh while its objects are listed, or turns fresh between a rate-limited delete and its retry, nor for one whose index vanishes. Removing the re-read fails four of them, moving it back before the object listing fails three, and moving it outside the retry closure fails the retry one. A new upload test holds the marker put open and asserts no object put starts until it resolves; it fails if the marker put stops being awaited. Five existing upload tests had their expected put lists updated for the marker. All 99 tests underapps/docs/scripts/publish/and all 272apps/docstests pass,sync-docs.mjswas run on the fixture corpus with a schedule file and wrote that schedule, the fetch script ran against the live API, andpnpm lint:actions, oxfmt and oxlint are clean.Upstream
No. This is Coder-specific publish tooling.
Linear: https://linear.app/codercom/issue/DOCS-1351/clear-the-pre-public-batch-fake-aws-key-internal-identifiers-flip-day. Finding: the publish pipeline items in coder/security-assessments#386, section D.
🤖 Built with AI assistance.