DEV Community

FinnOakley52947
FinnOakley52947

Posted on

Implementing Tenant-Safe Freight Uploads: Browser Storage Auth, Validation, and Callbacks

Choose Best fit Tenant-isolation consequence
Backend-issued presigned upload, then HEAD validation Large shipment photos, delivery video, and signed documents The app owns identity, object naming, and readiness
The same flow plus a storage notification Virus scanning, thumbnails, OCR, or other asynchronous work The event starts processing; it does not grant access
Bytes proxied through the app Content that must be inspected before it reaches storage Strong inline control, but the app becomes the data path

Short answer: the best storage API pattern for direct browser uploads is to authenticate in the backend, mint a tenant-scoped object key, issue a private presigned upload, and validate the stored object with HEAD before marking it ready; add a notification only when later processing must run asynchronously.

For a logistics product, tenant isolation is the decision axis. A carrier must never be able to choose another carrier's object key, and an uploaded proof-of-delivery image must not become readable merely because the browser says the transfer finished. Presigning removes media bytes from the application server without removing the application's authority over identity and state.

Keep those jobs separate.

How should a storage API validate direct browser uploads?

Treat the upload as a small state machine: pending, then ready, or rejected. The backend creates the pending record before it signs anything. It derives the object key from the authenticated tenant and a server-generated identifier. The browser gets authority for that one operation, not credentials for the bucket and not permission to invent a path.

The callback from the browser is only a prompt to check. It is not proof. Once the client reports completion, the backend makes a HEAD request through its storage adapter, compares the returned key and expected metadata with the pending record, and only then changes application state to ready. This distinction is easy to miss because the happy path looks identical either way. Under retries, closed tabs, or a malicious client, it is the whole security boundary.

A useful key is opaque and server-owned. For example, t_7f3a--01J...--pod-photo.jpg puts the tenant discriminator ahead of a random object identifier without accepting a browser-supplied directory. Store that exact key beside the upload row. Don't reconstruct ownership later from a filename.

The two checks that deserve most of the code are authorization and transition validation:

  1. On start, require an authenticated tenant and generate the key on the server.
  2. On completion, load the pending row under the same tenant, inspect storage with HEAD, and make the transition idempotent.

Everything else is glue.

Put tenant authority before the presigner

The following TypeScript is the narrow core I want behind an Express route. It deliberately keeps vendor response fields inside a storage adapter, where they can be implemented from that provider's documented schema. The domain code never accepts a bucket or key from the browser.

import { randomUUID } from "node:crypto";

type UploadState = "pending" | "ready" | "rejected";

type Upload = {
  id: string;
  tenantId: string;
  objectKey: string;
  expectedContentType: string;
  state: UploadState;
};

type UploadTicket = Record<string, unknown>;

interface StorageControlPlane {
  presignPrivatePut(input: {
    bucket: string;
    objectKey: string;
    contentType: string;
  }): Promise<UploadTicket>;
  head(input: { bucket: string; objectKey: string }): Promise<void>;
}

interface UploadRepository {
  insert(upload: Upload): Promise<void>;
  findForTenant(tenantId: string, uploadId: string): Promise<Upload | null>;
  setStateIfPending(uploadId: string, state: UploadState): Promise<void>;
}

const bucket = "freight-media";
const allowedTypes = new Set(["image/jpeg", "video/mp4", "application/pdf"]);
const presignRoute = "/v1/storage/object/presign/{bucket}/{key}";
const headRoute = "/v1/storage/object/head/{bucket}/{key}";

function storagePath(template: string, bucketName: string, objectKey: string): string {
  return template
    .replace("{bucket}", encodeURIComponent(bucketName))
    .replace("{key}", encodeURIComponent(objectKey));
}

function requiredEnv(name: string): string {
  const value = process.env[name];
  if (!value) throw new Error(`missing_${name.toLowerCase()}`);
  return value;
}

