Repository navigation
feat(uploads): fix the PDF path end to end and close the attachment auth hole - #34
Merged
Merged
Conversation
…uth hole The presign route inserted an attachment row with an unvalidated parentId, and the file route treated a doc parent as an auth oracle before the request was authenticated, so a contributor without publish rights could serve arbitrary files to unauthenticated traffic. The parent is now resolved and authorized against the caller's organization before insert, and publicness is derived from the doc row that actually owns the attachment. Bucket CORS, which was missing everywhere, is committed and applied from k8s/apply.sh, so cross-origin presigned PUTs stop dying at the browser preflight. Uploads gain progress, retry, drag and drop, paste, inline images and a PDF viewer, with correct content types and download dispositions. The PDF round trip is proven against MinIO: presign, PUT, then GET with the type intact.
# Conflicts: # packages/services/src/storage/s3.ts
📝 WalkthroughWalkthroughAttachment uploads now validate their parent, register sync metadata, resolve MIME types, use progress-aware retrying PUT requests, and expose upload progress. Storage authorization, S3 presigning, bucket CORS deployment, credential validation, and round-trip tests are also updated. ChangesAttachment upload flow
Storage runtime and deployment
Estimated code review effort: 4 (Complex) | ~60 minutes Sequence Diagram(s)sequenceDiagram
participant DocEditor
participant uploadDocFile
participant AttachmentAPI
participant S3StorageDriver
DocEditor->>uploadDocFile: start upload and receive progress
uploadDocFile->>AttachmentAPI: request presigned target
AttachmentAPI->>S3StorageDriver: create target
S3StorageDriver-->>uploadDocFile: return URL and content-type header
uploadDocFile->>S3StorageDriver: PUT file with retry
uploadDocFile->>AttachmentAPI: complete attachment
AttachmentAPI-->>DocEditor: return attachment and upload target
Possibly related PRs
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Comment |
There was a problem hiding this comment.
Actionable comments posted: 6
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@apps/web/src/app/api/attachments/presign/route.ts`:
- Around line 41-43: Extend the scope construction in the attachment presign
handler to handle project attachments: when attachment.parentType is "project",
append scopes.project(attachment.parentId) to scope, alongside the existing
organization, document, and issue cases.
In `@apps/web/src/features/docs/doc-editor.tsx`:
- Around line 214-218: Update the upload progress span rendered by the uploading
state in the doc editor to include aria-live="polite", preserving its existing
text, styling, and data-testid attributes.
In `@k8s/README.md`:
- Line 164: Update the shell command fences in k8s/README.md at lines 164, 172,
and 180 to use the sh language specifier on each opening fence.
- Around line 192-193: Update the S3 CORS troubleshooting text to state that a
successful preflight returns 200, not 204, and clarify that a 403 may result
from a rule mismatch involving the origin, method, or requested headers as well
as an unapplied CORS document.
In `@packages/services/src/storage/parent.ts`:
- Around line 73-80: Update assertUploadParent’s doc visibility authorization to
use the confirmed positive public-visibility enum/value when deciding whether to
require doc:publish, instead of treating every non-workspace value as
publishable. Preserve the existing workspace behavior and other parent
validation.
In `@packages/services/src/storage/round-trip.test.ts`:
- Around line 62-71: Strengthen the assertions in the round-trip test around
allows and the effective PUT rule so arbitrary request headers are rejected, not
merely content-type accepted. Verify the PUT rule permits only content-type, or
add a preflight assertion using an unexpected header that must return false,
while preserving the existing allowed-method and ETag checks.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: 64de1d37-5612-48b2-b907-5b956fdf7b91
📒 Files selected for processing (16)
apps/web/src/app/api/attachments/presign/route.tsapps/web/src/app/api/files/[...key]/route.tsapps/web/src/features/docs/doc-editor.tsxapps/web/src/features/docs/docs.test.tsapps/web/src/features/docs/upload.tsk8s/README.mdk8s/apply.shk8s/s3-cors.jsonpackages/services/src/storage/index.tspackages/services/src/storage/parent.test.tspackages/services/src/storage/parent.tspackages/services/src/storage/round-trip.test.tspackages/services/src/storage/s3.tspackages/services/src/storage/storage.test.tspackages/services/src/storage/types.tspackages/services/src/storage/validate.ts
… a11y Replace the workspace-negation with an isExternallyShared helper so a future visibility state cannot be misread as shared, publish attachment deltas on the project scope, assert the bucket CORS refuses arbitrary headers, announce upload progress to assistive tech, and correct the CORS runbook.
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.
Make PDF and file uploads work end to end, authorize the attachment parent so files cannot be served across entities, and configure S3 bucket CORS.
Greptile Summary
This PR wires up the full PDF/file upload path: presigned S3 PUT via XHR (with progress reporting and retry), authorization of the attachment parent, and S3 bucket CORS configuration so browser cross-origin uploads clear the preflight. It also closes an attachment auth hole where files belonging to another entity could be served.
fetch()withXMLHttpRequestfor the S3 PUT so progress events are available; adds aputFileretry loop for transient errors (status 0, 429, ≥ 500); addsuploadContentTypeto sniff PDF/image types from the file extension when the browser reportsapplication/octet-stream.assertUploadParentandisPubliclyReadableinpackages/services/src/storage/parent.ts, replacing the flatassertCan('attachment:upload')check with per-parent-type verification against the organization and visibility; the file-serving route now callsisPubliclyReadableinstead of the old inline doc-only check.k8s/s3-cors.jsonwith a tight allowlist (one origin, PUT/GET/HEAD, onlycontent-type) and bakes CORS application intoapply.sh, guarded by a requiredS3_BUCKETenv var.Confidence Score: 5/5
Safe to merge. The auth hole is closed by well-tested code, the CORS configuration is tight, and the XHR retry path is covered by the new upload tests.
Both new code paths (assertUploadParent and isPubliclyReadable) have database-backed tests covering org isolation, archived docs, and role gates. The CORS document is validated offline by the round-trip test suite. The two findings are UX-level nits that do not affect correctness or security.
apps/web/src/features/docs/upload.ts (offendingLabel helper) and apps/web/src/app/api/attachments/presign/route.ts (validation-before-auth ordering).
Important Files Changed
assertUploadParent; adds realtime sync event with per-parent scopes; minor ordering nit where file validation runs before the auth gate.offendingLabelshowsapplication/octet-streaminstead of the file extension when the browser declares that generic type for an unsupported file.assertUploadParentenforces org scope, archived-doc guard, and visibility-gated publish permission;isPubliclyReadablegates anonymous file reads to live public docs only.content-lengthfrom presigned headers so the browser's forbidden-header enforcement does not mismatch the S3 signature; onlycontent-typeis signed.isPubliclyReadablehelper, which also verifies org ownership and archived state; the rest of the download-and-redirect flow is unchanged.content-typeallowed header,ETagexposed; tight and correct for browser-direct uploads.S3_BUCKET; applies CORS document viaput-bucket-corsat the end of every apply run; skips CORS on dry-run with an informational echo.parent.tssymbols; adds startup guard that rejects coexistence of explicit static keys and an assumed pod-identity role.S3_BUCKETis absent; verifies content-type fidelity and thatapply.shreferences the CORS document.assertUploadParentandisPubliclyReadable, covering org isolation, archived-doc rejection, role gates, and cross-org doc visibility.uploadContentTypeunit tests covering extension sniffing and unsupported types.Sequence Diagram
sequenceDiagram participant B as Browser participant API as Next.js API participant DB as Postgres participant S3 as S3 / Minio B->>API: POST /api/attachments/presign API->>API: validateUpload() - type + size gate API->>DB: assertUploadParent() - org + role + visibility check API->>S3: presign PUT (content-type only, no content-length) API->>DB: "INSERT attachment (status=pending)" API->>API: publish SyncAction to realtime scopes API-->>B: "{attachment, upload:{url, headers}}" B->>S3: XHR PUT presigned-url (progress events, up to 3 retries) S3-->>B: 200 OK B->>API: "POST /api/attachments/{id}/complete" API->>DB: "UPDATE attachment status=ready" API-->>B: "{attachment}" Note over B,S3: Download path B->>API: "GET /api/files/{storageKey}" API->>DB: "SELECT attachment WHERE storageKey=?" API->>DB: isPubliclyReadable() OR check principal org API->>S3: presign GET (content-type + disposition pinned) API-->>B: 302 to presigned download URLReviews (3): Last reviewed commit: "fix(uploads): publish comment attachment..." | Re-trigger Greptile