DEV Community

CalderHayes9638
CalderHayes9638

Posted on

Private Property Backup Uploads Explained — Go Browser CORS, Presigned URLs, Proxies

Short answer: for large per-tenant property backups, let a Go control plane authorize a single private object key and issue a short-lived presigned URL, let the browser send the bytes directly to storage under a narrow CORS policy, and record completion separately; keep a server proxy for files that must be inspected before any byte reaches durable storage.

This is an architecture decision, not a browser trick. The deciding axis is large-file throughput: a proxy places every backup byte on the application path, while a direct upload keeps authorization, tenancy, and audit decisions on that path without making it carry the payload. The catch is that signing is not completion. A property manager who sees an upload progress bar reach 100% still does not have a restorable snapshot until the control plane verifies the expected object and commits an immutable completion event.

Decision record: separate the control plane from the byte path

The selected design has three operations. First, an authenticated browser asks the Go service to create an upload intent for one tenant and one snapshot. Second, the browser uses the returned signed URL to upload the backup directly into private object storage. Third, the browser submits the intent identifier for completion, after which the service verifies storage state and makes the snapshot eligible for restore.

Keep those operations distinct. A signed URL is a capability with a limited scope and lifetime; it should name a server-chosen object key rather than accept a browser-chosen tenant prefix. Completion is a ledger transition from authorized to verified, and retries must return the same result instead of creating a second snapshot. Restore reads only verified snapshots and resolves the object key from server-side metadata. The browser never gets to declare which tenant owns an object.

This split matters for a property-management system because the unit of isolation is not merely a user account. One operator may administer several buildings, a support employee may be granted temporary access, and a restore may be requested weeks after the upload session ended. Authorization must therefore be evaluated when the intent is created and again when restore access is issued, with tenant, snapshot, actor, checksum, size, and policy version preserved in an audit record. Don't treat the object key as proof of permission.

The object remains private. Browser reachability comes from a constrained signed request, not public-read access, and CORS only determines which browser origins may make and expose a cross-origin response.

CORS is not authorization.

That distinction is easy to blur because a bad CORS rule and a bad storage permission can both appear during frontend testing as a failed request, yet their security meanings are entirely different.

What must stay true for private SaaS document storage and selected snapshot restore?

Four invariants define correctness.

Every object key belongs to exactly one tenant; every completed snapshot refers to exactly one verified object; a repeated completion request has the same observable outcome; and a restore request can resolve only a snapshot visible to the currently authorized tenant. These are database constraints and transactional rules, not naming conventions. The audit trail should distinguish intent creation, byte verification, snapshot completion, restore authorization, and retention deletion, while retaining the idempotency key and policy version used for the decision. Exactly-once delivery across a browser, an application database, and object storage is not a realistic primitive, so the practical target is exactly-once effect: at-least-once requests, deterministic identifiers, conditional state transitions, and reconciliation. Reconciliation closes the gap left by interrupted clients: an upload may reach storage while the completion call never arrives, or a completion request may race with the storage system's observable state, which means a scheduled reconciler must inspect pending intents, verify the expected key and declared properties, complete eligible records through the same idempotent transition, and expire abandoned intents according to policy. Orphan cleanup should be driven by recorded intent state rather than a broad prefix deletion. Retention deserves the same discipline because lifecycle management can expire objects, but application metadata, legal holds, and restore eligibility must agree with that policy. AWS documents lifecycle configuration as a mechanism for managing objects through their lifecycle, while Google Cloud Storage documents its own storage controls; neither source can decide the compliance period for a property manager. I'm not sure which retention interval applies to a given jurisdiction and document class without counsel and the organization's records schedule. The architecture should store the governing policy version so that an auditor can reconstruct why a snapshot was retained or removed.

No guesswork.

How should a SaaS browser upload private documents with presigned URLs and CORS?

The browser should receive the smallest usable capability: one method, one object key, an expiry, and only the headers that the signer committed to. The storage CORS configuration should allow the production application origins, the upload method, the request headers actually sent, and the response headers the UI genuinely reads. Avoid wildcard origins for credentialed application flows, and test the preflight request as part of deployment because an upload endpoint can be correctly signed while the browser still refuses the cross-origin exchange.

A useful test matrix is deliberately uneven: approved origin and exact headers; unapproved origin; expired signature; altered object key; altered signed header; duplicate completion; completion before upload; cross-tenant restore; and restore after retention expiry. Record the expected HTTP class and state transition for each case. A 403 from an intentionally invalid signature test is evidence that the capability boundary held, whereas a 409 from a completion race should map to an idempotent read of the already-final state rather than a second record. Exact status choices belong to the application's contract; consistency matters more than ornament.

The critical Go path can stay provider-neutral by putting signing and object inspection behind narrow interfaces. This sample omits authentication middleware and database mechanics, but it shows the ownership boundary: the server derives the tenant, allocates the key, persists the intent before signing, and completes with a conditional transition.

package uploads

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

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

type ObjectStore interface {
    Stat(ctx context.Context, objectKey string) (ObjectInfo, error)
}

