Dev.to Security 🔐 Cybersecurity 👁 0 📖 6 min read

Node.js Tenant File Exports with Signed Download Links — A 4-Step Storage Handoff

Short answer: In Node.js, export tenant files by authorizing the tenant-owned object keys first, then issue short-lived signed download links from a private storage bucket. Keep the signer behind a small interface; it sh

Short answer: In Node.js, export tenant files by authorizing the tenant-owned object keys first, then issue short-lived signed download links from a private storage bucket. Keep the signer behind a small interface; it should never decide who owns an image.

The safest design is to make a tenant-scoped export a short-lived handoff, not a public object. Build the object key from a server-owned tenant identifier, verify every image belongs to that tenant, then ask the storage boundary for a signed GET URL with a narrow expiry. The browser downloads from that URL; your application never proxies the image bytes unless it has a specific reason to do so.

This split matters in a property-management system. A portfolio manager may export listing photos for one tenant while the bucket contains images for hundreds of tenants. A correct link is useful. A correctly authorized link is the feature.

Keep the bucket private.

How should Node.js handle exporting tenant files with signed download links?

Keep the export record small and explicit: tenantId, an export identifier, the selected object keys, a status, and an expiration timestamp. Do not accept a bucket name or an object key from the browser and pass it through to signing. Those are storage coordinates, not authorization.

The request path is straightforward. The API authenticates the operator, loads the tenant membership, checks the requested image IDs against that tenant, and creates one manifest. A worker can prepare a ZIP when the export is large; for a modest image set, returning one signed URL per already-stored object is often easier to audit. In both cases, the authorization decision happens before signing.

I start with the manifest because it gives operations something concrete to inspect. If a customer reports that an export contains the wrong image, the team can compare the export ID, tenant ID, object keys, and creation time without reconstructing a browser request.

Here is the storage boundary I use in a Node.js service. It leaves the provider-specific signing call behind one interface, so the rest of the application deals with policy rather than SDK details.

type ExportImage = {
  imageId: string;
  objectKey: string;
};

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

interface PrivateObjectStore {
  signRead(input: {
    objectKey: string;
    expiresInSeconds: number;
    responseContentDisposition: string;
  }): Promise<{ url: string; expiresAt: Date }>;
}

export async function createImageDownloads(
  store: PrivateObjectStore,
  tenantId: string,
  exportId: string,
  images: ExportImage[],
): Promise<SignedDownload[]> {
  if (images.length === 0 || images.length > 100) {
    throw new Error('Export image count is outside the allowed range');
  }

  return Promise.all(images.map(async (image) => {
    const expectedPrefix = `tenants/${tenantId}/`;
    if (!image.objectKey.startsWith(expectedPrefix)) {
      throw new Error('Image does not belong to the tenant');
    }

    const filename = `${exportId}-${image.imageId}.jpg`;
    const signed = await store.signRead({
      objectKey: image.objectKey,
      expiresInSeconds: 300,
      responseContentDisposition: `attachment; filename=\"${filename}\"`,
    });

    return {
      imageId: image.imageId,
      url: signed.url,
      expiresAt: signed.expiresAt.toISOString(),
    };
  }));
}

The prefix check is a useful guardrail, not a replacement for the database authorization query. An object named tenants/acme/ is not proof that the current operator may act for acme. The query must establish that relationship first. The prefix then catches mismatched data and programming errors before they become signed links.

The signer is not the policy engine.

Where should tenant isolation happen?

At every boundary that can change the set of files. The API should derive the tenant from authenticated membership, the database query should filter by that tenant, the manifest should record it, and the signer should receive only keys from that manifest. Storage prefixes make accidental mixing easier to detect; they do not create a complete tenant model by themselves.

There are two common export shapes. A set of individual links keeps the original files and makes a partial retry cheap. One generated archive gives the user a single download and a stable snapshot, but it creates another private object with its own retention and signing rules. I use individual links for small image sets and an archive worker when the user experience or object count requires it. That is a workflow decision, not a reason to loosen authorization.

The browser also needs a deliberate CORS policy if the download is initiated with fetch or an object URL from a different origin. A direct navigation to a signed URL has different browser behavior than a cross-origin scripted request. Allow the application origin and the methods and headers the client actually uses; do not treat * as a tenant control. CORS governs browser access, while the signature and server-side policy govern access to the object.

Individual links are a poor fit for a very large export: the response grows with every file, retries become noisy, and a user may expect one archive. A generated ZIP is a poor fit for a tiny export when it adds a queue, temporary storage, and another retention policy. The right boundary depends on object count and snapshot requirements.

How do signing systems differ without changing the policy?

The policy should remain provider-neutral, but the adapter cannot pretend that every storage system has identical controls. Amazon S3 presigned URLs, Google Cloud Storage signed URLs, and Azure Blob SAS tokens all represent time-limited delegated access, yet their SDKs, credential models, canonical request details, and response-header options differ. A portability boundary should normalize the small contract the application needs: object key, read permission, expiry, and download filename.

Storage approach Integration shape Good fit Main limitation
S3 presigned URL SDK signer Private object reads Request signing details stay provider-specific
Cloud Storage signed URL SDK or REST-compatible adapter Time-limited object delivery Credential and canonicalization rules differ
Blob SAS token SDK signer Delegated blob access Token permissions and expiry need careful scoping

That adapter is also where I keep provider-specific tests. Test that a generated URL expires when expected, permits the intended read operation, and rejects a different object key. Test response headers separately. Do not compare URL strings across providers; their shapes are implementation details.

The five-minute lifetime above is an example policy, not a universal number. Shorter lifetimes reduce replay exposure but make a slow export frustrating. Longer lifetimes are easier for a user to resume but leave a leaked link useful for longer. Choose the lifetime from the expected download window, and record the decision in the export audit event.

What fails after the first successful demo?

The first failure is often a race: an image is deleted or replaced after the manifest is created. Decide whether an export is a snapshot. If it is, copy the selected objects into an export-owned prefix and sign those copies. If it is not, record that the export reflects the source files available when each link is requested. Either behavior can be valid; an undocumented mixture is difficult to explain to a tenant.

The next failure is observability. Log the export ID, tenant ID, authenticated actor ID, object count, signer result, and expiry, but never log the full signed URL. Queryable identifiers are enough to investigate while avoiding another copy of a bearer credential in log storage. Metrics should distinguish authorization denials, missing objects, signing errors, and browser download failures.

Log identifiers, not credentials.

I also put a hard ceiling on link count and total export size. That protects the signer and makes abuse visible. A queue is appropriate for long-running archives; it should report a durable export state rather than hold an HTTP request open until a browser times out.

A practical review can stay short: confirm the tenant comes from authenticated context, verify image ownership in the database, validate the object-key namespace, keep the bucket private, set an expiry that matches the workflow, restrict download response headers, avoid URL logging, and exercise a cross-tenant test in CI. Then test the expired-link path. It is easy to test the happy path and forget that expiration is the security behavior you actually promised.

The result is a small, replaceable storage adapter wrapped in a stronger application rule: a tenant can receive links only for objects already proven to belong to that tenant. That rule survives a storage migration, an archive worker, and a different frontend because it lives above the signed URL mechanism.

Sources

References:

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