#!/bin/sh # Bootstrap of the S3 storage (MinIO), run by the one-shot service s3-init before api starts. # Idempotent: every step can be repeated (docker compose run --rm s3-init) without losing data. # 1. private bucket S3_BUCKET (no anonymous access, versioning off); # 2. policy messenger-api: only Get/Put/Delete/List objects of this bucket (JSON below); # 3. separate user for api/janitor with this policy. Root credentials stay in s3 and s3-init only. # Secrets are read from /run/secrets and are never printed. set -eu BUCKET="${S3_BUCKET:?S3_BUCKET is not set}" ROOT_USER="$(cat /run/secrets/s3_root_user)" ROOT_PASSWORD="$(cat /run/secrets/s3_root_password)" API_KEY="$(cat /run/secrets/s3_access_key_id)" API_SECRET="$(cat /run/secrets/s3_secret_access_key)" POLICY=messenger-api export MC_CONFIG_DIR=/tmp/mc # Least privilege for the api key: objects of ONE bucket. No bucket admin, policies, users or other buckets. cat > /tmp/policy.json </dev/null 2>&1; do i=$((i + 1)) [ "$i" -ge 30 ] && { echo "s3-init: MinIO is not reachable"; exit 1; } sleep 1 done mc mb --ignore-existing "local/${BUCKET}" >/dev/null mc anonymous set none "local/${BUCKET}" >/dev/null echo "s3-init: bucket ${BUCKET} exists" mc admin policy create local "$POLICY" /tmp/policy.json >/dev/null echo "s3-init: policy ${POLICY} created/updated" mc admin user add local "$API_KEY" "$API_SECRET" >/dev/null info="$(mc admin user info local "$API_KEY" 2>/dev/null || true)" case "$info" in *"$POLICY"*) ;; *) mc admin policy attach local "$POLICY" --user "$API_KEY" >/dev/null ;; esac echo "s3-init: api user exists with policy ${POLICY} only" access="$(mc anonymous get "local/${BUCKET}")" case "$access" in *private*) echo "s3-init: bucket is private (anonymous access: none)" ;; *) echo "s3-init: bucket is NOT private: $access"; exit 1 ;; esac