Dev.to Security πŸ” Cybersecurity πŸ‘ 0 πŸ“– 7 min read

Secure File Downloads Using Presigned URLs in Node.js: Cloud Storage Isolation

Customer-support backups need a secure file download design that answers one question before it answers how to sign a URL: which tenant is allowed to retrieve this exact snapshot? In a Node.js service, the practical answ

Customer-support backups need a secure file download design that answers one question before it answers how to sign a URL: which tenant is allowed to retrieve this exact snapshot? In a Node.js service, the practical answer is to authorize the snapshot in your application, then issue a short-lived, read-only presigned URL whose object key is derived from a server-side snapshot record. Cloud storage should never decide tenant membership for you.

Short-lived URLs are useful, but they are bearer credentials. Anyone holding one can usually use it until it expires. That makes tenant binding, object-key validation, response headers, and expiry policy more important than the signing call itself. For a restore workflow, I would also make the selected snapshot an immutable record and re-check its tenant immediately before issuing the link.

No SDK call can repair a wrong tenant lookup.

How do secure file downloads using presigned URLs protect tenants?

A support agent may select snapshot snap_0184 for tenant acme-eu, while the browser belongs to a different session, tab, or support account. The download endpoint has to establish all of these facts:

  • The authenticated operator can act for the requested tenant.
  • The snapshot belongs to that tenant.
  • The snapshot is in a downloadable state and has not been deleted or superseded by policy.
  • The object key came from trusted metadata, not from a path fragment supplied by the browser.

Only after those checks should the server ask an object store to sign a read request. A useful internal record is deliberately boring:

type Snapshot = {
  id: string;
  tenantId: string;
  objectKey: string;
  state: "ready" | "restoring" | "deleted";
  createdAt: string;
  byteLength: number;
};

function canDownloadSnapshot(
  snapshot: Snapshot,
  requestedTenantId: string,
  operatorTenantIds: ReadonlySet<string>,
): boolean {
  return (
    snapshot.tenantId === requestedTenantId &&
    operatorTenantIds.has(requestedTenantId) &&
    snapshot.state === "ready"
  );
}

The objectKey is an output of the lookup, not an input to a generic download?key= route. That distinction blocks a large class of confused-deputy bugs. It also keeps storage naming details out of support tooling and audit events.

The signature is the last step.

Why does tenant isolation fail after the URL is signed?

The common mistake is to treat signing as authorization. It is not. Signing proves that a server generated a request with particular parameters; it does not prove that the server selected the right tenant record. A valid signature for the wrong key is still a valid, damaging link.

There are three boundaries to keep separate. First, the application authorizes the operator and resolves the snapshot. Second, the signer constrains the read request, including the object key and expiry. Third, the browser follows the resulting URL. The browser is outside your trust boundary, and CORS does not turn it into one. CORS is a browser policy for cross-origin requests; it is not an access-control system for object data. MDN describes the request and response headers involved, including preflight behavior, but the server still has to make the authorization decision.

I prefer a single-purpose route with a narrow input shape. It accepts a snapshot identifier and a tenant identifier, performs the relationship check, and returns a URL plus metadata. It does not accept an arbitrary bucket, container, or object key. The signer interface can remain provider-neutral:

type SignedDownload = {
  url: string;
  expiresAt: string;
};

type SignRead = (input: {
  objectKey: string;
  expiresInSeconds: number;
  contentDisposition: string;
  contentType: string;
}) => Promise<SignedDownload>;

async function createSnapshotDownload(input: {
  tenantId: string;
  snapshotId: string;
  operatorTenantIds: ReadonlySet<string>;
  loadSnapshot: (id: string) => Promise<Snapshot | null>;
  signRead: SignRead;
}): Promise<SignedDownload> {
  const snapshot = await input.loadSnapshot(input.snapshotId);

  if (
    snapshot === null ||
    !canDownloadSnapshot(snapshot, input.tenantId, input.operatorTenantIds)
  ) {
    throw new Error("Snapshot is unavailable");
  }

  const filename = `support-backup-${snapshot.id}.zip`;

  return input.signRead({
    objectKey: snapshot.objectKey,
    expiresInSeconds: 60,
    contentDisposition: `attachment; filename=\"${filename}\"`,
    contentType: "application/zip",
  });
}

