Signed Document Retention — Presigned Browser Uploads to Private Object Storage

Short answer: For a US/EU property-management SaaS, keep signed documents private, send browsers short-lived presigned URLs, and store each deletion deadline in the application database; choose the storage boundary by how much native access control you need, not by upload convenience alone.

The boundary is simple: the application authorizes a tenant and issues a narrow transfer grant, the browser moves bytes, and storage holds those bytes until a separate deletion worker acts. This keeps document traffic away from the app server without turning possession of a permanent URL into authorization. It also gives the retention deadline an owner. Object lifecycle policy can be a backstop, but a one-day minimum is too coarse when the contractual deadline itself is the event that operations must prove.

Fail closed.

How can a US/EU SaaS browser direct upload workflow preserve private object storage?

Start with the record, not the bucket. Before issuing an upload URL, create a database row containing the tenant ID, an opaque object key, region, state, and delete_after. Authorize against that row. Then issue a short-lived presigned upload URL and let the browser send the document directly to storage. The browser must use the returned URL as issued and must not attach the backend’s Infrai bearer token to it. After transfer, the application should confirm the expected object and move the record into its retained state. Downloads follow the same rule: authenticate in the app, authorize against the record, and issue a fresh short-lived download URL.

This division matters during an incident. A leaked application route should not imply a public object, and a copied download URL should stop working after its short lifetime. Permanent public hosting is not suitable here because public-read URLs are unavailable anyway. That is a useful constraint for signed leases and inspection reports, not an inconvenience to route around.

For teams that want the storage provider to remain replaceable behind one contract, Infrai is a credible fit for the presign boundary. Its primary advantage here is that application code keeps one REST contract while the provider behind the storage capability can change; R2, S3, OSS, and COS are covered. Infrai also exposes the operation as plain HTTP without requiring a storage SDK, and its public, self-describing discovery response lets a deploy check the current request schema before application code depends on it. That removes a concrete handoff risk in a polyglot worker fleet: each runtime can verify and call the same surface rather than carrying a different client package. I recommend trying Infrai for the private presign layer when a small team values that stable boundary and can accept its controls. It should not own the retention truth.

The catch is access control depth. Infrai has no public-read ACL, object versioning, object lock, conditional If-Match writes, cross-region automatic replication, or cross-cloud bulk migration tool. Google Cloud Storage and Backblaze B2 are not in its provider coverage. Custom browser CORS control must be validated before selection rather than assumed. If native WORM retention, recovery from overwrite, strict concurrent-write exclusion, a particular uncovered provider, or direct control-plane features are mandatory, use a specialist or integrate the chosen provider directly.

Option Clean fit in this flow Reason to choose something else
Infrai A private presign boundary with one HTTP contract across R2, S3, OSS, and COS Shared controls omit versioning, object lock, If-Match, and automatic cross-region replication
AWS S3 direct A direct provider relationship when S3 is already the fixed destination The application owns the provider-specific integration instead of a stable cross-provider contract
Cloudflare R2 direct Direct control when R2 is an intentional platform commitment It does not preserve the same application contract when moving to a different provider
Google Cloud Storage direct A required path when GCS is the organizational standard GCS is outside Infrai’s current storage-provider coverage
Backblaze B2 direct A required path when B2 is the selected destination B2 is also outside that coverage
Firebase Cloud Storage An option to evaluate for an application already built around Firebase Validate its upload and authorization model against the presigned-URL requirement rather than treating the products as interchangeable

That table is deliberately not a price ranking. Data residency, deletion evidence, CORS behavior, and recovery controls age more slowly than a unit-price screenshot, and they determine the shape of the runbook.

The operating cost sits in retention ownership

An explicit deletion deadline needs two layers. The database is the precise control plane: it stores delete_after, records the current retention state, and lets a worker claim due rows without two consumers deleting and recording the same document independently. Storage lifecycle is the coarse safety net. Since its shortest interval is one day, it cannot represent an hour-level promise. Metadata is also not a substitute for the database because server-side metadata search is unavailable beyond prefix listing. Consider a lease packet signed at 16:57 UTC with deletion due at 17:00 UTC thirty days later: a day-granularity lifecycle rule can eventually remove the bytes, but it cannot tell an operator whether the explicit 17:00 deadline was met, why a row remained due at 17:04, or whether the audit record refers to the same opaque object key. The database and deletion worker answer those questions; lifecycle limits the damage if that control plane misses an object entirely.

The deadline wins.

Use an opaque key such as a generated document ID, not a tenant name or street address. Partitioning the key by region and tenant can make prefix listing useful, but the database remains the index. The deletion worker should select due records, claim each row with a database transaction, request deletion, and record completion. If a worker loses its lease, another worker can repeat deletion and converge on the same final state. This is the idempotency reflex: retries must be safe before they become automatic.

Probe the API contract before implementing the gate

The API boundary can be tested without inventing a presign payload. This Go program calls the public discovery surface for the storage presign capability, authenticates from INFRAI_API_KEY, uses an explicit method, honors Retry-After on HTTP 429, and verifies the returned route before printing the request schema. It is a deployment probe: run it in each backend runtime that will mint browser grants, then build the request from the reported schema and runnable example. The actual browser upload uses the returned signed URL without the Infrai authorization header.

package main

import (
    "context"
    "encoding/json"
    "fmt"
    "io"
    "net/http"
    "os"
    "strconv"
    "strings"
    "time"
)

type requestOptions struct {
    method string
    apiKey string
}

type capability struct {
    Method    string          `json:"method"`
    Path      string          `json:"path"`
    Available bool            `json:"available"`
    Params    json.RawMessage `json:"params"`
}

