# Presigned URLs and S4 extension parameters

> Generate presigned URLs to grant temporary upload and download access, and use S4 extension parameters for request limits, per-connection rate limits, Simul-Transfer, and media processing.

A presigned URL embeds the authorization for a single operation in the link. Anyone who has the link can upload or download the specified object during its validity period without an AccessKey. It suits direct uploads and downloads from browsers and apps without relaying through your server.

## How it works

An AccessKey is used to compute a signature over "method + bucket + object key + query parameters + validity period", and the signature is placed in the URL together with the parameters. When S4 receives the request, it recomputes the signature and compares.

- Generation happens locally and makes no network requests.
- The link carries the same permissions as the sub-user that generated it. If the sub-user has no permission, the link can still be generated, but accessing it returns 403.
- After you delete the AccessKey or revoke the permissions, links generated with it stop working.
- Parameters cannot be modified. Every query parameter in the URL is part of the signature, and adding, removing, or changing any one returns `SignatureDoesNotMatch`.

## Validity period

Specified by `X-Amz-Expires` in seconds, up to 604800 seconds (7 days). A larger value returns 400 `AuthorizationQueryParametersError`; an expired link returns 403 `AccessDenied` with the message `Request has expired`.

For public access over a longer period, use [public read](https://docs.bitiful.com/en/bitiful-s4/handbook/public-read.md) or a [CDN](https://docs.bitiful.com/en/cdn/intro.md).

## Supported operations

| Method | Operation                                  | Notes                                                                             |
| ------ | ------------------------------------------ | --------------------------------------------------------------------------------- |
| GET    | Download an object                         | Supports Range, so multithreaded downloads and resumable downloads work           |
| HEAD   | Retrieve metadata                          | A link generated for GET can be used directly for HEAD requests                   |
| PUT    | Upload an object, upload a part            | For multipart uploads, `uploadId` and `partNumber` are also part of the signature |
| POST   | Create or complete a multipart upload      |                                                                                   |
| DELETE | Delete an object, abort a multipart upload | Issue these with care                                                             |

A link cannot be used with a different method. A link generated for GET cannot be used for PUT.

> **Note**
>
> Presigned links are not restricted by the bucket's [access control](https://docs.bitiful.com/en/bitiful-s4/handbook/anti-leech.md) lists or [original file protection](https://docs.bitiful.com/en/coreix/handbook/origin-protect.md); they are equivalent to access by a holder of the permissions.

## Generate a link

The functions below also support attaching S4 extension parameters. The example uses `x-bitiful-max-requests` to generate a link that can be used only once and is valid for 10 minutes.

```python title="Python (boto3)"
import boto3
from botocore.config import Config

s3 = boto3.client(
    "s3",
    endpoint_url="https://s3.bitiful.net",
    region_name="cn-east-1",
    aws_access_key_id="<AccessKey>",
    aws_secret_access_key="<SecretKey>",
    config=Config(signature_version="s3v4", s3={"addressing_style": "virtual"}),
)


def presign(operation, method, params, expires, extra=None):
    """operation looks like GetObject, and method looks like get_object."""
    event = f"before-sign.s3.{operation}"

    def add_query(request, **kwargs):
        request.params.update(extra or {})

    s3.meta.events.register(event, add_query, unique_id="extra-query")
    try:
        return s3.generate_presigned_url(method, Params=params, ExpiresIn=expires)
    finally:
        s3.meta.events.unregister(event, unique_id="extra-query")


download_url = presign(
    "GetObject", "get_object",
    {"Bucket": "my-bucket", "Key": "docs/report.pdf"},
    600, {"x-bitiful-max-requests": "1"},
)
upload_url = presign(
    "PutObject", "put_object",
    {"Bucket": "my-bucket", "Key": "uploads/a.png", "ContentType": "image/png"},
    600, {"x-bitiful-max-requests": "1"},
)
```

```javascript title="JavaScript (AWS SDK v3)"
import { S3Client, GetObjectCommand, PutObjectCommand } 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: "<AccessKey>", secretAccessKey: "<SecretKey>" },
  // The content is unknown for presigned uploads, so do not attach the default checksum
  requestChecksumCalculation: "WHEN_REQUIRED",
});

function presign(command, expiresIn, extraQuery = {}) {
  command.middlewareStack.add(
    (next) => async (args) => {
      Object.assign(args.request.query, extraQuery);
      return next(args);
    },
    { step: "build", name: "extraQuery" },
  );
  return getSignedUrl(s3, command, { expiresIn });
}

const downloadUrl = await presign(
  new GetObjectCommand({ Bucket: "my-bucket", Key: "docs/report.pdf" }),
  600, { "x-bitiful-max-requests": "1" },
);
const uploadUrl = await presign(
  new PutObjectCommand({ Bucket: "my-bucket", Key: "uploads/a.png" }),
  600, { "x-bitiful-max-requests": "1" },
);
```

For other languages, see [Node.js](https://docs.bitiful.com/en/developer/sdk/nodejs-demo/start-to-use.md)、[Go](https://docs.bitiful.com/en/developer/sdk/golang-demo/start-to-use.md)、[Python](https://docs.bitiful.com/en/developer/sdk/python3-demo/start-to-use.md)、[Java](https://docs.bitiful.com/en/developer/sdk/java-demo/start-to-use.md)、[PHP](https://docs.bitiful.com/en/developer/sdk/php-demo/start-to-use.md)、[.NET](https://docs.bitiful.com/en/developer/sdk/dotnet-demo/start-to-use.md)、[Rust](https://docs.bitiful.com/en/developer/sdk/rust-demo/start-to-use.md)、[Ruby](https://docs.bitiful.com/en/developer/sdk/ruby-demo/start-to-use.md)、[Android](https://docs.bitiful.com/en/developer/sdk/android-demo/start-to-use.md)、[iOS / Swift](https://docs.bitiful.com/en/developer/sdk/swift-demo/start-to-use.md). For direct browser uploads, see [Browser JavaScript](https://docs.bitiful.com/en/developer/sdk/browser-demo/start-to-use.md).

## Use an upload link

```bash
curl -X PUT -T ./a.png -H "Content-Type: image/png" "<upload-link>"
```

- If `ContentType` was specified when signing and appears in `X-Amz-SignedHeaders`, the upload must send exactly the same `Content-Type`.
- Any `x-amz-*` headers sent with the upload (for example `x-amz-meta-*`) must be included as parameters when the link is generated, or the request returns 403.
- To upload from a browser, first configure [CORS](https://docs.bitiful.com/en/bitiful-s4/handbook/cors.md) on the bucket.

## Override response headers

When generating a download link, you can add these standard parameters to override response headers. They work for GET and HEAD.

| Parameter                      | Response header overridden |
| ------------------------------ | -------------------------- |
| `response-content-type`        | Content-Type               |
| `response-content-disposition` | Content-Disposition        |
| `response-cache-control`       | Cache-Control              |
| `response-content-encoding`    | Content-Encoding           |
| `response-content-language`    | Content-Language           |
| `response-expires`             | Expires                    |

For example, to specify the download file name, the boto3 parameter is `ResponseContentDisposition='attachment; filename="report.pdf"'`。

> **Note**
>
> When accessing through `*.s3.bitiful.net`, a Content-Disposition of `inline` is changed to `attachment`. To preview in the browser, use a CDN domain.

## S4 extension parameters

Like ordinary query parameters, extension parameters **must be added before signing**; you cannot append them to an already signed URL.

| Parameter                | Value                                                     | Applies to | Notes                                                                     |
| ------------------------ | --------------------------------------------------------- | ---------- | ------------------------------------------------------------------------- |
| `x-bitiful-max-requests` | Integer greater than 0                                    | GET, PUT   | Maximum number of successful requests                                     |
| `x-amz-limit-rate`       | Integer in bytes per second, at least 1024                | GET        | Per-connection download rate limit                                        |
| `no-wait`                | Integer from 0 to 10, in seconds                          | GET        | Simul-Transfer: how long to wait while the object is still being uploaded |
| CoreIX parameters        | See [CoreIX](https://docs.bitiful.com/en/coreix/basic.md) | GET        | Real-time image and video processing                                      |

### Limit the number of requests

`x-bitiful-max-requests=N` limits a link to at most N uses; the (N+1)th request returns 403 `ReachTheMaxRequests`.

Counting rules:

- Only effective for V4 presigned links, and counted separately for each link (signature). A regenerated link starts counting again.
- For downloads, if the connection drops after less than one third of the expected content was transferred, that request is not counted.
- Failed uploads are not counted.
- HEAD requests are not counted.
- **Each Range request counts once.** Multithreaded downloaders and video players send multiple Range requests, so set the limit high enough.

An empty value, 0, a negative number, or a non-integer means no limit.

> **Tip**
>
> When issuing upload links, set a short validity period together with `x-bitiful-max-requests=1` to prevent replay. For more usage, see [Request limits for presigned URLs](https://docs.bitiful.com/en/bitiful-s4/features/max-requests-limits.md).

### Per-connection rate limit

`x-amz-limit-rate=1048576` limits the download speed of a single connection to 1 MiB/s. `x-bitiful-limit-rate` is an alias for it; if both appear, `x-bitiful-limit-rate` takes precedence.

- The limit applies to a single connection. When a client opens multiple connections, the total speed adds up; you can combine it with the request limit.
- It is for lowering speed. Direct S4 connections already have a per-connection rate limit, and the parameter cannot raise the speed above the bucket's ceiling; see [Product updates](https://docs.bitiful.com/en/changelog/overview.md). For higher speeds, use a CDN.

### Simul-Transfer

`no-wait=N` is used for [Simul-Transfer](https://docs.bitiful.com/en/bitiful-s4/features/simul-transfer.md): downloading starts while the object is still being uploaded.

- N is the maximum number of seconds to wait while the object does not exist yet. If the upload starts during the wait, the download starts right away; if the object still does not exist after the timeout, the request returns 404.
- If the parameter is present but its value is invalid or outside 0 to 10, it is treated as 5 seconds.
- Objects uploaded with multipart upload are not supported; use PutObject to upload.

### Media processing

[CoreIX](https://docs.bitiful.com/en/coreix/basic.md) processing parameters (for example `w`, `fmt`, and `q`) must also be added before signing:

```text
https://my-bucket.s3.bitiful.net/photo.jpg?w=800&fmt=webp&X-Amz-Algorithm=...&X-Amz-Signature=...
```

- Image processing on a private bucket must be signed this way; appending `?w=800` after signing returns `SignatureDoesNotMatch`.
- The original file to process cannot exceed 200 MiB (video and frame extraction excepted), or the request returns 403 `TooLargeForCoreIX`.

## FAQ

<details>
<summary>Returns SignatureDoesNotMatch</summary>

The most common causes: the URL was modified after signing; the method does not match; `Content-Type` does not match; an intermediate proxy rewrote the Host or path. For the complete checklist, see [Error codes and troubleshooting](https://docs.bitiful.com/en/developer/s3/errors.md).

</details>

<details>
<summary>The link expired before its validity period ended</summary>

Check that the clock of the machine that generated the link is accurate. The validity period counts from `X-Amz-Date`, so a slow clock makes the link expire early.

</details>

<details>
<summary>Can I replace the domain of a presigned link with a CDN domain?</summary>

No. Access presigned links through the bucket domain. For temporary access authorization on a CDN, use the CDN's [advanced hotlink protection](https://docs.bitiful.com/en/best-practice/token-link.md).

</details>

<details>
<summary>Can one link limit both the request count and the speed?</summary>

Yes. Extension parameters can be used together, and also with `response-*` and CoreIX parameters.

</details>

## Related projects

- [s3-presigned-api-server](https://github.com/bitiful/s3-presigned-api-server): an open-source stateless signing service that wraps the parameters above.
- [Upload files securely from the client](https://docs.bitiful.com/en/best-practice/web-uploads.md)