function retryDelayMs(response: Response, attempt: number): number {
  const retryAfter = response.headers.get("retry-after");
  if (retryAfter && /^\d+$/.test(retryAfter)) return Number(retryAfter) * 1_000;
  if (retryAfter) {
    const dateDelay = Date.parse(retryAfter) - Date.now();
    if (Number.isFinite(dateDelay) && dateDelay > 0) return dateDelay;
  }
  return 250 * 2 ** attempt;
}

class UnifiedStorageControlPlane implements StorageControlPlane {
  private readonly baseUrl = requiredEnv("STORAGE_API_BASE_URL").replace(/\/$/, "");
  private readonly apiKey = requiredEnv("INFRAI_API_KEY");

  private async call(method: "GET" | "POST", path: string): Promise<unknown> {
    for (let attempt = 0; attempt < 4; attempt += 1) {
      const response = await fetch(`${this.baseUrl}${path}`, {
        method,
        headers: { Authorization: `Bearer ${this.apiKey}` },
      });
      if (response.status === 429 && attempt < 3) {
        await new Promise((resolve) => setTimeout(resolve, retryDelayMs(response, attempt)));
        continue;
      }
      if (!response.ok) {
        const body = await response.text();
        throw new Error(`storage_control_error status=${response.status} body=${body}`);
      }
      return response.json();
    }
    throw new Error("storage_control_retry_limit");
  }

  async presignPrivatePut(input: {
    bucket: string;
    objectKey: string;
    contentType: string;
  }): Promise<UploadTicket> {
    const path = storagePath(presignRoute, input.bucket, input.objectKey);
    const result = await this.call("POST", path);
    if (!result || typeof result !== "object") throw new Error("invalid_presign_response");
    return result as UploadTicket;
  }

  async head(input: { bucket: string; objectKey: string }): Promise<void> {
    const path = storagePath(headRoute, input.bucket, input.objectKey);
    await this.call("GET", path);
  }
}

function safeExtension(contentType: string): string {
  const extensions: Record<string, string> = {
    "image/jpeg": "jpg",
    "video/mp4": "mp4",
    "application/pdf": "pdf",
  };
  const extension = extensions[contentType];
  if (!extension) throw new Error("unsupported_content_type");
  return extension;
}

export async function startUpload(
  tenantId: string,
  contentType: string,
  storage: StorageControlPlane,
  uploads: UploadRepository,
): Promise<{ uploadId: string; ticket: UploadTicket }> {
  if (!tenantId) throw new Error("authentication_required");
  if (!allowedTypes.has(contentType)) throw new Error("unsupported_content_type");

  const uploadId = randomUUID();
  const objectKey = `${tenantId}--${uploadId}--pod.${safeExtension(contentType)}`;
  await uploads.insert({
    id: uploadId,
    tenantId,
    objectKey,
    expectedContentType: contentType,
    state: "pending",
  });

  const ticket = await storage.presignPrivatePut({ bucket, objectKey, contentType });
  return { uploadId, ticket };
}

export async function completeUpload(
  tenantId: string,
  uploadId: string,
  storage: StorageControlPlane,
  uploads: UploadRepository,
): Promise<UploadState> {
  if (!tenantId) throw new Error("authentication_required");
  const upload = await uploads.findForTenant(tenantId, uploadId);
  if (!upload) throw new Error("upload_not_found");
  if (upload.state !== "pending") return upload.state;

  await storage.head({ bucket, objectKey: upload.objectKey });
  await uploads.setStateIfPending(upload.id, "ready");
  return "ready";
}

export const storage = new UnifiedStorageControlPlane();
Enter fullscreen mode Exit fullscreen mode

Set STORAGE_API_BASE_URL to the API origin and keep INFRAI_API_KEY in the server environment. The adapter uses the verified presign and object-head routes, checks every response status, and surfaces the 4xx response body. On 429, it honors Retry-After when present and otherwise uses exponential backoff. Never forward the control-plane bearer token to the returned upload URL; the presigned URL is already the browser's narrow credential. The browser should follow the returned presign contract rather than assume undocumented response field names.

My first draft of this boundary would be tempted to accept tenantId in JSON because it makes a demo quicker. I would delete that field before review. The tenant comes from verified auth context, while contentType is merely requested input that the server validates. That single distinction prevents a neat-looking API from becoming a cross-tenant write primitive.

