DEV Community

SuttonHawkins6723
SuttonHawkins6723

Posted on

Course Image Isolation: 5 Private-Bucket Controls for Resizing and Signed URLs

Short answer: keep course media in a private bucket, authorize direct uploads against a server-owned tenant record, let a worker create a fixed set of thumbnails, and mint a signed URL only after the application rechecks tenant access to the finished derivative. The resize library is not the security boundary. The binding among tenant, source object, transform, and derivative is.

I've been paged by missed jobs and duplicate deliveries. That experience changes the design question: I don't ask whether one clean resize succeeds; I ask whether delayed and repeated work can ever cross a tenant boundary. For large lesson recordings, the application should control names and permissions without proxying the bytes.

Five controls make that answer testable.

1. Incident lesson: duplicate delivery is an authorization test

Create the media record before authorizing an upload. It should bind an opaque media ID to the authenticated tenant, a server-derived source key, an allowed content class, and a small catalog of permitted derivatives. A browser may supply a display filename, but it must not choose the tenant ID, bucket, or durable object key.

This is the central invariant: every later operation begins from (tenant ID, media ID) and derives storage locations from that pair. A raw key supplied by a client is never an authorization fact.

Consider two schools that both upload a file named week-04.mp4. A filename-based layout makes collision and disclosure bugs surprisingly easy to express. With server-owned identifiers, the two records resolve to unrelated namespaces even though the labels match. The database lookup also needs both columns; looking up only the opaque media ID quietly weakens the rule the key layout was meant to enforce.

The missed-job page asks whether work happened. A duplicate-delivery page asks a harder question: if the work happens again after surrounding state has moved, which authorization decision does it use? The media record answers both questions without trusting message timing. It gives an operator one durable place to distinguish absent work, repeated work, and a task whose claimed namespace does not match current ownership.

2. An authority matrix exposes the tenant boundary

Write down the authority of each actor before choosing the physical bucket layout. This is more useful than starting with a vendor feature list because a shared credential can defeat a careful key scheme.

Actor May read May write Must not decide
Browser uploader Its upload authorization One server-derived source key Tenant namespace or derivative key
Resize worker One verified immutable source Allowlisted deterministic derivatives Tenant ownership from message fields alone
Application signer One ready derivative record A bounded read capability Object identity from a client-provided key
Operator State and redacted audit events Controlled retry or cancellation Access through a logged signed URL

There are two reasonable physical layouts. A shared private bucket with tenant-prefixed keys centralizes policy and lifecycle administration, but key validation carries more of the isolation burden. A separate bucket or account for each tenant gives a stronger administrative boundary at the cost of more credentials, policies, deployment state, and deletion workflows. Use the second model when contracts or internal policy require that boundary. Don't pretend a prefix is equivalent.

Once those powers are explicit, authorize upload without accepting storage identity.

The application can issue narrowly scoped upload authorization, then let the browser transfer the large media file directly to object storage. That keeps video bytes off the application request path while preserving the application's authority over where those bytes may land.

The completion callback is not enough by itself.

After the client reports completion, verify the expected source object against the existing media record before moving its state forward. The important distinction is between “upload was authorized” and “the expected source is present.” A runbook should expose those as separate states because a worker must not infer ownership from a queue message or from a client assertion.

A practical state sequence is created, upload_authorized, source_verified, derivatives_pending, and ready. Transitions should be conditional: only the current expected state may advance, and a repeated completion event should converge on the state already reached. This is where a scheduling mindset helps. Messages can arrive twice or late; authorization cannot become timing-dependent.

The catch is that direct upload is not suitable when the application must inspect every byte synchronously before accepting it, or when the files are so small and infrequent that separate upload authorization adds more machinery than it removes. In that environment, proxying through the application can be the clearer operational choice. Keep the tenant-derived destination rule either way.

3. How should a private bucket resizing worker create object storage image thumbnails?

Treat each resize message as a reference to trusted state, not as a self-authorizing command. The worker receives tenant ID, media ID, transform name, and immutable source identity. It loads the media record, recomputes the source and destination keys, rejects any mismatch, and permits only a transform from the record's catalog.

Keep outputs deterministic. For one immutable source identity and one transform name, every delivery must address the same derivative key. Then duplicate delivery may repeat computation, but it cannot invent another owner or another output location. This matters during an awkward sequence: attempt A begins, its acknowledgment is delayed, attempt B receives the same task and finishes, and attempt A resumes. Both attempts should converge on one output and one conditional completion transition. Queue settings may reduce repeats; the consumer still owns idempotency.

Here is the preventative path in Go. The storage adapter can call a Node.js and Sharp service behind the interface if that is the chosen image runtime; the tenant check stays outside the image operation, where it can be tested without decoding a video frame.

package preview

import (
    "context"
    "errors"
    "fmt"
)

type Task struct {
    TenantID      string
    MediaID       string
    SourceVersion string
    Transform     string
    SourceKey     string
    OutputKey     string
}

