# S3

Files in a bucket of any S3-compatible store (AWS S3, Cloudflare R2,
Backblaze B2, MinIO, …), from the back end, every request signed with AWS
Signature Version 4, written out in Mote (the [aws](aws.md) extension's
`sigv4.mote`; the answers are read with [`xml`](data.md#xml)). Put, get, head, delete, list;
large files in parts; presigned addresses for a browser to send a file
straight to the bucket, or fetch one. An
[extension](../extensions/README.md): ordinary Mote in `extensions/s3/`.
Back to the [map](README.md).

```mote
use "pkg:s3/s3.mote"

server fn keepInvoice(order: string, pdf: bytes): string requires signedIn
  s3Upload(`invoices/${order}.pdf`, pdf, "application/pdf")?
  return s3PresignGet(`invoices/${order}.pdf`, 3600, `invoice-${order}.pdf`)?.url

// The page sends the file itself, straight to the bucket:
//   let up = s3UploadUrl(file.name, file.type)?
//   net.send("PUT", up.url, {headers: {"content-type": file.type}, body: file.bytes})?
```

It stands on the aws extension, which the program's `mote.toml` names too:

```toml
[packages]
s3 = "../mote/extensions/s3"
aws = "../mote/extensions/aws"
```

```sh
S3_BUCKET=shop S3_KEY_ID=… S3_SECRET=… S3_REGION=auto S3_ENDPOINT=https://<account>.r2.cloudflarestorage.com bun dist/server/main.js
```

**What was checked.** The signing is checked against the four examples
AWS publishes in its SigV4 documentation for S3 (a GET with a range, a PUT
with a body, a list with a query, a presigned GET), signature for
signature, in `extensions/s3/tests.mote`. Every call is run against a
stand-in store (`tests/svc_standin.mjs s3`) that works each signature out
again on its own and refuses one that differs. **No real store has been
asked**: the steps are [below](#checking-it-against-a-store).

## The settings

| | |
|---|---|
| `S3_BUCKET` | The bucket. |
| `S3_KEY_ID`, `S3_SECRET` | The access key's id, and its secret (a [secret that may be unset](back-end.md#secrets), never logged). Both unset: the back end's AWS keys, as the [aws](aws.md) extension finds them (its own, or a role's on EC2, ECS, EKS). |
| `S3_REGION` | The region signed for: `us-east-1` unsaid; `auto` for R2; B2's is in its endpoint (`us-west-004`). |
| `S3_ENDPOINT` | The store's address. Unset: AWS's, `https://s3.<region>.amazonaws.com`. R2: `https://<account id>.r2.cloudflarestorage.com`; B2: `https://s3.<region>.backblazeb2.com`; MinIO: `http://localhost:9000`. |
| `S3_STYLE` | `path` (`endpoint/bucket/key`) or `virtual` (`bucket.endpoint/key`). Unset: virtual at AWS, path anywhere else. |
| `S3_PART_SIZE` | How big each part of a large upload is: 8 MB unsaid, 5 MB at least at a real store. |
| `S3_UPLOADS` | Where `s3UploadUrl` puts people's files: `uploads/`. |

## The calls

| Call | |
|---|---|
| `s3Put(key, data, type)` | Writes the bytes at `key`, to be served as `type`: an `S3Object` (`key`, `size`, `etag`, `type`, `modified`). |
| `s3Upload(key, data, type)` | The same for a file of any size: one request up to a part's size, else in parts (begun, each part, finished with their ETags in order), and let go of if a part fails, so nothing half-sent is kept and paid for. |
| `s3Get(key)` | The bytes; fails `kind "missing"` where there are none. |
| `s3Head(key)` | What is kept there (size, type, ETag, when), or none. |
| `s3Delete(key)` | Takes it away (S3 answers the same whether there was anything). |
| `s3List(prefix, most)` | The keys under a prefix, in order, page by page (ListObjectsV2), `most` at most. |
| `s3Begin` · `s3Part` · `s3Finish` · `s3Abort` | The parts by hand, for a file read piece by piece. |
| `s3PresignGet(key, seconds, download)` | An address anyone holding it may fetch, for that long (a week at most); `download` a name to save it as. |
| `s3PresignPut(key, seconds, type)` | An address a browser may `PUT` a file to, with that `content-type` (signed: another type is refused, and it is served as that one). |
| `s3UploadUrl(name, type)` | A `server fn` (`requires signedIn`, 60 an hour): a presigned PUT for whoever asks, under `uploads/<their id>/`, good for ten minutes. |
| `s3Sign(who, ask, at, presign, expires)` | SigV4 itself (`sigv4.mote`), for another service AWS signs the same way: `service` is its name. |

- GET, HEAD, PUT and DELETE are tried again on 429 and 5xx; a POST (the
  parts' beginning and end) is not.
- **A presigned PUT cannot cap a file's size.** Look at it once the page says
  it is sent (`s3Head`), and delete what is too big; or take the file
  through the back end. The bucket's CORS rules must let the site's origin
  `PUT` (and send `content-type`) for a browser to use the address.
- Keys are text; each part is encoded as SigV4 says (`a b.png` is
  `a%20b.png`), slashes kept.

| Kind | |
|---|---|
| `"missing"` | No such key. |
| `"auth"` | The store refused the key or the signature: its code follows (`SignatureDoesNotMatch`, `AccessDenied`, `InvalidAccessKeyId`). |
| `"invalid"` | Anything else it refused (`EntityTooSmall`, `NoSuchBucket`, …). |
| `"limited"` | `SlowDown`. |
| `"store"`, `"offline"` | It broke; it did not answer. |

## A model's `file` field, kept in a bucket

Not yet. A model's [`file` field](models.md#files) is kept by the runtime
in `files/` of the data folder (`runtime/server/files.mote`): written as it
arrives (`fileTake`), read for serving with ranges (`fileServe`), read
whole (`files.bytes`), thumbnails beside it (`fileDerive`), deleted with
its row (`fileDrop`, `fileGone`). There is no seam between those and the
disk. The seam it would need: a store of four operations (write a file by
its id from a stream, read a range of it, its size, delete it) that the
runtime takes from a setting (`MOTE_FILES=s3`, with these same `S3_…`
settings), and serving that answers a read the model's rule allows with a
redirect to a presigned GET. Until then a program keeps the bytes in a
bucket itself (`s3Upload` in the `server fn` that takes them) and a key in
the row.

## Checking it against a store

MinIO on this machine is the quickest:

1. `minio server /tmp/minio` (it prints an access key and secret), make a
   bucket `shop`; then `S3_ENDPOINT=http://localhost:9000 S3_BUCKET=shop
   S3_KEY_ID=… S3_SECRET=… S3_REGION=us-east-1`.
2. `s3Put("a.txt", bytes("hi"), "text/plain")`, then `s3Get`, `s3Head`,
   `s3List("", 10)`, `s3Delete`: each answers, and `mc ls` agrees.
3. `s3Upload` of 20 MB: three parts, and `mc stat` says its ETag ends `-3`.
4. `s3PresignGet` in a browser: the file; an hour later: `AccessDenied`.
5. R2 and B2 the same, with their endpoints and `S3_REGION=auto` (R2).
   AWS: unset `S3_ENDPOINT`, set `S3_REGION`.

Recorded in `tests/expect/real_svc_s3.txt` (`tests/all.sh real_svc_s3`):
each call against the stand-in, the signatures as sent, a file in three
parts, a list in two pages, a browser's PUT to a presigned address with the
type it was signed for and with another, a presigned GET, the same signature
for another key, an address after its time; then the extension's own `mote
test`, with AWS's examples.
