Marketplace Object Storage Downloads: How to Generate Pre-Signed URLs for Tenant Files in Node.js

2026-11-29来源 dev.toEnglish

Short answer: authorize the report request before you create a signed object-storage URL, and make the object key tenant-specific. Treat the URL as a short-lived capability, not as proof that the requester may see the report. For a marketplace serving generated reports, the useful decision rule is simple: choose a server-mediated download when every access must be rechecked; choose a signed link when the object can be fetched directly after a server-side authorization decision. In both cases, bind the report to the authenticated tenant, record the decision, and test that a valid user from tenant A cannot retrieve tenant B's bytes.

Delivery choice Tenant boundary Operational cost Best fit
Server-mediated stream Checked on every request More application bandwidth and code Sensitive exports or revocable access
Short-lived signed link Checked when the link is minted Less application traffic; careful expiry and logging required Large reports with a bounded download window
Public object URL No application authorization boundary Easy to share, hard to control Public assets, not customer reports

My default for generated marketplace reports is the second row, with a short expiration and a separate authorization step. The key insight is that signing solves transport authorization for one object and one time window. It does not solve tenant identity, report ownership, browser policy, or deletion.

How should Node.js generate pre-signed download URLs for tenant files?

The request starts with an authenticated principal, not with a filename supplied by a browser. Resolve that principal to a tenant and an internal report record. Then check the report's tenant, state, and intended recipient before touching object storage. In Node.js, the code that generates pre-signed download URLs should receive a report ID and a principal, then derive the object key from trusted data. The files themselves should never be selected by a raw browser path.

A safe lookup looks conceptually like this:

type Report = { id: string; tenantId: string; objectKey: string; state: "ready" | "processing" | "failed"; contentType: string; }; function canDownload(report: Report, tenantId: string): boolean { return report.tenantId === tenantId && report.state === "ready"; } 

The browser may send a report ID. It should not send an object key that the server trusts. An object key is an internal address, and accepting it as an authorization input invites path confusion, guessed identifiers, and accidental cross-tenant reads. The database record is the authority; the storage key is an output of that record.

I also keep the tenant identifier in the key prefix, even though the prefix is not a security control by itself. A key such as tenants/t_482/reports/r_901/export.csv gives operators a useful audit shape and makes an incorrectly assembled key easier to spot. Authorization still compares the report row's tenant ID with the authenticated tenant ID.

The audit event should capture the principal, tenant, report ID, object key, outcome, and expiry chosen for the link. Do not put the signed URL in normal application logs. Query strings can leak through browser history, referrers, reverse proxies, and support screenshots.

How do you keep a signed link from becoming a tenant escape hatch?

There are four boundaries to keep separate.

First, identity is established by the session or token on the API request. A signed URL normally carries storage credentials in a different form; it is not a replacement for the application's identity check.

Second, ownership is decided from server-side data. Check both tenant equality and report readiness. If the report belongs to a user within a tenant, check that relationship too. A ready report with the wrong owner is still the wrong report.

Third, capability scope is narrow. The signing operation should name one object, permit one read operation, and expire in a bounded interval. Avoid signing a prefix or a broad listing permission for a download flow.

Fourth, response behavior should not disclose more than needed. A missing report and a report owned by another tenant can return the same not-found response to reduce enumeration clues. Log the richer internal reason separately.

This is where many implementations drift. They validate tenantId in a route, then concatenate a client-provided filename. The route check and the object lookup are two separate decisions. Put them behind one function so a future endpoint cannot quietly skip the second half.

A small Node.js boundary that is easy to test

The storage client is an adapter. Keep the policy outside it. That makes the tenant rule testable without a live bucket and keeps a change in storage infrastructure from changing the authorization model.

