Subscribe

Reading S3 objects in golang without trusting the size check

A HeadObject size check followed by a GetObject is a race: the object can be replaced with a huge one in between. Here is how I read S3 objects in Go with io.LimitReader and one extra byte, so the cap holds no matter what the size check said.

Reading S3 objects in golang without trusting the size check

We built a feature at work where users upload documents, mostly PDFs, straight to S3 with a presigned PUT URL. The API never sees the bytes during the upload. Afterwards the app calls a "confirm" endpoint, and the backend has to look at the object: check it isn't too big, hash it, look for duplicates, process it.

The obvious way to check the size is HeadObject, compare ContentLength with your limit, then GetObject and io.ReadAll. That has a hole in it. In this blog we will look at the hole, and the few lines of Go that close it.

Why the size check is not enough

See, the problem here is that a presigned PUT URL is not single use. It works for anyone holding it until it expires. So a client can upload a small file, call confirm, and while your server is between the HEAD and the GET, PUT a much bigger file to the same key. Your HEAD said 40 KB. Your io.ReadAll then reads whatever is there now.

It doesn't even need to be malicious. A retry loop in the app that uploads twice gives you the same race, just with less exciting sizes.

I wanted to see it fail for real and not just reason about it, so I wrote a tiny fake S3 server with httptest and pointed the real AWS SDK for Go v2 at it (service/s3 v1.116.0, Go 1.27.3). The fake lets the test swap the object, like a second PUT would.

func naiveRead(ctx context.Context, c *s3.Client, bucket, key string, between func()) ([]byte, error) {
    head, err := c.HeadObject(ctx, &s3.HeadObjectInput{Bucket: aws.String(bucket), Key: aws.String(key)})
    if err != nil {
        return nil, err
    }
    if aws.ToInt64(head.ContentLength) > maxBytes {
        return nil, ErrTooLarge
    }
    between() // the test swaps the object here
    out, err := c.GetObject(ctx, &s3.GetObjectInput{Bucket: aws.String(bucket), Key: aws.String(key)})
    if err != nil {
        return nil, err
    }
    defer out.Body.Close()
    return io.ReadAll(out.Body)
}

With a 10 MiB limit and a 50 MiB swap:

=== RUN   TestNaiveReadTrustsAStaleSize
    limit_test.go:96: naive read passed the size check and then read 52428800 bytes
--- PASS: TestNaiveReadTrustsAStaleSize (0.03s)

Size check passed, 50 MiB went into memory. Now picture 5 GB, which is the most a single PUT allows, on a container with 512 MB of memory.

Reading with a cap

The fix is to make the read itself enforce the limit. io.LimitReader stops after N bytes. The trick is to ask for one byte more than the limit:

var ErrTooLarge = errors.New("s3limit: object is larger than the limit")

// ReadAtMost reads r fully but never keeps more than max+1 bytes. The extra
// byte is how we tell "exactly max" apart from "more than max".
func ReadAtMost(r io.Reader, max int64) ([]byte, error) {
    data, err := io.ReadAll(io.LimitReader(r, max+1))
    if err != nil {
        return nil, err
    }
    if int64(len(data)) > max {
        return nil, ErrTooLarge
    }
    return data, nil
}

If you limit to exactly max instead, you can't tell a file of exactly max bytes from a bigger file that got cut. Both give you max bytes. I put that in a test to be sure I wasn't imagining it:

=== RUN   TestLimitWithoutPlusOne
    limit_test.go:159: size 10485760: copied 10485760, n == max is true
    limit_test.go:159: size 10485761: copied 10485760, n == max is true

Same count for both. So code that limits to max and then checks n == max either rejects a legal file of exactly max bytes, or (worse) treats a truncated big file as complete. It's actually an easy one to write by accident, the code looks correct at a glance.

Wrapping GetObject

Now S3 side. I use a one-method interface so tests can use a fake or a real client:

type GetObjectAPI interface {
    GetObject(ctx context.Context, in *s3.GetObjectInput, opts ...func(*s3.Options)) (*s3.GetObjectOutput, error)
}