The example uses a 60-second lifetime as a policy choice, not a universal security number. It is long enough for a user to start a request and short enough to limit accidental sharing. Large downloads may need a different value. Measure the time from link creation to the first byte, the completion rate, and the number of expired-link retries before changing it. A common initial assumption is that a longer lifetime helps support staff; the later discovery is that it also extends the useful life of a copied bearer credential.

A second trap is logging the full URL. Query parameters commonly carry the credential, so request logs, browser history, analytics tools, and support screenshots can become copies of the backup authorization. Log the snapshot ID, tenant ID, expiry timestamp, and a request correlation ID. Redact the URL before any structured logging middleware sees it.

The restore workflow is a different authorization event

Downloading a selected snapshot and restoring it should not share one permission check. A download is a read. A restore changes tenant state, may take minutes, and needs an explicit confirmation path. The link can identify the artifact, but it should not be treated as proof that the operator may restore it.

For a safe flow, store the selection as a server-side restore request containing the tenant, snapshot, requesting principal, and a state such as pending. When the restore worker starts, it loads that record again, verifies that the snapshot still belongs to the tenant, and checks that the request has not expired or already been consumed. The worker should fetch by the stored object key, not by a key reconstructed from a job payload supplied by a browser.

This costs a database read. Keep it. Tenant isolation is the primary decision axis here, and shaving one lookup creates a much harder incident to explain. The same rule applies to retries: an idempotency key prevents two support clicks from creating two restores, but it does not replace the tenant and snapshot relationship check.

Browser details that affect the design

For a direct download, the simplest browser behavior is a navigation to the signed URL. If the application uses fetch so it can show progress or save a response itself, the object endpoint must return the required CORS headers. The allowed origin should be the actual support application origin, not * for an authenticated workflow. Expose only the response headers the browser needs, such as Content-Length or Content-Disposition, and account for preflight when custom headers are sent.

The application server can avoid exposing the URL to JavaScript by returning a short-lived link and letting the browser navigate. That reduces one place where the bearer credential can be copied, although the URL can still appear in browser-managed state. For especially sensitive exports, a server-side streaming proxy can keep the storage URL private, but it adds bandwidth, connection handling, timeout, and backpressure work. The choice is operational, not ideological:

Pattern Main benefit Main cost
Direct signed navigation Storage handles the bytes URL is a bearer credential in the client
Browser fetch Progress and client-side control CORS and exposed headers need deliberate configuration
Server-side proxy Storage URL stays server-side Your service carries the download traffic and failure modes

Do not put a permanent public object URL in a support ticket or email. A signed URL is still a secret, even when the object itself is encrypted at rest. Encryption helps protect stored bytes; it does not revoke a copied read link. The trade-off is straightforward: direct presigned downloads reduce application bandwidth, while a proxy gives the application more control over revocation and inspection. The proxy is a poor fit for very large files unless its connection, timeout, and backpressure capacity are tested first.

What should be measured before changing the policy?

The useful metrics are tied to the workflow, not to the signing library. Track rejected tenant-snapshot mismatches, links created, links used after expiry, time to first byte, download completion rate, restore requests by state, and repeated restore attempts for the same idempotency key. Keep tenant identifiers out of high-cardinality metric labels if the tenant count is large; attach them to access-controlled audit events instead.

Test the boundaries directly. A good test matrix includes a valid operator and snapshot, a valid snapshot under another tenant, a missing snapshot, a deleted snapshot, an expired link, a link with an altered object key, and a restore request replayed after completion. Add a browser test for the real support origin and a preflight test if the client uses fetch.

The decision rule is plain: use a direct signed URL when the client can safely handle a bearer credential and your storage policy can constrain it; use a proxy when hiding the storage endpoint or applying server-side controls matters more than transfer simplicity. In both cases, authorization belongs to the application record that binds operator, tenant, and snapshot.

That binding is the part worth preserving if the storage backend changes. The signature format, endpoint hostname, and SDK can move. The tenant relationship, expiry policy, audit trail, and restore state machine should not.

Further reading

πŸ“° Read the original article on Dev.to Security

Originally published by Dev.to Security. Aggregated on AIWithGhost for educational purposes β€” full credit and traffic to the original publisher.