type Principal = { tenantId: string; subject: string }; type ReportRepository = { findById(id: string): Promise<Report | null> }; type Signer = { signRead(input: { key: string; expiresInSeconds: number; contentType: string }): Promise<string>; }; type DownloadResult = | { kind: "not-found" } | { kind: "link"; url: string; expiresInSeconds: number }; async function createReportDownload( principal: Principal, reportId: string, reports: ReportRepository, signer: Signer, ): Promise<DownloadResult> { const report = await reports.findById(reportId); if (!report || !canDownload(report, principal.tenantId)) { return { kind: "not-found" }; } const expiresInSeconds = 300; const url = await signer.signRead({ key: report.objectKey, expiresInSeconds, contentType: report.contentType, }); return { kind: "link", url, expiresInSeconds }; } 

The five-minute value is an example policy, not a universal setting. It should reflect report size, expected network conditions, support needs, and the consequences of a leaked link. A large export may need a longer transfer window or a server-mediated stream. A highly sensitive report may need a one-time download record and a proxy that can revoke access.

The adapter should map this generic operation to the signing API of the selected storage implementation. Keep that mapping in one module. Do not spread provider-specific request construction across route handlers, jobs, and tests. The article's important contract is signRead, not a particular SDK call.

This approach has a real limitation: once a pre-signed URL is issued, the application cannot reliably revoke that individual capability unless it controls the download path or changes the object's availability. A server-mediated stream is slower to operate and consumes application bandwidth, but it is the better choice when immediate revocation or per-request policy is mandatory. The signed-link pattern is a fit for bounded, immutable exports, not a universal answer for every file.

What breaks in production even when the URL is valid?

A valid signature does not guarantee a good browser download. Cross-origin requests are governed by CORS. If a frontend fetches the object from a different origin, the storage service must return an appropriate Access-Control-Allow-Origin value, and a request with credentials has stricter rules than an anonymous request. A normal top-level navigation can behave differently from a JavaScript fetch, so test the actual interaction used by the product.

Content disposition is another practical detail. Set the download name from a server-controlled report name, sanitize it, and keep the object key independent from that display name. Never let a customer-supplied name become a path segment.

Deletion needs a policy too. If a report is removed after the link is issued, the storage object should be removed or made unavailable according to the retention rule. If the object remains readable until the signature expires, document that behavior and include it in the threat model. A database status flag alone cannot revoke an already issued storage capability.

Test the negative paths directly:

  • tenant A requests tenant B's report ID;
  • a report is still processing;
  • the object key in the database is malformed or points outside the tenant prefix;
  • the signing adapter receives a request for a write or list operation;
  • the link is used after its expiry;
  • a browser uses the link through the intended navigation or fetch path.

The highest-value test is not a happy-path string assertion. It proves that the signer is never called when the tenant check fails.

When is the runner-up better?

Server-mediated streaming is the better choice when access must be revoked immediately, when each byte transfer requires an auditable application decision, or when the storage endpoint cannot be safely exposed to the client environment. It costs application bandwidth and adds a streaming path to operate. That trade can be correct for regulated or unusually sensitive exports.

A signed link is the better choice for large, immutable reports whose authorization can be evaluated at issuance time. It keeps the application focused on identity, policy, and audit while the storage layer handles the bytes. The boundary must be explicit: the link is a time-limited capability for one object, not a general-purpose download credential.

For a one-person SaaS, this matters in revenue-per-hour terms. I want the report job, authorization query, signer adapter, and audit event to be boring enough to ship weekly. I outsource the undifferentiated byte transfer to the storage layer, but I keep tenant policy in code I can test and review. That is a better use of scarce hours than building a custom file server before the product needs one.

The final review question is not “does this URL work?” It is “which authenticated tenant caused this exact object capability to exist, for how long, and what happens after that window?” If those answers are recorded and tested, the implementation has a defensible boundary.

References

原文:https://www.a8q9.cn/en/article/marketplace-object-storage-downloads-how-to-generate-pre-signed-urls-for-tenant--2e584f.html

相关文章