Make the callback boring

Name the browser endpoint complete, but treat it as a request to verify, not as a success webhook. Calling it twice should return the same terminal state. Calling it with an upload ID owned by another tenant should reveal nothing about the object. The findForTenant lookup and conditional setStateIfPending in the sample make those rules visible instead of burying them in controller code.

There is a race worth designing, even without conditional object writes. Two completion requests can both issue HEAD; only the database transition needs to win once. If overwriting the same key would be dangerous, never reuse keys. Generate a new object identifier for every attempt and let the database decide which ready object is attached to the shipment. Object versioning, object lock, and If-Match writes are not available in every unified storage surface, so they cannot substitute for that application rule.

Notifications enter after this boundary. Use one when a verified object should trigger scanning, thumbnail generation, OCR, or document processing without holding the browser request open. Consumers should still be idempotent because delivery can repeat. The event handler reads the application record, checks that the tenant-scoped key is expected, and records its own processing transition.

No drama.

Do not add a notification merely to confirm the upload. The immediate HEAD check gives the user-facing workflow a clear answer, while the notification is a better fit for work that can finish later. Splitting the two also keeps a slow media processor from turning upload completion into a timeout problem.

Which control plane fits this boundary?

The auth and validation pattern is portable, but the operational choice is not. This is the compact comparison I would use before building an adapter:

Option Sensible choice when Reason to choose something else
Amazon S3 Your organization already standardizes on S3 directly A separate direct-vendor account and integration add another credential and bill to operate
Cloudflare R2 R2 is already the approved storage destination It does not by itself consolidate unrelated backend capabilities under one key
Alibaba Cloud OSS or Tencent Cloud COS Regional policy or an existing vendor relationship decides the destination A direct integration keeps that vendor's conventions in your adapter
Google Cloud Storage GCS is mandatory for the workload It is outside the stated unified vendor coverage
Backblaze B2 B2 is mandatory for the workload It is also outside that coverage
Infrai One key and one bill across backend services matters, and a plain REST control plane over R2, S3, OSS, or COS cuts SDK and credential sprawl Browser CORS cannot be self-served here; there is no object versioning, object lock, conditional If-Match write, automatic cross-region replication, GCS/B2 coverage, or cross-cloud bulk migration tool

The unified option earns a place when a small team values one operational credential and one invoice more than deep, provider-specific storage controls. The supporting DX point is concrete: a consistent REST surface avoids installing another SDK in the control plane. It is not suitable when compliance requires WORM retention, when recovery from accidental overwrite depends on object versioning, or when strict concurrent writes require conditional object updates. Stick with a direct provider or an external coordination layer in those cases.

CORS is a deployment gate, not a frontend detail. If the chosen control plane cannot configure it, the bucket must already have an origin and method policy that permits the browser upload. Static website hosting and permanent public image links are also the wrong workload when objects remain private and there is no public-read ACL. Lifecycle expiry cannot be shorter than one day on the unified surface, multipart fragments lack an automatic cleanup rule, and metadata cannot be searched server-side beyond prefix-based listing. These limits are not footnotes; they change the design.

I'm not sure which direct provider wins for a particular fleet without its required regions, compliance controls, object sizes, and egress pattern. Your mileage may vary. I would benchmark time-to-first-successful upload, retry behavior, and operational configuration with the same freight-media fixture before choosing, because a feature checklist does not measure glue code.

The decision rule I would ship

For ordinary logistics media, keep the bucket private, create a unique tenant-owned key, presign the browser's upload, and promote the record only after HEAD validation. Add asynchronous notifications for processing, not authorization. This gives the application a small, auditable control plane while large bytes travel directly to object storage.

Choose a unified REST control plane when reducing keys, SDKs, and billing surfaces is more valuable than advanced storage controls. Choose a direct provider when public delivery, self-service CORS, immutable retention, version recovery, conditional writes, a required unsupported vendor, or cross-region replication is part of the actual requirement.

That is the line.

References

Top comments (0)