DEV Community

MortimerNilsson7694
MortimerNilsson7694

Posted on

Node.js Express Tenant Isolation for Browser Direct Uploads of Private User Documents

Short answer: model document intake as an authorization workflow, not as a file upload. For a Node.js and Express service storing private PDF and DOCX files, create a server-owned document record first, give the browser a short-lived presigned URL for that exact object, and require the same tenant check before restoring or downloading it. Multipart is an escalation path for large files, not the default.

That ordering is the important part. The browser can move bytes, but it must not decide which tenant owns them. The API decides. Storage enforces privacy. The database records the relationship.

Start with the restore operation

The application scenario here is a developer-tools product with per-tenant backups. A user selects snapshot snap_7f2 and asks for document doc_42 to be restored. The dangerous shortcut is to accept an object key from the browser and pass it to storage. A key is an address, not an authorization decision.

I use a narrower contract: the request contains a document ID and a snapshot ID; the server loads both records; both must belong to the authenticated tenant; only then does it copy or expose the object. The selected snapshot is data in the database, not a path supplied by the client.

This gives the system a useful invariant:

Every read, write, restore, and delete resolves through a server-owned record whose tenant matches the authenticated principal.

It also makes audit logs useful. Log the tenant, actor, document ID, snapshot ID, and decision. Never log the signed URL. A URL with authority embedded in it has no business in a long-lived log stream.

How can browser direct upload protect user documents with presigned URLs?

The smallest implementation separates intent from transfer. The endpoint below does not receive the file body. It validates the intended object, writes a pending record, and signs one upload request. The storage adapter is an interface so the policy remains portable across private object stores.

type DocumentKind = "pdf" | "docx";

type UploadIntent = {
  tenantId: string;
  actorId: string;
  filename: string;
  kind: DocumentKind;
  bytes: number;
};

type PendingDocument = {
  id: string;
  tenantId: string;
  objectKey: string;
  kind: DocumentKind;
  state: "pending_upload";
};

type PrivateStorage = {
  signPut(input: {
    key: string;
    contentType: string;
    contentLength: number;
    expiresInSeconds: number;
  }): Promise<string>;
};

const mediaTypes: Record<DocumentKind, string> = {
  pdf: "application/pdf",
  docx: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
};

function objectKey(tenantId: string, documentId: string, kind: DocumentKind): string {
  return `tenant/${tenantId}/document/${documentId}/source.${kind}`;
}

async function createIntent(
  input: UploadIntent,
  documentId: string,
  storage: PrivateStorage,
  save: (document: PendingDocument) => Promise<void>,
) {
  if (input.bytes <= 0 || input.bytes > 250 * 1024 * 1024) {
    throw new Error("document size is outside the accepted range");
  }

  const key = objectKey(input.tenantId, documentId, input.kind);
  await save({
    id: documentId,
    tenantId: input.tenantId,
    objectKey: key,
    kind: input.kind,
    state: "pending_upload",
  });

  return storage.signPut({
    key,
    contentType: mediaTypes[input.kind],
    contentLength: input.bytes,
    expiresInSeconds: 300,
  });
}
Enter fullscreen mode Exit fullscreen mode

The Express handler still has to derive tenantId from the authenticated session. It must not trust a tenant field in JSON, and it should treat the filename as display metadata rather than a path. Extension checks are a convenience; declared media type, byte count, object metadata, and a content inspection policy need to agree before the record becomes usable.

The browser sends the exact length and media type covered by the signature. Afterward, a completion request names the document ID. The server looks up the expected key, checks tenant ownership again, verifies that the object exists, and moves the state forward. Completion is idempotent: a retry returns the existing result instead of creating a second logical document.

One sentence matters here.

A successful PUT is not proof that the document is safe to restore.

Where do large files change the state machine?

Multipart transfer is useful when one request is a poor fit for the network. It adds an upload ID, part numbers, checksums or equivalent integrity checks, a completion call, and abandoned state. That is a real state machine, not a checkbox in a storage SDK.

For a 240 MB DOCX, for example, the browser can request part URLs, retry one failed part, and submit the final ordered part list. The service must bind the upload ID to the document record and tenant. It should reject a completion that names a different document, a missing part, or a part list that was not issued for that upload.

The cleanup job is part of the design. Expired upload sessions and uncommitted parts need a bounded lifetime, while a document stuck in pending_upload needs a visible explanation and a retry policy. Test a closed tab, a lost final response, two browser tabs, an expired signature, and a completion request repeated after a timeout. These are normal paths.

I'm not sure a single byte threshold works for every team. Measure request duration, memory pressure, retry rates, and user network conditions, then choose the point where multipart reduces failure cost enough to justify its state. Your mileage will vary.

The choice is easier to review when the transfer boundary is written down:

Approach Best fit Main burden
Browser direct upload with a presigned URL Ordinary private documents and a short application request CORS, expiry, and completion verification
Browser multipart upload Large files or networks where part retries matter Upload-session cleanup and idempotent completion
Server-mediated multipart ingest Synchronous transformation or inspection of every byte Application bandwidth, memory, and queue capacity

This table is a design decision, not a product ranking. I would record the chosen row beside the 300-second URL policy and the expected 403 behavior for an expired or unauthorized transfer.

Keep download links and backups on the same boundary

A download endpoint should receive a document ID, never an arbitrary object key. It loads the document, checks the tenant and state, then creates a short-lived signed GET. A restore endpoint follows the same pattern, except it also checks that the requested snapshot is an allowed source for that document.

app.post("/documents/:documentId/restore", requireUser, async (req, res) => {
  const document = await documents.find(req.params.documentId);
  const snapshot = await snapshots.find(req.body.snapshotId);

  if (
    !document ||
    !snapshot ||
    document.tenantId !== req.user.tenantId ||
    snapshot.tenantId !== req.user.tenantId ||
    document.state !== "ready"
  ) {
    res.sendStatus(404);
    return;
  }

  await restoreQueue.enqueue({
    tenantId: req.user.tenantId,
    documentId: document.id,
    snapshotId: snapshot.id,
  });
  res.sendStatus(202);
});
Enter fullscreen mode Exit fullscreen mode

The queue is deliberate. A restore can take longer than an HTTP request and should have a retryable job ID, an audit event, and a policy for partial work. The worker rechecks ownership before reading the source and writes into a newly generated destination key. It does not overwrite an existing object merely because the client reused a filename.

This architecture also clarifies CORS. CORS controls which browser origins can make a request; it is not tenant authorization. Configure the bucket or object store as private, allow only the required signed operations, and keep application authorization in the API.

What would I measure before changing the design?

I would benchmark time to first signed request, completion latency, retry rate by file size, orphan cleanup volume, and restore duration. I would add cross-tenant tests before load tests because a fast isolation failure is still a failure. A useful matrix includes tenant A reading tenant B's ID, replaying an expired URL, changing the content type, submitting a stale snapshot, and retrying a completed restore.

There are trade-offs. Direct browser transfer is not suitable when every byte must pass through a synchronous transformation or inspection service; a server-mediated ingest path is the clearer boundary then. Presigned URLs also bring expiry, clock skew, CORS, and observability work. Multipart improves resilience for large files but creates cleanup and idempotency obligations. A private store alone does not establish a compliance program: FedRAMP describes an authorization framework, while retention, encryption, access review, audit, deletion, and incident response still need explicit ownership.

For a small document service, start with one signed transfer and a pending-to-ready transition. Add multipart when measurements justify it. Keep restore authorization separate from upload authorization, even if both happen to touch the same object store.

Further reading

Top comments (0)