# Upload files securely from the client

> How to use presigned URLs to give clients secure, high-performance large-file uploads.

## 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

> **Warning**
>
> Security recommendation: never deliver an ak / sk through an API

## A better approach

### Generate a presigned link on the backend and deliver it through an API

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

### Generate a presigned upload link through a backend API: putObject-presigned-url

Your backend program (Go, Python, PHP, Node.js, and so on) calls the SDK to generate a presigned link that can only be used for PutObject, and returns it to the page script.

### 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**

> **Tip**
>
> 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>

### Examples of backend endpoints that generate PutObject presigned links in different languages

Before running, set the environment variables `S4_ACCESS_KEY` and `S4_SECRET_KEY` (a [sub-user's keys](https://docs.bitiful.com/en/bitiful-s4/handbook/access-keys.md), 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.

```python title="main.py"
# 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}
```

```javascript title="main.mjs"
// npm install express @aws-sdk/client-s3 @aws-sdk/s3-request-presigner
import { randomUUID } from "node:crypto";
import path from "node:path";
import express from "express";
import { PutObjectCommand, S3Client } from "@aws-sdk/client-s3";
import { getSignedUrl } from "@aws-sdk/s3-request-presigner";

const s3 = new S3Client({
  endpoint: "https://s3.bitiful.net",
  region: "cn-east-1",
  credentials: {
    accessKeyId: process.env.S4_ACCESS_KEY,
    secretAccessKey: process.env.S4_SECRET_KEY,
  },
  requestChecksumCalculation: "WHEN_REQUIRED",
});

const app = express();

app.get("/s3_upload_url", async (req, res) => {
  // Verify the login state here
  const ext = path.extname(String(req.query.filename ?? "")).toLowerCase();
  const Key = `uploads/${randomUUID()}${ext}`;
  const url = await getSignedUrl(
    s3,
    new PutObjectCommand({ Bucket: "my-bucket", Key }),
    { expiresIn: 600 },
  );
  res.json({ key: Key, url });
});

app.listen(8080);
```

```go title="main.go"
// go get github.com/aws/aws-sdk-go-v2/service/s3 github.com/aws/aws-sdk-go-v2/credentials
package main

import (
	"crypto/rand"
	"encoding/json"
	"log"
	"net/http"
	"os"
	"path"
	"strings"
	"time"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/credentials"
	"github.com/aws/aws-sdk-go-v2/service/s3"
)

func main() {
	client := s3.New(s3.Options{
		BaseEndpoint: aws.String("https://s3.bitiful.net"),
		Region:       "cn-east-1",
		Credentials: credentials.NewStaticCredentialsProvider(
			os.Getenv("S4_ACCESS_KEY"), os.Getenv("S4_SECRET_KEY"), ""),
	})
	presigner := s3.NewPresignClient(client)

	http.HandleFunc("GET /s3_upload_url", func(w http.ResponseWriter, r *http.Request) {
		// Verify the login state here
		ext := strings.ToLower(path.Ext(r.URL.Query().Get("filename")))
		key := "uploads/" + rand.Text() + ext
		req, err := presigner.PresignPutObject(r.Context(), &s3.PutObjectInput{
			Bucket: aws.String("my-bucket"),
			Key:    aws.String(key),
		}, s3.WithPresignExpires(10*time.Minute))
		if err != nil {
			http.Error(w, "Signing failed", http.StatusInternalServerError)
			return
		}
		w.Header().Set("Content-Type", "application/json")
		json.NewEncoder(w).Encode(map[string]string{"key": key, "url": req.URL})
	})
	log.Fatal(http.ListenAndServe(":8080", nil))
}
```

```php title="main.php"
<?php
// composer require aws/aws-sdk-php
require 'vendor/autoload.php';

$s3 = new Aws\S3\S3Client([
    'version'     => 'latest',
    'endpoint'    => 'https://s3.bitiful.net',
    'region'      => 'cn-east-1',
    'credentials' => [
        'key'    => getenv('S4_ACCESS_KEY'),
        'secret' => getenv('S4_SECRET_KEY'),
    ],
]);

// Verify the login state here
$ext = strtolower(pathinfo($_GET['filename'] ?? '', PATHINFO_EXTENSION));
$key = 'uploads/' . bin2hex(random_bytes(16)) . ($ext === '' ? '' : ".$ext");

$cmd = $s3->getCommand('PutObject', ['Bucket' => 'my-bucket', 'Key' => $key]);
$url = (string) $s3->createPresignedRequest($cmd, '+10 minutes')->getUri();

header('Content-Type: application/json');
echo json_encode(['key' => $key, 'url' => $url]);
```

```rust title="main.rs"
// [dependencies]
// actix-web = "4"
// serde = { version = "1.0", features = ["derive"] }
// serde_json = "1.0"
// anyhow = "1.0.75"
// aws-config = "1.3.0"
// aws-credential-types = { version = "1.2.0", features = ["hardcoded-credentials"] }
// aws-sdk-s3 = "1.25.0"
// aws-sdk-sts = "1.22.0"
// aws-smithy-types = { version = "1.1.8", features = ["rt-tokio"] }
// tokio = { version = "1.32.0", features = ["full"] }

use actix_web::{web, App, HttpResponse, HttpServer, Responder};
use aws_config::{BehaviorVersion, SdkConfig};
use aws_credential_types::{provider::SharedCredentialsProvider, Credentials};
use aws_sdk_s3::{config::Region, presigning::PresigningConfig, Client};
use std::time::Duration;

async fn get_upload_url(query: web::Query<serde_json::Value>) -> impl Responder {
    let key = query.get("key").and_then(|v| v.as_str()).unwrap_or("");
    let url = get_url(key);

    let response_data = serde_json::json!({ "url": url.await.unwrap_or("".to_string())});
    HttpResponse::Ok()
        .content_type("application/json") // Set the response Content-Type
        .json(response_data)
}

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    HttpServer::new(|| {
        App::new()
            .route("/s3_upload_url", web::get().to(get_upload_url))
    })
    .bind("127.0.0.1:8080")?
    .run()
    .await
}

async fn get_url(key: &str) -> anyhow::Result<String> {
    let client = Client::new(
        &SdkConfig::builder()
            .region(Region::new("cn-east-1"))
            .endpoint_url("https://s3.bitiful.net")
            .behavior_version(BehaviorVersion::v2023_11_09())
            .credentials_provider(SharedCredentialsProvider::new(Credentials::from_keys(
                "Sub-user AccessKey",
                "Sub-user SecretKey",
                None,
            )))
            .build(),
    );

    let request = client
        .put_object()
        .bucket("my-bucket")
        .key(key)
        .presigned(
            PresigningConfig::builder()
                .expires_in(Duration::from_secs(600))
        .build()?,
        )
        .await?;

    Ok(request.uri().to_string())
}
```

### Frontend upload example

```html title="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>
```

> **Tip**
>
> The script above strips the file's type before uploading, so the request carries no `Content-Type` and Bitiful's [MIME auto-detection](https://docs.bitiful.com/en/best-practice/auto-detect-mime.md) determines the type.

For multipart uploads of large files, retries, and cancellation, see [Browser JavaScript](https://docs.bitiful.com/en/developer/sdk/browser-demo/start-to-use.md). For app uploads, see [Android](https://docs.bitiful.com/en/developer/sdk/android-demo/start-to-use.md) and [iOS / Swift](https://docs.bitiful.com/en/developer/sdk/swift-demo/start-to-use.md).

### Make uploads safer

| Measure                     | How                                                                                                                                                                                                         |
| :-------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Shorten the validity period | Within 10 minutes                                                                                                                                                                                           |
| Prevent replay              | Add `x-bitiful-max-requests=1` when signing so the link can be used successfully only once. See [Request limits for presigned URLs](https://docs.bitiful.com/en/bitiful-s4/features/max-requests-limits.md) |
| Limit the size              | Specify `ContentLength` when signing; a mismatched actual size returns 403. For Node.js, see [Browser JavaScript](https://docs.bitiful.com/en/developer/sdk/browser-demo/start-to-use.md)                   |
| Limit the type              | Specify `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 directory         | Grant the sub-user that issues links access to the `uploads/` directory only                                                                                                                                |
| Prevent overwriting         | Use random values in object keys                                                                                                                                                                            |
| Limit origins               | Configure [CORS rules](https://docs.bitiful.com/en/bitiful-s4/handbook/cors.md) that allow only your own website                                                                                            |
