Sub topic 2
Presigned URLs and POST Policies: Granting Narrow, Short-Lived Access
Assume you know HTTP, browser JavaScript, one server-side language, and the basics of object storage such as Amazon S3. The goal is to keep large file bytes away from your API server while keeping authorization on your server.
Granting upload access
A presigned URL is a storage URL containing a temporary signature. Your API creates it after checking the authenticated user and requested object. The browser then uploads directly to storage. A presigned POST uses a signed form policy, which can constrain fields and file size.
import boto3
s3 = boto3.client("s3")
post = s3.generate_presigned_post(
Bucket="example-uploads",
Key="incoming/user-42/avatar.jpg",
Fields={"Content-Type": "image/jpeg"},
Conditions=[
{"Content-Type": "image/jpeg"},
["content-length-range", 1, 5 * 1024 * 1024],
],
ExpiresIn=300,
)Return only the URL and fields to the client. Keep the storage credentials private. Use unpredictable keys, narrow permissions, short expirations, and server-side ownership checks.
Validating and quarantining uploads
Validate at multiple boundaries:
- Enforce a maximum size in the policy and again after upload.
- Allowlist expected media types instead of trusting arbitrary
Content-Typevalues. - Inspect file signatures, sometimes called magic bytes, to compare content with the declared type.
- Store new objects in a quarantine prefix with private access.
- Scan them for malware before marking them available.
A failed scan should make the object inaccessible to viewers and should trigger cleanup or review.
Large and unreliable uploads
For large files, use multipart upload. The client divides the file into independently retryable parts. Each part has a number and an ETag. After all parts succeed, the server completes the upload with the recorded parts. Persist the upload ID and part status so a reconnect can resume rather than restart.
Asynchronous processing
Object-storage events can publish an upload-complete message to a queue. Workers consume that message, verify the object, scan it, and generate derived assets. Make workers idempotent: retrying the same event must not create conflicting records or publish unsafe files.
Image variants and modern formats
Workers can resize an original into several dimensions and encode WebP or AVIF variants. Store each variant under a content-addressed or versioned key. Record dimensions, format, and source identity in the database. Serve the smallest suitable variant and let the CDN cache immutable outputs.
Exercise
Why should a completed upload remain unavailable until validation and scanning finish?
Show answer
The client controls the upload contents and declared type, so the object is untrusted until checks and malware scanning succeed.