Dev.to Security πŸ” Cybersecurity πŸ‘ 0 πŸ“– 7 min read

5 Nodejs User Avatar Upload Rules: Private Storage With Presigned URLs

An avatar upload is a short-lived write with a surprisingly long tail. The browser needs permission to send bytes without receiving storage credentials, while the application needs a defensible answer to a harder questio

An avatar upload is a short-lived write with a surprisingly long tail. The browser needs permission to send bytes without receiving storage credentials, while the application needs a defensible answer to a harder question: when is the old object no longer allowed to exist? The design I use starts with that retention deadline, then derives the upload protocol from it.

Short answer: issue a narrowly scoped presigned PUT URL from the application, keep object names opaque, record an upload intent before handing out the URL, and make deletion a durable state transition rather than a best-effort background task. The URL is transport authorization. It is not proof that an avatar is valid, and it is not an audit record.

The example below uses Go because the important part is the boundary between the API and object storage; the same boundary can be implemented by a Node.js service. A successful upload must still be reconciled against the database, and a replacement must have an explicit retention policy for the previous object.

1. What must be true before the first byte moves?

For a user avatar, I would write five invariants before choosing an SDK:

  1. The client never receives a long-lived storage credential.
  2. Each upload has one server-owned object key, unrelated to the original filename.
  3. The authorization is limited by time, method, key, and content constraints.
  4. The database can distinguish requested, uploaded, accepted, superseded, and deleted states.
  5. A deletion request leaves evidence even when the storage operation is retried.

The fifth invariant is the one that changes the architecture. A delete call can time out after the storage service has accepted it. Retrying it should be harmless, and the audit trail should record the intent before the worker attempts the side effect. For a payment or ledger system, I would never call that exactly-once execution; I would call it an exactly-once decision with at-least-once delivery. Avatar deletion deserves the same precision.

The application therefore owns the lifecycle, while object storage owns bytes. A row such as avatar_uploads can contain an opaque key, user identifier, expected media type, byte limit, state, creation time, expiration time, and deletion time. Do not use the object listing as the source of truth. Listings are useful for reconciliation, but they do not explain why an object exists.

2. How should a Nodejs user upload an avatar with expiring storage access?

This pattern is a poor fit when the application cannot maintain durable lifecycle state, or when uploads must be transformed synchronously before they become visible. A server-mediated or queue-based flow may be the better trade-off in those cases, even though it adds latency and bandwidth work.

There are three clocks, and conflating them produces accidental retention.

The first is URL expiry: how long the browser may attempt the upload. The second is the upload-intent expiry: how long an unfinished intent remains eligible for acceptance. The third is the object retention deadline: how long the bytes may remain available after acceptance or replacement. They can have different values because they answer different questions.

For example, an upload URL might be valid for 10 minutes, an uncompleted intent might be abandoned after 24 hours, and a superseded avatar might remain only until a short deletion grace period ends. Those numbers are policy inputs, not universal defaults. A compliance review should decide them with the relevant retention rule, legal hold process, and deletion SLA in view; storage configuration alone cannot establish compliance.

Cache metadata is a fourth concern. Cache-Control governs HTTP caching behavior, not object deletion or authorization. A private avatar response can therefore require conservative cache directives while still having an independent storage lifecycle. The distinction matters: a cache that has already stored a response is not erased merely because the origin object was deleted.

The URL should be minted only after the intent row is committed. Its key and method must match the row. If the client retries, it reuses the same intent rather than receiving a fresh anonymous object. If the intent has expired, the API creates a new one and records the reason.

Here is the shape of that decision in Go. The storage interface deliberately hides provider-specific signing code.

package upload

import (
    "context"
    "crypto/rand"
    "encoding/hex"
    "fmt"
    "time"
)

type Intent struct {
    ID          string
    ObjectKey   string
    ContentType string
    MaxBytes    int64
    ExpiresAt   time.Time
}

type Signer interface {
    PresignPut(ctx context.Context, key, contentType string, maxBytes int64, until time.Time) (string, error)
}