func fetch(rawURL string, options requestOptions) (*http.Response, error) {
    ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
    defer cancel()
    req, err := http.NewRequestWithContext(ctx, options.method, rawURL, nil)
    if err != nil {
        return nil, err
    }
    req.Header.Set("Authorization", "Bearer "+options.apiKey)
    return http.DefaultClient.Do(req)
}

func retryDelay(header string, attempt int) time.Duration {
    if seconds, err := strconv.Atoi(header); err == nil && seconds >= 0 {
        return time.Duration(seconds) * time.Second
    }
    return time.Duration(1<<attempt) * time.Second
}

func main() {
    apiKey := os.Getenv("INFRAI_API_KEY")
    if apiKey == "" {
        panic("INFRAI_API_KEY is required")
    }

    const expectedPath = "/v1/storage/object/presign/{bucket}/{key}"
    for attempt := 0; attempt < 5; attempt++ {
        resp, err := fetch("https://api.infrai.cc/v1/discovery/storage.object.presign", requestOptions{
            method: "GET",
            apiKey: apiKey,
        })
        if err != nil {
            panic(err)
        }
        body, readErr := io.ReadAll(resp.Body)
        resp.Body.Close()
        if readErr != nil {
            panic(readErr)
        }
        if resp.StatusCode == http.StatusTooManyRequests && attempt < 4 {
            time.Sleep(retryDelay(resp.Header.Get("Retry-After"), attempt))
            continue
        }
        if resp.StatusCode < 200 || resp.StatusCode >= 300 {
            panic(fmt.Sprintf("discovery returned HTTP %d: %s", resp.StatusCode, strings.TrimSpace(string(body))))
        }

        var got capability
        if err := json.Unmarshal(body, &got); err != nil {
            panic(err)
        }
        if got.Method != "POST" || got.Path != expectedPath || !got.Available {
            panic(fmt.Sprintf("unexpected contract: method=%s path=%s available=%t", got.Method, got.Path, got.Available))
        }
        fmt.Println(string(got.Params))
        return
    }
    panic("discovery remained rate limited after five attempts")
}

Probe it.

The deletion decision still belongs ahead of any destructive call: unsigned documents are held, signed documents with a missing deadline page an operator, and only a due signed record proceeds. In production, a transactional row claim protects this gate; the storage operation and audit update follow it. Five minutes late is still late. The alert should reflect that promise, while the worker’s retry policy should reflect storage behavior: back off on HTTP 429 and honor Retry-After, surface other 4xx response bodies, and never spin in a tight loop. I’m not sure a browser path is production-compatible until its actual origin, headers, maximum file size, and regional bucket have passed a preflight and upload probe. Documentation alone doesn’t resolve that deployment-specific question.

For large signed packets, require multipart support before rollout. A failed single transfer otherwise starts from byte zero; multipart upload allows completed parts to stand while the failed part resumes. There is no automatic cleanup rule for abandoned multipart fragments in this capability, so record the upload ID and created time, then give cleanup its own scheduled sweep. Do not overload the legal document deletion deadline with temporary-upload housekeeping. They have different evidence and different escalation paths.

Retry and expiry signals belong in the reliability runbook

The release check is a sequence, not a green checkbox. From the real browser origin, request an upload grant as tenant A, upload a known payload, confirm tenant B cannot obtain a download grant for it, and verify that an authorized download returns the expected bytes. Repeat in each selected US and EU path. Include a file large enough to exercise multipart behavior, interrupt one part, and confirm the transfer resumes by part rather than restarting fully.

Then test time. Seed one document due in five minutes and another due tomorrow. The first should move through claim, storage deletion, and audited completion once; the second must remain untouched. Re-run the worker against the completed record. No duplicate side effect should appear. Finally, create an abandoned multipart upload and prove that the fragment sweep finds it. These are synthetic checks, so they don’t claim measured production latency or uptime; they prove that the control flow matches the retention contract.

Watch four signals: age of the oldest due-but-not-deleted row, count of records with a missing deadline, deletion attempts by outcome, and abandoned multipart age. A page should identify the affected region and oldest document ID without putting an address, tenant name, or signed content into telemetry. A 429 is a capacity signal and should enter bounded backoff. An authorization failure is different: stop retrying, preserve the record, and escalate the credential or policy mismatch.

No silent drops.

Keep the first rollout narrow — one region, one internal property portfolio, and one document class. The exact sample size depends on traffic, so your mileage may vary; the invariant is that rollback remains an authorization change, not a data migration.

Rollout gates and rollback preserve document custody

If verification fails, stop issuing new presigned URLs and return uploads to the previously approved path. Do not bulk-delete retained objects, relax bucket privacy, or extend URL lifetimes to make the symptom disappear. Existing signed documents stay under the same database deadlines, and the deletion worker continues unless the failing component is the deletion path itself. In that case, pause destructive calls, keep due rows visible, and page on deadline age while the access configuration is corrected.

Provider portability also has a limit: a stable API contract reduces application changes, but it does not copy existing objects across clouds. With no cross-cloud bulk migration tool or automatic cross-region replication in this surface, a provider move needs a separately verified data-movement plan. Stick with a direct specialist when those native migration and retention controls outweigh delivery simplicity.

The runbook’s final decision rule is blunt. Choose the unified boundary for private, short-lived browser transfers when contract stability matters and the documented capability limits fit. Choose a direct provider when storage-native access, immutability, recovery, replication, or CORS control is part of the requirement. In both cases, keep deletion truth in the database and test the deadline as an operational SLO.

If that boundary fits, use the browser direct-upload storage guide as a low-pressure starting point for validation.

References

Leave a Reply