# AWS

The AWS services a product uses week to week, from the back end, each a
file of ordinary Mote over one small core: SigV4 written out for any
service, the back end's keys found as AWS's own tools find them (keys of
its own, or a role's on EC2, ECS, EKS), and AWS's four ways of speaking
(JSON 1.0 and 1.1, the query API with XML back, REST with JSON). SQS,
DynamoDB, Lambda, SNS, SES behind [mail](mail.md)'s `mailSend`, Bedrock
behind the [ai](ai.md) extension, Secrets Manager, SSM Parameter Store,
EventBridge. [S3](s3.md) is its own extension, on this core. An
[extension](../extensions/README.md): `extensions/aws/`. Back to the
[map](README.md).

```text
use "pkg:aws/sqs.mote"
use "pkg:aws/dynamo.mote"

shape Order
  pk: string
  sk: string
  total: number
  paid: bool

// An order is kept once, and its receipt is queued; a consumer sends it.
server fn place(order: string, total: number): bool requires signedIn
  let me = auth.me()?
  awsDynamoPut("shop", {pk: `user#${me?.id}`, sk: `order#${order}`, total, paid: false}, {condition: "attribute_not_exists(pk)"})?
  awsSqsSend(env("RECEIPTS_QUEUE"), JSON.stringify({order}), {})?
  return true

fn awsSqsHandle(queue: string, m: AwsSqsMessage): bool
  let o: Order? = awsDynamoGet("shop", JSON.parse(m.body), true)?
  return o != none

server every 1000
  awsSqsPoll(env("RECEIPTS_QUEUE"), 10)?
```

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

**What was checked.** SigV4 against AWS's own published SigV4 test suite
(`get-vanilla`, `post-vanilla`, `get-vanilla-query-order-key-case`,
`get-vanilla-utf8-query`, `post-vanilla-query`,
`post-x-www-form-urlencoded`, `post-sts-header-after` with a session token),
the IAM `ListUsers` example of its documentation and its signing key, and
S3's four examples: signature for signature, in
`extensions/aws/tests.mote`. The event-stream reader against
aws-c-event-stream's `empty_message` and `int32_header` vectors (both
CRCs). Every service is run against a stand-in
(`tests/svc_aws_standin.mjs`, `tests/all.sh real_svc_aws`) that lends the
program a role's keys through a stand-in IMDSv2, works every signature out
again on its own from the request as it arrived, and refuses one that
differs or whose session token is not the one lent; SNS's part is played by
the stand-in signing an SES bounce with a key whose certificate it serves.
**Nothing here has met AWS**: the steps are [below](#checking-it-against-aws).

## The settings

As AWS's own tools read them.

| | |
|---|---|
| `AWS_REGION` | The region (`AWS_DEFAULT_REGION` too); `us-east-1` unsaid. |
| `AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`, `AWS_SESSION_TOKEN` | Keys of the back end's own. The secret and the token are read with [`secret("…", "")`](back-end.md#secrets): they may be unset (a back end on AWS has a role), and are never logged. |
| `AWS_WEB_IDENTITY_TOKEN_FILE`, `AWS_ROLE_ARN`, `AWS_ROLE_SESSION_NAME` | A role taken with a token in a file (EKS's IAM roles for service accounts): STS `AssumeRoleWithWebIdentity`. |
| `AWS_CONTAINER_CREDENTIALS_RELATIVE_URI`, or `_FULL_URI` with `AWS_CONTAINER_AUTHORIZATION_TOKEN` (or `_TOKEN_FILE`) | A task's role in ECS; EKS Pod Identity. |
| (none of those) | The instance's role, from its metadata service, IMDSv2 (a token by `PUT`, then the role's keys). `AWS_EC2_METADATA_DISABLED=true` not to ask; `AWS_EC2_METADATA_SERVICE_ENDPOINT` another address. |
| `AWS_ENDPOINT_URL`, `AWS_ENDPOINT_URL_<SERVICE>` | Another address for every service, or one (`_SQS`, `_DYNAMODB`, `_SESV2`, `_BEDROCK_RUNTIME`, `_SNS`, `_LAMBDA`, `_SECRETS_MANAGER`, `_SSM`, `_EVENTBRIDGE`, `_STS`): LocalStack, a stand-in. |
| `AWS_SNS_TOPICS` | The topics whose subscriptions `awsSnsCheck` confirms (ARNs, commas between; `*` any). |
| `SES_CONFIGURATION_SET` | With `MAIL_PROVIDER=ses`: the set whose events go to SNS. |

Keys that are lent (by STS, a container, an instance) are kept in the
model `AwsLent` (its secret and token `hidden`) until five minutes before
they end, and fetched again then; a request refused with `ExpiredToken`
drops them and is signed again once.

## The calls

Every call can fail with a sentence and a kind: `"auth"` (refused: the
keys, the signature, a policy), `"missing"` (no such queue, table,
function, secret), `"conflict"` (a condition did not hold, a transaction
was cancelled), `"limited"` (throttled, after the tries), `"invalid"`,
`"aws"` (5xx), `"offline"`; `data` is `{status, code, said, request}`,
AWS's own code and words. A call AWS can do twice harmlessly is asked
again (signed again) while AWS is busy or broke; one it cannot (an SQS send
without a FIFO key, an SES send, an `UpdateItem`, a Lambda invoke) is not.

| File | Calls |
|---|---|
| `aws.mote` | `awsCredentials()`, `awsEndpoint(service)`, `awsSend(request)` (one signed request, any service), `awsJson(service, version, target, body, tries, what)`, `awsQueryCall(service, version, action, fields, tries, what)` (its `<Action>Result`, read with `xml`), `awsRest(service, method, path, query, body, tries, what)`, `awsRefused`. For a service with no file here: three lines over these. |
| `sigv4.mote` | `awsSign(keys, ask, how, at)`: SigV4 in a header or (`awsPresigned`) in a query; the session token signed; the body's hash said in `x-amz-content-sha256` (S3) or not; the path encoded twice (every service but S3). |
| `sqs.mote` | `awsSqsUrl(name)`, `awsSqsSend(queue, body, {delay, group, dedupe, attributes})`, `awsSqsSendBatch`, `awsSqsReceive(queue, most, wait, visibility)` (long polling to 20 s), `awsSqsDelete`, `awsSqsVisibility`, `awsSqsPoll(queue, most)` (the consumer: each message to the program's `fn awsSqsHandle(queue, m): bool`, deleted when it says true), `awsSqsDeadLetters(queue, deadArn, receives)`, `awsSqsRedrive(deadArn)`, `awsSqsCount`. |
| `dynamo.mote` | `awsDynamoGet(table, key, consistent)`, `awsDynamoPut(table, item, {condition, names, values})`, `awsDynamoUpdate(table, key, update, …)`, `awsDynamoDelete`, `awsDynamoQuery` / `awsDynamoScan` (a page and its `next`), `awsDynamoQueryAll(table, ask, most)`, `awsDynamoBatchGet` (100 a request) and `awsDynamoBatchWrite` (25), each asking again for what DynamoDB left, `awsDynamoTransact(writes, token)` and `awsDynamoTransactGet`; `awsDynamoTo` / `awsDynamoFrom` (plain values to `{S}`, `{N}`, `{M}`… and back), `awsDynamoSet`, `awsDynamoBytes`. |
| `lambda.mote` | `awsLambdaInvoke(name, payload, log)` (its result, the end of its log; a function that threw fails with kind `"function"`), `awsLambdaQueue(name, payload)` (not waited for). |
| `sns.mote` | `awsSnsPublish(topic, message, {subject, group, dedupe, attributes})`, `awsSnsText(phone, message)`, `awsSnsCheck(body)` (a message SNS posted: checked, and a confirmation confirmed), `awsSnsSignWithSha256(topic)`. |
| `ses.mote` | `fn mailViaSes`: SES v2 `SendEmail` behind `mailSend` (`MAIL_PROVIDER=ses`): Simple content with its headers, or raw MIME with files; the route `POST /mail/ses/events` (SES's events through SNS: a permanent bounce or a complaint onto `MailSuppressed`, each once, then `fn mailSesHeard(e)`). |
| `bedrock.mote` | `fn aiViaBedrock`: Converse behind `aiChat`, `aiStreamTo`, `aiRun` (`AI_PROVIDER=bedrock`, `AI_MODEL` a model id or inference profile); ConverseStream read from its event stream. |
| `eventstream.mote` | `awsStreamRead(bytes)`: the whole messages and the rest; `awsStreamMake` for a test. |
| `secrets.mote` | `awsSecretValue(id, stage)`, `awsSecretJson(id)`, `awsParameter(name)`, `awsParameters(path)` (page by page). Nothing kept between calls; what is read is not a `secret(…)`, so never log it. |
| `events.mote` | `awsEventsPut(events)`: each one's id or why not, ten a request. |

### SNS's signatures

`awsSnsCheck` takes a message only when: its certificate's address is an
`https://sns.<region>.amazonaws.com/…pem` one (fetched over HTTPS, so
checked by TLS, and kept in `AwsSnsCert`); its signature is that
certificate's key's over the fields SNS signs; it is less than an hour from
now. A `SubscriptionConfirmation` is confirmed (its `SubscribeURL`, also
only at an SNS address, visited) only for a topic in `AWS_SNS_TOPICS`.

