Dev.to Security 🔐 Cybersecurity 👁 0 📖 9 min read

Best Practices for Implementing Presigned URLs in Browser Uploads — Retention and Deletion

The difficult part of a browser-to-object-storage upload is not moving bytes. It is deciding how a temporary authorization becomes an auditable record, and how that record survives long enough to prove deletion when a le

The difficult part of a browser-to-object-storage upload is not moving bytes. It is deciding how a temporary authorization becomes an auditable record, and how that record survives long enough to prove deletion when a learner asks for an old generated report to disappear.

TL;DR: issue a narrowly scoped, short-lived upload authorization from an authenticated backend; bind it to an immutable report identifier and expected content constraints; let the browser upload directly; then make the backend the source of truth for completion, retention, and deletion. Object storage is the byte store, not the workflow database.

A report for a student may contain assessment results, accommodations, or teacher comments. In an edtech system, the report is therefore a business record with a lifecycle, even when its physical representation is a PDF in a bucket. Presigned URLs help with transport. They do not decide who may request the report, whether a retry is safe, or whether every copy has gone away.

The browser is not the system of record.

That boundary matters.

How should we implement presigned URLs for browser uploads?

A useful model has three records: an upload intent, an object, and a deletion obligation. The intent is created only after the caller is authenticated and authorized to access the course or learner. It contains an opaque report ID, tenant ID, object key, expected media type, maximum size, creation time, and expiration. The object is the storage representation. The deletion obligation says when the object must be removed and what evidence the service must retain after removal.

That separation prevents a common mistake: treating a successful PUT as proof that a report is ready. A browser can receive a valid authorization and never use it. A network can fail after storage accepts the bytes but before the browser receives the response. A client can retry with a different payload if the authorization is broader than the report intent. The backend must reconcile these states rather than infer business completion from an HTTP response that it did not observe.

In payment systems, I learned to distrust a single success signal. The same discipline applies here. Give the intent an idempotency key, persist it before issuing authorization, and allow one report ID to reach one terminal upload state. At-least-once delivery is normal; duplicate business records are optional.

Retention is a policy decision, not a bucket default. A report may be retained for a defined period after generation, while access logs and a deletion receipt may need a different retention treatment. GDPR Article 17 describes a right to erasure, but it also describes exceptions; the application still needs a documented rule for which data is erased, which evidence is retained, and why. Legal review supplies the policy. The storage workflow enforces it.

The authorization should carry less power than the user

The authenticated user may be able to view a report in the application, but that does not mean the browser should receive a credential capable of listing a bucket, overwriting arbitrary keys, or reading neighboring tenants' data. A presigned request should be a capability for one operation on one unpredictable object key, with a narrow lifetime and explicit constraints.

The key should be generated server-side from an internal report ID, not accepted as an arbitrary path from the browser. Tenant separation belongs in the authorization decision and in the key namespace; it should not depend on a client-supplied prefix. The URL should be returned over an authenticated TLS connection, and it should be treated as a bearer capability: anyone who obtains it may be able to use it until it expires or the storage service rejects the request. Never put it in application logs, analytics events, or exception messages.

A practical request flow is:

  1. The browser sends a report ID and an idempotency key to the application API.
  2. The API checks identity, tenant membership, report state, and retention policy, then stores an upload intent.
  3. The API signs one upload request for the server-generated key and returns its expiration and expected constraints.
  4. The browser uploads directly and reports the result; the API verifies object metadata or a checksum before marking the report available.
  5. A worker applies the retention deadline and records deletion attempts, outcomes, and operator-visible evidence.

The storage service may enforce content length, content type, checksum, and required headers in different ways. That difference matters. An HTTP header shown in a browser form is not automatically a trustworthy declaration of what was uploaded; verify the stored object's metadata and, where supported, its checksum. A content type is useful for routing and display, but it is not malware detection. Generated PDFs still need a validation path appropriate to the threat model.

What should the backend record before the browser starts?

The minimum useful row is more specific than report_id and object_key:

Field Purpose
intent_id Stable identifier for retries and audit lookup
tenant_id, subject_id Authorization and erasure scope
object_key Server-generated, opaque storage location
expected_bytes, expected_type, checksum Completion validation
issued_at, expires_at Capability lifetime
state issued, uploaded, available, expired, or deleting
retain_until Application retention deadline
deleted_at, deletion_receipt Evidence of the terminal operation

Do not store the presigned URL as a durable secret. Store the intent and the authorization metadata needed to explain it; regenerate a URL for an unexpired, still-authorized intent when the client needs a retry. The exact signature format is an implementation detail of the storage protocol. The state transition is the durable contract.

Here is a deliberately generic Go shape for an idempotent intent handler. It does not sign a provider-specific request; that boundary belongs behind Signer, where its constraints can be tested independently.

type UploadIntent struct {
\tID           string
\tTenantID     string
\tReportID     string
\tObjectKey    string
\tExpectedType string
\tExpectedSize int64
\tExpiresAt    time.Time
\tState        string
}

type Signer interface {
\tPutURL(ctx context.Context, key, contentType string, size int64, expires time.Duration) (string, error)
}

