Node.js Private File Export Links: Presigned Delivery and Retention Audits

本文为原文前 6,000 字符的节选翻译,完整内容请查看原文。

Node.js Private File Export Links: Presigned Delivery and Retention Audits

Short answer: make the export record, not the object URL, your source of truth. Authorize the tenant against that record, issue a short-lived presigned download URL, and measure the record all the way through deletion. For an e-commerce platform, a training bundle is usually a ZIP of product guides, images, and a manifest. The old mental model is “upload, make a link, send email.” The safer model is a small state machine: created -> ready -> url_issued -> deleted. Object storage carries bytes; the application owns tenant isolation and retention. That distinction is the useful design decision. A URL can be valid and still point at the wrong tenant, survive the retention deadline, or be consumed by an automated mail scanner before a human clicks it. Links are credentials.

简短的回答是:将导出记录(而非对象 URL)作为你的事实来源。根据该记录对租户进行授权,签发一个短期的预签名下载 URL,并全程跟踪记录直至删除。对于电子商务平台,培训包通常是包含产品指南、图像和清单的 ZIP 文件。旧的思维模式是“上传、生成链接、发送邮件”。更安全的模式是一个小型状态机:已创建 -> 就绪 -> 已签发 URL -> 已删除。对象存储负责承载字节,而应用程序负责租户隔离和保留策略。这种区分是关键的设计决策。一个 URL 可能在技术上有效,但却指向了错误的租户、超过了保留期限,或者在用户点击前就被自动邮件扫描器消耗掉了。链接本身就是凭证。

Start with a retention record, not a bucket path. Give every export an immutable record containing tenantId, exportId, objectKey, state, expiresAt, and a checksum. The request should contain only an export ID. The server loads the row, checks the authenticated tenant, and derives the object key. A user-supplied tenant string must never become a bucket prefix by concatenation. Retention is an application decision and a storage policy. Compare expiresAt with the current time at every download request. Return 410 Gone for an expired export and 409 Conflict while it is still assembling. A lifecycle rule remains a useful cleanup backstop, but it is not evidence that deletion happened on time.

从保留记录开始,而不是从存储桶路径开始。为每次导出提供一个不可变的记录,包含 tenantId、exportId、objectKey、状态、expiresAt 和校验和。请求应仅包含导出 ID。服务器加载该行,检查已认证的租户,并推导出对象键。用户提供的租户字符串绝不能通过拼接成为存储桶前缀。保留策略是应用程序的决策,也是一种存储策略。在每次下载请求时,将 expiresAt 与当前时间进行比较。对于已过期的导出返回 410 Gone,对于仍在组装中的导出返回 409 Conflict。生命周期规则仍然是一个有用的清理后盾,但它不能证明删除操作是按时发生的。

Here is the narrow boundary I use in Node.js. It keeps provider syntax out of the authorization path and makes the policy easy to unit-test.

以下是我在 Node.js 中使用的边界定义。它将提供商特定的语法排除在授权路径之外,并使策略易于进行单元测试。

type ExportRecord = { tenantId: string; objectKey: string; state: "ready" | "assembling" | "expired"; expiresAt: Date; };
type PrivateStore = { headObject(input: { bucket: string; key: string }): Promise<{ size: number }>; presignGet(input: { bucket: string; key: string; expiresInSeconds: number; contentDisposition: string; }): Promise<string>; };

async function issueExportLink( record: ExportRecord, requesterTenantId: string, store: PrivateStore, bucket: string, ): Promise<string> {
  if (record.tenantId !== requesterTenantId) throw new Error("forbidden");
  if (record.state !== "ready") throw new Error("export_not_ready");
  if (record.expiresAt.getTime() <= Date.now()) throw new Error("export_expired");
  await store.headObject({ bucket, key: record.objectKey });
  return store.presignGet({ bucket, key: record.objectKey, expiresInSeconds: 120, contentDisposition: "attachment; filename=training-export.zip", });
}

The metadata check is intentional. It confirms that the object is visible before a link is issued, instead of trusting an earlier upload acknowledgement. Emit an export.download_url_issued event with tenant, export, expiry, and a request ID. Never put the signed URL in logs; its query string is a bearer credential. Which Node.js presigned download URL flow protects a private export? Use an authenticated application link as the durable bookmark, then redirect to a newly signed object URL. The application link can be disabled when a tenant is suspended and can record a redemption. The object itself stays private. Keep redemption idempotent because scanners and previews may request a URL before the recipient does.

元数据检查是有意为之的。它在签发链接前确认对象是可见的,而不是盲目信任之前的上传确认。触发一个包含租户、导出信息、过期时间和请求 ID 的 export.download_url_issued 事件。切勿将签名后的 URL 放入日志中;其查询字符串是持有者凭证。哪种 Node.js 预签名下载 URL 流程能保护私有导出?使用经过身份验证的应用程序链接作为持久书签,然后重定向到新签名的对象 URL。当租户被暂停时,应用程序链接可以被禁用,并能记录兑换情况。对象本身保持私有。保持兑换的幂等性,因为扫描器和预览功能可能会在收件人之前请求 URL。

