{"slug": "tenant-isolated-multipart-uploads-for-ai-generated-property-images-and-their", "title": "Tenant-Isolated Multipart Uploads for AI-Generated Property Images (and Their Exports)", "summary": "A developer describes a tenant-isolated multipart upload design for AI-generated property images, in which upload sessions are created from an authenticated tenant context, object keys are opaque, and exports are built from metadata snapshots rather than bucket listings. The approach uses an append-only image record with tenant, property, checksum and lifecycle fields, plus a shadow-manifest migration that compares old and new selection logic before the new path becomes authoritative. The developer argues multipart upload is only a transport technique and that tenant identity, export membership and reconciliation remain application-level decisions.", "body_md": "The difficult part of storing AI-generated property images is not moving large objects; it is proving, during an export, that every selected object belongs to the requesting tenant. I would therefore begin with an export audit and a migration inventory, then derive the upload state machine from those records. Multipart upload is a transport technique. Tenant identity, export membership, and reconciliation remain application decisions.\n\nShort answer: create an upload session from an authenticated tenant context, reserve an opaque object key, upload parts with bounded size and checksums, complete the upload through a conditional state transition, and generate exports from metadata snapshots rather than bucket listings. CORS controls which browser origins may send requests; it does not provide tenant isolation.\n\nA property manager may have buildings, units, maintenance records, and generated staging images in the same system. Before changing storage behavior, inventory each existing image by database owner, object key, content metadata, and current access path. Record unresolved rows rather than guessing. The migration question is not whether an object can be downloaded; it is whether the system can explain why this tenant is allowed to receive it.\n\nFor new images, I use an append-only image record containing an internal image ID, tenant ID, property ID, upload session ID, object key, content type, byte count, checksum, and lifecycle status. The object key can be opaque, for example `objects/7f/1b/<image-id>`. Human-readable tenancy belongs in authorization data and audit events, not in a string that a client can edit. This trades some operational convenience for a boundary that is easier to test. I first assumed a tenant prefix would make exports easier to operate; I changed that decision after considering how a renamed property or copied key could make an operational convention look like authorization.\n\nThe export job snapshots selected image IDs and the metadata version at creation time. It resolves each image by ID, verifies that the status is `available`, and writes a manifest containing the tenant ID, export ID, image ID, object key, checksum, and generation timestamp. If an image changes while the job runs, policy must choose a deterministic omission or the snapshot version. Silent substitution is unacceptable in a compliance-sensitive workflow.\n\nThat is the control plane.\n\nStart with one property-management tenant and run a shadow manifest. Compare the old selection logic with a metadata query constrained by tenant, property, or unit scope. Keep the comparison long enough to expose abandoned multipart sessions and stale ownership rows; a five-minute dashboard number cannot explain a week of historical disagreement.\n\nThe useful metrics are sessions by state and age, completion retries, parts rejected by size or checksum, orphan objects, metadata-to-object mismatches, export omissions, and authorization denials by tenant. An outbox or reconciliation loop is appropriate because object storage and the application database do not normally commit one distributed transaction together. Persist the intended transition and audit event, perform the storage operation, then record the observed result.\n\nNew writes can move through the session state machine while exports compare old and new selection logic. Once the mismatch rate is understood, make the new path authoritative and retain the old manifest as evidence for rollback analysis. A migration that deletes ambiguous objects first destroys the evidence needed to resolve ownership.\n\nMultipart upload is useful when generated images are large enough that retrying one failed request would waste meaningful work, or when a worker can upload independent chunks concurrently. It does not solve authorization, deduplication, export consistency, or cleanup.\n\nThe service should reserve a session and return only the upload information needed for the next step. Bound the part number and permitted content length, expire the session, and require the server-observed part identifiers and final object size at completion. A client may retry an individual part, but a retry must not silently overwrite a completed image.\n\nThe four useful states are `created`, `uploading`, `completing`, and `available`. Rejected, expired, and aborted sessions are terminal. That small state machine is easier to reconcile than a boolean called `uploaded`.\n\nThe storage adapter below is generic. It can be backed by a self-hosted service or a managed object store, while the application retains the tenant check and state transition.\n\n```\npackage images\n\nimport (\n    \"context\"\n    \"errors\"\n    \"fmt\"\n    \"time\"\n)\n\nvar ErrForbidden = errors.New(\"tenant access denied\")\n\ntype UploadSession struct {\n    ID        string\n    TenantID  string\n    ImageID   string\n    ObjectKey string\n    ExpiresAt time.Time\n    Status    string\n}\n\ntype Part struct {\n    Number int\n    ETag   string\n    Size   int64\n}\n\ntype Store interface {\n    CreateMultipart(ctx context.Context, key string, contentType string) (uploadID string, err error)\n    CompleteMultipart(ctx context.Context, key, uploadID string, parts []Part) error\n    AbortMultipart(ctx context.Context, key, uploadID string) error\n}\n\ntype Repository interface {\n    FindSession(ctx context.Context, sessionID, tenantID string) (UploadSession, error)\n    MarkCompleting(ctx context.Context, sessionID string) error\n    MarkAvailable(ctx context.Context, sessionID string, size int64) error\n}\n\nfunc Complete(ctx context.Context, repo Repository, store Store, sessionID, tenantID string, parts []Part, total int64) error {\n    session, err := repo.FindSession(ctx, sessionID, tenantID)\n    if err != nil {\n        return err\n    }\n    if session.TenantID != tenantID || session.Status != \"uploading\" || time.Now().After(session.ExpiresAt) {\n        return ErrForbidden\n    }\n    if len(parts) == 0 || total <= 0 {\n        return fmt.Errorf(\"invalid multipart completion\")\n    }\n    if err := repo.MarkCompleting(ctx, sessionID); err != nil {\n        return err\n    }\n    if err := store.CompleteMultipart(ctx, session.ObjectKey, session.ID, parts); err != nil {\n        return err\n    }\n    return repo.MarkAvailable(ctx, sessionID, total)\n}\n```\n\n`MarkCompleting` needs a conditional update such as “change `uploading` to `completing` only if the current state is `uploading`.” A second completion request then observes `completing` or `available` and follows an explicit retry path instead of invoking storage completion twice. The exact storage API differs across systems; the invariant does not.\n\nUse terminal states for rejected, expired, and aborted sessions. A retry may create a new session, but it must not reuse a completed image ID without an explicit deduplication rule. This is where an exactly-once mindset helps: the operation may be retried, but the business transition is recorded once.\n\nThis design has a boundary. The limitation is operational overhead: for small objects that do not need resumable transfer, a single bounded upload may be easier to operate; multipart state is additional bookkeeping. The state machine earns its cost when retryability, auditability, or tenant-scoped export evidence matters.\n\nFor a browser flow, configure CORS for exact application origins and only the methods and headers required by the upload. A preflight response tells a browser whether a cross-origin request is permitted. MDN describes CORS as a browser-enforced mechanism, so it cannot authenticate the caller, bind a request to a tenant, or stop a malicious server-side client from sending the same request.\n\nKeep the browser credential narrow. A presigned part request should identify one upload session and one object key, expire quickly, and expose no permission to list a bucket or read unrelated objects. The application must validate the origin and session before issuing it. When a worker produces the image, CORS is irrelevant; the tenant and state checks still apply.\n\nSeparate content validation from extension validation. A declared `image/png` value is a hint, not evidence that the bytes are PNG. After completion, a worker can inspect content, enforce pixel and decompression limits, and produce a derived safe representation. The export policy decides which status is eligible.\n\nTest the boundary as a matrix: tenant A requesting tenant B's session, a replayed completion, an expired part, a reordered part list, a missing object, a changed property assignment, and an export whose source image becomes invalid during processing. Each case should produce a stable result and an audit event. The happy path is the least interesting test.\n\nA periodic reconciliation scan should find abandoned sessions and metadata that remains in `completing` past its deadline. It should alert on disagreement; it should not delete an object merely because one read was temporarily unavailable. The export itself gets an ownership record, and a download token refers to the export ID rather than only to a path. Every read checks the caller's tenant and records a download event.\n\nThe design rule is compact: tenant identity belongs in the authenticated service context, upload progress belongs in a state machine, and export membership belongs in a database snapshot. Multipart upload then becomes an implementation technique for moving bytes, rather than the place where authorization is accidentally invented.\n\nReplays happen.", "url": "https://wpnews.pro/news/tenant-isolated-multipart-uploads-for-ai-generated-property-images-and-their", "canonical_source": "https://dev.to/fletchervance3712/tenant-isolated-multipart-uploads-for-ai-generated-property-images-and-their-exports-171m", "published_at": "2026-11-26 13:12:47+00:00", "updated_at": "2026-11-26 13:19:09.726582+00:00", "lang": "en", "topics": ["ai-infrastructure", "ai-tools", "mlops"], "entities": [], "also_reported_by": [], "takeaway": "Derive tenant-scoped exports from metadata snapshots keyed by image ID with checksums, not bucket listings or tenant prefixes, and run a shadow manifest comparing old and new selection logic until the mismatch rate is understood.", "recommendation": {"advice": "Build exports from tenant-constrained metadata snapshots with per-image checksums, and run a shadow manifest against the old selection logic before making the new path authoritative.", "playbook": "production-ops", "playbook_url": "https://wpnews.pro/playbooks/production-ops"}, "alternates": {"html": "https://wpnews.pro/news/tenant-isolated-multipart-uploads-for-ai-generated-property-images-and-their", "markdown": "https://wpnews.pro/news/tenant-isolated-multipart-uploads-for-ai-generated-property-images-and-their.md", "text": "https://wpnews.pro/news/tenant-isolated-multipart-uploads-for-ai-generated-property-images-and-their.txt", "jsonld": "https://wpnews.pro/news/tenant-isolated-multipart-uploads-for-ai-generated-property-images-and-their.jsonld"}}