Sub topic 5
Presigned URLs and POST policies: granting narrow, short-lived access
This chapter assumes you know HTTP methods and headers, have a rough idea of how S3-style object storage works, and can read Python and browser JavaScript. It covers how your server can let a client write to one specific object without sharing your credentials.
The problem presigning solves
In a direct upload, the browser sends bytes straight to object storage. The storage service must still know the request is allowed. You can't put long-lived credentials in the browser, and you don't want to make the bucket publicly writable.
Presigning solves this. Your server uses its own credentials to compute a signature over the details of one request. It gives the client the signed result. The storage service recomputes the signature when the request arrives. If it matches and the request has not expired, the service accepts the request as if your server had sent it.
The client gets a capability, not an identity. That capability is limited to what was signed, and it stops working after a short time.
Two mechanisms: presigned PUT URLs and presigned POST policies
S3 and compatible stores offer two ways to grant upload access.
A presigned URL signs one specific request, such as a PUT to one key. The signature covers the method, the key, the expiry time, and any signed headers. The client sends the file as the request body.
A presigned POST policy signs a policy document instead. The policy lists conditions, such as an exact key, a content type, and a size range. The client submits a multipart/form-data form with the policy fields and the file.
| Property | Presigned PUT URL | Presigned POST policy |
|---|---|---|
| Request shape | `PUT` with the file as the body | `POST` with a multipart form |
| Size limit enforced by storage | No | Yes, with `content-length-range` |
| Constraints on key and headers | Fixed values only | Exact match, prefix match, or ranges |
| Fits a plain `<form>` | No | Yes |
| Typical use | Multipart upload parts, simple internal uploads | Untrusted user uploads |
The size row is the main reason to prefer POST policies for user content. A presigned PUT URL can't make the storage service reject an oversized body. You would find the oversized object afterward and have to delete it.
Creating a POST policy
This server code creates a policy that pins the key and content type, limits the size to 5 MiB, and expires after five minutes.
import boto3
s3 = boto3.client("s3")
post = s3.generate_presigned_post(
Bucket="example-uploads",
Key="incoming/3f2a9c/avatar.jpg",
Fields={"Content-Type": "image/jpeg"},
Conditions=[
{"Content-Type": "image/jpeg"},
["content-length-range", 1, 5 * 1024 * 1024],
],
ExpiresIn=300,
)
# Return post["url"] and post["fields"] to the client.Each part of this call narrows the grant:
Keyfixes the destination. The client can't overwrite another user's file or write outsideincoming/.FieldsandConditionswork as a pair.Fieldsare values that go into the form.Conditionsare rules that go into the signed policy. If you add a value toFieldsbut forget the matching condition, the storage service may reject the upload, or you may leave a field unconstrained. Keep them consistent.content-length-rangesets the minimum and maximum body size. The storage service rejects anything outside it with aEntityTooLargeorEntityTooSmallerror.ExpiresInis in seconds. Five minutes is enough for most single-request uploads.
The key should be generated by your server, not taken from the client. A random or hashed segment, as in 3f2a9c, prevents collisions and keeps user-supplied filenames out of storage paths. The next chapters on validation and key design explain why that matters.
Sending the upload from the browser
The client builds a form from the fields your server returned and appends the file.
async function upload(post, file) {
const form = new FormData();
for (const [name, value] of Object.entries(post.fields)) {
form.append(name, value);
}
form.append("file", file); // the file field must come last
const res = await fetch(post.url, { method: "POST", body: form });
if (!res.ok) {
throw new Error(`Upload failed with status ${res.status}`);
}
}Do not set the Content-Type header yourself. The browser must generate it, because it includes the multipart boundary string.
Common errors
Most failures with presigned uploads come from a small set of causes.
- The file field is not last. S3 ignores any form field that appears after
file. Missing signature fields then produce an access error that doesn't mention ordering. - The content type differs from the signed one. The condition is an exact match. If the browser reports
image/jpgor an empty string, the policy rejects the upload with a 403 status. Use the type your server signed, notfile.type, or return an error before signing if they differ. - The URL has expired. Clock skew counts too. If your server's clock is a few minutes off, a short expiry can fail immediately. Keep server clocks synchronized.
- CORS is not configured. A browser upload from your site's origin to the storage domain is a cross-origin request. The bucket needs a CORS rule that allows your origin, the
POSTorPUTmethod, and any headers you send. The error appears in the browser console as a CORS failure, not as an S3 error. - The signer lacks permission. A presigned request carries the permissions of whoever signed it. If the server role can't
s3:PutObjecton that key, the upload fails even though signing succeeded. Signing never checks permission. - Temporary credentials expire first. If your server signs with a role's temporary credentials, the presigned request stops working when those credentials expire, even if
ExpiresInis longer.
Design decisions
Before returning a presigned grant, your server should decide four things.
Who may upload. Authenticate the user and check any quota. Presigning is an authorization decision, so make it in your API, where you already have session and database context.
Where the file goes. Choose the key on the server, under a prefix such as incoming/ that is treated as untrusted. Later chapters cover moving files out of this prefix after validation and scanning.
How narrow the grant is. Use the shortest expiry that works for your slowest realistic client, and pin as much as you can: key, type, and size. A leaked URL is only as dangerous as what it permits. A grant that allows one 5 MiB JPEG to one key for five minutes is low risk.
How you learn the upload finished. The client saying "done" isn't proof. Treat the storage service's event notification as the source of truth, and have the client call your API only to update the interface. The post-upload pipeline chapter builds on this.
Presigned URLs are also bearer tokens. Anyone who holds the URL can use it until it expires. Don't log full URLs, and don't put them in analytics events or error reports.
Presigned URLs for download and for parts
The same mechanism signs reads. A presigned GET URL lets a user download a private object for a limited time. This is a simple form of delivery access control, and a later chapter compares it with CDN signed URLs and cookies.
Presigning also supports multipart uploads. For each part, your server signs an upload_part request, and the client sends the part to that URL. Each part is its own small grant, so a failed part can be retried with a fresh URL. The resumable uploads chapter uses this.
Exercise
A teammate uses a presigned PUT URL for avatar uploads and checks the file size in the browser before uploading. Why is this unsafe, and what would you change?
Show answer
Browser checks can be bypassed, and a presigned PUT URL gives the storage service no way to enforce a maximum body size. A user could send a file of any size to that key. Switch to a presigned POST policy with a content-length-range condition so the storage service rejects oversized bodies. Also pin the key and content type, and keep a short expiry.
Exercise
An upload works in a test script but fails from the browser with an error in the console about a cross-origin request, and no S3 error body is shown. What is the most likely cause?
Show answer
The bucket has no CORS rule that allows your site's origin and the POST method. The browser blocks the response before your code can read the S3 error. Add a CORS configuration for the bucket that allows your origin, the method, and the headers you send.