DEV Community

KellanRhodes1542
KellanRhodes1542

Posted on

Classroom Tenant Boundaries for Direct Browser Uploads into Object Storage

TL;DR: let the browser send lesson media straight to private object storage, but never let it choose the tenant, final object key, or authorization scope. The application should authenticate the teacher, allocate an upload record, and issue a narrowly scoped presigned operation. A worker can derive thumbnails only after the application has verified completion. CORS permits a browser request; it does not isolate tenants.

Choice App handles media bytes? Isolation boundary Best fit Main liability
App-server proxy Yes App request and server credentials Small files or mandatory inline inspection Ties uploads to app capacity
Presigned single request No Server-issued object key and upload record Predictable, modest media Retry restarts the object
Presigned multipart No Upload ID, server-issued key, and signed parts Large lesson videos and unreliable networks More state and cleanup work

Recommendation: use direct, multipart ingestion for large classroom media, with an application-owned upload ledger as the authority. Keep the bucket private. Derive thumbnails asynchronously into a separate keyspace. The runner-up, an app-server proxy, is better when bytes must be inspected before they can enter storage or the files are too small to justify multipart coordination.

This is the revenue-per-hour choice I would make for a one-person SaaS. Shipping weekly means keeping bulk transfer off the application fleet, while refusing to outsource tenant identity to a browser field.

Why can a direct browser thumbnail upload fail against object storage?

A presigned operation answers a narrow question: may this request perform this storage action before the signature expires? It does not prove that the current browser belongs to the tenant embedded in an object key. It does not make a private object public. It does not tell a thumbnail worker which course owns the result.

CORS answers a different question. The browser checks whether an origin, method, and requested headers are allowed by the storage service's CORS response. A signature can be valid while the browser blocks the response because the CORS policy does not admit that request shape. The inverse is dangerous to misunderstand: a permissive CORS response is not authorization.

That split produces a common debugging trap. A request works in a server-side client, then fails in the browser. The storage credentials and key may be fine; the browser has added an Origin header and may send a preflight before the upload. Changing bucket visibility does not repair that policy mismatch. It changes the security model.

Keep the three checks separate:

  1. The application decides who may create an upload and which tenant owns it.
  2. The storage signature constrains the permitted operation.
  3. CORS admits only the browser origins, methods, and headers the UI actually uses.

Short list. Big boundary.

No shortcut there.

The two criteria that decide the design

Tenant isolation comes first. Never accept a complete object key such as tenant-a/courses/biology/video.mp4 from the client and sign it as received. The server should derive the tenant from the authenticated session, generate an opaque upload ID, and construct the key itself. The browser may supply display metadata such as a filename, but that filename does not belong in an authorization decision.

The upload record should connect four things: authenticated tenant, generated storage key, expected media constraints, and lifecycle state. A completion request must look up that record under the current tenant. Knowing another tenant's upload ID should buy nothing. Thumbnail output follows the same rule: its key is derived from the trusted record, not from a callback payload or a browser-selected prefix.

The second criterion is failure recovery. Large classroom recordings meet interrupted Wi-Fi, closed laptops, and expired signatures. A single-request upload makes the client repeat the whole object after a lost connection. Multipart upload divides an object into independently uploaded parts; after initiation, the client uploads parts and completes the upload by identifying them. The storage service then assembles the object. Incomplete multipart uploads need an explicit abort or lifecycle cleanup policy because uploaded parts remain until completion or abortion.

This extra state is justified for large media. It is overhead for a small avatar. I would keep both paths behind one application-level upload contract and select the transport from a server policy, not a client preference.

The trade-off is explicit: direct multipart upload removes media bytes from the application request path, but the application now has to coordinate initiation, part signing, completion, abandonment, and processing state. Imagine a teacher who starts an upload in one course tab, switches to another tenant context, and later resumes the first transfer. The browser still possesses signed operations, yet the completion call must be authorized against the tenant stored with the original upload record. CORS cannot settle that question. Neither can the filename. The ledger can, because it binds the generated key and multipart ID to the tenant established at initiation. That same record gives an operator one place to diagnose a stalled transfer without exposing a signed URL in logs.

A minimal tenant-bound TypeScript contract

The useful abstraction is not getPresignedUrl(key). That function invites arbitrary keys. Model intent instead. These interfaces leave signing and storage implementations outside the domain layer while making the ownership checks visible.

type UploadState = "initiated" | "uploaded" | "processing" | "ready" | "failed";

type UploadRecord = {
  id: string;
  tenantId: string;
  sourceKey: string;
  thumbnailKey: string;
  state: UploadState;
  multipartId?: string;
};

type StartMediaInput = {
  originalName: string;
  contentType: string;
  sizeBytes: number;
};

interface UploadStore {
  insert(record: UploadRecord): Promise<void>;
  findForTenant(uploadId: string, tenantId: string): Promise<UploadRecord | null>;
  markUploaded(uploadId: string): Promise<void>;
}

