DEV Community

IrvinCole5861
IrvinCole5861

Posted on

Implementing Signed Browser Upload URLs for Private File Storage (With Deletion Deadlines)

Short answer: For signed B2B documents, keep the file body out of the application server: record a durable upload intent and deletion deadline, issue a narrowly scoped upload capability, let the browser write to private storage, and accept the document only after independently verifying the stored object.

The upload response is not the commit point. Verification is.

Cost begins with retained capacity

Start with the bill because retention, rather than signing, usually determines the long-running shape of this system. A useful capacity model is documents per month x mean bytes per document x retained months; request classes, retrieval, lifecycle operations, and data transfer are separate dimensions that must then be added from the selected service's current pricing documentation. For example, 50,000 documents per month at 40 MiB each and an internally approved 84-month retention period converge on roughly 160 TiB of document bodies. This is a planning example, not a compliance recommendation: counsel and the data owner must determine the applicable period for each document class and jurisdiction.

The material cost change is an enforceable finite deadline. Compression may help at the margin, while deleting an expired 40 MiB object removes all 40 MiB from every later byte-month. The trade-off is real — once verified deletion occurs, the body cannot be recovered for a later dispute. Keep only the opaque object identifier, checksum, policy version, deletion evidence, and tombstone after expiry, and be explicit that this thinner audit record cannot reproduce the original document.

Compare file-body paths before signing

Direct browser-to-storage transfer is suitable when large bodies would otherwise consume application bandwidth and workers, the browser may reach the storage endpoint, and the control plane can independently verify object evidence. It is not suitable when policy requires every byte to pass through application-layer inspection before persistence, network rules prohibit direct browser access to storage, or the selected storage system cannot enforce the required retention and deletion semantics. Keep an application proxy in the first two cases, or use a controlled quarantine-and-promotion worker when inspection may be deferred. Those designs cost more application capacity or add states and operational delay, but the policy boundary takes precedence over throughput.

Boundary File-body path Appropriate when Principal limitation
Presigned direct transfer Browser to private storage Large files and an independently trusted control plane Browser must be allowed to reach storage
Application proxy Browser through the application Inspection is mandatory before persistence Application carries every byte
Quarantine worker Browser to quarantine, then worker promotion Inspection may complete asynchronously More states and delayed availability

The rest of this implementation assumes the first row. That is a conditional choice, not a general ranking.

The retention ledger makes deletion enforceable

Define the retention invariant before implementing upload. Every logical document has one tenant, one opaque object key, one immutable policy-derived delete_at value, and an append-only history of state changes. A normal retry cannot extend delete_at. A legal hold, if the business supports one, is a separately authorized and audited policy decision; a mutable object tag or an operator's delayed job must not quietly become the system of record.

There are two unrelated clocks. The presigned upload capability expires quickly according to the application's risk model, while the retention deadline may be months or years away. Conflating them creates a subtle failure: reissuing an expired upload could accidentally restart retention. The intent record prevents that because the first accepted idempotency key fixes the business deadline, and every later authorization for that intent reads rather than recalculates it.

Model deletion as a state transition with evidence, not as a periodic best-effort cleanup. A worker claims due records idempotently, asks the generic storage adapter to remove the object, verifies absence, appends a tombstone, and marks the record deleted. If it loses its lease after removal, the next attempt observes absence and converges on the same terminal record. This is an exactly-once business result built on operations that may execute more than once.

The following domain code makes the critical rule executable without binding it to a storage product or web framework:

package retention

import (
    "errors"
    "time"
)

type State string

const (
    Verified State = "verified"
    Deleted  State = "deleted"
)

type Document struct {
    ID            string
    State         State
    DeleteAt      time.Time
    PolicyVersion string
    SHA256        string
    DeletedAt     *time.Time
}

func MarkDeleted(d Document, observedAbsent bool, now time.Time) (Document, error) {
    if d.State == Deleted {
        return d, nil
    }
    if d.State != Verified || now.Before(d.DeleteAt) {
        return Document{}, errors.New("document is not due for deletion")
    }
    if !observedAbsent {
        return Document{}, errors.New("object absence has not been verified")
    }
    d.State = Deleted
    d.DeletedAt = &now
    return d, nil
}
Enter fullscreen mode Exit fullscreen mode

