Dev.to Security 🔐 Cybersecurity 👁 0 📖 8 min read

AI-Generated Image Storage — Private Signed URLs, Retention, and Deletion

A gaming service cannot choose image storage sensibly until it knows when a private upload must disappear. Short answer: keep originals in a private object bucket, issue narrowly scoped signed download URLs, and make ret

A gaming service cannot choose image storage sensibly until it knows when a private upload must disappear. Short answer: keep originals in a private object bucket, issue narrowly scoped signed download URLs, and make retention plus verifiable deletion part of the data model rather than a bucket setting someone remembers later.

There is no universal “best” object store for this workload. For a SaaS serving US and EU players, the useful choice is the service that passes its residency, deletion, signing, and failure-injection tests with acceptable operational cost. S3 compatibility can reduce integration work, but it doesn't prove those properties.

The concrete case here is a player uploading a private source image that an AI pipeline turns into an avatar or game asset. The source, intermediate render, and accepted result have different reasons to exist. Treating all three as “an image” creates the kind of retention gap that later becomes a support, privacy, and abuse-response problem.

How should a SaaS keep AI-generated images private with signed URLs?

Start with three records, not one vague blob: an upload session, an immutable object revision, and a grant to download that revision. The application database owns status and policy. Object storage owns bytes. A queue or scheduled worker reconciles the two.

Keep the bucket private. After authorization, the application signs a short-lived GET for the exact object key and returns it to the caller. A signed URL is a bearer credential — anyone who has it may use it until its effective expiry — so don't put it in analytics events, exception messages, chat transcripts, or long-lived browser storage. This is the same discipline I use around OTP delivery: the happy path is less interesting than replay, leakage, delay, and a credential arriving after the user no longer expects it.

Expiry is not revocation. If a moderator blocks an asset or a player deletes an account, a previously issued URL may remain usable until it expires. Design the expiry budget from that fact. Ten minutes might be tolerable for a one-time download screen; it may be far too long for a moderation action. Your mileage may vary because the right number comes from the product's threat model, not an object-storage feature matrix.

The browser adds another boundary. A successful signed GET can still look broken when its origin, method, or headers do not satisfy the bucket's CORS policy. CORS tells browsers which cross-origin responses frontend code may read; it is not authorization and does not make a private object public. Test the exact production origin and the preflight path rather than allowing every origin to get a demo moving.

Make access failures boring. An expired or altered signature should produce a 403; a missing current revision should be presented as unavailable without revealing whether another tenant owns that key. The API that mints a URL should also recheck tenant membership, asset state, and purpose every time. Don't cache signed URLs across users.

The key itself should carry no email address, player handle, or prompt text. An opaque layout such as tenant_id/asset_id/revision_id supports partitioning and investigation without leaking personal data into inventory reports. Random, server-created identifiers also prevent one tenant from guessing another tenant's object name.

Retention starts in the schema, not in lifecycle configuration

Write down a state machine before choosing a provider. A compact version could be pending -> active -> delete_requested -> deleted, with quarantined as a separate moderation state. Store retention_class, delete_after, legal_hold, the current revision, and the last deletion verification time. The key point is that “delete requested” and “confirmed absent” are different facts.

This distinction matters when one player action fans out into several objects. Suppose a source upload creates four candidate renders, one thumbnail, and one accepted avatar. The player replaces the avatar after 28 days, then closes the account. Deleting only the database row loses the manifest needed to find six objects. Deleting only the accepted image leaves the source and rejected candidates behind. A prefix-wide delete, meanwhile, can race with a retry that is still writing a late render. That is why the deletion job should enumerate object revisions from an immutable manifest, fence new writes for the asset, delete each named object, and then verify absence before recording completion.

Slow down here.

Lifecycle rules remain useful as a backstop for abandoned multipart uploads, temporary renders, and objects whose delete_after time has passed. They are not a substitute for an application deletion workflow because the application must explain which policy applied, respect a hold, and expose progress without claiming completion early. Versioning changes the proof obligation too: hiding the current object does not necessarily establish that every stored revision is gone. The exact deletion semantics and timing are provider-specific, so verify them in current documentation and in the contract for the selected region.

A small policy function makes the decision testable without coupling it to a storage SDK:

from dataclasses import dataclass
from datetime import datetime, timedelta, timezone


