74 lines
2.3 KiB
Bash
74 lines
2.3 KiB
Bash
#!/bin/sh
|
|
set -eu
|
|
umask 077
|
|
|
|
bucket=${S3_BUCKET:-messenger-attachments}
|
|
case "$bucket" in
|
|
''|*[!a-z0-9.-]*) echo 'Invalid S3 bucket name' >&2; exit 1 ;;
|
|
esac
|
|
|
|
config=$(mktemp -d)
|
|
trap 'rm -rf "$config"' EXIT
|
|
export MC_CONFIG_DIR="$config"
|
|
root_user=$(cat /run/secrets/s3_root_user)
|
|
root_password=$(cat /run/secrets/s3_root_password)
|
|
api_user=$(cat /run/secrets/s3_access_key_id)
|
|
api_password=$(cat /run/secrets/s3_secret_access_key)
|
|
endpoint=${S3_ENDPOINT:-http://s3:9000}
|
|
|
|
if [ "${1:-}" = verify ]; then
|
|
export MC_HOST_api="http://$api_user:$api_password@${endpoint#http://}"
|
|
key="attachments/probe-${config##*/}"
|
|
object="api/$bucket/$key"
|
|
trap 'mc rm "$object" >/dev/null 2>&1 || true; rm -rf "$config"' EXIT
|
|
printf '%s' 'lab6-private-bucket-probe' | mc pipe "$object" >/dev/null
|
|
test "$(mc cat "$object")" = 'lab6-private-bucket-probe'
|
|
python3 - "$endpoint/$bucket/$key" <<'PYTEST'
|
|
import sys
|
|
from urllib.error import HTTPError
|
|
from urllib.request import urlopen
|
|
|
|
try:
|
|
with urlopen(sys.argv[1], timeout=5):
|
|
raise SystemExit("FAIL: anonymous GET succeeded")
|
|
except HTTPError as exc:
|
|
if exc.code != 403:
|
|
raise
|
|
print("PASS: authenticated round trip; anonymous GET returned 403")
|
|
PYTEST
|
|
mc rm "$object" >/dev/null
|
|
exit 0
|
|
fi
|
|
|
|
attempt=0
|
|
until mc alias set storage "$endpoint" "$root_user" "$root_password" >/dev/null 2>&1 &&
|
|
mc admin info storage >/dev/null 2>&1; do
|
|
attempt=$((attempt + 1))
|
|
if [ "$attempt" -ge 30 ]; then
|
|
echo 'S3 bootstrap could not connect or authenticate' >&2
|
|
exit 1
|
|
fi
|
|
sleep 1
|
|
done
|
|
|
|
mc mb --ignore-existing "storage/$bucket"
|
|
mc anonymous set none "storage/$bucket"
|
|
cat > "$config/api-policy.json" <<POLICY
|
|
{
|
|
"Version": "2012-10-17",
|
|
"Statement": [{
|
|
"Effect": "Allow",
|
|
"Action": ["s3:GetObject", "s3:PutObject", "s3:DeleteObject"],
|
|
"Resource": ["arn:aws:s3:::$bucket/attachments/*"]
|
|
}, {
|
|
"Effect": "Allow",
|
|
"Action": ["s3:GetBucketLocation"],
|
|
"Resource": ["arn:aws:s3:::$bucket"]
|
|
}]
|
|
}
|
|
POLICY
|
|
mc admin policy create storage lab6-attachments "$config/api-policy.json"
|
|
mc admin user add storage "$api_user" "$api_password" >/dev/null
|
|
mc admin policy attach storage lab6-attachments --user "$api_user"
|
|
echo 'PASS: private S3 bucket and scoped API policy configured'
|