Accept file uploads to S3 with presigned URLs
Let a client upload with a presigned URL into an encrypted, versioned bucket with a lifecycle rule, and prove who can read it.
By Invicly Tech, , in AWS Cloud Engineering. About 11 minutes to read.
In short
A presigned URL lets a browser or phone upload one file straight to S3 without ever holding AWS credentials. Your backend signs the URL with its own role, the client sends a PUT to it, and the bucket stays private, encrypted and versioned. A lifecycle rule then cleans up old versions and half-finished uploads so storage costs do not creep up.
Think of it like this: A presigned URL is a single-use delivery slip: the courier can drop off one named parcel at the warehouse before it expires, but cannot open any other shelf.
Explained simply
Amazon S3 stores files, which it calls objects, inside buckets. Each object has a key, which looks like a file path such as uploads/user-42/report.pdf. In our sample service, users upload files that a worker later processes, so the bucket is the front door of the whole system.
You do not want users to have AWS keys, and you do not want every upload to pass through your server. A presigned URL solves both. Your backend asks the AWS SDK to sign a URL for one PUT on one key. The client sends the file to that URL, directly to S3, before it expires.
The bucket itself stays private. Block Public Access stops anyone from accidentally making it public, a bucket policy can insist on HTTPS, and every object is encrypted at rest. Versioning keeps older copies when a file is overwritten or deleted, which saves you from mistakes.
Old versions and abandoned uploads still cost money, so a lifecycle rule tidies up. It can delete noncurrent versions after 30 days, abort unfinished multipart uploads after 7 days, or move old files to a cheaper storage class. Finally you test access: a stranger is refused, your app is allowed.
Press Play on a diagram to walk through it one step at a time.
- Client to Your API: Ask to upload report.pdf1Ask to upload report.pdf
- 2Check the user, pick key uploads/{user}/{uuid}.pdfYour API to Your API: Check the user, pick key uploads/{user}/{uuid}.pdf
- Your API to Client: Return presigned PUT URL, valid 5 minutes3Return presigned PUT URL, valid 5 minutes
- Client to Amazon S3: PUT file bytes to the URL4PUT file bytes to the URL
- 5Check signature, encrypt and store new versionAmazon S3 to Amazon S3: Check signature, encrypt and store new version
- Amazon S3 to Client: 200 OK with ETag6200 OK with ETag
- Filter
- Prefix such as uploads/
- Object tags
- Object size range
- Transition
- Standard-IA after 30+ days
- Glacier classes for archives
- Expire current
- Delete after N days
- Adds delete marker if versioned
- Expire noncurrent
- Remove old versions after N days
- Optionally keep the newest few
- Clean up
- Abort incomplete multipart uploads
- Remove expired delete markers
In depth
What a presigned URL really contains
A presigned URL is a normal S3 URL plus query parameters created by Signature Version 4: the access key ID, the date, the expiry in seconds, the signed headers and the signature. S3 recomputes the signature when the request arrives. If the method, key, signed headers or time window do not match, S3 returns 403. The URL can never do more than the identity that signed it, so sign with a role that may only call s3:PutObject on the uploads/ prefix. The longest expiry with Signature Version 4 is 7 days, but a URL signed with temporary role credentials stops working when those credentials expire. Keep upload URLs short, such as 5 to 15 minutes. Note that the AWS CLI command aws s3 presign only creates GET URLs; for uploads use an SDK method such as generate_presigned_url with put_object, or a presigned POST, which can also limit file size.
- Server chooses the key, never the client
- Sign the Content-Type you expect
- Use presigned POST to cap file size with content-length-range
- Short expiry, minutes not days
Layers of protection on the bucket
Think of bucket security as several independent locks. Block Public Access is the outer lock: with all four settings on, S3 ignores public ACLs and rejects public bucket policies. New buckets have it on by default, and they also default to the bucket owner enforced setting, which turns ACLs off so only policies decide access. The bucket policy is the next lock. A common pattern denies any request where aws:SecureTransport is false, forcing HTTPS. The IAM policy on your app role grants only the actions it needs on the prefixes it uses. Encryption at rest happens automatically with SSE-S3; switching the default to SSE-KMS adds a key policy and CloudTrail records of key use, at extra request cost. Each lock covers a different mistake, which is why you keep all of them.
- 1Block Public Access
Overrides anything that would make data public
- 2Bucket policy
Deny non-HTTPS, limit to your account or VPC endpoint
- 3IAM policy on the caller
App role may PutObject on uploads/ only
- 4KMS key policy
Only when the bucket uses SSE-KMS
- 5Object
Encrypted at rest, versioned
Versioning and what delete really means
When versioning is on, every write creates a new version ID. Overwriting report.pdf keeps the old bytes as a noncurrent version. A plain DELETE does not remove data at all; it adds a delete marker that hides the object. To recover, you delete the delete marker or copy an older version back. Only a DELETE that names a specific version ID removes bytes for good. Once enabled, versioning cannot be turned off, only suspended, so plan for it. Without a lifecycle rule, noncurrent versions pile up forever and you pay for each one. The usual answer is a rule that expires noncurrent versions after a set number of days and removes expired delete markers.
- Overwrite: new version, old one becomes noncurrent
- Delete: adds a delete marker
- Delete with versionId: permanent
- Versioning can be suspended, not disabled
Writing a sensible lifecycle rule
A lifecycle configuration is a list of rules, each with a filter (a prefix, tags or object size) and actions. Transition actions move objects to cheaper classes such as S3 Standard-IA or S3 Glacier Flexible Retrieval; objects must be at least 30 days old before moving to Standard-IA. Expiration actions delete current objects, noncurrent versions or expired delete markers. AbortIncompleteMultipartUpload removes parts of uploads that never finished, which are invisible in normal listings but still billed. Cheaper classes have minimum storage durations and retrieval charges, so moving small or short-lived files can cost more, not less. For an uploads bucket where files are processed within minutes, expiring raw uploads after a few weeks is often simpler than transitions.
Learn it in 5 short steps
About 35m each. Track them with a timer in your plan.
- 1Generate a presigned upload URL~35m
- 2Block public access~35m
- 3Write a bucket policy~35m
- 4Turn on versioning and encryption~35m
- 5Add a lifecycle rule~35m
Key points
- The URL carries the signer's permissions, limited to one bucket, key, method and expiry.
- Block Public Access and the bucket owner enforced setting are on by default for new buckets; keep them on.
- Every new object is encrypted at rest with SSE-S3 by default; choose SSE-KMS when you need key-level audit and control.
- Versioning keeps overwritten and deleted objects as noncurrent versions, so pair it with a lifecycle rule.
- Prove access by testing: an anonymous GET must fail, and the app role must succeed.
Key terms
Tap a card to flip it. 0/5 known
Examples
import boto3, uuid
s3 = boto3.client("s3")
key = f"uploads/user-42/{uuid.uuid4()}.pdf"
url = s3.generate_presigned_url(
"put_object",
Params={"Bucket": "invicly-lab-uploads", "Key": key, "ContentType": "application/pdf"},
ExpiresIn=300, # seconds
)
print(url)
# client: curl -X PUT -H "Content-Type: application/pdf" --upload-file report.pdf "$URL"The client must send the same Content-Type that was signed, or S3 rejects the request.
Lock down a new uploads bucket from the CLI
Prerequisites: a sandbox account with a budget alert and an AWS CLI profile. Step 1: create the bucket. Step 2: make sure all four Block Public Access settings are on. Step 3: enable versioning. Step 4: apply a lifecycle file that expires noncurrent versions after 30 days and aborts incomplete multipart uploads after 7 days. Evidence: get-bucket-versioning prints Status Enabled and get-bucket-lifecycle-configuration echoes your rule. S3 storage for a few test files costs cents, but delete the bucket afterwards.
B=invicly-lab-uploads-<account-id>
aws s3api create-bucket --bucket $B --region eu-west-1 \
--create-bucket-configuration LocationConstraint=eu-west-1
aws s3api put-public-access-block --bucket $B --public-access-block-configuration \
BlockPublicAcls=true,IgnorePublicAcls=true,BlockPublicPolicy=true,RestrictPublicBuckets=true
aws s3api put-bucket-versioning --bucket $B --versioning-configuration Status=Enabled
aws s3api put-bucket-lifecycle-configuration --bucket $B \
--lifecycle-configuration file://lifecycle.json
aws s3api get-bucket-versioning --bucket $B
# cleanup: aws s3 rm s3://$B --recursive, delete versions, then aws s3api delete-bucketProve who can read an uploaded file
Upload a test file through a presigned URL, then check access three ways. First, a plain curl to the object's https URL without a signature should return 403 AccessDenied. Second, the app role (or your admin profile) should read it with aws s3api head-object and see ServerSideEncryption in the output. Third, IAM Access Analyzer for S3 in the console should report no public or cross-account access for the bucket. Write the three results down; that record is the evidence a reviewer wants.
curl -s -o /dev/null -w "%{http_code}\n" \
https://invicly-lab-uploads-<account-id>.s3.eu-west-1.amazonaws.com/uploads/test.pdf
# expect 403
aws s3api head-object --bucket invicly-lab-uploads-<account-id> --key uploads/test.pdf
# expect ServerSideEncryption and a VersionIdQuick reference
- aws s3 presign makes GET URLs only; use an SDK put_object URL or presigned POST for uploads
- SigV4 presigned URLs last at most 7 days, and never longer than the signer's credentials
- New buckets: Block Public Access on, ACLs disabled, SSE-S3 encryption by default
- Deny requests where aws:SecureTransport is false to force HTTPS
- Versioned delete adds a delete marker; delete with versionId to remove bytes
- Always add AbortIncompleteMultipartUpload and noncurrent version expiration rules
- Standard-IA transitions need objects at least 30 days old
Common mistakes
- Signing with a role session: the URL stops working when that session's credentials expire, even if ExpiresIn is longer.
- Letting the client choose the object key, which allows overwriting other users' files.
- Turning on versioning without a noncurrent-version expiration rule, so deleted files keep costing money.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Write a lifecycle.json that, for the uploads/ prefix, expires noncurrent versions after 30 days and aborts incomplete multipart uploads after 7 days.
- Exercise 2medium
Write a bucket policy statement that denies every request made over plain HTTP to the bucket and its objects.
- Exercise 3hard
Write a small Python function that returns a presigned POST for one user, limits the file to 10 MB, fixes the key under that user's prefix and expires in 5 minutes.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- Is S3 encrypted by default?
- Yes. Since January 2023 every new object is encrypted at rest with SSE-S3 unless you choose another option such as SSE-KMS.
- Can I make a presigned URL that never expires?
- No. With Signature Version 4 the longest expiry is 7 days, and temporary credentials can make it shorter. Generate a fresh URL when the client needs one.
- Do I need a public bucket to let users upload?
- No. Presigned URLs work on private buckets, and keeping the bucket private is the whole point.
- Can I try this without paying?
- S3 for a handful of small test files costs very little, but it is not zero. For a fully local practice run, an S3-compatible emulator lets you test the presign flow; check its licence terms first.