Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 3 of 5 · Lab · 30 min · revision 3

Lab: Object Storage with Presigned URLs

Build an authenticated FastAPI service that records each upload in a database, issues presigned POST tickets with size limits, verifies the stored object, and signs short-lived downloads only for the file owner.

Contentsand lesson path

What you will learn

  • Store files in S3-compatible object storage with metadata in the database, and serve them through short-lived presigned URLs.
  • Let clients upload large files directly to object storage with presigned uploads, and post-process them asynchronously before marking them available.

01. Lab architecture: direct client-to-storage uploads

Streaming large files through your API ties up memory, worker slots and network bandwidth on the API servers. A presigned URL lets the client send the bytes straight to object storage, while the API keeps control of who may upload, what they may upload, and who may read it later. In this lab the flow has four steps:

  1. Ticket: the signed-in client calls POST /files/presign-upload. The API checks the declared type, inserts a database row with status pending, chooses the storage key itself, and returns a presigned POST whose signed policy limits the key, the content type and the size.
  2. Direct upload: the client posts the file to the storage endpoint. Storage checks the signature and the policy; the bytes never pass through the API.
  3. Complete: the client calls POST /files/{id}/complete. The API does not trust the client's word: it calls head_object, compares the stored size and type with the row, records the object's ETag, then sets the status to scanning and starts a background job. Only that job marks the file ready.
  4. Download: GET /files/{id}/download loads the row, checks that the caller owns it, that it is ready and that the object still has the recorded ETag, and only then signs a GET URL that expires in five minutes.

Step 4 is where many real systems leak data. A download endpoint that signs any key a client sends is a textbook case of broken object level authorisation (BOLA, OWASP API1): anyone who can guess or copy a key gets a valid link. Clients therefore send a file ID, never a storage key, and the server checks ownership before it signs anything.

02. Setup: versions, storage server and folder layout

You need Python 3.12 or newer and Docker. The lab was tested with Python 3.12.13, FastAPI 0.165.0, Pydantic 2.14.4, Starlette 1.10.0, boto3 1.44.12, pytest 9.2.0 and SeaweedFS 4.51. Any S3-compatible server works, because the code depends only on endpoint_url.

The page address still says MinIO because earlier versions of this lab used it; the lab now uses SeaweedFS. MinIO's community edition is now distributed as source code only, its GitHub repository was archived in April 2026, and by November 2026 the minio/minio image on Docker Hub no longer accepted anonymous pulls. The lab therefore uses SeaweedFS, an Apache-2.0 project whose single-node weed mini mode includes an S3 endpoint on port 8333 and supports presigned URLs and POST policy uploads. Pin the version, and treat the credentials below as local-only. Without Docker, run the same weed mini -dir=<folder> command with the release binary from the SeaweedFS GitHub releases page; it reads the same three environment variables.

Create a folder with the files from this lab: files_api.py, test_files_api.py, test_concurrency.py, and upload_client.py for the end-to-end run.

Bash · start storage and install the Python packages
docker run -d --name lab-s3 -p 8333:8333 \
  -e AWS_ACCESS_KEY_ID=lab-admin -e AWS_SECRET_ACCESS_KEY=lab-secret \
  -e S3_BUCKET=secure-uploads \
  chrislusf/seaweedfs:4.51 mini -dir=/data

mkdir presign-lab && cd presign-lab
python3 -m venv .venv && . .venv/bin/activate
pip install "fastapi[standard]==0.165.0" "boto3==1.44.12" "pytest==9.2.0"

export S3_ENDPOINT=http://localhost:8333
export S3_ACCESS_KEY=lab-admin S3_SECRET_KEY=lab-secret

03. Step 1: the files API

A presigned PUT URL is simple, but it cannot express a size range. A presigned POST carries a signed policy document with conditions. With ["content-length-range", 1, 10485760], storage itself rejects a body outside 1 byte to 10 MB with EntityTooSmall or EntityTooLarge before it stores anything.

