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

Object Storage Service for Signed Download URLs — Fintech Retention Deadlines

For signed fintech documents with a fixed deletion deadline, use private object storage and issue a fresh, short-lived download URL only after your application authorizes the requester. A permanent public URL is easier t

For signed fintech documents with a fixed deletion deadline, use private object storage and issue a fresh, short-lived download URL only after your application authorizes the requester. A permanent public URL is easier to deliver, but it cannot express who may retrieve a contract or when that permission should end.

Choice Access control Delivery simplicity Deletion deadline
Public object URL Weak: possession is enough Simplest Object deletion only
Long-lived signed URL Time-limited, but easy to forward Simple Can outlive intended access
Authorization check plus short-lived URL Application decides on every request One extra request Separates access expiry from object deletion
Application-streamed download Application controls every byte Most moving parts Separates access expiry from object deletion

Recommendation: start with an authorization check followed by a short-lived signed URL. Keep the document private, store its deletion deadline as application data, and run deletion as a separate, observable workflow. This gives the browser direct delivery without turning the link itself into the complete authorization system.

What should an object storage service check before issuing a signed download URL?

A download URL expiring and a document being deleted are different events. Confusing them is the sharpest failure mode in this design.

Two clocks.

The URL expiry limits how long one bearer credential can be used. The deletion deadline says when the retained object must cease to exist. A user can request another URL while the object remains eligible for access, so expiring a link does not enforce retention. Conversely, deleting an object makes an otherwise unexpired URL useless. Model both clocks.

For a signed agreement, I would keep at least the tenant ID, document ID, storage key, access state, deletion deadline, and deletion state in an application record. The storage key should be opaque. Do not let a browser choose it, and do not derive authorization from its path. The application first checks tenant membership and document state; only then does the storage adapter sign a read request.

This costs one small API call before the download. That is a good trade-off. Directly handing out durable object locations removes glue at first, then pushes authorization bugs into logs, support tools, and incident response. Consider a contract whose deletion deadline passes between the page rendering and the user clicking Download: a URL minted during page rendering can remain usable, while a click-time authorization check sees the new state and refuses to sign. The same check blocks a tenant membership revoked after the page was opened. I judge the happy path by time-to-first-call, but I judge the boundary by how hard it is to misuse.

The two criteria that decide the design

The first criterion is where authorization runs. A signed URL is a bearer credential: anyone who receives it can use it until it expires or the object disappears. The application therefore needs to decide whether the requester may receive that credential right now. Check tenant scope, the document's status, and the deletion deadline before signing. Avoid a cached authorization result whose lifetime exceeds the download URL.

The second criterion is whether deletion is provable. A scheduled job should select records whose deadline has passed, request object deletion, and record a terminal result only after the storage operation succeeds. Retries must be safe. Keep enough audit data to answer which document was targeted, when the attempt ran, and whether a later read check found the object absent. Do not keep the signed document itself in that audit trail.

There are two useful failure states here: deletion is due but not confirmed, and deletion is confirmed. A single deleted boolean hides too much. Network timeouts are ambiguous; the request may have reached storage even when the worker never received a response. The next attempt should tolerate an already-absent object.

Short URLs help, but don't fetishize a specific number. The right lifetime covers the real browser transfer and modest retry delay while limiting the value of a copied link. Measure download duration by file-size band and region, then choose a lifetime from that distribution. No fake benchmark belongs in a security decision.

Links leak.

A narrow TypeScript boundary

The adapter below keeps policy in the application and storage mechanics behind a small interface. It deliberately exposes two clocks. The URL lifetime is measured in seconds; document retention uses an absolute deadline.

type DocumentRecord = {
  id: string;
  tenantId: string;
  objectKey: string;
  fileName: string;
  deleteAfter: Date;
  state: "available" | "deletion_due" | "deleted";
};

type DownloadGrant = {
  url: string;
  expiresAt: Date;
  contentDisposition: string;
};

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

  delete(key: string): Promise<void>;
}

