105 lines
4.7 KiB
Python
105 lines
4.7 KiB
Python
"""Повторяемая настройка bucket и IAM-политик RustFS через проверенный TLS."""
|
|
import json
|
|
import os
|
|
import re
|
|
import ssl
|
|
import time
|
|
from botocore.exceptions import ClientError
|
|
import urllib.error
|
|
import urllib.parse
|
|
import urllib.request
|
|
|
|
import boto3
|
|
from botocore.auth import S3SigV4Auth
|
|
from botocore.awsrequest import AWSRequest
|
|
from botocore.credentials import Credentials
|
|
|
|
ENDPOINT = os.environ["S3_ENDPOINT_URL"]
|
|
REGION = os.getenv("S3_REGION", "us-east-1")
|
|
BUCKET = os.environ["S3_BUCKET"]
|
|
CA_FILE = os.environ["TLS_CA_FILE"]
|
|
ROOT_KEY = os.environ["S3_ROOT_ACCESS_KEY"]
|
|
ROOT_SECRET = os.environ["S3_ROOT_SECRET_KEY"]
|
|
|
|
|
|
def admin(method, path, payload):
|
|
url = ENDPOINT + "/rustfs/admin/v3/" + path
|
|
body = json.dumps(payload, separators=(",", ":")).encode()
|
|
request = AWSRequest(method=method, url=url, data=body,
|
|
headers={"Content-Type": "application/json"})
|
|
S3SigV4Auth(Credentials(ROOT_KEY, ROOT_SECRET), "s3", REGION).add_auth(request)
|
|
signed = urllib.request.Request(url, data=body,
|
|
headers=dict(request.headers), method=method)
|
|
context = ssl.create_default_context(cafile=CA_FILE)
|
|
try:
|
|
with urllib.request.urlopen(signed, context=context, timeout=5) as response:
|
|
response.read()
|
|
except urllib.error.HTTPError as exc:
|
|
# Из тела ответа печатается только короткий код ошибки, не произвольные данные сервера.
|
|
if exc.code not in (409, 501):
|
|
raw = exc.read(4096).decode("utf-8", "replace")
|
|
match = re.search(r"<Code>([A-Za-z0-9_]+)</Code>", raw)
|
|
safe_code = match.group(1) if match else "unknown"
|
|
message_match = re.search(r"<Message>([^<]{0,300})</Message>", raw)
|
|
safe_message = message_match.group(1) if message_match else "unavailable"
|
|
safe_message = re.sub(r"[0-9a-fA-F]{32,}", "[redacted]", safe_message)
|
|
safe_message = safe_message.replace(ROOT_KEY, "[redacted]").replace(ROOT_SECRET, "[redacted]")
|
|
raise RuntimeError(f"RustFS IAM bootstrap failed with HTTP {exc.code} ({safe_code}): {safe_message}") from None
|
|
|
|
|
|
def main():
|
|
root = boto3.client("s3", endpoint_url=ENDPOINT, region_name=REGION,
|
|
aws_access_key_id=ROOT_KEY, aws_secret_access_key=ROOT_SECRET,
|
|
verify=CA_FILE)
|
|
for attempt in range(30):
|
|
try:
|
|
root.list_buckets()
|
|
break
|
|
except Exception:
|
|
if attempt == 29:
|
|
raise RuntimeError("RustFS did not become ready") from None
|
|
time.sleep(1)
|
|
else:
|
|
raise RuntimeError("RustFS did not become ready")
|
|
try:
|
|
root.head_bucket(Bucket=BUCKET)
|
|
except ClientError as exc:
|
|
code = str(exc.response.get("Error", {}).get("Code", ""))
|
|
if code not in ("404", "NoSuchBucket", "NotFound"):
|
|
raise RuntimeError("RustFS bucket check failed") from None
|
|
root.create_bucket(Bucket=BUCKET)
|
|
|
|
bucket_arn = f"arn:aws:s3:::{BUCKET}"
|
|
api_policy = {
|
|
"Version": "2012-10-17",
|
|
"Statement": [
|
|
{"Effect": "Allow", "Action": ["s3:ListBucket", "s3:GetBucketLocation"], "Resource": [bucket_arn]},
|
|
{"Effect": "Allow", "Action": ["s3:GetObject", "s3:PutObject", "s3:DeleteObject"],
|
|
"Resource": [bucket_arn + "/staging/*", bucket_arn + "/original/*", bucket_arn + "/variants/*"]},
|
|
],
|
|
}
|
|
worker_policy = {
|
|
"Version": "2012-10-17",
|
|
"Statement": [
|
|
{"Effect": "Allow", "Action": ["s3:GetObject", "s3:DeleteObject"],
|
|
"Resource": [bucket_arn + "/staging/*"]},
|
|
{"Effect": "Allow", "Action": ["s3:PutObject"],
|
|
"Resource": [bucket_arn + "/original/*", bucket_arn + "/variants/*"]},
|
|
],
|
|
}
|
|
for name, policy in (("messenger-api", api_policy), ("messenger-worker", worker_policy)):
|
|
admin("PUT", "add-canned-policy?" + urllib.parse.urlencode({"name": name}), policy)
|
|
for name in ("api", "worker"):
|
|
access = open(f"/run/identity/s3_{name}_access_key", encoding="utf-8").read().strip()
|
|
secret = open(f"/run/identity/s3_{name}_secret_key", encoding="utf-8").read().strip()
|
|
policy = "messenger-api" if name == "api" else "messenger-worker"
|
|
admin("PUT", "add-user?" + urllib.parse.urlencode({"accessKey": access}),
|
|
{"secretKey": secret, "status": "enabled"})
|
|
query = urllib.parse.urlencode({"policyName": policy, "userOrGroup": access, "isGroup": "false"})
|
|
admin("PUT", "set-user-or-group-policy?" + query, {})
|
|
print("RustFS bucket and scoped API/worker identities are ready.")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|