Read the code for these decisions:

  • get_current_user turns the Authorization header into a user. The two demo tokens stand in for your real session or JWT check from the authentication skill; never ship them.
  • The storage key is documents/<uuid>.<ext>, and the extension comes from the allowed content type. A client filename such as x.html or ../a.pdf never reaches the key.
  • load_own_file answers 404 both for a missing ID and for someone else's file, so callers cannot probe which IDs exist.
  • Storage credentials come from environment variables, not from source code.
  • connect() opens SQLite with check_same_thread=False. FastAPI can run a sync dependency such as get_db and the endpoint that uses it in different worker threads, and SQLite's default refuses a connection used from a second thread. timeout=10 lets a writer wait up to 10 seconds for a lock (Python's default is 5) before it raises database is locked. The table is created once, in the lifespan, not on every request.
  • The upload ticket stays valid for 10 minutes, so the owner could post different bytes to the same key after /complete has checked it. Recording the ETag at /complete and comparing it before signing a download narrows that gap: a replaced object is refused with 409. It does not close it completely, because a URL signed earlier is not tied to that ETag; keep download URLs short-lived, and re-check the ETag wherever a later step (such as a scan) trusts the stored bytes.
  • get_s3 imports boto3 inside the function, so tests can replace the whole client through dependency_overrides without a storage server.
Python · files_api.py
import os
import sqlite3
import uuid
from contextlib import asynccontextmanager

from fastapi import BackgroundTasks, Depends, FastAPI, Header, HTTPException
from pydantic import BaseModel, Field

BUCKET = os.environ.get("S3_BUCKET", "secure-uploads")
DB_PATH = os.environ.get("FILES_DB", "files.db")
MIN_BYTES, MAX_BYTES = 1, 10 * 1024 * 1024
EXTENSIONS = {"image/jpeg": "jpg", "image/png": "png", "application/pdf": "pdf"}
# Lab stand-in for real authentication (session cookie or verified JWT).
DEMO_TOKENS = {"alice-token": "alice", "bob-token": "bob"}



def get_s3():
    import boto3  # imported here so tests can swap in a fake client
    from botocore.config import Config

    return boto3.client(
        "s3",
        endpoint_url=os.environ["S3_ENDPOINT"],  # e.g. http://localhost:8333
        aws_access_key_id=os.environ["S3_ACCESS_KEY"],
        aws_secret_access_key=os.environ["S3_SECRET_KEY"],
        region_name="us-east-1",
        config=Config(signature_version="s3v4", s3={"addressing_style": "path"},
                      connect_timeout=5, read_timeout=30),  # botocore default: 60 s
    )


def connect() -> sqlite3.Connection:
    # FastAPI may run a sync dependency and the endpoint that uses it in different
    # threads, so SQLite must allow that (as in FastAPI's SQL tutorial).
    # timeout: wait up to 10 s for another writer (the default is 5 s).
    db = sqlite3.connect(DB_PATH, check_same_thread=False, timeout=10)
    db.row_factory = sqlite3.Row
    return db


@asynccontextmanager
async def lifespan(app: FastAPI):
    db = connect()
    db.execute(  # create the table once, at startup
        "CREATE TABLE IF NOT EXISTS stored_files (id TEXT PRIMARY KEY,"
        " owner_id TEXT NOT NULL, storage_key TEXT NOT NULL,"
        " content_type TEXT NOT NULL, size INTEGER, etag TEXT,"
        " status TEXT NOT NULL)"
    )
    db.close()
    yield


app = FastAPI(lifespan=lifespan)


def get_db():
    db = connect()
    try:
        yield db
    finally:
        db.close()


def get_current_user(authorization: str = Header(default="")) -> str:
    token = authorization.removeprefix("Bearer ")
    if token not in DEMO_TOKENS:
        raise HTTPException(401, "authentication required")
    return DEMO_TOKENS[token]


def load_own_file(file_id: str, user: str, db: sqlite3.Connection):
    row = db.execute("SELECT * FROM stored_files WHERE id = ?", (file_id,)).fetchone()
    if row is None or row["owner_id"] != user:
        # Same answer for "missing" and "not yours": do not confirm the ID exists.
        raise HTTPException(404, "file not found")
    return row


class PresignRequest(BaseModel):
    content_type: str = Field(pattern=r"^(image/(jpeg|png)|application/pdf)$")


