#!/usr/bin/env bash
# lab4a/seed-aws.sh
# Seeds a deliberately weak IAM stub in LocalStack for the cloud pentest lab (Lab 17.4a).
# Creates:
#   - S3 bucket "lab-public-data" with a public-read policy
#   - IAM user "lab-lowpriv" with minimal permissions + sts:AssumeRole
#   - IAM role "lab-overpermissioned" with S3 full access (the privesc target)
#   - A secret object in the bucket readable by the over-permissioned role
# Run: docker compose --profile lab4a run --rm aws-tools bash /lab4a/seed-aws.sh
set -euo pipefail

ENDPOINT="http://localstack:4566"
REGION="us-east-1"
ACCOUNT="000000000000"

echo "[*] Waiting for LocalStack..."
until curl -sf "${ENDPOINT}/_localstack/health" | grep -q '"s3": "available"'; do sleep 2; done
echo "[*] LocalStack ready."

echo "[*] Creating S3 bucket and seeding secret object..."
awslocal --endpoint-url="${ENDPOINT}" s3api create-bucket \
    --bucket lab-public-data --region "${REGION}" 2>/dev/null || true
awslocal --endpoint-url="${ENDPOINT}" s3 cp \
    /dev/stdin "s3://lab-public-data/secret-data.txt" <<'EOF'
Stub secret: IAM role credentials would appear here via SSRF -> IMDS -> role-name -> AccessKeyId.
This file demonstrates the S3 object that becomes readable after sts:AssumeRole escalation.
EOF

echo "[*] Creating IAM user lab-lowpriv..."
awslocal --endpoint-url="${ENDPOINT}" iam create-user --user-name lab-lowpriv 2>/dev/null || true
awslocal --endpoint-url="${ENDPOINT}" iam create-access-key --user-name lab-lowpriv

echo "[*] Creating over-permissioned IAM role..."
awslocal --endpoint-url="${ENDPOINT}" iam create-role \
    --role-name lab-overpermissioned \
    --assume-role-policy-document '{
      "Version":"2012-10-17",
      "Statement":[{
        "Effect":"Allow",
        "Principal":{"AWS":"arn:aws:iam::'"${ACCOUNT}"':root"},
        "Action":"sts:AssumeRole"
      }]
    }' 2>/dev/null || true
awslocal --endpoint-url="${ENDPOINT}" iam attach-role-policy \
    --role-name lab-overpermissioned \
    --policy-arn arn:aws:iam::aws:policy/AmazonS3FullAccess 2>/dev/null || true

echo ""
echo "[*] Stub seeded. Lab-lowpriv access keys printed above."
echo "[*] Next: run 'pacu' or 'scout aws' from this container against http://localstack:4566"
echo "[*] See README Lab 17.4a for the full walkthrough."
