Dev.to Security ๐Ÿ” Cybersecurity ๐Ÿ‘ 0 ๐Ÿ“– 6 min read

Private Browser Avatar Uploads: 5 Object Storage Preflight Controls

Store private uploads under opaque keys, keep the browser on a short-lived path, and make deletion a state you can prove. For a patient portal serving US and EU users, the deciding constraint is retention. A failed CORS

Store private uploads under opaque keys, keep the browser on a short-lived path, and make deletion a state you can prove. For a patient portal serving US and EU users, the deciding constraint is retention. A failed CORS preflight must never be mistaken for a storage failure.

TL;DR: a presigned PUT authorizes one upload request; it does not configure browser CORS, validate file contents, impose retention, or prove deletion. Treat those as separate controls. Issue a narrow upload grant, allow only the exact portal origins and request headers, record lifecycle metadata, and expose downloads through a fresh expiring URL only after validation.

1. Why can a direct browser avatar upload fail object storage preflight?

A browser may send an OPTIONS preflight before the PUT. That preflight asks whether the target origin permits the page origin, method, and requested headers. The signature on the later request does not answer those browser questions. If the storage CORS policy omits PUT, rejects the portal origin, or does not allow a header such as content-type, the browser stops there. Zero file bytes reach the object write.

This split is easy to miss because the console often puts both failures under the broad CORS label. Diagnose it in order: inspect the OPTIONS request, compare its Origin, Access-Control-Request-Method, and Access-Control-Request-Headers values with the response, and only then inspect the signed PUT. Don't add wildcard origins as a reflex. A private health portal normally knows its production US and EU web origins, so list those exact origins and keep local development separate.

Two policy engines are involved. CORS tells the browser which cross-origin response it may expose. The presigned request tells object storage what operation was authorized. Passing one proves nothing about the other.

Three parties. Two policies. One misleading console error.

2. Bind one upload grant to one intended object

The application server should choose the object key. Use an opaque upload ID rather than a patient name, email address, or original filename. Record the owner, purpose, creation time, retention deadline, and state before returning the upload grant. OWASP also recommends allowlisting extensions, validating the actual file type rather than trusting Content-Type, changing filenames, setting size limits, and allowing only authorized uploaders.

Keep the signed request narrow: one key, one method, a short expiry, and the headers the browser will really send. Header drift is a nasty trap. If content-type participates in signing, the client must send the matching value; if the browser asks permission to send that header, CORS must allow it too. More config hides the mismatch. It doesn't fix it.

Here is the smallest boundary I would want in an SDK. The signer and database are injected because their implementations are deployment choices, not domain logic.

type UploadState = "pending" | "available" | "deleting" | "deleted";

type UploadRecord = {
  id: string;
  ownerId: string;
  objectKey: string;
  deleteAfter: string;
  state: UploadState;
};

interface UploadStore {
  create(record: UploadRecord): Promise<void>;
}

interface ObjectSigner {
  signPut(input: {
    key: string;
    contentType: string;
    expiresInSeconds: number;
  }): Promise<string>;
}

export async function createAvatarGrant(
  ownerId: string,
  contentType: "image/jpeg" | "image/png",
  objectKey: string,
  deleteAfter: Date,
  store: UploadStore,
  signer: ObjectSigner,
) {
  const uploadId = crypto.randomUUID();
  const expiresInSeconds = 300;

  await store.create({
    id: uploadId,
    ownerId,
    objectKey,
    deleteAfter: deleteAfter.toISOString(),
    state: "pending",
  });

  return {
    uploadId,
    putUrl: await signer.signPut({ key: objectKey, contentType, expiresInSeconds }),
    headers: { "content-type": contentType },
  };
}

Five minutes is an example policy choice, not a universal safe value. Benchmark completion time on the networks users actually have, then choose an expiry that covers the slow tail without leaving reusable authority around longer than needed. I care about time-to-first-call, but one extra server call is cheap compared with an upload capability that is vague about scope.