@dataclass(frozen=True)
class AssetPolicy:
    source_days: int = 7
    rejected_render_days: int = 2
    accepted_render_days: int = 30


def deletion_deadline(kind: str, created_at: datetime, policy: AssetPolicy) -> datetime:
    days_by_kind = {
        "source": policy.source_days,
        "rejected_render": policy.rejected_render_days,
        "accepted_render": policy.accepted_render_days,
    }
    if created_at.tzinfo is None:
        raise ValueError("created_at must include a timezone")
    try:
        days = days_by_kind[kind]
    except KeyError as exc:
        raise ValueError(f"unknown asset kind: {kind}") from exc
    return created_at.astimezone(timezone.utc) + timedelta(days=days)

Policy changes need migration semantics. If accepted assets move from 30 days to 14, decide whether existing objects keep their original deadline or receive the new one, record that decision, and run a dry count before scheduling deletes. I'm not sure a global retroactive update is ever safe without checking legal holds, active disputes, and restore expectations; those inputs, plus counsel's retention guidance, resolve the uncertainty.

Compare candidates only after defining deletion evidence

Run the same acceptance suite against at least three plausible services. AWS S3, Cloudflare R2, and Backblaze B2 are reasonable names to include in an S3-compatible evaluation, but their appearance on a shortlist is not an endorsement. Compatibility has edges, and a successful upload says little about residency or erasure.

Decision point Evidence to collect Failure that disqualifies a candidate
Private access Signed GET works only for the intended key and expires within the tested window Anonymous reads succeed or a signature can be widened
US/EU placement Contract and account configuration identify where object data is stored The required residency boundary cannot be established
Deletion Current and historical revisions become absent under the documented process Old revisions remain retrievable after the promised completion point
CORS Production origins pass GET and preflight tests; an unlisted origin fails Wildcard policy is required for the application to work
Portability The signing, multipart, checksum, and error cases pass through the chosen client Critical behavior depends on an undocumented extension
Cost Model stored bytes, operations, retrieval, egress, and replication from a measured trace A material charge cannot be forecast from published terms

AWS publishes storage-class, request, retrieval, transfer, and related S3 pricing dimensions; the important lesson is methodological, not that one line item wins. Use a 30-day trace from the application to count PUTs, GETs, bytes stored by retention class, deletion requests, and outbound bytes. Then apply each candidate's current published terms. Price belongs in the model once, alongside compliance and behavior, rather than becoming the headline.

The catch is that an S3-compatible endpoint is not suitable when the team needs a provider-specific governance control that the compatibility layer cannot express. In that case, use the native API deliberately and isolate it behind a narrow adapter. Conversely, stick with the current object provider when it passes the deletion and residency tests and migration would only shave a speculative line item; moving private data adds copy verification, dual-write logic, credential exposure, and rollback work.

Do not score a marketing checkbox called “EU.” Ask which data the commitment covers: object bytes, replicas, metadata, access logs, and support access may have different terms. If the evidence is incomplete, mark it unknown. A false green cell is worse than an honest blank.

Roll out with shadow checks and an exit path

The rollout can stay compact. First, deploy the asset manifest and explicit deadlines while the existing storage path remains unchanged. Next, run the deletion worker in report-only mode and compare its proposed keys with database ownership. Enable deletion for a test tenant, verify current and historical revisions, then expand by cohort. Keep a kill switch for new signing and another for deletion; access and destruction have different risk.

Track counts for objects created, URLs minted, denied signing attempts, deletion requests, deletion confirmations, and overdue confirmations. Logs should carry tenant and asset identifiers but never a full signed URL. Alert on the age of the oldest overdue deletion rather than only on worker errors, because a quiet queue can be stuck while emitting no exception.

Test the ugly timing cases: URL expiry during download, account deletion during rendering, duplicate queue delivery, a retry after deletion, and a CORS preflight from an unexpected origin. Inject a 403 from an expired signature and prove the client requests fresh authorization instead of retrying the same URL. For destructive tests, use isolated buckets and synthetic keys.

Finally, rehearse exit. Export the manifest, copy objects while preserving revision identity and checksums, stop new writes, reconcile source and destination, switch signing, and retain the old copy only for the approved rollback window. Then delete it through the same evidenced workflow. The winning design is the one that can prove why an object exists, who may fetch it, and when every revision stopped existing.

No product name answers those questions for you.

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.