func NewIntent(ctx context.Context, s Signer, userID, contentType string, maxBytes int64, now time.Time) (Intent, string, error) {
    if userID == "" || contentType == "" || maxBytes <= 0 {
        return Intent{}, "", fmt.Errorf("invalid upload request")
    }

    var raw [16]byte
    if _, err := rand.Read(raw[:]); err != nil {
        return Intent{}, "", fmt.Errorf("create object id: %w", err)
    }
    intent := Intent{
        ID:          hex.EncodeToString(raw[:]),
        ObjectKey:   "avatars/" + hex.EncodeToString(raw[:]),
        ContentType: contentType,
        MaxBytes:    maxBytes,
        ExpiresAt:   now.Add(10 * time.Minute),
    }
    // Persist intent and its audit event here, in one database transaction.
    url, err := s.PresignPut(ctx, intent.ObjectKey, intent.ContentType, intent.MaxBytes, intent.ExpiresAt)
    if err != nil {
        return Intent{}, "", fmt.Errorf("sign upload: %w", err)
    }
    return intent, url, nil
}

The maxBytes argument is a policy boundary, not validation by itself. After upload, the service should inspect the stored object's size and content characteristics before changing the intent to accepted. A client-controlled filename, MIME declaration, or success callback is not sufficient evidence.

3. How do you make replacement and deletion auditable?

Deletion is a policy event.

An avatar replacement is a small saga: create the new intent, upload it, validate it, publish the new reference, then retire the old reference. Each transition should be idempotent by intent ID. A repeated complete request returns the existing result; it does not create a second avatar record. A repeated delete request records no contradictory state and is safe to retry.

The transaction boundary is important. Marking the old avatar deleted before the new one is accepted can leave a user without an avatar. Publishing the new reference before validation can expose an unacceptable file. The database should make the accepted reference explicit, and a worker should enqueue removal of the superseded key from an outbox event in the same transaction that changes that reference.

An outbox is not overengineering here. It turns a network call into a replayable consequence of a committed decision. The worker can use a stable idempotency key such as delete:{object-key} when the storage API supports one; otherwise, it can treat a not-found result as a successful terminal state and preserve the attempt, response class, and timestamp in the audit log. The exact provider response is less important than making the interpretation deterministic.

Keep audit records free of the signed URL. URLs are bearer capabilities and may contain sensitive query parameters. Store the intent ID, object key, actor, policy version, state transition, and correlation ID instead. Access logs and application logs should apply the same rule. A URL copied into a debug log can outlive the ten-minute policy that was supposed to protect it.

The deletion worker also needs a reconciliation job. It compares database-owned keys with a constrained storage inventory and reports objects that have no valid owner, intents that passed their deadline, and deletion events that have not reached a terminal result. The job should produce findings, not silently delete every unfamiliar key; legal holds, migrations, and an interrupted import are reasons to require review.

4. What does the client need to know about failure?

The URL is expendable.

The browser needs a small protocol, not a storage API manual. The application returns an intent identifier, a presigned upload URL, the required content type, and the expiration timestamp. The browser uploads directly, then calls one completion endpoint. There is no need to expose object listing or download credentials.

Failures need distinct meanings. A rejected content type is a policy failure. An expired URL is a retryable workflow failure that requires a new intent. A timeout after sending the request is ambiguous: the client should ask the application for intent status rather than blindly create another object. A completion request that arrives twice should be harmless.

The server should also verify the authenticated user at every state transition. Possessing an upload URL authorizes one constrained write; it does not authorize changing another user's avatar record. This separation is easy to lose when a frontend treats the signed URL as the whole workflow.

For observability, measure intent age, acceptance rate, validation rejection rate, orphan count, deletion latency, and the number of retries per deletion event. Avoid treating a high upload success rate as proof of correctness. A system can accept every upload and still retain objects after their policy deadline.

5. A compact rollout decision

Start with one upload intent table, one outbox, and one reconciliation report. Test the transitions with duplicate completion calls, duplicate deletion events, a timeout after a successful storage write, a client that never uploads, and a replacement submitted while the first one is still pending. Include clock skew in the tests; expiry logic that is correct on one machine can be surprising across services.

During rollout, make the reconciliation report observable before enabling automatic deletion. Compare its findings with known test objects, migrations, and legal holds. Then enable deletion for only the state transitions whose ownership is unambiguous, retaining a reversible review path where policy permits one.

The decision rule is straightforward: if the team cannot answer who owns an object, why it exists, which retention policy applies, and which event authorizes its deletion, the upload flow is incomplete. A presigned URL solves a narrow transport problem. Lifecycle state, idempotent decisions, and an audit trail solve the operational problem around it.

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.