Files
mtusi2026lab7-fork/infra/s3-init.sh
2026-11-23 14:39:13 +03:00

40 lines
2.4 KiB
Bash

#!/bin/sh
# Idempotent bootstrap: private bucket + THREE scoped S3 users (api, worker, sweeper). Runs with the S3 root credentials, then exits.
# api : write/delete staging/*, read attachments/* (accepts uploads, serves downloads)
# worker : read/delete staging/*, write attachments/* (cannot read finished attachments, cannot write staging, cannot list)
# sweeper: list bucket, read/delete staging/* and attachments/* (no PutObject)
set -eu
: "${S3_ENDPOINT:?}" "${S3_BUCKET:?}"
RU="$(cat /run/secrets/s3_root_user)"; RP="$(cat /run/secrets/s3_root_password)"
i=0
until mc alias set local "$S3_ENDPOINT" "$RU" "$RP" >/dev/null 2>&1; do
i=$((i+1)); [ "$i" -lt 60 ] || { echo "S3 not reachable over TLS" >&2; exit 1; }; sleep 1
done
mc mb --ignore-existing "local/$S3_BUCKET"
mc anonymous set none "local/$S3_BUCKET"
printf ok | mc pipe "local/$S3_BUCKET/attachments/.ready"
B="arn:aws:s3:::$S3_BUCKET"
cat > /tmp/p-api.json <<P
{"Version":"2012-10-17","Statement":[
{"Effect":"Allow","Action":["s3:PutObject","s3:DeleteObject","s3:AbortMultipartUpload","s3:ListMultipartUploadParts"],"Resource":["$B/staging/*"]},
{"Effect":"Allow","Action":["s3:GetObject"],"Resource":["$B/attachments/*"]}]}
P
cat > /tmp/p-worker.json <<P
{"Version":"2012-10-17","Statement":[
{"Effect":"Allow","Action":["s3:GetObject","s3:DeleteObject"],"Resource":["$B/staging/*"]},
{"Effect":"Allow","Action":["s3:PutObject","s3:AbortMultipartUpload","s3:ListMultipartUploadParts"],"Resource":["$B/attachments/*"]}]}
P
cat > /tmp/p-sweeper.json <<P
{"Version":"2012-10-17","Statement":[
{"Effect":"Allow","Action":["s3:ListBucket","s3:GetBucketLocation"],"Resource":["$B"]},
{"Effect":"Allow","Action":["s3:GetObject","s3:DeleteObject"],"Resource":["$B/attachments/*","$B/staging/*"]}]}
P
for r in api worker sweeper; do
key="svc-$r"; [ "$key" != "$RU" ] || { echo "service key must differ from root" >&2; exit 1; }
mc admin policy remove local "messenger-$r" --force >/dev/null 2>&1 || true
mc admin policy create local "messenger-$r" "/tmp/p-$r.json"
mc admin user add local "$key" "$(cat /run/secrets/s3_${r}_secret)" # idempotent: re-running = secret rotation
out=$(mc admin policy attach local "messenger-$r" --user "$key" 2>&1) || { echo "$out" | grep -qi already || { echo "$out" >&2; exit 1; }; }
done
echo "PASS: bucket $S3_BUCKET private; users svc-api, svc-worker, svc-sweeper with separate policies"