This deliberately does not decide how long a signed contract must be retained. Compliance periods are legal and business inputs. The code enforces a decision and records which policy version made it; it does not invent that decision inside a tutorial.

Implement the server-side intent record

The server action is a control-plane adapter. It authenticates the caller, resolves the tenant, validates declared media type and size against policy, creates or finds the intent by idempotency key, assigns an opaque key, and asks a signer for a one-object write capability. It returns the URL, expiry, intent identifier, and exact headers the browser must reproduce. It never accepts the document body, never produces a public read URL, and never trusts a filename as an object key.

That last point deserves attention. A filename is user input; it may disclose customer information in logs, collide after normalization, or acquire path-like meaning in an adapter. Store it as separately protected display metadata only if the product needs it. Generate the object key from server-owned opaque identifiers, and set Content-Disposition on an authorized download response when the application needs to suggest a filename. The header's browser behavior and filename parameters are documented by MDN.

Here is the storage-facing Go service that a server action can invoke after authentication. The signer is intentionally an interface because S3-compatible signing implementations differ in configuration even when they expose the same conceptual operation.

package upload

import (
    "context"
    "errors"
    "fmt"
    "time"
)

type Signer interface {
    SignPut(ctx context.Context, key, contentType string, size int64, expiresAt time.Time) (string, map[string]string, error)
}

type Repository interface {
    CreateOrGet(ctx context.Context, intent Intent) (Intent, error)
}

type Request struct {
    TenantID       string
    DocumentID     string
    IdempotencyKey string
    ContentType    string
    Size           int64
    DeleteAt       time.Time
}

type Intent struct {
    ID             string
    TenantID       string
    DocumentID     string
    IdempotencyKey string
    ObjectKey      string
    ContentType    string
    DeclaredSize   int64
    DeleteAt       time.Time
}

type Ticket struct {
    IntentID string            `json:"intentId"`
    URL      string            `json:"url"`
    Headers  map[string]string `json:"headers"`
    Expires  time.Time         `json:"expiresAt"`
}

func Authorize(ctx context.Context, repo Repository, signer Signer, now time.Time, r Request) (Ticket, error) {
    if r.TenantID == "" || r.DocumentID == "" || r.IdempotencyKey == "" {
        return Ticket{}, errors.New("tenant, document, and idempotency identifiers are required")
    }
    if r.Size <= 0 || r.Size > 512<<20 {
        return Ticket{}, errors.New("declared size is outside policy")
    }
    if !r.DeleteAt.After(now) {
        return Ticket{}, errors.New("deletion deadline must be in the future")
    }

    intent, err := repo.CreateOrGet(ctx, Intent{
        TenantID:       r.TenantID,
        DocumentID:     r.DocumentID,
        IdempotencyKey: r.IdempotencyKey,
        ObjectKey:      fmt.Sprintf("tenants/%s/documents/%s/original", r.TenantID, r.DocumentID),
        ContentType:    r.ContentType,
        DeclaredSize:   r.Size,
        DeleteAt:       r.DeleteAt,
    })
    if err != nil {
        return Ticket{}, fmt.Errorf("record upload intent: %w", err)
    }

    expires := now.Add(10 * time.Minute)
    url, headers, err := signer.SignPut(ctx, intent.ObjectKey, intent.ContentType, intent.DeclaredSize, expires)
    if err != nil {
        return Ticket{}, fmt.Errorf("sign upload: %w", err)
    }
    return Ticket{IntentID: intent.ID, URL: url, Headers: headers, Expires: expires}, nil
}
Enter fullscreen mode Exit fullscreen mode

The 512 MiB ceiling and ten-minute expiry are sample policy constants. They are not portable defaults. Actual document-size distributions, client uplink rates, threat analysis, and the chosen signer's constraints determine suitable values; I'm not sure what timeout fits an unknown tenant population, and a controlled pilot's p95 completion time would resolve that uncertainty.

