2026 年 Marketplace 生成圖片預簽名下載 URL 過期問題解説
Expired Presigned Download URLs for Generated Marketplace Images Explained in 2026
文章説明 SaaS 如何處理 AI 生成 Marketplace 圖片的預簽名下載 URL 過期問題:持久保存租戶範圍內的 object key,並在每次請求完成授權後才簽發短時效 URL。
TL;DR
When generated marketplace report images stop loading because a presigned download URL expired, store an immutable tenant-scoped object key instead; authorize every SaaS app request, mint a short-lived URL only after that check, and treat the URL as a disposable delivery credential.
An expired link is usually doing its job. The operational mistake is letting that temporary credential become durable application state in a database row, queue payload, cached API response, or browser history. Once those lifetimes are coupled, a report can still exist and the customer can still be entitled to it while the image refuses to load.
That distinction matters more than the signing library.
How should a SaaS app troubleshoot expired presigned download URLs for AI-generated images?
Start at the customer request and trace four identities separately: the authenticated principal, the tenant, the report, and the object key. A marketplace often has buyer, seller, and operator roles under one account model; a valid session is not proof that every role may fetch every report. The server must resolve the report inside the caller's tenant before it asks object storage for a temporary download credential.
The first diagnostic split is simple. If the application cannot map the request to exactly one authorized tenant and report, stop before signing. If it can, generate a fresh URL and inspect the client request. A 401 belongs at the application authentication boundary. A 404 can deliberately hide a report that is absent or outside the tenant. A 403 from a temporary object request points the investigation toward credential scope, expiry, clock alignment, or a changed object identity. Don't turn those cases into one generic broken-image event.
I initially treated every missing preview as a storage alert. On-call history with missed jobs and duplicate deliveries points to a better reflex: prove the state transition first. In this workflow the relevant transition is authorized report reference -> newly signed object request -> completed download. Record a correlation ID, tenant ID, report ID, object-key hash, signing timestamp, expiry timestamp, and outcome at those boundaries. Never log the URL itself; its query string is a credential. OWASP recommends managing secrets across creation, rotation, revocation, and expiration, and the same lifecycle thinking applies to the signing key behind these links.
Keep one uncertainty visible: a browser's generic image error doesn't reveal which boundary rejected the request. I'm not sure which boundary failed until server logs, storage access logs, and a captured response status agree. Your mileage may vary with proxies and browser caching, so reproduce with a newly minted URL before changing expiry policy.
A useful triage order is:
- Confirm the user session and tenant membership at request time.
- Resolve the report by both
tenant_idandreport_id, never by report ID alone. - Compare the stored object key with the key passed to the signer.
- Mint once, fetch once, and record the response status without recording the credential.
- Check server and signer clocks, then check any cache that could replay an older application response.
No guessing.
What should remain durable when a delivery credential expires?
The durable row should describe ownership and identity: tenant ID, report ID, object key, media type, creation time, and perhaps a content digest. The response URL is derived data. It should not be copied into the report row because its lifetime is intentionally shorter than the report's retention period. It should also stay out of long-lived queue messages. A job that generates a report can publish the object key and report ID; the customer-facing request path performs the current authorization check and signs later.
This model closes a tenant-isolation gap that longer expirations cannot close. Suppose seller A receives a link, an administrator later revokes A's report access, and the link remains valid for hours. The application has no opportunity to enforce that revocation while the old credential is still accepted by storage. Shorter lifetimes reduce that exposure, but they increase refresh frequency and make offline viewing less forgiving. There is no universal duration. Set it from the maximum acceptable revocation delay, expected download time, retry behavior, and clock tolerance, then test those assumptions.
The catch is that presigned delivery is not suitable when access must be revoked immediately after issuance. Use an application-controlled download proxy for that requirement, accepting the bandwidth, connection, and capacity burden. Stick with direct signed downloads when bounded credential lifetime is acceptable and the object service should carry the data path. For public, non-sensitive assets, a public origin or cacheable publishing path may be simpler; don't impose per-request authorization where the product has no private-access rule.
Generated report images add one more trap: object creation and report publication must have an explicit order. Upload the final object, verify the application has the expected object identity, and only then mark the report ready. For large objects, multipart upload divides data into parts and requires completion before the assembled object is available as the final upload; abandoned multipart uploads also need lifecycle attention. A customer should never receive a ready report that still points at an in-progress object.
Implement tenant-scoped signing in Go
Keep the HTTP handler responsible for authentication and authorization, while a small interface hides the storage-specific signing operation. The interface makes the security boundary obvious: it accepts a server-owned object key, not an arbitrary URL or a client-supplied bucket and key.
package downloads
import (
"context"
"encoding/json"
"errors"
"net/http"
"time"
)
type Report struct {
ID string
TenantID string
ObjectKey string
}
type ReportStore interface {
FindReady(ctx context.Context, tenantID, reportID string) (Report, error)
}
type Signer interface {
SignDownload(ctx context.Context, objectKey string, expiresIn time.Duration) (string, error)
}
type Handler struct {
Reports ReportStore
Signer Signer
TTL time.Duration
}
type identity struct {
TenantID string
}
type identityKey struct{}
func (h Handler) DownloadURL(w http.ResponseWriter, r *http.Request) {
caller, ok := r.Context().Value(identityKey{}).(identity)
if !ok || caller.TenantID == "" {
http.Error(w, "unauthorized", http.StatusUnauthorized)
return
}
reportID := r.PathValue("reportID")
report, err := h.Reports.FindReady(r.Context(), caller.TenantID, reportID)
if err != nil {
http.Error(w, "report not found", http.StatusNotFound)
return
}
if report.TenantID != caller.TenantID {
http.Error(w, "report not found", http.StatusNotFound)
return
}
downloadURL, err := h.Signer.SignDownload(r.Context(), report.ObjectKey, h.TTL)
if err != nil {
http.Error(w, "download unavailable", http.StatusServiceUnavailable)
return
}
w.Header().Set("Cache-Control", "private, no-store")
w.Header().Set("Content-Type", "application/json")
if err := json.NewEncoder(w).Encode(map[string]any{
"url": downloadURL,
"expires_in": int64(h.TTL.Seconds()),
}); err != nil && !errors.Is(err, context.Canceled) {
return
}
}
The database query behind FindReady must include tenant and readiness predicates in the same lookup. Checking the tenant afterward is defense in depth, not the primary isolation control. Likewise, the real route can be any application route; the important contract is that it names an application report, not a raw object key. Clients shouldn't be allowed to turn the signing endpoint into a credential vending machine for guessed keys.
The response says how long the credential lasts so the client can decide whether to request a new one before a user-initiated download. It does not promise a stable URL. A page reload can request another credential. A background refresh should be conservative — refresh only while the report view is active, deduplicate concurrent refreshes, and stop retrying when the application authorization endpoint returns 401 or 404.
How can you verify tenant isolation and rollback before release?
Unit tests are necessary but insufficient because the failure crosses a database, signer, clock, cache policy, and browser. In a staging environment, create two tenants with one generated report each. Assert that tenant A can request A's report and cannot request B's report, including when B's report ID is supplied directly. Then fetch A's object before expiry, wait past a deliberately short test duration, confirm the old credential is rejected, request a new application URL, and confirm that the new credential retrieves the same object.
Test duplication too. Two simultaneous refresh requests may produce two valid disposable URLs; that must not duplicate the report, mutate ownership, or enqueue generation again. The signing path should be read-only from the product's point of view. If signing has a request charge or rate limit in a chosen service, coalesce identical in-flight refreshes at the application layer, but don't share the result across tenant cache keys.
For observability, graph application signing attempts, authorization denials, URL issuance latency, and storage download outcomes separately. Alert on a sustained change in ratios rather than every expected expiry. Expected expiration is customer-safe when the UI obtains a replacement; a spike in replacement loops is the actionable signal. Keep raw URLs and signing secrets out of traces, analytics payloads, screenshots, and support tickets. Rotate the signing secret under a runbook that covers overlapping credentials, verification, and rollback.
Rollout should begin with a small tenant cohort and a reversible response shape. Preserve the old read path long enough to roll back application code, but do not write new temporary URLs into durable rows. If the new path increases authorization denials, pause expansion and compare tenant/report joins before touching storage policy. If issuance latency rises, roll back the handler while retaining the durable object-key migration; that data model is useful independent of one delivery mechanism.
The release gate is concrete: no cross-tenant download in negative tests, no URL in durable state or logs, successful renewal after test expiry, and a documented choice between direct delivery and a proxy. Ship only when all four are true.
References
來源:DEV Community · dev.to