**Both signature versions.** A topic signs with SHA-1 (version 1) unless
told otherwise: that is checked by `crypto.verify`'s `RS1`, which verifies
and never signs. Version 2 (SHA-256) is checked as RS256; set it with
`awsSnsSignWithSha256(topic)` or in the console if you prefer it. The
certificate's public key is read by `crypto.cert`.

## Left out, on purpose or for now

- **CloudFront signed URLs and cookies.** They are RSA with SHA-1, signed
  with the key pair's private key. The runtime will not sign RSA-SHA1, on
  purpose: `RS1` is verify-only, there for services that still sign so, and
  nothing new should be signed with SHA-1. So they are not built. (The
  policy, its base64 with CloudFront's `-_~`, and the address would be a
  dozen lines on `crypto.sign` with `{alg: "RS1"}`, were it ever allowed.)
- **SES classic, SNS mobile push, SQS's query API**: SES v2, FCM/APNs
  (the gcloud extension), SQS's JSON protocol take their place.
- **Textract, Rekognition, Transcribe.** Each call is `awsJson(…)` (Textract
  `Textract.DetectDocumentText`, Rekognition
  `RekognitionService.DetectLabels`, JSON 1.1) with its body: not written out
  until a product needs one. Transcribe's streaming is the event stream over
  HTTP/2.