The browser performs one job: send the body to the returned URL with precisely the signed method and headers, without cookies or application credentials. Cross-origin policy must allow the application origin, method, and headers without broadening access unnecessarily. If the file size calls for multipart upload, represent the multipart session, bounded part numbers, and final ordered part evidence inside the same logical intent; do not create a new business document for each part.

Keep signed URLs out of logs. They are bearer capabilities until expiry.

Test completion evidence before acceptance

A successful browser transfer says that a transport operation completed. It does not prove that the object belongs to the expected intent, has the declared length, passed the application's acceptance rules, or is ready for a downstream signature workflow. The browser therefore reports only the intent identifier after transfer; the server queries object metadata through its storage adapter and performs the authoritative transition from authorized to verified.

This distinction also makes retries understandable. Two authorization requests with the same tenant and idempotency key return the same logical intent. Two completion requests may race, but only matching evidence can produce or replay the verified outcome. A request whose observed length conflicts with the declaration is rejected and audited, rather than overwriting the accepted record or creating a second document. The audit event needs actor, timestamp, idempotency key, prior and next state, opaque object key, declared and observed length, checksum, and policy version; it does not need the filename, document content, or complete signed query string.

package upload

import (
    "errors"
    "time"
)

type State string

const (
    Authorized State = "authorized"
    Verified   State = "verified"
)

type Evidence struct {
    ObservedSize int64
    SHA256       string
    ObservedAt   time.Time
}

type Intent struct {
    State        State
    DeclaredSize int64
    SHA256       string
    DeleteAt     time.Time
}

func Verify(i Intent, e Evidence) (Intent, error) {
    if i.State == Verified && i.DeclaredSize == e.ObservedSize && i.SHA256 == e.SHA256 {
        return i, nil
    }
    if i.State != Authorized {
        return Intent{}, errors.New("invalid state transition")
    }
    if i.DeclaredSize != e.ObservedSize || e.SHA256 == "" {
        return Intent{}, errors.New("object evidence does not match intent")
    }
    i.State = Verified
    i.SHA256 = e.SHA256
    return i, nil
}
Enter fullscreen mode Exit fullscreen mode

The checksum contract must be chosen deliberately. A value supplied only by the browser does not independently establish integrity, and storage services vary in which checksum metadata they calculate or preserve for single-part and multipart operations. Bind the algorithm and evidence source into the intent schema, then verify the exact behavior against the selected implementation's primary documentation and integration tests.

Test the state machine before optimizing the transfer path. Include a zero-byte declaration, an object one byte over policy, a changed content type, reuse of an idempotency key with different attributes, an expired capability, a client disconnect, completion before metadata is observable, checksum disagreement, and two concurrent completion calls. Run sustained transfers using the expected size distribution; a workload made entirely of tiny fixtures says little about large-file throughput. Measure authorization latency separately from browser-to-storage duration, and record time from authorization to verified completion, abandoned intent count, checksum mismatch count, bytes by coarse size bucket, and deletion lag past deadline.

Short logs are safer. Tenant IDs, original filenames, signed query strings, and document contents should not become metric labels.

How should private file storage browser uploads enter production?

Deploy the intent schema and append-only audit writer before enabling uploads. Next, deploy authorization without downstream consumption; then enable verification; finally, permit only verified documents to enter the business workflow. Keep event consumers tolerant of the prior schema version during rollout. Enable the deletion worker only after a staging exercise proves that due records become verified tombstones and that deletion lag is observable.

Storage cost belongs in this acceptance process, but a headline byte price is insufficient. AWS's S3 pricing page, for example, separates storage from requests, data retrieval, transfer, management, and replication dimensions, and an S3-compatible service may expose a different billing model or set of limits. Estimate the actual mix of retained bytes, upload operations, metadata checks, downloads, multipart parts, lifecycle actions, and regional transfer using current primary documentation. Do not choose the architecture from a single rate.

The production acceptance rule can stay concise: a document becomes usable only after observed evidence matches its recorded intent; retries cannot create a second logical document or extend retention; and expiry results in verified absence plus a durable tombstone. What the system deliberately stops keeping is the expired body. That reduces retained capacity, while accepting that later investigations have audit evidence rather than recoverable content.

References

Further reading

Top comments (0)