func GetLimited(ctx context.Context, api GetObjectAPI, bucket, key, etag string, max int64) ([]byte, error) {
    in := &s3.GetObjectInput{Bucket: aws.String(bucket), Key: aws.String(key)}
    if etag != "" {
        in.IfMatch = aws.String(etag)
    }
    out, err := api.GetObject(ctx, in)
    if err != nil {
        return nil, err
    }
    defer out.Body.Close()

    // Cheap early exit. This is the length of the object we are reading
    // right now, so it can't be stale, but it can be missing.
    if out.ContentLength != nil && *out.ContentLength > max {
        return nil, ErrTooLarge
    }
    return ReadAtMost(out.Body, max)
}

The ContentLength on the GET response is fine to use as a fast path, because it belongs to the same response you are reading. It just can't be the only check. When I made the fake server send the body chunked, with no Content-Length header, the SDK gave me a nil ContentLength:

=== RUN   TestChunkedContentLength
    cl_test.go:22: ContentLength nil=true

Real S3 sends the header, but proxies, S3 compatible stores and test doubles don't always do it. The LimitReader doesn't care either way, and the chunked 50 MiB test still came back with ErrTooLarge.

If-Match, when you did check something

Sometimes you really do want to HEAD first, for example to read metadata before deciding anything. Then pass the ETag you saw as IfMatch on the GET. If the object changed in between, S3 refuses with 412 and you don't get the new bytes at all:

var apiErr smithy.APIError
if errors.As(err, &apiErr) && apiErr.ErrorCode() == "PreconditionFailed" {
    // the object changed after we looked at it, ask the client to confirm again
}

My test swaps the object after the HEAD and gets back code=PreconditionFailed. Keep the cap anyway. If-Match protects you from a changed object, it doesn't protect you from an object that was too big from the start.

Streaming to disk instead of memory

For files you don't want in memory at all, the same idea works with io.Copy. I hash on the way through so the duplicate check doesn't need a second read:

func CopyAtMost(w io.Writer, r io.Reader, max int64) (int64, string, error) {
    h := sha256.New()
    n, err := io.Copy(io.MultiWriter(w, h), io.LimitReader(r, max+1))
    if err != nil {
        return n, "", err
    }
    if n > max {
        return n, "", ErrTooLarge
    }
    return n, hex.EncodeToString(h.Sum(nil)), nil
}

When it returns ErrTooLarge, delete the temp file. Writing max+1 bytes to disk before you give up is the price, and it's a fixed price.

Read once, keep that copy

This is the part people miss. After the confirm step reads the object, the presigned URL may still be valid for a few more minutes. If later processing downloads the object again, it can get a different file than the one you checked and hashed.

In our confirm step itself the backend reads the staging object once through the cap and hashes that copy. Then it writes those same bytes to a final key that no presigned URL points at, and deletes the staging object. A later PUT to the staging key changes nothing, nobody reads it again.

You can also shrink the window on the upload side. A presigned PUT can pin the size the client said it would send. With the v2 SDK you set ContentLength on the input and it becomes a signed header:

ps := s3.NewPresignClient(client)
req, err := ps.PresignPutObject(ctx, &s3.PutObjectInput{
    Bucket:        aws.String("docs"),
    Key:           aws.String("u/1.pdf"),
    ContentType:   aws.String("application/pdf"),
    ContentLength: aws.Int64(48213),
}, s3.WithPresignExpires(15*time.Minute))
X-Amz-SignedHeaders=content-length;content-type;host

That stops a 5 GB swap through that URL. It doesn't stop a different file of the same size, so the read once rule still stands. The Bhavcopy post uses the same capped read for an HTTP download, where you trust the other side even less.

Running the tests

All of this runs offline, with no AWS account, since the client points at the httptest server:

func newClient(url string) *s3.Client {
    return s3.New(s3.Options{
        Region:       "ap-south-1",
        BaseEndpoint: aws.String(url),
        UsePathStyle: true,
        Credentials:  credentials.NewStaticCredentialsProvider("test", "test", ""),
    })
}
go test -v -count=1 ./...

That's it. Any time you see io.ReadAll(out.Body) on an S3 object that a user controls, put a LimitReader with max+1 in front of it.