Skip to content
Console

Upload files securely from the client

Why not upload files directly with a client SDK such as the JavaScript SDK?

  1. The ak / sk can easily be exposed by decompiling
  2. It is not flexible enough

Security recommendation: never deliver an ak / sk through an API

A better approach

The frontend can send a PUT request directly to the presigned link. The benefits are:

  1. More secure: the critical AccessKey and SecretKey are never leaked through exposed client code or decompilation;
  2. More flexible: explicitly specifying Content-Type and Content-Length prevents a cracked client from bypassing your business policy limits
  3. Low cost: the server delivers presigned links uniformly, so client developers only need to make a PUT HTTP request and do not have to learn and debug S3 SDKs in different languages (usage differs considerably between AWS SDK language versions).
  4. High performance: upload requests still go directly to Bitiful S4, with no relaying through your server.

How it works

The client sends a PUT request to putObject-presigned-url and completes the upload

The page script PUTs the local file to this link.

Presigned URL API

Bitiful has open-sourced a full-featured presigned API project that you can deploy locally. It is stateless, so you can quickly integrate it into your system as a microservice.

Github: https://github.com/bitiful/s3-presigned-api-server

Before running, set the environment variables S4_ACCESS_KEY and S4_SECRET_KEY (a sub-user's keys, which need write permission on the upload directory), and replace my-bucket with your bucket name. The server generates the object key; do not use the path sent by the client directly, to avoid overwriting other people's files.

# pip install boto3 flask
import os
import uuid

import boto3
from botocore.config import Config
from flask import Flask, request

app = Flask(__name__)
s3 = boto3.client(
    "s3",
    endpoint_url="https://s3.bitiful.net",
    region_name="cn-east-1",
    aws_access_key_id=os.environ["S4_ACCESS_KEY"],
    aws_secret_access_key=os.environ["S4_SECRET_KEY"],
    config=Config(signature_version="s3v4"),
)


@app.get("/s3_upload_url")
def get_upload_url():
    # Verify the login state here
    ext = os.path.splitext(request.args.get("filename", ""))[1].lower()
    key = f"uploads/{uuid.uuid4()}{ext}"
    url = s3.generate_presigned_url(
        "put_object",
        Params={"Bucket": "my-bucket", "Key": key},
        ExpiresIn=600,
    )
    return {"key": key, "url": url}

Frontend upload example

upload_demo.web.html
<!DOCTYPE html>
<html>
<body>
  <input type="file" id="file">
  <progress id="bar" max="1" value="0"></progress>
  <pre id="log"></pre>
  <script>
    const log = (text) => (document.getElementById("log").textContent = text);

    document.getElementById("file").addEventListener("change", async (event) => {
      const file = event.target.files[0];
      const res = await fetch(`/s3_upload_url?filename=${encodeURIComponent(file.name)}`);
      const { key, url } = await res.json();

      const xhr = new XMLHttpRequest();
      xhr.open("PUT", url);
      xhr.upload.onprogress = (e) => (document.getElementById("bar").value = e.loaded / e.total);
      xhr.onload = () => log(xhr.status === 200 ? `Upload complete: ${key}` : xhr.responseText);
      xhr.onerror = () => log("Network error, or request blocked by CORS");
      // Remove the type inferred by the browser so S4 detects it automatically
      xhr.send(file.slice(0, file.size, ""));
    });
  </script>
</body>
</html>

The script above strips the file's type before uploading, so the request carries no Content-Type and Bitiful's MIME auto-detection determines the type.

For multipart uploads of large files, retries, and cancellation, see Browser JavaScript. For app uploads, see Android and iOS / Swift.

Make uploads safer

MeasureHow
Shorten the validity periodWithin 10 minutes
Prevent replayAdd x-bitiful-max-requests=1 when signing so the link can be used successfully only once. See Request limits for presigned URLs
Limit the sizeSpecify ContentLength when signing; a mismatched actual size returns 403. For Node.js, see Browser JavaScript
Limit the typeSpecify ContentType when signing, and confirm it appears in the link's X-Amz-SignedHeaders. The client must then send the same Content-Type and can no longer use auto-detection
Limit the directoryGrant the sub-user that issues links access to the uploads/ directory only
Prevent overwritingUse random values in object keys
Limit originsConfigure CORS rules that allow only your own website