- **DynamoDB**: PartiQL, streams, table admin; numbers past 2^53 lose digits
  read back (keep such a one as text).
- **STS AssumeRole by keys, SSO profiles, `~/.aws` files**: a back end is
  given keys, or a role.

## Checking it against AWS

Nothing above has met AWS. To check it, in a sandbox account, read-only
calls first:

1. Keys: an IAM user with `ReadOnlyAccess` (or a role), `AWS_REGION` set.
   `aws sts get-caller-identity` works with them.
2. Secrets and SSM: `aws secretsmanager create-secret --name mote/test
   --secret-string '{"a":1}'`; `awsSecretJson("mote/test")` gives `{a: 1}`;
   `aws ssm put-parameter --name /mote/a --value 1 --type String`;
   `awsParameters("/mote/")`.
3. SQS: `aws sqs create-queue --queue-name mote-test`; `awsSqsUrl`,
   `awsSqsSend`, `awsSqsReceive(q, 1, 20, 30)` (it waits), `awsSqsDelete`;
   then a `.fifo` queue with `group` and `dedupe`; then a dead-letter queue
   with `awsSqsDeadLetters(q, deadArn, 2)` and a handler that says false.
4. DynamoDB: a table `mote-test` (pk, sk strings); put, a put with
   `attribute_not_exists(pk)` twice (the second fails `"conflict"`),
   update, query of a dozen items with `most: 5`, a transaction whose
   check fails.
5. Lambda: a function that echoes; `awsLambdaInvoke(name, {a: 1}, true)`; one
   that throws.
6. SES (sandbox mode, a verified address as sender and recipient):
   `MAIL_PROVIDER=ses`, a message with and without a file; then a
   configuration set with an SNS destination (try the topic with its
   SignatureVersion left at 1, then set to 2), an HTTPS subscription to `/mail/ses/events` with
   `AWS_SNS_TOPICS` set (it is confirmed), and a mail to
   `bounce@simulator.amazonses.com`: the address is on `MailSuppressed`.
7. Bedrock: a model enabled in the account, `AI_PROVIDER=bedrock`,
   `AI_MODEL=<its id>`; `aiChat`, then `aiStreamTo` (the event stream), then
   `aiRun` with a tool.
8. On EC2 (IMDSv2 required), in ECS and in EKS with a service account's
   role, with no keys set: any call above works, and `awsCredentials().source`
   says which way.
