# S3

`S3` is the Storage driver for Amazon S3 and S3-compatible stores (MinIO, Cloudflare R2, Wasabi).
Besides the [Storage](/guide/storage/overview/) contract every disk shares, it has three things of
its own, for bytes that should not travel through your server:

- **presigned URLs** — a link that lets someone read or write one object for a limited time, with
  no credentials;
- **the `Uploads` handle** — a Multipart Upload whose parts a browser sends straight to the bucket;
- **ranged reads** — a window of an object instead of the whole of it.

They are S3 only: reach them on the driver itself, not on the `Storage` facade.

```php
use Bootgly\ABI\Resources\Storage;

$Storage = new Storage([
   'disks' => [
      'media' => [
         'driver' => 's3',
         'root'   => 'uploads',      // every path below is inside this prefix
         'bucket' => 'assets',
         'region' => 'us-east-1',
         'key'    => '…',
         'secret' => '…',
      ],
   ],
]);

/** @var Storage\Drivers\S3 $S3 */
$S3 = $Storage->open('media');
```

Every method below returns `false` when it is refused or fails, and leaves the reason on
`$S3->error`. Opening the disk is the exception: it throws `InvalidArgumentException` when a
`key`, `region`, `service` or `token` holds a space or a control character — a trailing newline
read from a secrets file, for one — because those values go into the `Authorization` header and
the query string.

## A time-limited download link

```php
$URL = $S3->presign('GET', 'invoices/2026-11.pdf', 300);
// https://assets.s3.us-east-1.amazonaws.com/uploads/invoices/2026-11.pdf?X-Amz-Algorithm=…

if ($URL === false) {
   // $S3->error says why
}
```

Whoever opens the URL in the next 300 seconds downloads that object — no session, no credentials,
no request through your application. `presign()` makes no request itself: it only signs.

To make the browser save the file under a name, or to fix its type, pass the response overrides.
They are signed with the URL, so the holder cannot change them:

```php
$URL = $S3->presign('GET', 'invoices/2026-11.pdf', 300, [
   'response-content-disposition' => 'attachment; filename="invoice.pdf"',
   'response-content-type' => 'application/pdf',
]);
```

A presigned `PUT` lets the holder store one object in a single request:

```php
$URL = $S3->presign('PUT', 'avatars/42.png', 60);
```

A URL signed like that covers the method, the object and the lifetime — not what is uploaded:
whoever holds it chooses the bytes, their size and their `Content-Type`. To decide them on the
server, bind them as the fifth argument:

```php
$URL = $S3->presign('PUT', 'avatars/42.png', 60, [], [
   'Content-Type' => 'image/png',
   'Content-Length' => 204800,                        // exactly this many bytes
   'Content-MD5' => base64_encode(md5($bytes, true)), // exactly these bytes
   'x-amz-meta-owner' => '42',
]);
```

Each header you bind is signed with the URL: the upload must carry it with exactly that value, or
the store refuses it. Bind only what you need — any subset works:

| Header | What it fixes | What the client sends |
|---|---|---|
| `Content-Length` | The size of the body, in bytes. | Nothing extra: a browser sets it from the body. |
| `Content-Type` | The type the object is stored with. | The same `Content-Type` header. |
| `Content-MD5` | The bytes themselves — the base64 of their MD5. | The same `Content-MD5` header. |
| `x-amz-meta-*` | One metadata entry of the object. | The same header, with the same value. |

From a browser, `Content-MD5`, `x-amz-meta-*` and a `Content-Type` such as `image/png` are
request headers the page sets itself, so the bucket's CORS rule must list them in its allowed
headers. `Content-Length` needs nothing.

> [!WARNING]
> A `PUT` URL with nothing bound is a blank cheque for one object: any bytes, of any size and
> type. Hand it only to code you trust, or bind at least `Content-Length` and `Content-Type`.
> For a large file, use the `Uploads` handle below.

### What a presigned URL is

A presigned URL is a secret that works until it expires. Anyone who reads it — in a log, in a
referrer, in a shared screenshot — can use it. So:

- keep the lifetime short: seconds or minutes, never the 7-day maximum by habit;
- never log it, and never put it in an error message or an exception;
- hand it to the client that asked for it, over HTTPS, and nowhere else.

