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

Generate Tenant Report Files with Presigned Download URLs and Explicit Retention

TL;DR: to generate a presigned URL for a file download in S3-compatible Node.js storage, authorize the customer first, then sign a short-lived GET request for the exact object key. Return it to the client and treat delet

TL;DR: to generate a presigned URL for a file download in S3-compatible Node.js storage, authorize the customer first, then sign a short-lived GET request for the exact object key. Return it to the client and treat deletion as a separate retention workflow. The URL is a capability, not an authorization system.

For a B2B SaaS export, the decision boundary is simple: a presigned link fits a customer download that can go directly to object storage, while tenant ownership, retention, and deletion stay in the database and workers. A 60-second link can reduce load on the application server. It cannot decide if a report should still exist.

The signature is not the policy.

That is the catch.

Choice Good fit Main cost
Application-proxied download Extra inspection, transformation, or per-byte policy Application bandwidth and connection handling
Presigned GET A private, already-authorized object can go straight to the customer Leakage risk and a second failure surface
Public object URL Truly public assets No useful customer-level access control

The middle option is usually the practical one for generated reports. The boundary matters more than the signature format.

How do I generate a presigned URL for a file download?

A request for /reports/7f.../download should not turn into β€œsign whatever key the client supplied.” The server needs a report identifier, the authenticated principal, and the tenant relationship. It then loads the report row, checks its state, derives the object key from server-owned data, and signs that key. The browser never chooses the bucket or object path.

This is also where retention belongs. A report can be ready, expired, or deleted even if an old URL has not reached its expiry time. Checking the row before signing prevents a current request from reviving an expired record. It does not revoke a URL already issued, which is why the expiry window should be short and sensitive reports may need the proxy path.

A useful record has at least these fields: tenant ID, report ID, object key, creation time, retention deadline, deletion state, and an audit timestamp for the last link issuance. Keep the opaque report ID separate from the storage key. That gives you room to change key layout without changing customer-facing URLs.

Why do retention and link expiry need separate clocks?

They answer different questions. Link expiry asks how long a bearer capability may be used. Retention asks how long the business is allowed or expected to keep the report.

For example, a report may be retained for 30 days while each download link lasts 60 seconds. A cleanup worker can mark the report for deletion when the retention deadline passes, remove the object, and keep the metadata needed for an audit trail. If deletion is asynchronous, the state transition needs to be explicit: ready to deleting to deleted, with retries that are safe to repeat.

Do not use URL expiry as your deletion mechanism. It creates a misleading guarantee: the link stops working, but the bytes can remain in storage indefinitely. Object-storage lifecycle rules can help with broad age-based cleanup, while an application-owned deletion job is better for tenant-specific retention, legal holds, and an audit record. The right choice depends on which policy needs to be explainable later.

The limitation is operational: direct delivery gives the application less control once the URL leaves the server. The tradeoff is deliberate. A proxy offers immediate policy enforcement, but it also owns streaming, range requests, connection limits, and bandwidth.

The boring part is the valuable part. Keep the authorization lookup, signer, retention state, and deletion worker separate enough that each one can be tested without a browser in the loop. Then test the browser anyway.

The workflow I would put on a runbook is concrete: the export job writes a private object and a ready row in one application-controlled sequence; the download endpoint resolves the tenant from the session, reads that row, checks the retention deadline, and signs only the stored key; the client follows the URL without sending application credentials to storage; and the cleanup worker claims due rows before deleting objects. A retry must be safe after a timeout, because a timeout does not tell the worker whether the delete reached storage. Keep the row until the delete result is recorded, and alert on rows stuck in deleting. This makes a missing object diagnosable instead of turning every failed click into a generic 404.

A small Node.js signing boundary

The signing code should be boring. Put policy decisions around it, not inside a sprawling storage helper. This example uses the standard S3 client and presigner interfaces, but the endpoint is configuration so the same application boundary can target an S3-compatible service.

import { GetObjectCommand, S3Client } from "@aws-sdk/client-s3";
import { getSignedUrl } from "@aws-sdk/s3-request-presigner";

const storage = new S3Client({
  region: process.env.STORAGE_REGION ?? "us-east-1",
  endpoint: process.env.STORAGE_ENDPOINT,
  forcePathStyle: process.env.STORAGE_PATH_STYLE === "true",
});

type ReadyReport = {
  bucket: string;
  objectKey: string;
  filename: string;
};

export async function createDownloadUrl(report: ReadyReport) {
  const command = new GetObjectCommand({
    Bucket: report.bucket,
    Key: report.objectKey,
    ResponseContentDisposition: `attachment; filename="${report.filename}"`,
  });

  return getSignedUrl(storage, command, { expiresIn: 60 });
}

The example assumes ReadyReport came from an authorization-aware lookup. It is not a safe controller by itself. In the controller, validate the authenticated tenant first, reject non-ready states, and pass only the stored bucket and key into this function. Sanitize the download filename before placing it in a response header; a report title is user data, not a header value.

The query string in a presigned URL is part of the signed request. Changing a signed response header or object key can invalidate the signature. That is useful integrity protection, but it also makes browser behavior worth testing. For cross-origin downloads, configure CORS for the actual browser origin and method. CORS controls browser access; it does not make a leaked bearer URL private.

How should the failure paths behave?

There are several independent failures: the report row may be missing, the tenant may be wrong, the object may have been deleted, the URL may expire before the download begins, or the storage endpoint may reject the request. Keep those states distinguishable in server logs, but do not expose bucket names, object keys, or signer details to the customer.

Return a stable application-level response for an expired or unavailable report. Log the report ID, tenant ID, deletion state, and a request correlation ID. Never log the complete presigned URL. Query parameters commonly contain credentials or signature material, and ordinary reverse-proxy access logs can retain them for much longer than the URL lifetime.

Test the contract at three layers. Unit-test that an unauthorized tenant cannot reach the signer. Integration-test a real private object with a short expiry. Then run a browser test from the production-like origin, because a URL that works in a server-side HTTP client can still fail due to CORS or a forced download header. Measure time to issue the URL, object-download latency, expired-link rate, and deletion backlog. The useful benchmark is the whole customer action, not just the signing function.

When is a presigned link the wrong answer?

An application proxy is the better boundary when every byte needs policy enforcement, when the response must be transformed, or when a download must be revoked immediately after issuance. The application then owns streaming, range requests, connection limits, and bandwidth costs. That is more code. It is also a clearer control point.

Direct links fit when the object is already classified, the tenant check is complete, the expiry is short, and the storage CORS policy is narrow. Do not add a configuration layer for every optional header before measuring a real need. The fastest developer experience is a small signing boundary plus a visible retention state machine.

The durable design is therefore unglamorous: authorize from application data, sign one exact object request, expire the capability quickly, delete through an idempotent workflow, and observe the customer-visible path. Storage handles bytes. Your service owns meaning.

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.