How to Operate Private File Uploads: Signed Downloads with Tenant Isolation
Short answer: Use a private file upload architecture in which the app assigns every e-commerce training artifact a tenant-scoped object storage key, then gives the browser separate signed upload and download grants. The control plane must own region, validation state, and an immutable deletion deadline; possession of an object key must never be enough to mint a download. Fail closed.
That shape keeps bulky transfers away from the app while leaving authorization where it belongs. A signed URL is a temporary capability, not proof that the caller may read the file. Treating those as the same thing is how one tenant's product-photo labeling set ends up visible to another.
The runbook has four states: pending, quarantined, ready, and deleting. Upload into quarantine, verify the stored object, promote the metadata to ready, and allow downloads only from that state. Persist delete_at when the artifact is created rather than recalculating it from today's policy. That's what makes retention reproducible after a policy change.
What fails in private file upload and signed download for app users?
The dangerous failure is a control plane that treats a user-supplied key or a previously issued signed URL as authorization. Split the system into a control plane and a data plane. The authenticated app API is the control plane: it chooses a region from the tenant record, generates an opaque object key, records ownership and retention, and asks a storage signer for a narrowly scoped upload or download grant. The browser-to-object-storage request is the data plane. It carries bytes, but it doesn't choose the tenant, bucket, region, object key, or expiration.
Do not put storage signing credentials in browser code. OWASP's secrets guidance recommends centralizing and limiting access to secrets, while its file upload guidance calls for authorized uploaders, generated filenames, size limits, and storage outside the webroot or on a separate host. Direct upload changes the route the bytes take; it doesn't remove those controls.
Use an application-level record like this:
- Field
- Set by
- Operational purpose
tenant_id- authenticated server context - authorization boundaryobject_key- server - unguessable storage addressregion- tenant policy - prevents browser-selected placementstate- validation workflow - blocks premature downloaddelete_at- retention policy at creation - stable deletion obligationpolicy_version- server configuration - explains why that deadline exists
The catch is that a shared bucket with tenant-prefixed keys concentrates policy mistakes. It can be suitable when every signing and metadata lookup enforces the tenant predicate and those checks are tested as invariants. Use separate buckets or accounts when contractual isolation, separate administrative ownership, or independent encryption authority matters more than operational simplicity. Signed URLs don't settle that decision.
Implement the tenant grant control plane
The following Go program is deliberately storage-neutral. Signer is the only adapter a deployment must connect to an object store. The demo signer returns inert example URLs so the program runs locally without credentials; production code must return real signed grants from a server-side implementation. The handlers show the security boundary that should remain unchanged.
package main
import (
"encoding/json"
"fmt"
"log"
"net/http"
"strings"
"sync"
"time"
)
type Artifact struct {
ID string `json:"id"`
TenantID string `json:"tenant_id"`
ObjectKey string `json:"object_key"`
Region string `json:"region"`
ContentType string `json:"content_type"`
State string `json:"state"`
DeleteAt time.Time `json:"delete_at"`
PolicyVersion string `json:"policy_version"`
}
type Grant struct {
URL string `json:"url"`
Method string `json:"method"`
Headers map[string]string `json:"headers"`
ExpiresAt time.Time `json:"expires_at"`
}
type Signer interface {
SignUpload(objectKey, contentType string, expiresAt time.Time) (Grant, error)
SignDownload(objectKey string, expiresAt time.Time) (Grant, error)
}
type DemoSigner struct {}
func (DemoSigner) SignUpload(key, contentType string, expires time.Time) (Grant, error) {
return Grant{
URL: "/signed-upload/" + key,
Method: http.MethodPut,
Headers: map[string]string{"Content-Type": contentType},
ExpiresAt: expires,
}, nil
}
func (DemoSigner) SignDownload(key string, expires time.Time) (Grant, error) {
return Grant{
URL: "/signed-download/" + key,
Method: http.MethodGet,
ExpiresAt: expires
}, nil
}
type Server struct {
mu sync.RWMutex
artifacts map[string]Artifact
signer Signer
}
func tenantID(r *http.Request) string {
// Demo input only. Production must derive this value from verified authentication.
return r.Header.Get("X-Demo-Tenant")
}
func writeJSON(w http.ResponseWriter, status int, value any) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
_ = json.NewEncoder(w).Encode(value)
}
func (s *Server) createUpload(w http.ResponseWriter, r *http.Request) {
tenant := tenantID(r)
var in struct {
ArtifactID string `json:"artifact_id"`
ContentType string `json:"content_type"`
}
if tenant == "" || json.NewDecoder(r.Body).Decode(&in) != nil {
http.Error(w, "invalid request", http.StatusBadRequest)
return
}
if in.ArtifactID == "" || !strings.HasPrefix(in.ContentType, "image/") {
http.Error(w, "file type is not allowed", http.StatusUnprocessableEntity)
return
}
now := time.Now().UTC()
artifact := Artifact{
ID: in.ArtifactID,
TenantID: tenant,
ObjectKey: fmt.Sprintf("quarantine/%s/%s", tenant, in.ArtifactID),
Region: "tenant-policy-region",
ContentType: in.ContentType,
State: "pending",
DeleteAt: now.Add(30 * 24 * time.Hour),
PolicyVersion: "training-v3",
}
s.mu.Lock()
if _, exists := s.artifacts[artifact.ID]; exists {
s.mu.Unlock()
http.Error(w, "artifact already exists", http.StatusConflict)
return
}
s.artifacts[artifact.ID] = artifact
s.mu.Unlock()
grant, err := s.signer.SignUpload(artifact.ObjectKey, artifact.ContentType, now.Add(5 * time.Minute))
if err != nil {
http.Error(w, "grant unavailable", http.StatusServiceUnavailable)
return
}
writeJSON(w, http.StatusCreated, struct {
Artifact Artifact `json:"artifact"`
Upload Grant `json:"upload"`
}{artifact, grant})
}
func (s *Server) createDownload(w http.ResponseWriter, r *http.Request) {
tenant := tenantID(r)
id := r.PathValue("id")
s.mu.RLock()
artifact, exists := s.artifacts[id]
s.mu.RUnlock()
if !exists || artifact.TenantID != tenant {
// One response prevents cross-tenant existence probing.
http.Error(w, "artifact not found", http.StatusNotFound)
return
}
if artifact.State != "ready" || !time.Now().UTC().Before(artifact.DeleteAt) {
http.Error(w, "artifact is not downloadable", http.StatusConflict)
return
}
grant, err := s.signer.SignDownload(artifact.ObjectKey, time.Now().UTC().Add(5 * time.Minute))
if err != nil {
http.Error(w, "grant unavailable", http.StatusServiceUnavailable)
return
}
writeJSON(w, http.StatusOK, grant)
}
func main() {
server := &Server{artifacts: make(map[string]Artifact), signer: DemoSigner{}}
mux := http.NewServeMux()
mux.HandleFunc("POST /api/artifacts/uploads", server.createUpload)
mux.HandleFunc("POST /api/artifacts/{id}/downloads", server.createDownload)
log.Fatal(http.ListenAndServe(":8080", mux))
}
Start it with Go 1.22 or later, then request a grant. The URL is intentionally non-routable, but the JSON contract and authorization path can be exercised locally.
go run main.go
curl -sS -X POST localhost:8080/api/artifacts/uploads \
-H 'Content-Type: application/json' \
-H 'X-Demo-Tenant: shop-eu-17' \
-d '{"artifact_id":"catalog-labels-2026-08","content_type":"image/png"}'
A production create handler also needs a request-body limit, an allowlist appropriate to the training pipeline, quota checks, and idempotency. Do not trust the original filename or use it as the object key. The example's 409 artifact already exists is deliberate: retries must converge on one record instead of silently creating a second retention obligation.
Test quarantine before signed download
A successful PUT proves only that storage accepted bytes. It does not prove that the declared content type matches the file, that the size is allowed, or that downstream decoders can safely open it. OWASP recommends defense in depth: extension and type checks, a generated filename, size limits, malware scanning where available, and protection against parser attacks. For direct uploads, perform those checks after an object-created signal or a controlled completion call, while the metadata remains non-downloadable.
The transition must be compare-and-set: pending -> quarantined -> ready. A repeated event should observe the current state and return success without repeating promotion. I've been paged by missed jobs and duplicate deliveries; the durable lesson is that delivery is a hint, not a transaction. Record a validation attempt ID, object version or checksum supplied by storage, observed byte count, and final decision. Never let an event's tenant field override the tenant already bound to the artifact record. Keep it boring.
There is one awkward boundary here: I'm not sure which file inspection policy fits a given model-training pipeline without its accepted formats and threat model. Resolve that before launch with sample artifacts and the actual parsers. The invariant is still clear: inspection failure leaves the record unavailable, and only an explicit successful decision can make it ready.
Operate expiry and deletion as idempotent jobs
Test the negative paths first. Create the same human-readable artifact name in two tenants and confirm that the server generates distinct keys. Ask tenant B for tenant A's artifact and expect the same 404 used for an unknown ID. Try a download while the record is pending, after delete_at, and after the object version changes. Confirm that none produces a grant. Then replay the completion event and the deletion job; both must be idempotent.
For observability, count grant decisions by operation, region, state, and outcome, but don't put raw signed URLs, credentials, or user filenames in logs. Alert on old pending records, validation lag, objects still present after their stored deadline, and metadata whose object cannot be found. Those signals correspond to actionable queues rather than traffic volume.
Deletion order matters. Mark the row deleting, remove the exact object version, verify absence, write an audit event that contains no secret URL, and only then remove or tombstone metadata according to the application's record policy. A worker lease needs an expiry so another worker can recover a missed job. Duplicate delivery should find deleting or the tombstone and finish cleanly. The deadline remains the persisted delete_at; a later change from 30 days to 14 days should affect new records unless a separately reviewed migration intentionally changes existing obligations.
Residency is also a server decision. Bind each tenant to its approved storage region and validation workers, then reject any request that would cross that boundary. A US/EU dropdown in the browser is not an authorization control, and choosing an EU region by itself is not a complete GDPR program. Legal basis, access handling, erasure workflow, processor terms, and backups require review outside this upload path.
When should this architecture be rolled back?
Deploy the metadata schema and decision logging before enabling direct browser transfers. Next, shadow-create grants without returning them and verify that keys, regions, deadlines, and content constraints match policy. Enable one tenant cohort, watch the old-pending and deletion-deadline signals, then expand. The useful success measure is not raw upload throughput; it is the absence of cross-tenant grants and the bounded age of unfinished and overdue records.
Rollback should switch new uploads back to an authenticated app proxy while preserving the same artifact records, object keys, validation states, and deletion workers. Do not make a private bucket public, lengthen grants broadly, or bypass validation to recover traffic. If the signer adapter is unavailable, fail closed and retain the metadata for a retry. Existing short-lived grants expire on their own; revocation that must be immediate requires a storage-side policy change or object/key rotation planned for that threat model.
This architecture is not suitable when the browser must transform a secret format that cannot safely reach the chosen storage endpoint, or when policy requires every byte to pass synchronously through an application-controlled inspection boundary. Stick with an app proxy in those cases. For large e-commerce training sets where direct transfer is acceptable, the control-plane split works well because tenant authorization and reproducible retention remain explicit, testable state rather than properties inferred from a URL.
Comments
No comments yet. Start the discussion.