A URL cannot be revoked one by one: it stops working when it expires, or when the access key
that signed it is disabled.

What it authorizes is narrow by construction:

| | |
|---|---|
| **Method** | `GET`, `HEAD` or `PUT` — the one it was signed for. Deleting, listing and the multipart steps are never presigned here. |
| **Object** | The one path, resolved inside the disk's `root` like every other operation. `../` cannot leave the prefix, and the root itself is refused. |
| **Lifetime** | 1 to 604800 seconds (7 days), counted by the store from the moment of signing. |
| **Query** | Only the six `response-*` overrides, on `GET`/`HEAD`. Anything else — a subresource, an `x-amz-*` parameter — is refused. |
| **Headers** | Only `Content-Type`, `Content-Length`, `Content-MD5` and `x-amz-meta-*`, on `PUT`. Anything else — an ACL, a copy source — is refused. Amazon S3 also rejects an `x-amz-*` header the URL did not sign; check that your S3-compatible store does the same. |

## Upload from the browser straight to the bucket

A large file does not need to pass through your server. The server opens a Multipart Upload,
signs one URL per part, the browser `PUT`s each part to the bucket, and the server joins them.

The handle is `$S3->Uploads`. It keeps no state: an upload spans several requests, so every step
takes the object path and the upload id.

**1. Open the upload** — the server decides the path, the type and the metadata:

```php
$id = $S3->Uploads->create('videos/42/source.mp4', [
   'type' => 'video/mp4',
   'meta' => ['owner' => '42'],
]);
// store $id with your own record of the upload, then send it to the client
```

**2. Sign each part** — as the client asks for them:

```php
$URL = $S3->Uploads->sign('videos/42/source.mp4', $id, $part, 900);   // $part: 1..10000
```

The client sends the bytes of that part with a plain `PUT` to the URL — no headers needed. A
part sent again replaces the earlier one, so a failed part is simply retried.

To fix the size of a part — or its bytes — bind it, as on a presigned `PUT`:

```php
$URL = $S3->Uploads->sign('videos/42/source.mp4', $id, $part, 900, [
   'Content-Length' => 8 * 1024 * 1024,   // this part is exactly 8 MiB
]);
```

A part binds `Content-Length` and `Content-MD5` only: the type and the metadata were set by
`create()`. The last part is usually shorter, so the client says how many bytes it will send
and the server decides whether that size is acceptable before signing.

**3. Check what arrived, then complete:**

```php
$Parts = $S3->Uploads->list('videos/42/source.mp4', $id);
// [1 => ['etag' => '"9b2c…"', 'size' => 8388608], 2 => […], …] — or false

$size = 0;
foreach ($Parts ?: [] as $Part) {
   $size += $Part['size'];
}

if ($Parts === false || $Parts === [] || $size > 2_000_000_000) {
   $S3->Uploads->abort('videos/42/source.mp4', $id);
}
else {
   $S3->Uploads->complete('videos/42/source.mp4', $id, $Parts);
}
```

`list()` is what the store actually holds: the sizes are measured by the store, not reported by
the uploader, and the ETags are the ones `complete()` needs. Completing from `list()` means the
browser never has to read a response header, so the bucket's CORS rules only need to allow the
`PUT` — plus `Content-MD5` as an allowed header, when a part binds it.

**Resume** — `list()` is also how an interrupted upload continues: the parts already there do not
need to be sent again.

**Abort** — an upload that is never completed keeps its parts, and the store bills for them.
Call `abort()` when the user cancels or a check fails, and set a lifecycle rule on the bucket
that aborts incomplete uploads after some days, for the ones nobody cancels.

> [!IMPORTANT]
> Treat the upload id as part of your own state. Keep it on the server next to the record it
> belongs to (who started it, which path), and take the path from that record — never from the
> request. The handle refuses an id that is not a plain token, but it cannot know whose upload
> it is.

### Notes for S3-compatible stores