interface ObjectSigner {
  signSinglePut(key: string, contentType: string): Promise<string>;
  beginMultipart(key: string, contentType: string): Promise<{
    multipartId: string;
    signPart(partNumber: number): Promise<string>;
  }>;
}
Enter fullscreen mode Exit fullscreen mode

The application service derives every authoritative identifier. Values such as the multipart threshold, accepted media types, expiry, and part count are policy inputs; hard-coding arbitrary numbers here would turn an architectural example into accidental production advice.

async function startLessonMedia(
  tenantId: string,
  input: StartMediaInput,
  deps: { uploads: UploadStore; signer: ObjectSigner; ids: () => string },
) {
  validateMediaPolicy(input);

  const uploadId = deps.ids();
  const sourceKey = `tenants/${tenantId}/media/${uploadId}/source`;
  const thumbnailKey = `tenants/${tenantId}/media/${uploadId}/thumb`;
  const useMultipart = shouldUseMultipart(input.sizeBytes);

  if (!useMultipart) {
    await deps.uploads.insert({
      id: uploadId, tenantId, sourceKey, thumbnailKey, state: "initiated",
    });
    const url = await deps.signer.signSinglePut(sourceKey, input.contentType);
    return { uploadId, transport: "single" as const, operations: [{ url }] };
  }

  const multipart = await deps.signer.beginMultipart(sourceKey, input.contentType);
  await deps.uploads.insert({
    id: uploadId, tenantId, sourceKey, thumbnailKey,
    state: "initiated", multipartId: multipart.multipartId,
  });

  return {
    uploadId,
    transport: "multipart" as const,
    operations: await signInitialWindow(multipart.signPart),
  };
}
Enter fullscreen mode Exit fullscreen mode

Completion is a second authorization decision. Load the record with both uploadId and the authenticated tenantId, verify the stored object against server policy, and only then move the record to uploaded. Enqueue thumbnail work using the record ID. The worker reloads the record and writes only to thumbnailKey.

Do not trust a browser's thumbnailKey, tenant prefix, or claim that all parts arrived. Those are convenient inputs for an attacker and unnecessary inputs for your API.

Thumbnail processing is a state machine

Direct transfer shortens the synchronous request path, but it creates an asynchronous product state. The lesson editor needs to distinguish uploading, uploaded, processing, ready, and failed. Returning a guessed thumbnail URL immediately hides that reality and tends to produce broken images or repeated work.

A storage event can wake a worker, but the database record remains the ownership authority. The worker should be idempotent: repeated delivery for one upload ID produces the same destination key and converges on the same state. It should reject a source object that does not match the stored key or accepted media policy. Reads remain private; the application can authorize a read and issue a short-lived access mechanism when the UI needs the source or thumbnail.

Observability should follow the upload ID across application logs, completion handling, and thumbnail processing. Record state transitions and failure categories, not signed URLs. A signed URL is a bearer capability until it expires, so logging the full value expands its exposure. Useful operating signals include stalled initiated uploads, incomplete multipart work, processing age, repeated completion attempts, and cross-tenant lookup denials.

Test the boundaries. Unit tests should prove that client-supplied names cannot alter a key and that tenant B cannot complete tenant A's upload. An integration test should run an actual browser preflight from an allowed origin, then repeat it with a disallowed origin or header. Another test should retry the same processing event and confirm that it neither creates a second logical thumbnail nor regresses a ready record.

This is more code than a generic upload endpoint. It is also the code that prevents media plumbing from consuming the time reserved for product work. Outsource byte transfer and image transformation where appropriate. Keep identity, state, and authorization in the product.

When the proxy is the better runner-up

Proxy uploads through the application when policy requires synchronous inspection before storage acceptance, when transformation must happen inline, or when payloads are consistently small enough that direct multipart coordination adds more moving pieces than value. The proxy has one clear virtue: browser CORS applies at the application boundary you already control.

Limitations: direct upload is a poor fit when every byte must pass an application-side scanner before storage acceptance, when clients cannot implement retry and multipart state correctly, or when the operational burden of abandoned parts outweighs the saved application capacity. In those cases, choose a deliberately isolated proxy or media-ingest service. A proxy is the weaker choice for long classroom recordings when it would force the product API to carry the entire transfer.

The bill arrives in application capacity and failure coupling. Every byte occupies your network path, and a long media transfer shares operational fate with normal product traffic unless it is isolated. For a solo operator, that can consume the same attention needed to ship classroom features.

There is a middle ground. The application can receive a small thumbnail directly while the original media uses private direct ingestion, or it can authorize an upload before a separate media service handles the transfer. Choose based on the real inspection boundary. Do not choose based on the mistaken idea that CORS secures objects.

The durable decision rule is plain: if tenant authorization can happen before byte transfer and validation can happen after arrival, direct ingestion keeps the hot path lean. If bytes must be judged before they enter storage, proxy them through a deliberately isolated service. In both designs, the application owns the tenant mapping and the media state machine.

Sources

Top comments (0)