# Exercise 2: Write Least-Privilege Policies for Four Workloads

Write the **trust policy** and **permissions policy** for each role. Use exact ARNs (account `111111111111`, region `eu-west-1`), conditions where they add protection, and no `*` actions.

1. **Lambda `thumbnailer`**: triggered by S3 uploads to `petpal-uploads` under `incoming/`; reads the original, writes to `thumbnails/` in the same bucket; logs to its own log group; objects are encrypted with KMS key `alias/petpal-uploads`.
2. **ECS task role `orders-api`**: reads/writes items in DynamoDB table `orders` (and its GSI `byStatus`) but only `GetItem`, `PutItem`, `UpdateItem`, `Query`; sends messages to SQS queue `order-events`; reads secret `prod/orders/*`.
3. **GitHub Actions deploy role**: can be assumed only from repository `acme/petpal`, environment `production`; may update the ECS service `api` in cluster `petpal-prod`, register task definitions, and pass only the `orders-api` task role and `ecs-execution` role to ECS.
4. **Third-party monitoring vendor** (account `999999999999`): read-only CloudWatch metrics and EC2/RDS describe calls, assumable only with ExternalId `petpal-7f3c`.

Then:

5. Identify the privilege-escalation risk in the deploy role if `iam:PassRole` were on `*`.
6. Use IAM Access Analyzer's policy generation: describe the steps to tighten an existing over-privileged role based on 90 days of CloudTrail.

## Requirements Checklist

- [ ] 1: trust `lambda.amazonaws.com` (+ `aws:SourceAccount`); `s3:GetObject` on `petpal-uploads/incoming/*`, `s3:PutObject` on `petpal-uploads/thumbnails/*`, `kms:Decrypt`/`kms:GenerateDataKey` on the key with `kms:ViaService = s3.eu-west-1.amazonaws.com`, logs actions on its log group ARN.
- [ ] 2: trust `ecs-tasks.amazonaws.com` with `aws:SourceArn`/`SourceAccount`; DynamoDB actions on the table ARN and `table/orders/index/byStatus`; `sqs:SendMessage` on the queue ARN; `secretsmanager:GetSecretValue` on `secret:prod/orders/*`.
- [ ] 3: trust `token.actions.githubusercontent.com` with `aud = sts.amazonaws.com` and `sub = repo:acme/petpal:environment:production`; `ecs:UpdateService` on the service ARN, `ecs:RegisterTaskDefinition`, `ecs:DescribeServices`; `iam:PassRole` scoped to the two role ARNs with `iam:PassedToService = ecs-tasks.amazonaws.com`.
- [ ] 4: trust `arn:aws:iam::999999999999:root` with `sts:ExternalId = petpal-7f3c`; read-only `cloudwatch:Get*/List*/Describe*`, `ec2:Describe*`, `rds:Describe*` (or the AWS managed ReadOnly policies scoped down).
- [ ] 5: PassRole on `*` lets the deployer pass an admin role to a task/function and run code with it.
- [ ] 6: Access Analyzer → generate policy from CloudTrail for the role → review → replace → monitor AccessDenied → iterate.
