DEV Community

GodfreySterling1574
GodfreySterling1574

Posted on

How to Design 3-Stage Object Storage Thumbnail Uploads Around Browser Policy

A logistics app that receives product photos from a browser should use a three-stage intake: a short-lived upload authorization, a private original object, and a server-owned thumbnail job. The browser never becomes the authority for tenant access. This arrangement makes CORS a browser permission check instead of a storage security boundary, and it keeps retention and deletion decisions auditable.

The bill starts with bytes retained, requests made, and data transferred. For image intake, retained originals usually dominate because a 4 MB source kept for 180 days costs more than a small thumbnail, while failed preflights mainly cost developer time and retries. I therefore measure the retention window and thumbnail ratio before changing a bucket policy.

Layer Authority Retention decision
Browser Origin policy None
Upload signer Tenant-scoped key Short expiry
Worker and ledger Server role Policy and legal hold

The retention-first intake contract

For a product image, create an intake record before issuing an upload authorization. Store tenant ID, object key, content type, expected size, retention class, and an idempotency key in the ledger. The key should be derived from the application record, not from a filename supplied by a browser.

Here is a small Go handler that illustrates the contract. The storage signer is deliberately an interface; a production adapter can target any service that supports constrained signed writes.

package intake

import (
    "context"
    "fmt"
    "net/http"
    "time"
)

type Signer interface {
    SignPut(ctx context.Context, key, contentType string, ttl time.Duration) (string, error)
}

type Intake struct {
    TenantID string
    ImageID  string
    Signer   Signer
}

func (i Intake) Authorize(w http.ResponseWriter, r *http.Request) {
    if r.Method != http.MethodPost {
        http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
        return
    }
    // The application chooses the key, so a tenant cannot select another tenant's prefix.
    key := fmt.Sprintf("tenants/%s/originals/%s", i.TenantID, i.ImageID)
    url, err := i.Signer.SignPut(r.Context(), key, "image/jpeg", 10*time.Minute)
    if err != nil {
        http.Error(w, "authorization unavailable", http.StatusServiceUnavailable)
        return
    }
    w.Header().Set("Content-Type", "text/plain")
    fmt.Fprint(w, url)
}
Enter fullscreen mode Exit fullscreen mode

The client uploads once, then calls an application endpoint to mark completion. That is the handoff.

The completion path checks object metadata with a trusted server credential, records the checksum, and enqueues resizing. A retry with the same idempotency key returns the existing intake state instead of creating a second ledger row. Exactly once is an accounting property we approximate with idempotent transitions, not a promise that a network packet is delivered once. When a browser reports a CORS error, I first capture the Origin, Access-Control-Request-Method, and Access-Control-Request-Headers values, then compare them with the deployed rule. I also replay the same request with a server-side client: if the server succeeds while the browser refuses to expose the response, the storage authorization is intact and the missing allowance is in the browser policy. If both fail, the signed operation or object key is wrong. This distinction prevents an engineer from widening a private bucket just to silence a console message, which would turn a presentation problem into a data boundary problem. The completion path checks object metadata with a trusted server credential, records the checksum, and enqueues resizing. A retry with the same idempotency key returns the existing intake state instead of creating a second ledger row. Exactly once is an accounting property we approximate with idempotent transitions, not a promise that a network packet is delivered once.

The export manifest is the audit boundary.

A tenant-scoped export should contain object key, checksum, dimensions, retention class, and deletion state. It should never contain a bearer URL that outlives the export job. The manifest is the durable answer to “what did we release?”; signed download links are temporary delivery details.

Testing the boundary before production.

Test the browser path with an actual preflight, an expired signature, a wrong content type, and a cross-tenant key. Test it again from the deployed origin, because localhost success says nothing about a production origin. Instrument authorization issuance, upload completion, resize latency, and deletion outcomes with the tenant and idempotency key, while redacting signed query strings.

I keep one deliberately boring failure test: replay the completion request five times and assert one intake row, one thumbnail job, and one audit transition. It catches the expensive class of bug where a retry multiplies storage and billing without changing the user-visible result.

Why does a private bucket reject a direct thumbnail upload?

CORS is enforced by the user agent. A bucket can be private and still answer a preflight with the exact origin, method, and headers that the browser requested. If the response omits Access-Control-Allow-Origin, the browser blocks JavaScript from reading the response, even if the storage service accepted the write. A 403 seen in developer tools is often an authorization decision; a CORS console message is the browser declining to expose that decision. Those are different failures with different owners. It failed.

No shortcut.

A presigned request changes who signs one operation, not who owns the policy. Its URL encodes an object key, expiry, and constrained method; it does not grant a tenant a general listing capability. It also cannot make a private object public, remove a required encryption header, or bypass an origin policy. The upload still needs a matching CORS rule, and the server must validate the key and metadata before issuing the signature.

What should the thumbnail worker delete, and when?

The worker writes thumbnails/{tenant}/{image}/small.webp only after the original is present and readable by the worker role. It records source checksum, output dimensions, and code version in an audit event. A tenant export reads those records, filters by tenant ID, and emits a manifest; it does not infer ownership from a user-provided prefix.

Retention is a state machine: pending, available, expired, and erased. A scheduled deletion marks expired, deletes the original and derivatives, and records the deletion request and object version. If legal hold or a reconciliation job says the object is still needed, deletion stays pending with a reason. This is where the storage bill changes: deleting originals sooner reduces retained bytes, but it removes the evidence needed to regenerate a thumbnail after a bad resize.

The catch is important. A short original-retention window is not suitable when claims, customs documents, or dispute review require the source image; keep an immutable archive or choose a workflow with a longer hold in that case. Conversely, keeping every original forever is wasteful for catalog photos that can be re-uploaded. Your mileage may vary because the retention clock belongs to policy and contract, not to the upload URL.

References

Further reading

Top comments (0)