For a browser navigation, CORS does not gate the download. CORS matters when a front end uses fetch() or XHR and reads the response in JavaScript. If the training UI needs progress or client-side ZIP inspection, allow only its exact origin, method, and response headers, and test the preflight from the deployed origin. A permissive wildcard is a poor substitute for tenant authorization. Presigned URLs are bearer tokens, so expiry is a risk budget, not a revocation system. Two minutes may fit a small bundle; a large export, range requests, or a corporate scanner may need a different value. Signature V4 URLs have a seven-day maximum, and temporary signing credentials can end sooner. I’m not sure which delay your object store’s lifecycle scheduler will show, so verify it in a disposable bucket and record the observation.

对于浏览器导航,CORS 不会限制下载。当前端使用 fetch() 或 XHR 并在 JavaScript 中读取响应时,CORS 才至关重要。如果培训 UI 需要进度条或客户端 ZIP 检查,请仅允许其确切的来源、方法和响应头,并从部署的来源测试预检请求。宽松的通配符是租户授权的糟糕替代品。预签名 URL 是持有者令牌,因此过期时间是一种风险预算,而不是撤销系统。两分钟可能适合小文件包;大型导出、范围请求或企业扫描器可能需要不同的值。Signature V4 URL 最长有效期为七天,临时签名凭证可能会更早失效。我不确定你的对象存储生命周期调度程序会有多大延迟,因此请在一次性存储桶中进行验证并记录观察结果。

Make publication and deletion observable. The worker should write the object, collect its metadata, and then mark the database row ready. The signer performs its own metadata check. This ordering prevents a queue consumer from seeing ready before the bytes are available. Retries use an idempotency key such as exportId:recipientId; delayed messages still re-check expiresAt and cannot resurrect an expired export. In practice, the interesting trace is the gap between those operations: a worker may finish uploading at 10:02:14, the database transaction may commit at 10:02:15, and a mail job may be dequeued at 10:02:15.2. If the signer trusts only the row, it can hand out a link before a reader can see the object.

使发布和删除过程可观测。工作进程应写入对象、收集其元数据,然后将数据库行标记为就绪。签名者执行自己的元数据检查。这种顺序防止了队列消费者在字节可用之前看到“就绪”状态。重试使用幂等键,例如 exportId:recipientId;延迟的消息仍会重新检查 expiresAt,无法复活已过期的导出。在实践中,有趣的追踪点是这些操作之间的间隔:工作进程可能在 10:02:14 完成上传,数据库事务可能在 10:02:15 提交,而邮件任务可能在 10:02:15.2 被出队。如果签名者仅信任数据库行,它可能会在读取者看到对象之前就发放链接。

Recording the object size and checksum with the state transition gives the API something concrete to verify, while the request ID ties the check, the redirect, and the eventual download to one searchable record. That small amount of bookkeeping also makes a retry boring: the same export and recipient produce one redemption event instead of a trail of apparently different links. Track four transitions: created, ready, url_issued, and deleted. Useful alerts include tenant and export IDs, never the URL. A spike in url_issued without downloads may mean an email prefetcher, a broken message, or an authorization mistake. A 404 after ready points to a publication race or cleanup that ran too early. I also run one cross-tenant negative test on every deploy: tenant A must receive 403 for tenant B’s export ID, even when the ID is guessed correctly. It is a tiny test. It catches the expensive class of isolation regression. Test the denial path.

在状态转换时记录对象大小和校验和,为 API 提供了可验证的具体内容,而请求 ID 将检查、重定向和最终下载关联到一个可搜索的记录中。这种少量的簿记工作也使重试变得简单:相同的导出和收件人只会产生一个兑换事件,而不是一串看似不同的链接。跟踪四个转换:已创建、就绪、已签发 URL 和已删除。有用的警报应包含租户和导出 ID,绝不要包含 URL。url_issued 的激增而没有下载可能意味着邮件预取器、损坏的消息或授权错误。就绪后的 404 错误指向发布竞争或过早执行的清理操作。我还在每次部署时运行一个跨租户负面测试:即使正确猜出了租户 B 的导出 ID,租户 A 也必须收到 403 错误。这是一个很小的测试,但它能捕获代价高昂的隔离回归问题。请务必测试拒绝路径。

Delivery shapeIsolation and retention controlStrengthCost or limitation
Authenticated redirect to presigned GETApplication before signingSimple clients and direct transferA forwarded URL works
交付形式隔离与保留控制优势成本或限制
经过身份验证的重定向至预签名 GET签名前的应用程序控制简单的客户端和直接传输转发的 URL 有效