Short answer: Keep exports private, authorize by tenant and export record, issue a short-lived presigned download link, and delete the object at an immutable deadline.
The clean design is a two-step export. An authenticated API creates an export record and a private object. A second API checks that record, then returns a short-lived presigned download URL. A background worker deletes the object at the recorded deadline. The browser never receives storage credentials.
That sounds routine until the files are signed game agreements, the customer is a tenant, and deletion is a contractual event rather than housekeeping. The important boundary is not the URL. It is the authorization decision made immediately before the URL is minted.
How should I implement file export with a temporary download link?
Store tenantId, exportId, objectKey, deleteAt, and status together in your application database. Generate an unpredictable object key. When a user asks for a download, load the record through the authenticated tenant context, reject expired or deleted records, and sign exactly one object for a short window.
The storage object should remain private. The signed URL is a capability with an expiry, not a replacement for application authorization. It also cannot enforce a deletion deadline by itself: a URL that was copied before deletion remains usable until its own expiry, so the signer must refuse late requests and the deletion worker must remove the object on time.
I would make deleteAt immutable after the export enters ready. A support workflow can create a new export with a new policy decision. Quietly extending an existing deadline is how an operational convenience becomes a retention bug.
The deadline is policy data, not a comment on the object.
What should happen when a tenant requests a download?
The request path needs a narrow sequence:
- Authenticate the caller.
- Resolve the tenant from the trusted session or token claims, never from a body field.
- Fetch the export by both
tenantIdandexportId. - Check status and
deleteAtusing the database clock. - Mint a presigned
GETfor the exact private object key.
The fourth step is the one teams skip. Checking the deadline only when the export is created leaves a long-lived download route that keeps working after the retention policy says the file is gone. Checking only in the browser is worse; browser code is not a security boundary.
Here is the smallest interface I would put around the provider-specific signer. The application owns the policy. An adapter owns the storage SDK.
type ExportStatus = "building" | "ready" | "deleting" | "deleted";
type ExportRecord = {
id: string;
tenantId: string;
objectKey: string;
status: ExportStatus;
deleteAt: Date;
};
type Signer = (input: {
objectKey: string;
expiresInSeconds: number;
}) => Promise<string>;
async function createDownloadLink(
signer: Signer,
record: ExportRecord,
requestTenantId: string,
now: Date,
): Promise<string> {
if (record.tenantId !== requestTenantId) {
throw new Error("export not found");
}
if (record.status !== "ready" || record.deleteAt <= now) {
throw new Error("export unavailable");
}
const secondsUntilDeletion = Math.floor(
(record.deleteAt.getTime() - now.getTime()) / 1000,
);
const expiresInSeconds = Math.max(1, Math.min(300, secondsUntilDeletion));
return signer({
objectKey: record.objectKey,
expiresInSeconds,
});
}
The five-minute ceiling is a policy choice, not a provider requirement. I prefer it because a download link should be useful for a normal retry without becoming a second retention system. The upper bound also makes accidental leakage less durable. For very large exports, use a resumable transfer design deliberately; do not solve slow networks by making the URL live for a week.
One subtlety: the API can return a valid URL and the worker can delete the object a moment later. That is expected at the deadline boundary. Clients should treat an object-not-found response as a completed retention outcome, not retry forever.
Why a private object is not enough for tenant isolation
Object names are identifiers, not authorization. A prefix such as tenants/acme/... helps operations, but it does not prove that the caller belongs to Acme. The proof belongs in the database lookup and in the signer input.
I use an opaque export identifier and a server-generated key. The key can contain a tenant namespace for diagnostics, but it should not be constructed from a user-supplied filename. Filenames bring path separators, Unicode normalization, confusing extensions, and log-injection problems. Keep the display name in metadata; keep the object key boring.
The export creation transaction should reserve the record before work starts. A worker then writes to the reserved key, verifies that the generated artifact belongs to the same tenant and export, and changes building to ready. If generation fails, the record is marked failed and the partial object is cleaned up. A successful upload without a matching ready record is not downloadable.
For game operations, this matters during a busy release window. A player-support agent may have access to several tenants, and a copied export ID should still be useless outside its original tenant. The query shape should make the safe path the easy path:
async function findExportForDownload(
db: { exports: { findFirst: Function } },
tenantId: string,
exportId: string,
): Promise<ExportRecord | null> {
return db.exports.findFirst({
where: { id: exportId, tenantId },
});
}
In production code, use the concrete database client type instead of Function; the deliberately tiny example is showing the compound lookup, not prescribing an ORM. Test that lookup with two tenants and identical export IDs. A route-level test with only one tenant proves almost nothing.
How should signing adapters handle provider differences?
The policy should stay provider-neutral, but the signing primitive will not. Amazon S3 uses presigned requests, Google Cloud Storage exposes signed URLs, and Azure Blob Storage commonly uses a shared access signature. They differ in credential models, request construction, and the exact permissions encoded in the token. That is an implementation detail worth isolating because the retention rule, tenant lookup, and audit record should not change when an adapter changes. The contract should say what the application needs: one exact object, read access, a bounded expiry, and no storage credentials in the client. It should not leak a provider's request builder into route handlers, tests, or job code.
That difference is enough reason to hide them behind the Signer function. It is not a reason to pretend the adapters are interchangeable line for line. A provider migration still needs tests for method, object identity, expiry, and permission scope.
| Concern | Adapter contract | Test that matters |
|---|---|---|
| Object identity | Signs one exact key | A sibling tenant's key cannot be fetched |
| Method | Grants read access only | A download token cannot write or delete |
| Lifetime | Receives the bounded expiry | A request after deleteAt is refused by the API |
| Response behavior | Supports the expected download headers | The browser can handle the file name and size |
Cross-origin behavior is a browser concern layered on top. If the frontend is hosted on a different origin, configure the bucket's CORS policy for the required origin and method, and expose only headers the browser needs. CORS does not grant storage permission; it controls which browser origins may read a response. A non-browser client is unaffected by that browser policy.
Do not log the complete signed URL. Query parameters are part of the capability. Log the export ID, tenant ID, signer adapter, expiry timestamp, and outcome instead. Redact authorization headers and query strings in reverse proxies as well. This is a small operational rule with a large blast radius.
What I would change at scale
The basic flow is enough for a first implementation. At higher volume, I would add an outbox event when an export becomes ready, a deletion queue keyed by deleteAt, and a periodic sweeper for missed jobs. The sweeper must be idempotent: deleting an already absent object is success, while a permission error is retryable and visible.
The database remains the source of truth for eligibility. The queue is a delivery mechanism. Mixing those roles creates a familiar failure: a delayed queue message accidentally becomes permission to download an object that should already be expired.
Measure four times: export creation latency, time from ready to deletion, rejected cross-tenant attempts, and signed-link issuance after the deadline. The last two are security signals, not vanity metrics. Add an alert for deletion lag rather than pretending a best-effort worker is a deadline guarantee.
There is a real trade-off here. A strict deletion deadline can interrupt a download that started before the deadline. A grace period improves user experience but changes the retention contract. Pick one explicitly, document the clock used, and test the boundary with timestamps one second before, exactly at, and one second after deleteAt.
The decision rule is uncomplicated: keep authorization and retention in your application, keep objects private, keep signing provider-specific, and make the URL shorter-lived than the deletion window. For signed game documents, tenant isolation is the invariant. The download link is only the temporary transport mechanism.
Further reading
- https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/CORS
- https://docs.aws.amazon.com/AmazonS3/latest/userguide/using-presigned-url.html
- https://cloud.google.com/storage/docs/access-control/signed-urls
- https://learn.microsoft.com/en-us/azure/storage/blobs/sas-service-create-javascript
- https://datatracker.ietf.org/doc/html/rfc9110
Top comments (0)