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

Direct Media Delivery: Creating Time-Limited Download Links from Object Storage

Short answer: Create a short-lived signed read link and send the downloader directly to object storage; keep large media bytes out of the Node.js process. A large media export should travel from object storage to the do

Short answer: Create a short-lived signed read link and send the downloader directly to object storage; keep large media bytes out of the Node.js process.

A large media export should travel from object storage to the downloader, not through your Node.js process. That constraint decides the design: your service authenticates the request, signs a narrow object-storage request for a short lifetime, and returns the URL. The service never reads the file.

The hard part is not generating a URL. It is making the URL useful without pretending it is revocable, private forever, or equally safe in every browser. I treat a signed URL as a bearer capability with an expiry, an exact object key, and a deliberately small permission surface.

How do I create time-limited download links for object storage files?

The request path should look like this:

client -> Node.js authorization endpoint -> signed GET URL -> object storage -> client

The Node.js endpoint checks the user, export record, and current status. It then asks the storage adapter for a signed read URL. The client follows that URL. For a 4 GB video, the application handles metadata and authorization while the storage service handles the 4 GB transfer. That is the throughput win.

The expiry is a boundary, not a kill switch. A URL copied before expiry can usually be used by whoever has it until the signature expires. If a download must be stopped immediately, put an authenticated download proxy or a CDN policy in the path and accept the extra operational cost.

What should the smallest implementation actually sign?

Keep the storage-specific code behind one interface. The rest of the application should not know whether the adapter uses a query signature, a tokenized path, or another standards-based mechanism. It should know the object key, the intended response name, and the lifetime.

Here is the application-shaped part. The signRead method is intentionally abstract; its concrete adapter must use the storage provider's official signing implementation rather than a hand-rolled hash.

type ExportRecord = {
  id: string;
  ownerId: string;
  objectKey: string;
  downloadName: string;
  status: "ready" | "building" | "failed";
};

type ReadLink = { url: string; expiresAt: Date };

interface ObjectStore {
  signRead(input: {
    key: string;
    expiresInSeconds: number;
    responseContentDisposition: string;
    responseContentType: string;
  }): Promise<ReadLink>;
}

async function createDownloadLink(
  userId: string,
  exportId: string,
  store: ObjectStore,
  findExport: (id: string) => Promise<ExportRecord | null>,
): Promise<ReadLink> {
  const record = await findExport(exportId);

  if (!record || record.ownerId !== userId || record.status !== "ready") {
    throw new Error("Download is unavailable");
  }

  const safeName = record.downloadName.replace(/[\r\n"\\]/g, "_");

  return store.signRead({
    key: record.objectKey,
    expiresInSeconds: 300,
    responseContentDisposition: `attachment; filename="${safeName}"`,
    responseContentType: "application/octet-stream",
  });
}

Five minutes is an example policy, not a universal answer. I would start with 300 seconds for a user-initiated export, then test the slowest supported network and the largest normal file. A lifetime that is shorter than the expected transfer is a broken user experience. A lifetime measured in hours increases the damage from a leaked URL.

The filename deserves attention too. It is response metadata, not a trusted HTML fragment. Strip line breaks and delimiter characters before putting it into Content-Disposition. Keep the object key server-owned; never concatenate an untrusted filename into a bucket path.

Why does the browser still fail after the link works?

A URL can be valid in a command-line client and still fail in browser JavaScript. That is usually a CORS policy problem, not a signing problem. A frontend that only navigates to the URL may need less access than code that calls fetch, reads headers, or downloads a Blob.

For a browser fetch, configure the storage endpoint to allow the exact application origin and the methods and response headers the frontend needs. Do not use a wildcard origin for a credentialed browser request. MDN's CORS guidance explains why the browser makes this distinction and why the server's response headers matter.

There is another trap: a cross-origin response can contain a useful Content-Disposition header while browser JavaScript cannot read it unless the storage response exposes that header. Decide whether the UI needs to inspect headers. If it does, expose only the necessary headers.

Test both paths:

const response = await fetch(downloadUrl);

if (!response.ok) {
  throw new Error(`Download failed with HTTP ${response.status}`);
}

const contentLength = response.headers.get("content-length");
const file = await response.blob();

console.info({
  bytesAdvertised: contentLength ? Number(contentLength) : null,
  bytesReceived: file.size,
});

A direct navigation tests delivery. fetch tests CORS, exposed headers, and browser memory behavior. They are different contracts. For very large files, a navigation or a native download flow is often a better browser path than buffering the whole response in JavaScript.\n+

The storage services differ at the edges

The broad pattern is shared by Amazon S3 presigned requests, Google Cloud Storage signed URLs, and Azure Blob Storage shared access signatures: a credential-bearing URL grants limited access for a limited interval. The details are not interchangeable. Signature construction, response overrides, allowed methods, and maximum lifetimes depend on the service and signing mode.

That is why the adapter should own the provider SDK and its tests. A test that merely asserts url.includes("expires") proves almost nothing. Use a real test object in an isolated environment, verify that a valid URL reads the expected bytes, then verify that an expired URL is rejected. Include a non-owner request and a key containing path-like characters.

Concern S3 presigned request Cloud Storage signed URL Azure Blob SAS
Main capability Signed request for a specific object Signed URL for a resource Delegated SAS permissions
Policy surface Request method and expiry are part of the signature URL version and signed fields matter Permissions, resource type, and expiry are explicit
Adapter risk Mixing signing versions or regions Signing the wrong canonical fields Granting broader permissions than read

The table is a reminder to isolate differences, not a ranking. Read the primary signing documentation for the exact request shape you deploy.

What changes when the file is large?

Large-file throughput is mostly a path and retry problem. Keep the bytes off the application network path. Put the object in the region and storage class appropriate for the workload. Measure time to first byte, sustained throughput, failed transfers, and retry volume separately; one average hides too much.\n+
Range requests can make interrupted downloads less painful, but they do not magically make every signed URL compatible with every client or policy. If your product needs resumable media delivery, verify that the signature covers the intended request and that the storage service accepts the range behavior. Also decide whether the object can change during a multi-request download. Immutable export keys are much easier to reason about than mutable ones.

At scale, I would add a download-attempt record with the export ID, user ID, issued time, expiry, and outcome. Do not store the full bearer URL in application logs. Redact query strings at the edge and in error reports. Log the object key only if its sensitivity is acceptable.

I would also move repeated downloads behind a CDN only after measuring the access pattern. A CDN can reduce origin load and improve geographic delivery, but it adds another cache and invalidation policy. It does not turn a leaked origin URL into a revocable credential.

The operational rule is simple: authorize at issuance, constrain the signed read, observe the transfer, and assume the URL can be copied until it expires.

What I would change at scale

For an internal tool with occasional exports, the small adapter above is enough. At higher volume, I would separate export readiness from link issuance, keep object keys immutable, and make expiry a policy value rather than a magic number in a controller.

I would add contract tests for each storage adapter, a browser test for the CORS path, and a load test that measures direct storage throughput with files near the product's upper bound. I would not add a proxy just to make authorization feel more centralized. The proxy is justified when the business requires immediate revocation, per-byte inspection, or a response transformation that storage cannot provide.

That trade-off is the decision rule. If the application only needs to decide who may read a ready object, issue a short-lived direct link. If it must control every byte after issuance, keep the bytes in a controlled path and budget for the throughput and maintenance that follows.

Sources

πŸ“° 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.