type Media struct {
    TenantID      string
    MediaID       string
    SourceVersion string
    Allowed       map[string]bool
}

type Repository interface {
    Find(ctx context.Context, tenantID, mediaID string) (Media, error)
    MarkReady(ctx context.Context, tenantID, mediaID, transform string) error
}

type Resizer interface {
    Create(ctx context.Context, sourceKey, outputKey, transform string) error
}

func keys(m Media, transform string) (string, string) {
    base := fmt.Sprintf("tenants/%s/media/%s/versions/%s", m.TenantID, m.MediaID, m.SourceVersion)
    return base + "/source", base + "/previews/" + transform
}

func Process(ctx context.Context, repo Repository, resize Resizer, task Task) error {
    media, err := repo.Find(ctx, task.TenantID, task.MediaID)
    if err != nil {
        return err
    }
    if media.SourceVersion != task.SourceVersion || !media.Allowed[task.Transform] {
        return errors.New("task does not match the approved media transform")
    }

    source, output := keys(media, task.Transform)
    if task.SourceKey != source || task.OutputKey != output {
        return errors.New("task keys do not match tenant-owned media")
    }
    if err := resize.Create(ctx, source, output, task.Transform); err != nil {
        return err
    }
    return repo.MarkReady(ctx, media.TenantID, media.MediaID, task.Transform)
}
Enter fullscreen mode Exit fullscreen mode

The interface deliberately says little about codecs. Sharp in a Node.js worker is one implementation choice, but changing libraries does not change the isolation contract: validate ownership, pin the source identity, allowlist transforms, use a deterministic output, and make completion retry-safe.

I used to frame duplicate delivery mainly as a queue configuration problem. Production paging taught me to put the guarantee in the consumer instead. Short version: retries are normal.

4. Enforce read capability at the signing boundary

A signed URL is a temporary capability to access a specific object. The application should first load the media record through the authenticated tenant, confirm that the requested transform is ready, derive the output key itself, and only then ask the storage layer to sign that exact read. It should not sign a client-provided key, even if the key appears to contain the right tenant prefix.

Keep uploader, worker, and viewer authority separate. The uploader may write the one expected source. The worker may read that immutable source and write approved derivatives. The viewer may read one ready derivative for a bounded period. A broad credential shared among all three roles makes an isolation review depend on application convention rather than enforceable scope.

Expiry has no universal correct number. It must cover the expected playback or preview window without outliving the user's need, and refreshing it must repeat authorization. I'm not sure the same duration should serve a teacher preview, a student lesson page, and an administrative export; access patterns and policy requirements should settle that choice. What does not vary is the lookup: tenant plus media record first, derived object key second.

Do not log the full signed URL. Operational logs commonly live longer than the access window, so record the tenant, media ID, transform, decision, and expiry policy identifier instead. The capability itself does not belong in a durable diagnostic trail.

5. Release evidence, operating signals, and explicit exceptions

The release gate should attack ordering and substitution, not merely confirm that a thumbnail looks correct. Submit the same task twice. Finish a newer source version before a delayed task for the older version. Put tenant A's real media ID into tenant B's read request. Replace the queued source key while leaving the tenant field unchanged. Ask for a signed URL while the derivative is pending. The expected result is one stable derivative for the approved source, no cross-tenant read or write, and no read capability before the ready transition.

No shortcuts.

Run those cases against the deployed storage and queue adapters as well as local fakes. A unit test can prove key derivation and state transitions; an adapter test must prove that private access, scoped signing, immutable source identity, and conditional completion survive the real integration. The useful dashboard follows the same invariant. Track the age of the oldest verified source without a ready preview, duplicate jobs that converged, rejected key mismatches, and denied cross-tenant lookups. Each alert should map to an operator decision: retry an idempotent task, stop a malformed producer, or investigate an authorization path.

Retention deserves a place in this gate. Source media and generated previews can have different lifetimes, and object lifecycle management can automate transitions and expiration. Deletion must cover both the media record and every deterministic derivative; otherwise a tidy database can conceal abandoned storage. AWS documents lifecycle management for objects, while Backblaze publishes its storage pricing dimensions. Those are inputs to a design review, not reasons to select either service: compare lifecycle behavior, request and transfer accounting, policy boundaries, and operational workload against the same tenant model.

This pattern is a poor fit for arbitrary resize dimensions generated on every read. A fixed derivative catalog keeps authorization, resource limits, cache behavior, and deletion enumerable. Use a dedicated image-delivery layer when dynamic transformation is the actual product requirement and its policy model satisfies tenant isolation. Use synchronous processing when volume is low and fewer moving parts matter more than removing media bytes from the application path. Use separate storage boundaries when administrative isolation outweighs configuration overhead.

The final postmortem question is precise: can every signed preview be traced to one authenticated tenant, one immutable source version, one approved transform, and one completed state transition? If the answer requires reading a worker log or trusting message order, the pipeline is not ready.

References

Top comments (0)