@app.post("/files/presign-upload")
def presign_upload(
    req: PresignRequest,
    user: str = Depends(get_current_user),
    db: sqlite3.Connection = Depends(get_db),
    s3=Depends(get_s3),
):
    file_id = uuid.uuid4().hex
    # The server picks the key; the extension comes from the allowed type.
    key = f"documents/{file_id}.{EXTENSIONS[req.content_type]}"
    db.execute(
        "INSERT INTO stored_files VALUES (?, ?, ?, ?, NULL, NULL, 'pending')",
        (file_id, user, key, req.content_type),
    )
    db.commit()
    ticket = s3.generate_presigned_post(
        Bucket=BUCKET,
        Key=key,
        Fields={"Content-Type": req.content_type},
        Conditions=[
            {"Content-Type": req.content_type},
            ["content-length-range", MIN_BYTES, MAX_BYTES],
        ],
        ExpiresIn=600,
    )
    return {"file_id": file_id, "upload": ticket}


def post_process(file_id: str) -> None:
    # Lesson 04 replaces this with a queued job that sniffs and scans the bytes.
    db = connect()
    db.execute(
        "UPDATE stored_files SET status = 'ready'"
        " WHERE id = ? AND status = 'scanning'",
        (file_id,),
    )
    db.commit()
    db.close()


@app.post("/files/{file_id}/complete")
def complete_upload(
    file_id: str,
    jobs: BackgroundTasks,
    user: str = Depends(get_current_user),
    db: sqlite3.Connection = Depends(get_db),
    s3=Depends(get_s3),
):
    row = load_own_file(file_id, user, db)
    if row["status"] != "pending":
        raise HTTPException(409, f"file is already {row['status']}")
    try:
        head = s3.head_object(Bucket=BUCKET, Key=row["storage_key"])
    except Exception:  # botocore ClientError 404 when nothing was uploaded
        raise HTTPException(409, "object has not been uploaded") from None
    size, ctype = head["ContentLength"], head["ContentType"]
    if not MIN_BYTES <= size <= MAX_BYTES or ctype != row["content_type"]:
        db.execute("UPDATE stored_files SET status='rejected' WHERE id=?", (file_id,))
        db.commit()
        raise HTTPException(422, "stored object does not match the ticket")
    # Record the ETag: the ticket stays valid for a while, so the owner could
    # overwrite the object after this check. Later steps compare the ETag.
    db.execute(
        "UPDATE stored_files SET status = 'scanning', size = ?, etag = ? WHERE id = ?",
        (size, head["ETag"], file_id),
    )
    db.commit()
    jobs.add_task(post_process, file_id)
    return {"file_id": file_id, "status": "scanning"}


@app.get("/files/{file_id}/download")
def download_url(
    file_id: str,
    user: str = Depends(get_current_user),
    db: sqlite3.Connection = Depends(get_db),
    s3=Depends(get_s3),
):
    row = load_own_file(file_id, user, db)  # authorise before signing
    if row["status"] != "ready":
        raise HTTPException(409, f"file is {row['status']}")
    if s3.head_object(Bucket=BUCKET, Key=row["storage_key"])["ETag"] != row["etag"]:
        raise HTTPException(409, "object changed after it was verified")
    url = s3.generate_presigned_url(
        "get_object",
        Params={
            "Bucket": BUCKET,
            "Key": row["storage_key"],
            "ResponseContentDisposition": "attachment",
        },
        ExpiresIn=300,
    )
    return {"download_url": url, "expires_in": 300}

04. Step 2: negative tests for authorisation and verification

Security rules need tests that try to break them. The fake S3 client below records what would be signed, so the tests run without Docker. They check that anonymous calls get 401, that another user gets 404 and no signed URL, that /complete refuses a missing or oversized object, that an object replaced after the check cannot be downloaded, and that the key extension ignores the client filename.

Python · test_files_api.py
import pytest
from fastapi.testclient import TestClient

import files_api

ALICE = {"Authorization": "Bearer alice-token"}
BOB = {"Authorization": "Bearer bob-token"}


class FakeS3:
    """Records what would be signed; no storage server or boto3 needed."""

    def __init__(self):
        self.objects = {}

    def generate_presigned_post(self, Bucket, Key, Fields, Conditions, ExpiresIn):
        return {"url": f"http://s3.test/{Bucket}", "fields": {"key": Key, **Fields}}

    def head_object(self, Bucket, Key):
        if Key not in self.objects:
            raise KeyError(Key)
        return self.objects[Key]

    def generate_presigned_url(self, method, Params, ExpiresIn):
        return f"http://s3.test/{Params['Bucket']}/{Params['Key']}?X-Amz-Signature=x"