That 300-second grant is measurable. Record how often a grant expires before completion, split the result by region and connection class, and adjust from evidence rather than habit.

3. Make the browser request boring

The browser should use the method and headers returned by the grant endpoint exactly. Avoid opportunistic custom headers. Every added non-simple header expands the preflight contract and often the signature contract.

type BrowserUploadGrant = {
  uploadId: string;
  putUrl: string;
  headers: { "content-type": string };
};

export async function uploadAvatar(file: File, grant: BrowserUploadGrant) {
  const response = await fetch(grant.putUrl, {
    method: "PUT",
    headers: grant.headers,
    body: file,
  });

  if (!response.ok) {
    throw new Error(`Avatar upload failed with status ${response.status}`);
  }

  return grant.uploadId;
}

This function deliberately does not return a permanent object URL. After upload, the service should verify the stored object, run its file-safety checks, and move the record to available. A download request can then authorize the current user and mint a new expiring read URL. Public storage and guessable paths are the wrong abstraction for private profile data.

Cache behavior needs an explicit decision. MDN documents that no-store tells caches not to store a response, while private permits storage only in a private cache. Set the chosen directive at the response layer and test it; an expiring URL alone does not define cache handling.

4. Treat deletion as a workflow, not a button

Deleting the database row first destroys the map to the object you still need to remove. Mark the record deleting, reject new download grants, delete the object, verify the expected result, and then mark the record deleted. Keep only the audit data the applicable policy and legal basis require.

Races matter. A validation worker may finish just as deletion starts; an old download URL may remain usable until its expiry; retries may deliver the same delete job twice. State transitions should be conditional, deletion should be idempotent, and read URLs should be short-lived enough that the revocation delay is understood.

At scale, I would add a periodic reconciler that compares overdue application records with storage state, plus metrics for pending age, validation age, deletion lag, and failed preflight count by allowed origin. Log upload IDs and opaque keys, not patient filenames or signed URLs. Signed URLs are credentials. Redact them.

Test retention with a clock you control: before the deadline, exactly at it, after repeated delete delivery, and while validation is in flight. Run browser tests from both configured portal origins. A server-side HTTP client doesn't enforce browser CORS, so it cannot prove preflight works.

5. Choose the boundary with the fewest hidden policies

Direct upload keeps file bytes away from the application server and can reduce a bandwidth bottleneck, but it creates a three-party contract among browser, signer, and storage. A proxied upload centralizes validation and avoids storage CORS in the browser path, at the cost of moving every byte through the service. Neither is automatically safer. The better boundary is the one a team can test, observe, and delete through on schedule.

Direct upload has real limitations. It is unsuitable when policy requires synchronous inspection before any untrusted byte reaches persistent storage, when clients cannot reliably perform the signed request, or when the team cannot operate CORS and post-upload reconciliation. In those cases, choose an application proxy and accept its capacity and streaming burden. The reverse trade-off applies when large files would make that proxy an expensive choke point and asynchronous quarantine is permitted.

No magic boundary exists.

Question Direct browser upload Application proxy
Where do bytes travel? Browser to object storage Browser through application service
Early validation Limited client checks; authoritative checks after write Application can inspect during intake
Browser CORS surface Portal origin plus storage origin Usually the portal API origin only
Deletion responsibility Metadata plus object deletion workflow The same; proxying does not solve retention
Main DX cost Aligning CORS, signed headers, and client request Operating upload capacity and streaming correctly

The acceptance test is concrete: from each real portal origin, a permitted image uploads with the exact granted headers; a foreign origin and an unapproved header fail; the object cannot be downloaded without fresh authorization; and an overdue record converges to deleted under retry. Benchmark those paths. Count configuration fields too. A system that needs twelve loosely documented toggles for one upload deserves suspicion.

Do not ship a private upload flow until deletion has an observable terminal state. A green PUT is only the beginning.

References

๐Ÿ“ฐ 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.