type IntentStore interface {
    Create(ctx context.Context, intent UploadIntent) error
    CompleteOnce(ctx context.Context, intentID, tenantID string, object ObjectInfo) (Snapshot, error)
}

type ObjectInfo struct {
    Size     int64
    Checksum string
}

type UploadIntent struct {
    ID             string
    TenantID       string
    ObjectKey      string
    IdempotencyKey string
    ExpiresAt      time.Time
}

type Snapshot struct {
    ID        string
    TenantID  string
    ObjectKey string
}

type Service struct {
    signer  Signer
    objects ObjectStore
    intents IntentStore
    now     func() time.Time
}

func (s *Service) Begin(ctx context.Context, tenantID, intentID, idemKey, contentType string) (string, map[string]string, error) {
    if tenantID == "" || intentID == "" || idemKey == "" {
        return "", nil, errors.New("missing authorization context")
    }

    expiresAt := s.now().Add(15 * time.Minute)
    objectKey := fmt.Sprintf("tenants/%s/backups/%s", tenantID, intentID)
    intent := UploadIntent{
        ID:             intentID,
        TenantID:       tenantID,
        ObjectKey:      objectKey,
        IdempotencyKey: idemKey,
        ExpiresAt:      expiresAt,
    }
    if err := s.intents.Create(ctx, intent); err != nil {
        return "", nil, err
    }

    return s.signer.SignPut(ctx, objectKey, expiresAt, contentType)
}

func (s *Service) Complete(ctx context.Context, tenantID string, intent UploadIntent) (Snapshot, error) {
    if intent.TenantID != tenantID {
        return Snapshot{}, errors.New("intent is outside tenant boundary")
    }
    object, err := s.objects.Stat(ctx, intent.ObjectKey)
    if err != nil {
        return Snapshot{}, err
    }
    return s.intents.CompleteOnce(ctx, intent.ID, tenantID, object)
}
Enter fullscreen mode Exit fullscreen mode

The 15-minute expiry is an example configuration, not a universal recommendation. Large backups, slow uplinks, and multipart semantics change the required window; measure real upload duration distributions and set the expiry with a documented margin. Your mileage may vary. If the chosen storage API supports multipart or resumable uploads, the intent model must track the provider-neutral upload session and verify final assembly before completion, because a collection of accepted parts is not yet a restorable backup.

CORS tests belong beside the signer contract tests. Generate a request, preserve every signed header, exercise a browser preflight from an allowed origin, then mutate one dimension at a time. A test that changes both the origin and a signed content type cannot tell the team which boundary rejected the request. It's tedious, but ambiguity here becomes an operational tax during every frontend release.

The throughput trade-off in one table

Path Large-file data path Strong reason to choose it Principal cost
Browser direct upload Browser to private object storage; application handles authorization and metadata Keeps backup bytes away from application workers and supports storage-native large-upload mechanisms Requires precise signing, CORS, completion, and orphan reconciliation
Server proxy Browser through application to object storage Allows synchronous inspection or transformation before persistence Consumes application bandwidth and ties transfer lifetime to application capacity
Managed upload gateway Browser through a specialized intake layer Centralizes upload protocol handling for teams that accept another operational dependency Adds a service boundary whose tenancy, audit, and failure contract still require verification

No row wins in isolation. Benchmark with representative backup sizes and constrained client uplinks, then observe application egress, worker saturation, completion latency, abandoned intent count, checksum mismatches, and restore verification results. A throughput test that stops when upload returns success measures intake, not backup reliability.

The restore drill is the proof.

The cloud products most teams evaluate expose different APIs and operational controls, so portability should live in the application's intent, completion, and audit model rather than in an imaginary lowest-common-denominator upload call. AWS S3 and Google Cloud Storage are examples supported by the primary documentation in the references; product selection still depends on region, compliance scope, upload protocol, lifecycle controls, and the team's existing operational competence. This ADR does not rank them.

Why reject the server proxy, and when should you keep it?

For the stated property-backup workload, reject the proxy as the default because large-file throughput is the primary axis and the application gains little from relaying unchanged bytes. It would have to scale network capacity and connection lifetime with every concurrent backup, even though its durable responsibilities are authorization, state transition, audit, and restore policy. Direct upload leaves those responsibilities in the Go service while assigning byte transport to the storage system.

Direct upload is not suitable when policy requires malware scanning, data-loss prevention, format validation, encryption transformation, or redaction before the original may be persisted. Keep a proxy or a dedicated intake tier in that case. A proxy is also reasonable for small bounded files when operational simplicity outweighs transfer efficiency, or when client networks cannot reach the storage endpoint. These are valid constraints, not edge-case embarrassments.

There is a middle design: upload into a private quarantine namespace, scan asynchronously, and promote only accepted objects into the restorable snapshot namespace. That can preserve the direct byte path, but it does not satisfy a rule that forbids even temporary persistence before inspection. Compliance language decides the boundary. The architecture diagram cannot.

The final acceptance test should restore a selected snapshot into an isolated environment, verify its checksum and tenant identity, and record who authorized the exercise. Upload success is provisional; verified restore is the system outcome.

References

Top comments (0)