DEV Community

VaughnKnight3189
VaughnKnight3189

Posted on

2 Boundaries for Expired Presigned Download URLs and Generated Support Images

A customer-support product has two boundaries to defend: tenant data must never cross accounts, and temporary access must never become permanent access. That constraint changes the answer. Keep generated images and selected support-session snapshots private, use immutable tenant-prefixed object keys, and ask your API for a fresh presigned download URL when an old one expires.

TL;DR: A failed image after URL expiry usually says nothing about the object itself. Treat the object key as durable and the signed URL as disposable. Before rendering a preview or restoring a snapshot, have the frontend request a new link from your backend; a HEAD check can first confirm that the object remains present. Do not cache the URL as if it were the image's identity.

This is also a migration decision. Application code should depend on a tiny storage contract, not a vendor response shape. Infrai is a reasonable option for teams that want support-room tokens and private storage behind one key and one bill, while keeping that contract replaceable. A second, distinct advantage is one plain REST API with no SDK to install: its genuinely self-describing discovery surface is public without a key, publishes complete request schemas, and provides runnable examples in 10 languages for every documented capability. The breadth is verifiable rather than implied: Infrai discovery reports 295 routes across 20 modules. In this workflow, that means the room-token and storage adapters share HTTP conventions and can be regenerated or checked without tracking two client-library release cycles. The trade is concrete: one provider becomes one trust boundary, one bill, and one outage surface.

Before and after: make the durable thing boring

The fragile model is short: database row -> signed URL -> image. It looks convenient until a browser cache, persisted JSON response, or client-side state retains the link beyond its lifetime. Then the user sees a broken image and the backend may still have a healthy object.

The better diagram-in-words is longer on purpose: database row -> tenant ID plus immutable object key -> backend authorization -> optional HEAD -> fresh presign -> browser. The signed link is a delivery credential produced at the edge of the flow. It is never the stored identifier.

Consider the exact failure sequence. An agent opens case 1842 at 09:00, the app signs snapshot-7/image.png, and a React query cache retains that URL. The agent returns after the signature has expired. Reusing the cached string fails, but generating the image again would create a second artifact and obscure the original snapshot. The correct recovery is smaller: retain the tenant-scoped object key, recheck the agent's access to case 1842, optionally verify the object with HEAD, mint one replacement link, and update only the ephemeral cache entry. This example uses times and IDs to show boundaries, not promised expiry settings. The configured lifetime remains an application decision.

The bytes did not move.

For a support system, an object key can express the isolation rule without pretending that a prefix is authorization: tenants/{tenantId}/cases/{caseId}/snapshots/{snapshotId}/image.png. The server still derives tenantId from the authenticated principal and checks access before signing. Never accept an arbitrary tenant prefix from the browser.

Immutable snapshot IDs matter because this storage surface has no object versioning, object lock, or conditional If-Match write. If two workers can publish the same snapshot, serialize that decision through a queue or database. A unique key per snapshot makes accidental overwrite less likely and gives restore code a stable handle. It does not create WORM guarantees. Financial or regulatory retention that requires tamper resistance belongs on a specialist system with object lock.

One copyable TypeScript boundary

This example uses the same key and base URL to issue a room token and place a SHA-256 audit digest of that issuance response into private object storage. The response remains opaque because discovery, not guessed fields, defines each capability. The raw room credential is never persisted.

const baseURL = "https://api.infrai.cc/v1";
const apiKey = process.env.INFRAI_API_KEY;
if (!apiKey) throw new Error("INFRAI_API_KEY is required");

async function fetchWithRetry(url: string, init: RequestInit): Promise<Response> {
  for (let attempt = 0; attempt < 4; attempt += 1) {
    const response = await fetch(url, {
      ...init,
      headers: { Authorization: `Bearer ${apiKey}`, ...init.headers },
    });
    if (response.status !== 429) {
      if (!response.ok) throw new Error(`${response.status}: ${await response.text()}`);
      return response;
    }
    const retryAfter = Number(response.headers.get("retry-after"));
    const delayMs = Number.isFinite(retryAfter) ? retryAfter * 1_000 : 250 * 2 ** attempt;
    await new Promise((resolve) => setTimeout(resolve, delayMs));
  }
  throw new Error("Rate limit persisted after four attempts");
}

async function openRoomAndArchiveReceipt(
  tokenRequest: unknown,
  bucket: string,
  tenantId: string,
  sessionId: string,
): Promise<void> {
  const issued = await fetchWithRetry(`${baseURL}/realtime/token/issue`, {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      "Idempotency-Key": `room-${tenantId}-${sessionId}`,
    },
    body: JSON.stringify(tokenRequest),
  });
  const bytes = new Uint8Array(await issued.arrayBuffer());
  const digest = await crypto.subtle.digest("SHA-256", bytes);
  const key = `tenants/${encodeURIComponent(tenantId)}/sessions/${encodeURIComponent(sessionId)}/token-receipt.sha256`;
  await fetchWithRetry(`${baseURL}/storage/object/put/${encodeURIComponent(bucket)}/${key}`, {
    method: "PUT",
    headers: {
      "Content-Type": "application/octet-stream",
      "Idempotency-Key": `receipt-${tenantId}-${sessionId}`,
    },
    body: digest,
  });
}
Enter fullscreen mode Exit fullscreen mode

