Skip to content

feat(uploads): fix the PDF path end to end and close the attachment auth hole - #34

Merged
pulkitxm merged 6 commits into
mainfrom
feat/s9-uploads
Jul 23, 2026
Merged

pulkitxm merged 6 commits into
mainfrom
feat/s9-uploads

Conversation

@pulkitxm

@pulkitxm pulkitxm commented Jul 23, 2026 •

Copy link
Copy Markdown
Member

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.

  • Upload path: replaces fetch() with XMLHttpRequest for the S3 PUT so progress events are available; adds a putFile retry loop for transient errors (status 0, 429, ≥ 500); adds uploadContentType to sniff PDF/image types from the file extension when the browser reports application/octet-stream.
  • Auth: adds assertUploadParent and isPubliclyReadable in packages/services/src/storage/parent.ts, replacing the flat assertCan('attachment:upload') check with per-parent-type verification against the organization and visibility; the file-serving route now calls isPubliclyReadable instead of the old inline doc-only check.
  • S3 CORS: adds k8s/s3-cors.json with a tight allowlist (one origin, PUT/GET/HEAD, only content-type) and bakes CORS application into apply.sh, guarded by a required S3_BUCKET env 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

Filename Overview
apps/web/src/app/api/attachments/presign/route.ts Replaces flat permission check with per-parent assertUploadParent; adds realtime sync event with per-parent scopes; minor ordering nit where file validation runs before the auth gate.
apps/web/src/features/docs/upload.ts New XHR-based upload with progress, retry, and extension-sniffing; offendingLabel shows application/octet-stream instead of the file extension when the browser declares that generic type for an unsupported file.
packages/services/src/storage/parent.ts New file: assertUploadParent enforces org scope, archived-doc guard, and visibility-gated publish permission; isPubliclyReadable gates anonymous file reads to live public docs only.
packages/services/src/storage/s3.ts Drops content-length from presigned headers so the browser's forbidden-header enforcement does not mismatch the S3 signature; only content-type is signed.
apps/web/src/app/api/files/[...key]/route.ts Delegates public-readability check to the new isPubliclyReadable helper, which also verifies org ownership and archived state; the rest of the download-and-redirect flow is unchanged.
k8s/s3-cors.json New CORS document: single origin placeholder, PUT/GET/HEAD methods, only content-type allowed header, ETag exposed; tight and correct for browser-direct uploads.
k8s/apply.sh Guards non-render runs behind S3_BUCKET; applies CORS document via put-bucket-cors at the end of every apply run; skips CORS on dry-run with an informational echo.
packages/services/src/storage/index.ts Exports new parent.ts symbols; adds startup guard that rejects coexistence of explicit static keys and an assumed pod-identity role.
packages/services/src/storage/round-trip.test.ts New test: validates CORS document correctness offline; skips real S3 round-trips when S3_BUCKET is absent; verifies content-type fidelity and that apply.sh references the CORS document.
packages/services/src/storage/parent.test.ts Full DB-backed tests for assertUploadParent and isPubliclyReadable, covering org isolation, archived-doc rejection, role gates, and cross-org doc visibility.
apps/web/src/features/docs/docs.test.ts Extends upload tests with an XHR stub, progress events, retry cases, and uploadContentType unit 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 URL
Loading

Reviews (3): Last reviewed commit: "fix(uploads): publish comment attachment..." | Re-trigger Greptile

pulkitxm added 2 commits July 24, 2026 00:17
…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
@coderabbitai

coderabbitai Bot commented Jul 23, 2026 •

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

Attachment 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.

Changes

Attachment upload flow

Layer / File(s) Summary
Attachment authorization and registration
packages/services/src/storage/parent.ts, packages/services/src/storage/parent.test.ts, apps/web/src/app/api/attachments/presign/route.ts, apps/web/src/app/api/files/[...key]/route.ts
Parent validation and public-readability helpers enforce organization, visibility, archive, and permission rules. Presigning registers syncId metadata and publishes attachment sync actions.
Browser upload pipeline
apps/web/src/features/docs/upload.ts, apps/web/src/features/docs/doc-editor.tsx, apps/web/src/features/docs/docs.test.ts, packages/services/src/storage/types.ts, packages/services/src/storage/validate.ts
Uploads resolve supported MIME types, use XMLHttpRequest progress callbacks and retries, omit upload size from the target contract, and display percentage progress in the editor. Tests cover MIME resolution, signed headers, retries, progress, and completion failures.

Storage runtime and deployment

Layer / File(s) Summary
Storage credentials and presigning
packages/services/src/storage/index.ts, packages/services/src/storage/s3.ts, packages/services/src/storage/storage.test.ts, k8s/apply.sh, k8s/s3-cors.json, k8s/README.md
Storage rejects simultaneous pod-identity and static credentials. S3 targets sign only content-type, while deployment renders and applies the templated bucket CORS rule.
CORS and storage round-trip validation
packages/services/src/storage/round-trip.test.ts
Tests validate CORS preflight rules, upload and download round trips for multiple MIME types, stored content metadata, and mismatched client content types.

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
Loading

Possibly related PRs

  • Noveum/orbit#23: Both update shared storage-driver credential selection and validation.
  • Noveum/orbit#30: Both modify the S3 upload-target and client credential resolution path.
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title matches the main changes: end-to-end upload fixes and tighter attachment authorization.
Description check ✅ Passed The description is directly related to the PR’s upload, auth, and S3 CORS changes.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/s9-uploads

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

📥 Commits

Reviewing files that changed from the base of the PR and between d95080c and b42c5d4.

📒 Files selected for processing (16)
  • apps/web/src/app/api/attachments/presign/route.ts
  • apps/web/src/app/api/files/[...key]/route.ts
  • apps/web/src/features/docs/doc-editor.tsx
  • apps/web/src/features/docs/docs.test.ts
  • apps/web/src/features/docs/upload.ts
  • k8s/README.md
  • k8s/apply.sh
  • k8s/s3-cors.json
  • packages/services/src/storage/index.ts
  • packages/services/src/storage/parent.test.ts
  • packages/services/src/storage/parent.ts
  • packages/services/src/storage/round-trip.test.ts
  • packages/services/src/storage/s3.ts
  • packages/services/src/storage/storage.test.ts
  • packages/services/src/storage/types.ts
  • packages/services/src/storage/validate.ts

Comment thread k8s/README.md Resolved
Comment thread k8s/README.md Resolved
Comment thread packages/services/src/storage/parent.ts Resolved
… 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.
@pulkitxm
pulkitxm merged commit d4c7754 into main Jul 23, 2026
6 checks passed
@pulkitxm
pulkitxm deleted the feat/s9-uploads branch July 23, 2026 23:39
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant