Limit file size when uploading to Cloud Storage

Radu Diță
2 min readMar 28, 2021

--

When using Google Cloud there are cases when you want to save files to Cloud Storage.

If the files are provided by end users you usually end up with allowing them to upload file directly to Cloud Storage without going thru your server.

This lowers the load on your backend, but opens up an exploitable route for your service: users can now abuse this route to upload any kind of files or (almost) arbitrary size.

Signed URLs

Google Cloud offers signed urls to solve this issue.

Signed URLs offer a way to limit what an end user can upload to your Cloud Storage. The way this works is by signing the HTTP headers and sending this signature to the frontend.

Because Google Cloud needs to identify you as having access to upload to Cloud Storage you need to provide sensitive information to it. This is why you should do the signing on the Backend and return the signed URL to the Frontend.

If an upload is attempted with headers that differ from the signed ones the signatures will not match and Google Cloud will reject the upload.

Limiting file size

For uploading the file size upload you need to sign the content-length HTTP header.

By signing this header you lock-in the size of the file. Trying to upload a file with a different size will get rejected by Google Cloud as the signatures will not match.

Before signing the request you should check the size of the file and reject any attempt to upload a file that is larger than the desired max size.

The code

The following code is written in TS.

Final notes

By signing content-length you are limiting the size as Google Cloud will honour this value.

Even if an attacker will try to set content-length to the same size, but then try to upload a larger file Google Cloud will check for the size and interrupt the upload.

Trying to use X-Upload-Content-Length header will not have the same result. As an attacker can upload a file with a larger size, use the same value for X-Upload-Content-Length and Google Cloud will not check the real size of the file and allow for the upload.

--

--

Responses (2)