Files
mtusi2026lab4-fork/infra/minio/bootstrap.py
T
2026-11-06 13:57:29 +03:00

78 lines
3.3 KiB
Python

"""Idempotent private bucket and least-privilege application account setup."""
import json
import os
from pathlib import Path
import re
import subprocess
import tempfile
from urllib.parse import quote, urlsplit
def main():
bucket = os.environ["S3_BUCKET"]
endpoint = urlsplit(os.environ["S3_ENDPOINT_URL"])
if not re.fullmatch(r"[a-z0-9][a-z0-9.-]{1,61}[a-z0-9]", bucket):
raise ValueError("Invalid S3_BUCKET")
if endpoint.scheme not in ("http", "https") or not endpoint.netloc:
raise ValueError("Invalid S3_ENDPOINT_URL")
root_user = os.environ["MINIO_ROOT_USER"]
root_password = os.environ["MINIO_ROOT_PASSWORD"]
access_key = os.environ["S3_ACCESS_KEY"]
secret_key = os.environ["S3_SECRET_KEY"]
if access_key == root_user or secret_key == root_password:
raise ValueError("API credentials must differ from MinIO root credentials")
if len(secret_key) < 32 or len(root_password) < 32:
raise ValueError("S3 secret and root password must contain at least 32 characters")
mc_env = {
**os.environ,
"MC_HOST_store": "%s://%s:%s@%s" % (
endpoint.scheme, quote(root_user, safe=""),
quote(root_password, safe=""), endpoint.netloc,
),
}
secrets = (root_user, root_password, access_key, secret_key, mc_env["MC_HOST_store"])
with tempfile.TemporaryDirectory(prefix="minio-bootstrap-") as temporary:
def run_mc(step, *arguments, stdin=None):
result = subprocess.run(
["mc", "--config-dir", temporary, *arguments],
input=stdin, env=mc_env, text=True, capture_output=True, timeout=30,
)
if result.returncode:
detail = result.stderr
for value in secrets:
detail = detail.replace(value, "[redacted]")
raise RuntimeError("%s: %s" % (step, detail[:1000]))
run_mc("create bucket", "mb", "--ignore-existing", "store/" + bucket)
run_mc("disable anonymous access", "anonymous", "set", "none", "store/" + bucket)
policy = {
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": ["s3:GetBucketLocation", "s3:ListBucket"],
"Resource": ["arn:aws:s3:::" + bucket],
},
{
"Effect": "Allow",
"Action": ["s3:GetObject", "s3:PutObject", "s3:DeleteObject"],
"Resource": ["arn:aws:s3:::" + bucket + "/originals/*"],
},
],
}
path = Path(temporary) / "api-policy.json"
path.write_text(json.dumps(policy), encoding="utf-8")
run_mc("create policy", "admin", "policy", "create", "store", "messenger-api", str(path))
# stdin avoids placing keys in process arguments. AddUser is an upsert.
run_mc("create API user", "admin", "user", "add", "store", stdin=access_key + "\n" + secret_key + "\n")
# mc treats an already attached policy as success.
run_mc("attach policy", "admin", "policy", "attach", "store", "messenger-api", "--user", access_key)
print("PASS: private bucket and separate restricted API account configured")
if __name__ == "__main__":
main()