function attachmentValue(fileName: string): string {
  const asciiFallback = fileName.replace(/[^\x20-\x7e]/g, "_").replace(/["\\]/g, "_");
  const encoded = encodeURIComponent(fileName);
  return `attachment; filename="${asciiFallback}"; filename*=UTF-8''${encoded}`;
}

async function createDownloadGrant(input: {
  document: DocumentRecord;
  requesterTenantId: string;
  now: Date;
  store: PrivateObjectStore;
}): Promise<DownloadGrant> {
  const { document, requesterTenantId, now, store } = input;

  if (document.tenantId !== requesterTenantId) throw new Error("not_found");
  if (document.state !== "available") throw new Error("not_available");
  if (document.deleteAfter.getTime() <= now.getTime()) throw new Error("not_available");

  const contentDisposition = attachmentValue(document.fileName);
  const signed = await store.signDownload({
    key: document.objectKey,
    expiresInSeconds: 300,
    responseContentDisposition: contentDisposition,
  });

  return { ...signed, contentDisposition };
}

Five minutes in this example is an explicit test value, not a universal recommendation. Put it in one application setting, not in every call site. Config spreads fast. Soon nobody knows which expiry is real.

Content-Disposition: attachment tells the browser the response should be downloaded, while filename and filename* provide naming information. MDN documents the header syntax and the different encoding behavior of those parameters. Treat the original filename as untrusted display data: normalize it for your product, reject control characters at ingestion, and test names with spaces, quotes, and non-ASCII characters.

The public handler should return a generic missing response for both a cross-tenant lookup and an unknown document ID. That avoids confirming another tenant's document identifiers. Log the internal denial reason with a request ID, never the signed URL; query strings can carry the credential.

Test the deadline, not just the happy path

Most SDK demos stop after one successful download. The useful tests begin at the boundaries. With an injected clock and a fake storage adapter, cover these cases:

  1. An authorized tenant receives a grant before deleteAfter.
  2. Another tenant receives no grant for the same document ID.
  3. A request exactly at deleteAfter is denied.
  4. A document marked deletion_due cannot receive a new grant.
  5. A repeated delete succeeds when the object is already absent.
  6. A filename containing quotes or Unicode produces a controlled disposition value.

Then run integration tests against every storage implementation you intend to deploy. Assert that the object is private by default, the signed response downloads with the expected filename, an expired link fails, and deletion makes retrieval fail. Run the same contract suite in US and EU deployments. S3 compatibility in a request signature does not prove identical behavior around response headers, clocks, redirects, or deletion; the adapter test is the evidence your system needs.

Observe issuance, download outcomes, and deletion separately. Useful counters include authorization denials, grants issued, signing failures, deletion attempts, deletion retries, and overdue records. Never attach full URLs, object keys, document names, or user-supplied filenames to high-cardinality metric labels. A gauge for the oldest overdue deletion is more actionable than a pile of success logs.

When should the application stream the file?

The runner-up is application streaming. It is better when access must be reevaluated throughout delivery, when each byte must pass through content transformation, or when storage endpoints cannot be exposed to clients. It also gives the application direct control of response headers.

The limitation of direct signed delivery is precise: after issuance, the application cannot revoke that individual bearer URL without deleting or otherwise making the object unavailable. This approach does not fit a policy that demands immediate per-session revocation during an active transfer. Application streaming is the clearer choice there.

The bill is operational complexity. Your service now owns bandwidth, backpressure, partial responses, client disconnects, and regional egress paths. Large files can turn a lightweight authorization tier into a data plane. Benchmark concurrency, memory, first-byte latency, and aborted transfers before accepting that role.

A public URL is suitable only when the file is intentionally public and disclosure has no tenant boundary. A longer-lived signed link can fit asynchronous handoff where the recipient cannot call your application again, but its lifetime expands the window for forwarding. Neither choice removes the deletion workflow.

Keep the decision plain: use application authorization plus short-lived direct delivery for ordinary private downloads; stream only when policy or transformation truly requires an application data path. The retention deadline remains an independent state machine in both designs.

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.