- **Equal part sizes.** Amazon S3 only requires every part but the last to be at least 5 MiB.
  Cloudflare R2 also requires every part but the last to have the **same** size, and refuses the
  completion otherwise. Pick one part size on the client (8 or 16 MiB, for example), cut the
  file in parts of exactly that size, and check the sizes in `list()` before completing — or
  bind `Content-Length` when signing each part, so no other size can be uploaded.
- **`http` endpoints.** A disk whose `endpoint` is `http://…` (a local MinIO, a test fake) is
  refused at construction unless it sets `'insecure' => true`, and its presigned URLs are `http`
  as well: the URL — a secret — and the bytes travel in clear text. Use it for development only.

## Read a window of an object

`read()` takes an offset and a length after the sink:

```php
$Sink = fopen('php://memory', 'r+');

$S3->read('videos/42/source.mp4', $Sink, 0, 1024);          // the first 1024 bytes
$S3->read('videos/42/source.mp4', $Sink, 1_048_576, 4096);  // 4096 bytes from offset 1 MiB
$S3->read('videos/42/source.mp4', $Sink, 1_048_576);        // from offset 1 MiB to the end
```

The sink never receives a byte outside the window:

- a window that goes past the end of the object is cut at the end;
- an offset at or past the end is `false` (`range not satisfiable (HTTP 416)`), with nothing
  written;
- an endpoint that ignores the range and answers the whole object, or answers another window, is
  `false`, with nothing written — never the wrong bytes in the sink.

A window can still be cut in transit: the connection drops, or the answer ends before its last
byte. `read()` is then `false` with the first bytes of the window already in the sink. When you
append windows to a file, note the sink's position before each `read()` and truncate back to it
on `false` before retrying:

```php
$position = ftell($Sink);

if ($S3->read('videos/42/source.mp4', $Sink, $offset, $length) === false) {
   ftruncate($Sink, $position);
   fseek($Sink, $position);
   // retry, or give up — $S3->error says why
}
```

With no offset and no length, `read()` is the whole-object read every driver has. The window is
part of `S3::read()` only: `Storage::read()` and the other drivers keep `read($path, $sink)`.

## Sign requests yourself

The driver signs with `Storage\Drivers\S3\Signer`, an AWS Signature Version 4 signer you can use
on its own — to call an S3 operation the driver does not wrap, or another service that takes the
same signature:

```php
use Bootgly\ABI\Resources\Storage\Drivers\S3\Signer;

$Signer = new Signer($key, $secret, 'us-east-1');

// Header auth: the headers to send with the request
$headers = $Signer->sign(
   'GET',
   'assets.s3.us-east-1.amazonaws.com',
   '/uploads/a%20b.txt',                 // already percent-encoded
   ['versionId' => '3'],                 // raw: encoded and sorted by the signer
   ['Range' => 'bytes=0-9'],             // signed, and sent by you
   hash('sha256', '')                    // the body's SHA-256
);

// Query auth: the query string of a presigned URL
$query = $Signer->presign('GET', 'assets.s3.us-east-1.amazonaws.com', '/uploads/a%20b.txt', [], 300);
$URL = "https://assets.s3.us-east-1.amazonaws.com/uploads/a%20b.txt?{$query}";
```

The signer signs what it is given: unlike `S3::presign()`, it has no root prefix and no list of
allowed methods or parameters. It throws `InvalidArgumentException` for input that is not
canonical — a line break in the method, the host, the path, a header or the payload hash, a `?`
in the path, a lifetime outside 1..604800, an `X-Amz-*` authentication parameter in the query.
Query values are data: whatever they hold is percent-encoded.

## Reference

### S3

```php
public function presign (string $method, string $path, int $expires, array $query = [], array $headers = []): string|false
```

Presigns one request for an object and returns its absolute URL, without making a request.
`$method` is `GET`, `HEAD` or `PUT`; `$expires` is the lifetime in seconds, 1..604800
(`Signer::LIFETIME`); `$query` takes the `response-content-disposition`, `response-content-type`,
`response-cache-control`, `response-content-encoding`, `response-content-language` and
`response-expires` overrides of a `GET`/`HEAD`, as strings; `$headers` takes what a `PUT` must
send — `Content-Type`, `Content-Length`, `Content-MD5` and `x-amz-meta-*`, each once, as a string
or an integer.
Returns `false` — reason on `$error` — for any other method, parameter or header, a header
value that is empty or malformed, a lifetime out of range, the disk root as path, or a disk
with no `key`/`secret`.