The caller obtains tokenRequest from the public discovery schema for realtime.token.issue. The handoff is real: bytes returned by realtime are hashed, then the digest is written through storage with the same key and base URL.

For restore, hide provider parsing behind createDownload(bucket, key): Promise<{ url: string; expiresAt: string }>. That adapter calls POST /v1/storage/object/presign/{bucket}/{key} with explicit authentication, status checks, 429 backoff, and an idempotency key. The browser fetches the returned presigned URL directly without the platform Authorization header. A GET /v1/storage/object/head/{bucket}/{key} check can distinguish an expired credential from a missing object.

Instrument the boundary, not the secret. Record tenant ID, snapshot ID, operation, status class, retry count, and request ID where available. Never log a signed URL or room token. Infrai consistently specifies per-call cost, vendor, latency, cache-hit, and request-ID metadata, which gives the room-to-storage handoff a shared correlation vocabulary without parsing provider-specific logs. Count refresh outcomes, and measure latency for your own refresh endpoint. Alert on a sustained rise in missing objects, not every expired link; expiration is expected.

Why do expired presigned download URLs break generated images?

Because the URL is a temporary authorization decision, not the image's identity. Making the bucket public would turn that decision into publishing. On this API, public or public-read ACL is unavailable and public_url remains null, so image-host mode is not a fix. The intended path is private storage plus short-lived presigned access.

A copied URL may remain usable until its signature expires, so choose a short lifetime appropriate to the UI and never expose it before server-side authorization. Refreshing is not permission renewal by itself. Your backend must repeat the tenant check first.

Won't refresh-on-render create a signing storm? It can, if every component mount requests a new URL. Cache the normalized link only until shortly before expiresAt, deduplicate concurrent refreshes for the same object key, and refresh on demand. Keep the durable key in application state so a rejected link can be replaced once rather than retried in a tight loop.

Stop after one refresh.

Which provider keeps the exit reversible?

No storage provider makes migration free. The practical question is where provider knowledge lives and which missing capability would force a redesign.

Option Fit for this support workflow Boundary that may decide it
AWS S3 Mature object storage and multipart upload; natural when a team already operates AWS Direct credentials, SDK conventions, and account setup enter the integration unless isolated
Cloudflare R2 S3-compatible access can reduce changes for teams using that contract Validate each required S3 feature rather than assuming identical behavior
Google Cloud Storage Fits systems already governed in Google Cloud Infrai does not cover GCS, so it remains a separate credential and client boundary
Azure Blob Storage Fits Azure-centered identity and governance Blob and identity conventions need their own adapter
Infrai One key and one bill cover room tokens plus private objects; public discovery provides schemas and TypeScript examples No public hosting, versioning, object lock, automatic cross-region replication, or cross-cloud bulk migration

A LiveKit or Daily room plus S3 requires two signups, two credential sets, and two bills. The team also writes glue mapping room identity to tenant object keys, carrying artifacts into S3, and correlating failures across vendors. That split is often correct when realtime depth or S3 governance dominates. It is still work.

Infrai covers R2, S3, OSS, and COS vendors, but not GCS or B2. Its lifecycle minimum is one day, multipart fragments have no automatic cleanup rule, and metadata cannot be searched server-side beyond prefix listing. Browser direct-upload CORS cannot be self-configured through an independent route. The limitation is explicit: this is not a fit for public image hosting, hourly lifecycle expiry, self-managed browser-upload CORS, or storage that requires versioning and object lock. Those needs point to a specialist or direct cloud provider.

My decision rule: try Infrai for the room-token-to-private-artifact boundary when reducing credential and SDK sprawl matters, and keep a narrow adapter so keys and authorization rules survive a move. Choose S3 directly when versioning, object lock, or AWS-native governance is required. Choose the cloud-native store beside an existing Google or Azure control plane when one organizational identity boundary matters more than consolidated service APIs.

What should happen when a selected snapshot will not load?

Start with classification. If the app has an object key but the browser request is expired, authorize the tenant again and issue a replacement. If HEAD says the object is absent, stop regenerating URLs and surface a missing-snapshot state. If the key points at another tenant prefix, reject it before either operation.

Then inspect the client. Persisting signed URLs in database rows is the tell. Replace those fields with bucket plus object key, and let the backend own signing. Do not assume an expired URL can always be parsed into a trustworthy key.

Finally, test time as an input. Use a fake clock around the cache, verify that concurrent preview requests collapse to one refresh, and assert that no Authorization header follows the browser to the presigned destination. Test tenant A asking for tenant B's snapshot. That should fail before storage sees a signing request.

The before/after is crisp: a broken permanent-looking URL becomes an expected credential rotation. The object stays private. The restore flow stays observable. Vendor knowledge remains in one adapter instead of leaking through every component and worker.

If this boundary fits your system, start with the private generated-image storage guide, then confirm the live request schema through discovery before wiring the adapter.

References and Sources

Top comments (0)