func CreateIntent(ctx context.Context, repo Repository, signer Signer, tenantID, reportID, idem string) (UploadIntent, string, error) {
\tif existing, ok := repo.IntentByKey(ctx, tenantID, idem); ok {
\t\tif existing.State == "issued" && time.Now().Before(existing.ExpiresAt) {
\t\t\turl, err := signer.PutURL(ctx, existing.ObjectKey, existing.ExpectedType, existing.ExpectedSize, time.Until(existing.ExpiresAt))
\t\t\treturn existing, url, err
\t\t}
\t\treturn existing, "", nil
\t}

\tintent := UploadIntent{
\t\tID:           NewID(),
\t\tTenantID:     tenantID,
\t\tReportID:     reportID,
\t\tObjectKey:    "reports/" + NewID() + ".pdf",
\t\tExpectedType: "application/pdf",
\t\tExpectedSize: 10 << 20,
\t\tExpiresAt:    time.Now().Add(10 * time.Minute),
\t\tState:        "issued",
\t}
\tif err := repo.InsertIntent(ctx, idem, intent); err != nil {
\t\treturn UploadIntent{}, "", err
\t}
\turl, err := signer.PutURL(ctx, intent.ObjectKey, intent.ExpectedType, intent.ExpectedSize, 10*time.Minute)
\treturn intent, url, err
}

The transaction boundary deserves attention. If the database insert commits and URL signing fails, the intent can be retried. If signing succeeds but the response is lost, the same idempotency key can return a fresh capability for the same object, subject to authorization and expiration. That is a much cleaner recovery story than creating a second report object on every browser retry.

Which failure modes deserve explicit tests?

The happy path is short. The test matrix is not. Test an expired URL, a reused URL with a different object key, an oversized object, a wrong content type, a checksum mismatch, a browser retry after an accepted upload, and a duplicate completion callback. Test a user whose course membership was revoked between intent creation and upload completion. Test deletion racing with a late completion message.

The hardest case is the ambiguous write: storage may have accepted the object while the client sees a timeout. The completion endpoint should be idempotent and should inspect the expected key, size, type, and checksum before advancing state. That check is deliberately boring: load the intent, confirm that the caller still has authority, read the object metadata, compare the immutable values, and perform one conditional state transition. If verification cannot establish that the object matches the intent, quarantine or delete it according to policy; do not make it visible because the filename looks right. This is also where a retention worker needs a clear rule: an unverified object is not an available report, but it is still an object that must be accounted for before deletion.

Observe the workflow with correlation IDs, intent IDs, tenant IDs where policy permits, and object keys only in controlled audit records. Metrics should distinguish authorization issuance, upload verification, expiry, deletion success, deletion retry, and orphan cleanup. A single upload_failed counter hides the difference between a bad client payload and a storage outage.

Also test the clock. Signature expiration and retention deadlines depend on time from different systems. Keep clocks synchronized, use server-side timestamps for policy, and make the expiration margin visible in tests. Ten minutes is an example policy value, not a universal security boundary.

How do storage choices affect the contract?

The important comparison is capability semantics, not a leaderboard. Amazon S3 presigned URLs, Azure SAS, and Google Cloud Storage signed URLs all provide time-limited authorization mechanisms, but their signing inputs, header constraints, revocation behavior, and policy surfaces differ. A team that hides those differences behind a small interface can keep application code focused on report lifecycle while still testing the provider adapter against its official documentation.

The trade-off is portability. A lowest-common-denominator interface may omit useful checksum enforcement or policy conditions. A provider-specific interface may enforce stronger guarantees but make migration and local testing harder. Keep the domain contract generic and expose provider capabilities as explicit validation results; do not silently pretend that every backend enforces the same constraint.

A provider comparison should answer concrete questions: Can the authorization be limited to one key and one method? Can the service constrain size or checksum? Is revocation immediate, or does it require denying the underlying identity or changing the object? Which audit events are available? What happens to incomplete multipart uploads? These answers belong in an ADR and in integration tests, not in a marketing table.

Roll out the lifecycle before increasing upload volume

Start with one report type and a small retention policy. Persist intents, verify completion, and run a dry-run deletion worker that only reports candidates. Compare its candidate set with application records, then enable deletion for objects whose policy and ownership are unambiguous. Keep an orphan inventory: an object without a current intent is an operational fact that requires triage, not an invitation to delete blindly.

During rollout, make the state machine observable to support staff. A customer-facing “report unavailable” message is less useful than an internal explanation that distinguishes expired from uploaded-but-unverified. Keep the browser contract stable while iterating on the signer adapter, because frontend retries should not decide backend retention semantics.

The final decision rule is straightforward: use direct browser upload when the backend can issue a narrowly scoped capability and later verify the exact object against a durable intent. Add a proxy or a quarantine step when the required validation, inspection, or deletion evidence cannot be established at the storage boundary. The URL is temporary; the lifecycle record is what makes the system accountable.

Sources

📰 Read the original article on Dev.to Security

Originally published by Dev.to Security. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.