@pytest.fixture
def client(tmp_path, monkeypatch):
    monkeypatch.setattr(files_api, "DB_PATH", str(tmp_path / "files.db"))
    fake = FakeS3()
    files_api.app.dependency_overrides[files_api.get_s3] = lambda: fake
    with TestClient(files_api.app) as c:
        c.fake = fake
        yield c
    files_api.app.dependency_overrides.clear()


def store(client, key, size, etag='"etag-1"'):
    obj = {"ContentLength": size, "ContentType": "application/pdf", "ETag": etag}
    client.fake.objects[key] = obj  # what the direct upload would have stored


def upload_ready_file(client, size=48_201):
    body = {"content_type": "application/pdf"}
    ticket = client.post("/files/presign-upload", json=body, headers=ALICE).json()
    key = ticket["upload"]["fields"]["key"]
    store(client, key, size)
    done = client.post(f"/files/{ticket['file_id']}/complete", headers=ALICE)
    return ticket["file_id"], key, done


def test_anonymous_requests_get_401(client):
    body = {"content_type": "application/pdf"}
    assert client.post("/files/presign-upload", json=body).status_code == 401
    assert client.get("/files/abc/download").status_code == 401


def test_key_extension_comes_from_type_not_filename(client):
    body = {"content_type": "image/png", "filename": "evil.html"}
    ticket = client.post("/files/presign-upload", json=body, headers=ALICE).json()
    assert ticket["upload"]["fields"]["key"].endswith(".png")


def test_owner_can_download_once_ready(client):
    file_id, key, done = upload_ready_file(client)
    assert done.json() == {"file_id": file_id, "status": "scanning"}
    resp = client.get(f"/files/{file_id}/download", headers=ALICE)
    assert resp.status_code == 200
    assert key in resp.json()["download_url"]


def test_other_user_gets_404_and_no_signed_url(client):
    file_id, _, _ = upload_ready_file(client)
    resp = client.get(f"/files/{file_id}/download", headers=BOB)
    assert resp.status_code == 404
    assert "download_url" not in resp.json()
    assert client.post(f"/files/{file_id}/complete", headers=BOB).status_code == 404


def test_complete_before_upload_is_refused(client):
    body = {"content_type": "application/pdf"}
    ticket = client.post("/files/presign-upload", json=body, headers=ALICE).json()
    resp = client.post(f"/files/{ticket['file_id']}/complete", headers=ALICE)
    assert resp.status_code == 409


def test_oversized_object_is_rejected(client):
    file_id, _, done = upload_ready_file(client, size=files_api.MAX_BYTES + 1)
    assert done.status_code == 422
    resp = client.get(f"/files/{file_id}/download", headers=ALICE)
    assert resp.status_code == 409


def test_object_replaced_after_check_is_refused(client):
    file_id, key, _ = upload_ready_file(client)
    store(client, key, 50_000, etag='"etag-2"')  # re-POST with the same ticket
    resp = client.get(f"/files/{file_id}/download", headers=ALICE)
    assert resp.status_code == 409
Python · test_concurrency.py
import socket
import threading
import time
from concurrent.futures import ThreadPoolExecutor

import httpx
import uvicorn

import files_api
from test_files_api import ALICE, FakeS3


def test_concurrent_requests_do_not_fail(tmp_path, monkeypatch):
    # A real server, so FastAPI runs dependencies in its thread pool as in production
    monkeypatch.setattr(files_api, "DB_PATH", str(tmp_path / "files.db"))
    fake = FakeS3()
    files_api.app.dependency_overrides[files_api.get_s3] = lambda: fake
    with socket.socket() as s:
        s.bind(("127.0.0.1", 0))
        port = s.getsockname()[1]
    config = uvicorn.Config(files_api.app, port=port, log_level="warning")
    server = uvicorn.Server(config)
    thread = threading.Thread(target=server.run, daemon=True)
    thread.start()
    while not server.started:
        time.sleep(0.05)
    url = f"http://127.0.0.1:{port}/files/presign-upload"

    def presign(_):
        body = {"content_type": "application/pdf"}
        # httpx waits 5 s by default; a writer may wait 10 s for the SQLite lock
        return httpx.post(url, json=body, headers=ALICE, timeout=30).status_code

    try:
        with ThreadPoolExecutor(max_workers=8) as pool:
            codes = list(pool.map(presign, range(200)))
    finally:
        server.should_exit = True
        thread.join()
        files_api.app.dependency_overrides.clear()
    assert codes.count(200) == 200, {c: codes.count(c) for c in set(codes)}