```php
public function read (string $path, $sink, int $offset = 0, null|int $length = null): bool
```

Streams the object — or the window of `$length` bytes starting at `$offset` — into the writable
resource `$sink`. A `null` length reads to the end. Returns `false` for a negative offset, a
length below 1, a missing object, an offset at or past the end, or an answer that is not the
window asked for — with nothing written, when a window was asked for — and for a window cut in
transit, with its first bytes already written.

```php
public private(set) Uploads $Uploads
```

The Multipart Upload handle of the disk.

### S3\Uploads

```php
public function create (string $path, array $options = []): string|false
```

Starts a Multipart Upload for the object and returns its upload id. `$options` are the write
options: `type` (Content-Type) and `meta` (a `x-amz-meta-*` map).

```php
public function sign (string $path, string $id, int $part, int $expires, array $headers = []): string|false
```

Presigns the `PUT` of one part (1..10000, `Uploads::PARTS`) of that upload and returns its URL,
without making a request. `$expires` is the lifetime in seconds, 1..604800 (`Signer::LIFETIME`);
`$headers` takes what the `PUT` must send — `Content-Length` and `Content-MD5`, each once.
Returns `false` for any other header.

```php
public function list (string $path, string $id): array|false
```

Lists every part the store holds for the upload, following every page:
`[number => ['etag' => string, 'size' => int]]`, ascending. Returns `false` when any page fails
or is malformed — never a partial list.

```php
public function complete (string $path, string $id, array $parts): bool
```

Joins the parts into the object. `$parts` is what `list()` returns, or
`[number => ['etag' => …]]` built from the ETags the uploader received. A failed completion
leaves the upload open: complete again, or abort.

```php
public function abort (string $path, string $id): bool
```

Aborts the upload and releases its parts. An upload the store no longer knows counts as aborted.

```php
public const int PARTS = 10000;
```

The most parts one upload holds, and the highest part number.

### S3\Signer

```php
public function __construct (string $key, string $secret, string $region = 'us-east-1', string $service = 's3', string $token = '')
```

Binds a signer to one set of credentials and one signing scope. `$token` is the session token of
temporary credentials. Throws when the key, region, service or token holds a space or a control
character.

```php
public function sign (string $method, string $host, string $path, array $query, array $headers, string $payload, null|int $time = null): array
```

Signs a request for header auth and returns the headers to add to it: `Authorization`,
`x-amz-date`, `x-amz-content-sha256` and, with a session token, `x-amz-security-token`. Every
header in `$headers` is signed, so send them all. `$path` is the percent-encoded request path,
`$host` the `Host` header as sent, `$payload` the lowercase hex SHA-256 of the body or
`Signer::UNSIGNED`.

```php
public function presign (string $method, string $host, string $path, array $query, int $expires, array $headers = [], null|int $time = null): string
```

Signs a request for query auth and returns its query string, the signature last. The `Host`
header and every header in `$headers` are signed — the request must send them with those
values — and the payload is not.

```php
public static function encode (array $query): string
```

The canonical query string of raw parameters: percent-encoded per RFC 3986 and sorted.

```php
public const string ALGORITHM = 'AWS4-HMAC-SHA256';
```

The signing algorithm, as it is named on the wire.

```php
public const string UNSIGNED = 'UNSIGNED-PAYLOAD';
```

The payload hash of a request whose body is not covered by the signature — what `sign()` takes
as `$payload` when the body is not hashed.

```php
public const int LIFETIME = 604800;
```

The longest presigned URL lifetime Signature Version 4 accepts, in seconds (7 days): the upper
bound of `$expires` on `presign()`, `S3::presign()` and `Uploads::sign()`.

```php
public private(set) string $key
```

The access key id.

```php
public private(set) string $region
```

The signing region (`us-east-1`, `auto`, …).

```php
public private(set) string $service
```

The signing service (`s3`).

## Next references

- **[Storage](/guide/storage/overview/)** — disks, drivers and the file API every driver shares.
