# AWS

On AWS, give long-lived EC2 instances their own canary, and give everything that scales or gets replaced (Auto Scaling groups, ECS and Fargate tasks, Lambda functions) one canary per role, stored in Secrets Manager next to the role's real secrets.

The commands below use the AWS CLI v2 and read the decoy from stdin, so the key never appears on a command line or your screen. `create-secret` and `put-secret-value` print the secret's name and version, never its value.

## EC2 instances you keep

Use the [cloud-init install](/docs/servers#cloud-init-and-terraform) in the instance's user-data. To keep the auth key out of user-data, store it in Parameter Store and fetch it at boot; the instance profile needs `ssm:GetParameter` on it:

```sh
#!/bin/sh
aws ssm get-parameter --name /ops/enroll-key --with-decryption --query Parameter.Value --output text > /run/enroll-key
curl -fsSL https://get.snitchwallet.com | sh -s -- --authkey-file /run/enroll-key
rm -f /run/enroll-key
```

## Auto Scaling groups

Instances come and go, so give the group one canary. Store it in Secrets Manager:

```sh
curl -fsSL https://get.snitchwallet.com | sh -s -- --decoy json:- --name live-web-asg \
  | aws secretsmanager create-secret --name live/payout-signer --secret-string file:///dev/stdin
```

Then have the launch template's user-data put it where a real service would keep a wallet. The instance profile needs `secretsmanager:GetSecretValue` on the secret:

```sh
#!/bin/sh
install -d -m 700 /etc/payout-service
aws secretsmanager get-secret-value --secret-id live/payout-signer \
  --query SecretString --output text > /etc/payout-service/hot-wallet.json
chmod 600 /etc/payout-service/hot-wallet.json
```

Every instance carries the same canary, and an intruder who uses an instance's role to read Secrets Manager finds it there too.

## ECS and Fargate

Store the canary in Secrets Manager and inject it into the task as an environment variable, like any other secret. Pick whichever of these matches how your service already gets its secrets.

### A secret of its own

```sh
curl -fsSL https://get.snitchwallet.com | sh -s -- --decoy json:- --name live-api \
  | aws secretsmanager create-secret --name live/payout-wallet --secret-string file:///dev/stdin
```

Inject the whole secret as one variable. With the CDK:

```ts
const wallet = secretsmanager.Secret.fromSecretNameV2(this, "PayoutWallet", "live/payout-wallet");

taskDefinition.addContainer("api", {
  // ...
  secrets: {
    PAYOUT_WALLET_KEYSTORE: ecs.Secret.fromSecretsManager(wallet),
  },
});
```

With Terraform, in the container definition:

```hcl
data "aws_secretsmanager_secret" "payout_wallet" {
  name = "live/payout-wallet"
}

# in container_definitions:
secrets = [
  { name = "PAYOUT_WALLET_KEYSTORE", valueFrom = data.aws_secretsmanager_secret.payout_wallet.arn }
]
```

The task's execution role needs `secretsmanager:GetSecretValue` on the secret; the CDK grants it for you. Look the secret up by name rather than creating it in Terraform, or the key ends up in your Terraform state.

### Your app's existing JSON secret

If your app loads its settings from one JSON secret, add the canary's two variables to it. Run this in bash or zsh; it stops before writing anything if a step fails:

```sh
set -euo pipefail
ID=live/app-secrets
add=$(curl -fsSL https://get.snitchwallet.com | sh -s -- --decoy env:- --name live-api \
  | jq -Rnc '[inputs | select(length > 0) | capture("^(?<key>[^=]+)=(?<value>.*)$")] | from_entries')
cur=$(aws secretsmanager get-secret-value --secret-id "$ID" --query SecretString --output text)
new=$(printf '%s' "$cur" | jq -c --argjson add "$add" '. + $add')
printf '%s' "$new" | aws secretsmanager put-secret-value --secret-id "$ID" --secret-string file:///dev/stdin
```

Secrets Manager keeps the previous version as `AWSPREVIOUS`, so you can roll back.

### An environment file in S3

If your tasks load an environment file from S3, upload the decoy as its own file:

```sh
curl -fsSL https://get.snitchwallet.com | sh -s -- --decoy env:- --name live-api \
  | aws s3 cp - s3://YOUR-CONFIG-BUCKET/live/payout.env
```

Then list it in the container's `environmentFiles` (CDK: `ecs.EnvironmentFile.fromBucket(bucket, "live/payout.env")`). The file name must end in `.env`, the task's execution role needs `s3:GetObject` on it and `s3:GetBucketLocation` on the bucket, and Fargate needs platform version 1.4.0 or later.

### Roll it out

Running tasks only pick up secrets when they start. Start new ones:

```sh
aws ecs update-service --cluster live --service api --force-new-deployment
```

## Lambda

Lambda doesn't inject Secrets Manager values into environment variables by itself, but CloudFormation can resolve one at deploy time. The key then appears in the function's configuration, where an intruder with `lambda:GetFunctionConfiguration` would look, but not in your template. Store the canary as in [A secret of its own](#a-secret-of-its-own), then with the CDK:

```ts
const wallet = secretsmanager.Secret.fromSecretNameV2(this, "PayoutWallet", "live/payout-wallet");

new lambda.Function(this, "Payouts", {
  // ...
  environment: {
    PAYOUT_WALLET_KEYSTORE: wallet.secretValue.unsafeUnwrap(),
  },
});
```

`unsafeUnwrap()` puts a `{{resolve:secretsmanager:...}}` reference in the template, not the value. With Terraform, reading the secret into an environment variable puts the key in your state; that's acceptable for bait but worth knowing.

## Send alerts to Amazon SNS

To page through the same SNS topic as your CloudWatch alarms, point a SnitchWallet webhook at a small Lambda function with a function URL. In the dashboard, add a **Webhook** alert channel with the function URL and a signing secret. The function checks the signature and publishes the alert:

```python
import base64, hashlib, hmac, json, os
import boto3

sns = boto3.client("sns")

def handler(event, context):
    body = event.get("body") or ""
    if event.get("isBase64Encoded"):
        body = base64.b64decode(body).decode()
    want = "sha256=" + hmac.new(os.environ["WEBHOOK_SECRET"].encode(), body.encode(), hashlib.sha256).hexdigest()
    if not hmac.compare_digest(event.get("headers", {}).get("x-snitch-signature", ""), want):
        return {"statusCode": 401}
    alert = json.loads(body)
    sns.publish(TopicArn=os.environ["TOPIC_ARN"], Subject=("SnitchWallet: " + alert["kind"])[:100], Message=alert["headline"])
    return {"statusCode": 204}
```

Give the function URL auth type `NONE` (the signature is the authentication), the environment variables `WEBHOOK_SECRET` and `TOPIC_ARN`, and `sns:Publish` on the topic. Each alert is JSON with `kind` (`fired`, `confirmed`, `armed`, `retired`, `unverified` or `test`), `headline`, `hostname`, `txid` and more. Forward only `fired`, `confirmed` and `unverified` if the topic pages someone. Use **Send a test alert** in the dashboard to check it.

## Logs

To catch anyone harvesting secrets from CloudWatch Logs, see [Logs](/docs/logs#cloudwatch-logs).