Illustrative output of `pytest -q` for both test files (the time varies)
$ pytest -q
........                                                                 [100%]
8 passed in 5.95s

The second test file starts the app under a real Uvicorn server and sends 200 presign requests from 8 threads. TestClient runs one request at a time, so it cannot show thread problems. Without check_same_thread=False, this test fails with sqlite3.ProgrammingError: SQLite objects created in a thread can only be used in that same thread.

To see that the ownership test has teeth, change if row is None or row["owner_id"] != user: to if row is None: and run pytest again. test_other_user_gets_404_and_no_signed_url fails, because Bob now receives a signed link to Alice's file. Restore the line before you continue.

05. Step 3: end-to-end run against the storage server

Start the API with fastapi dev files_api.py (it listens on port 8000), then in a second terminal run the client below. Any PDF of 10 MB or less works; the run below used a 48,201-byte test file made with python -c "open('sample.pdf', 'wb').write(b'%PDF-1.4\n' + b'0' * 48192)".

The client posts the policy fields first and the file last. S3-compatible servers read form fields in order and expect the file to be the final field. A successful POST returns 204 No Content by default. The client then completes the upload, waits for the background job, downloads through the presigned GET URL, and finally asks for the same file as Bob.

Python · upload_client.py
import sys
import time

import httpx

API = "http://localhost:8000"
ALICE = {"Authorization": "Bearer alice-token"}
BOB = {"Authorization": "Bearer bob-token"}

body = {"content_type": "application/pdf"}
ticket = httpx.post(f"{API}/files/presign-upload", json=body, headers=ALICE).json()
file_id, upload = ticket["file_id"], ticket["upload"]
with open(sys.argv[1], "rb") as f:
    # httpx sends the policy fields first and the file last, as S3 requires
    sent = httpx.post(upload["url"], data=upload["fields"], files={"file": f})
print("upload to storage:", sent.status_code)
done = httpx.post(f"{API}/files/{file_id}/complete", headers=ALICE).json()
print("complete:", done["status"])
for _ in range(20):  # wait for the background job to mark the file ready
    resp = httpx.get(f"{API}/files/{file_id}/download", headers=ALICE)
    if resp.status_code != 409:
        break
    time.sleep(0.25)
print("alice download:", resp.status_code)
got = httpx.get(resp.json()["download_url"])  # a GET URL is signed for GET only
print("presigned GET:", got.status_code, len(got.content), "bytes")
other = httpx.get(f"{API}/files/{file_id}/download", headers=BOB)
print("bob download:", other.status_code, other.json())
Expected output (SeaweedFS 4.51, the 48,201-byte sample.pdf)
$ python upload_client.py sample.pdf
upload to storage: 204
complete: scanning
alice download: 200
presigned GET: 200 48201 bytes
bob download: 404 {'detail': 'file not found'}

06. Check your understanding

Practice check · 3 questions

Presigned URLs and authorisation

Three questions on the decisions in this lab.

Q1. In this lab, `GET /files/{id}/download` answers 404 when the file exists but belongs to another user. Why not 403?
Q2. Why does `presign_upload` build the storage key from a UUID and the allowed content type, instead of from the filename the client sent?
Q3. Alice gets a download URL signed with `ExpiresIn=300` and pastes it into a group chat two minutes later. What happens?
Practice only: not graded, not saved, not evidence.

07. Apply it

Extend the lab towards the skill project:

  • Replace get_current_user with the real authentication from your app, and keep the 401 and 404 tests.
  • Add a per-user quota check in presign_upload, counting pending, scanning and ready rows.
  • Add a scheduled clean-up that deletes pending rows and objects older than 24 hours, plus a bucket lifecycle rule that aborts incomplete multipart uploads after a few days.
  • Configure CORS on the bucket for your front-end origin and try the upload from a browser form.

In the next lesson the post_process stub becomes a queued job that checks the real file type and scans it before the file becomes ready.

08. Review prompt

Without looking back, draw the four steps of the flow and the status of the database row after each one. Explain why presigned POST can enforce a size range when presigned PUT cannot, what the server must check before it signs a download URL, and why the /complete step reads the object's metadata from storage instead of trusting the client.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

6 questions · about 5 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check