forked from mtusi2026/mtusi2026lab7
ЛР 7: Безопасность, mTLS и OpenBao
This commit is contained in:
@@ -0,0 +1,211 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Initialize/unseal OpenBao and configure a limited AppRole."""
|
||||
import json
|
||||
import os
|
||||
import ssl
|
||||
import time
|
||||
import urllib.request
|
||||
import base64
|
||||
import secrets
|
||||
from urllib.error import HTTPError
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
ROOT = Path("/app")
|
||||
SECRETS = ROOT / ".secrets"
|
||||
STATE = SECRETS / "openbao.json"
|
||||
API_POLICY = (ROOT / "infra/openbao/messenger-policy.hcl").read_text(encoding="utf-8")
|
||||
WORKER_POLICY = (ROOT / "infra/openbao/messenger-worker-policy.hcl").read_text(encoding="utf-8")
|
||||
CA = SECRETS / "certs/internal-ca.crt"
|
||||
ADDR = "https://openbao:8200"
|
||||
|
||||
|
||||
def call(path, method="GET", body=None, token=None):
|
||||
context = ssl.create_default_context(cafile=str(CA))
|
||||
headers = {"Content-Type": "application/json"}
|
||||
if token:
|
||||
headers["X-Vault-Token"] = token
|
||||
data = json.dumps(body).encode("utf-8") if body is not None else None
|
||||
request = urllib.request.Request(
|
||||
ADDR + path,
|
||||
data=data,
|
||||
headers=headers,
|
||||
method=method,
|
||||
)
|
||||
with urllib.request.urlopen(request, context=context, timeout=5) as response:
|
||||
raw = response.read()
|
||||
if not raw:
|
||||
return {}
|
||||
return json.loads(raw)
|
||||
|
||||
|
||||
def wait_ready():
|
||||
for _ in range(60):
|
||||
try:
|
||||
call("/v1/sys/health")
|
||||
except HTTPError as error:
|
||||
if error.code in (429, 472, 473, 501, 503):
|
||||
return
|
||||
time.sleep(1)
|
||||
except Exception:
|
||||
time.sleep(1)
|
||||
else:
|
||||
return
|
||||
raise SystemExit("OpenBao did not become ready")
|
||||
|
||||
|
||||
def root_token_is_valid(root):
|
||||
try:
|
||||
call("/v1/auth/token/lookup-self", "GET", token=root)
|
||||
return True
|
||||
except HTTPError as error:
|
||||
if error.code in (403, 400):
|
||||
return False
|
||||
raise
|
||||
|
||||
|
||||
def recover_root_token(unseal_key):
|
||||
otp_bytes = secrets.token_bytes(16)
|
||||
otp = base64.b64encode(otp_bytes).decode("ascii")
|
||||
attempt = call(
|
||||
"/v1/sys/generate-root/attempt",
|
||||
"PUT",
|
||||
{"otp": otp},
|
||||
)
|
||||
nonce = attempt["nonce"]
|
||||
update = call(
|
||||
"/v1/sys/generate-root/update",
|
||||
"PUT",
|
||||
{"key": unseal_key, "nonce": nonce},
|
||||
)
|
||||
if not update.get("complete"):
|
||||
raise SystemExit("OpenBao root token recovery did not complete")
|
||||
encoded = base64.b64decode(update["encoded_root_token"])
|
||||
decoded = bytes(value ^ otp_bytes[index] for index, value in enumerate(encoded))
|
||||
return decoded.decode("ascii")
|
||||
|
||||
|
||||
def main():
|
||||
SECRETS.mkdir(parents=True, exist_ok=True)
|
||||
SECRETS.chmod(0o700)
|
||||
wait_ready()
|
||||
if STATE.exists():
|
||||
state = json.loads(STATE.read_text(encoding="utf-8"))
|
||||
STATE.chmod(0o600)
|
||||
else:
|
||||
init = call("/v1/sys/init", "PUT", {"secret_shares": 1, "secret_threshold": 1})
|
||||
state = {
|
||||
"unseal_key": init["keys"][0],
|
||||
"root_token": init["root_token"],
|
||||
}
|
||||
STATE.write_text(json.dumps(state), encoding="utf-8")
|
||||
STATE.chmod(0o600)
|
||||
|
||||
try:
|
||||
health = call("/v1/sys/health")
|
||||
except Exception:
|
||||
health = {"sealed": True}
|
||||
if health.get("sealed"):
|
||||
call("/v1/sys/unseal", "PUT", {"key": state["unseal_key"]})
|
||||
|
||||
marker = SECRETS / "approle-created"
|
||||
root = state["root_token"]
|
||||
if not root_token_is_valid(root):
|
||||
root = recover_root_token(state["unseal_key"])
|
||||
state["root_token"] = root
|
||||
STATE.write_text(json.dumps(state), encoding="utf-8")
|
||||
STATE.chmod(0o600)
|
||||
try:
|
||||
call(
|
||||
"/v1/sys/mounts/secret",
|
||||
"POST",
|
||||
{"type": "kv", "options": {"version": "2"}},
|
||||
root,
|
||||
)
|
||||
except HTTPError as error:
|
||||
if error.code != 400:
|
||||
raise
|
||||
call("/v1/sys/policies/acl/messenger-api", "PUT", {"policy": API_POLICY}, root)
|
||||
call("/v1/sys/policies/acl/messenger-worker", "PUT", {"policy": WORKER_POLICY}, root)
|
||||
try:
|
||||
call("/v1/sys/auth/approle", "POST", {"type": "approle"}, root)
|
||||
except HTTPError as error:
|
||||
if error.code != 400:
|
||||
raise
|
||||
call(
|
||||
"/v1/auth/approle/role/messenger-api",
|
||||
"POST",
|
||||
{
|
||||
"token_policies": ["messenger-api"],
|
||||
"token_ttl": "10m",
|
||||
"token_max_ttl": "30m",
|
||||
},
|
||||
root,
|
||||
)
|
||||
call(
|
||||
"/v1/auth/approle/role/messenger-worker",
|
||||
"POST",
|
||||
{
|
||||
"token_policies": ["messenger-worker"],
|
||||
"token_ttl": "10m",
|
||||
"token_max_ttl": "30m",
|
||||
},
|
||||
root,
|
||||
)
|
||||
call(
|
||||
"/v1/secret/data/messenger/api",
|
||||
"POST",
|
||||
{"data": {
|
||||
"role": "api",
|
||||
"pg_user": os.environ["API_DB_USER"],
|
||||
"pg_password": os.environ["API_DB_PASSWORD"],
|
||||
"s3_access": os.environ["S3_API_ACCESS_KEY"],
|
||||
"s3_secret": os.environ["S3_API_SECRET_KEY"],
|
||||
"broker_user": os.environ["BROKER_API_USER"],
|
||||
"broker_password": os.environ["BROKER_API_PASSWORD"],
|
||||
}},
|
||||
root,
|
||||
)
|
||||
call(
|
||||
"/v1/secret/data/messenger/worker",
|
||||
"POST",
|
||||
{"data": {
|
||||
"role": "worker",
|
||||
"pg_user": os.environ["WORKER_DB_USER"],
|
||||
"pg_password": os.environ["WORKER_DB_PASSWORD"],
|
||||
"s3_access": os.environ["S3_WORKER_ACCESS_KEY"],
|
||||
"s3_secret": os.environ["S3_WORKER_SECRET_KEY"],
|
||||
"broker_user": os.environ["BROKER_WORKER_USER"],
|
||||
"broker_password": os.environ["BROKER_WORKER_PASSWORD"],
|
||||
}},
|
||||
root,
|
||||
)
|
||||
api_role = call("/v1/auth/approle/role/messenger-api/role-id", "GET", token=root)
|
||||
worker_role = call("/v1/auth/approle/role/messenger-worker/role-id", "GET", token=root)
|
||||
api_secret = call(
|
||||
"/v1/auth/approle/role/messenger-api/secret-id",
|
||||
"POST",
|
||||
{},
|
||||
root,
|
||||
)
|
||||
worker_secret = call(
|
||||
"/v1/auth/approle/role/messenger-worker/secret-id",
|
||||
"POST",
|
||||
{},
|
||||
root,
|
||||
)
|
||||
for path, value in (
|
||||
(SECRETS / "api-role-id", api_role["data"]["role_id"]),
|
||||
(SECRETS / "api-secret-id", api_secret["data"]["secret_id"]),
|
||||
(SECRETS / "worker-role-id", worker_role["data"]["role_id"]),
|
||||
(SECRETS / "worker-secret-id", worker_secret["data"]["secret_id"]),
|
||||
):
|
||||
path.write_text(value, encoding="utf-8")
|
||||
path.chmod(0o644)
|
||||
marker.write_text("configured", encoding="utf-8")
|
||||
marker.chmod(0o600)
|
||||
print("PASS: OpenBao is unsealed and scoped AppRoles are configured")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,59 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Add independent random service credentials to the local ignored .env file."""
|
||||
import secrets
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
ENV_FILE = ROOT / ".env"
|
||||
PASSWORD_KEYS = (
|
||||
"API_DB_PASSWORD",
|
||||
"WORKER_DB_PASSWORD",
|
||||
"S3_API_SECRET_KEY",
|
||||
"S3_WORKER_SECRET_KEY",
|
||||
"BROKER_API_PASSWORD",
|
||||
"BROKER_WORKER_PASSWORD",
|
||||
)
|
||||
FIXED_VALUES = {
|
||||
"API_DB_USER": "messenger_api",
|
||||
"WORKER_DB_USER": "messenger_worker",
|
||||
"S3_API_ACCESS_KEY": "messenger-api",
|
||||
"S3_WORKER_ACCESS_KEY": "messenger-worker",
|
||||
"BROKER_API_USER": "messenger-api",
|
||||
"BROKER_WORKER_USER": "messenger-worker",
|
||||
}
|
||||
|
||||
|
||||
def main():
|
||||
if not ENV_FILE.is_file():
|
||||
raise SystemExit("Copy .env.example to .env before generating local credentials")
|
||||
|
||||
lines = ENV_FILE.read_text(encoding="utf-8").splitlines()
|
||||
existing = {}
|
||||
for line in lines:
|
||||
if "=" in line and not line.lstrip().startswith("#"):
|
||||
key, value = line.split("=", 1)
|
||||
existing[key.strip()] = value.strip()
|
||||
|
||||
additions = {}
|
||||
for key, value in FIXED_VALUES.items():
|
||||
if not existing.get(key):
|
||||
additions[key] = value
|
||||
for key in PASSWORD_KEYS:
|
||||
if not existing.get(key) or "replace-with" in existing[key]:
|
||||
additions[key] = secrets.token_urlsafe(36)
|
||||
|
||||
if additions:
|
||||
lines.extend(["", "# Generated locally; do not commit these service credentials."])
|
||||
lines.extend(key + "=" + value for key, value in additions.items())
|
||||
temporary = ENV_FILE.with_suffix(".env.tmp")
|
||||
temporary.write_text("\n".join(lines) + "\n", encoding="utf-8")
|
||||
temporary.chmod(0o600)
|
||||
temporary.replace(ENV_FILE)
|
||||
ENV_FILE.chmod(0o600)
|
||||
|
||||
print("PASS: local service credentials are present; values were not displayed")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,197 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Create a local CA and service certificates outside Git."""
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from pathlib import Path
|
||||
import ipaddress
|
||||
|
||||
from cryptography import x509
|
||||
from cryptography.hazmat.primitives import hashes, serialization
|
||||
from cryptography.hazmat.primitives.asymmetric import rsa
|
||||
from cryptography.x509.oid import ExtendedKeyUsageOID, NameOID
|
||||
import argparse
|
||||
|
||||
|
||||
APP_ROOT = Path("/app")
|
||||
ROOT = APP_ROOT if (APP_ROOT / ".secrets").exists() else Path(__file__).resolve().parents[1]
|
||||
OUT = ROOT / ".secrets" / "certs"
|
||||
OUT.mkdir(parents=True, exist_ok=True)
|
||||
OUT.parent.chmod(0o700)
|
||||
OUT.chmod(0o700)
|
||||
|
||||
|
||||
def key():
|
||||
return rsa.generate_private_key(public_exponent=65537, key_size=2048)
|
||||
|
||||
|
||||
def write_key(path, private_key):
|
||||
path.write_bytes(private_key.private_bytes(
|
||||
serialization.Encoding.PEM,
|
||||
serialization.PrivateFormat.TraditionalOpenSSL,
|
||||
serialization.NoEncryption(),
|
||||
))
|
||||
path.chmod(0o600)
|
||||
|
||||
|
||||
def write_cert(path, cert):
|
||||
path.write_bytes(cert.public_bytes(serialization.Encoding.PEM))
|
||||
|
||||
|
||||
def ca(name):
|
||||
private_key = key()
|
||||
subject = x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, name)])
|
||||
cert = (
|
||||
x509.CertificateBuilder()
|
||||
.subject_name(subject)
|
||||
.issuer_name(subject)
|
||||
.public_key(private_key.public_key())
|
||||
.serial_number(x509.random_serial_number())
|
||||
.not_valid_before(datetime.now(timezone.utc) - timedelta(minutes=5))
|
||||
.not_valid_after(datetime.now(timezone.utc) + timedelta(days=365))
|
||||
.add_extension(x509.BasicConstraints(ca=True, path_length=1), critical=True)
|
||||
.add_extension(
|
||||
x509.KeyUsage(
|
||||
digital_signature=True,
|
||||
key_encipherment=False,
|
||||
key_cert_sign=True,
|
||||
crl_sign=True,
|
||||
content_commitment=False,
|
||||
data_encipherment=False,
|
||||
key_agreement=False,
|
||||
encipher_only=False,
|
||||
decipher_only=False,
|
||||
),
|
||||
critical=True,
|
||||
)
|
||||
.add_extension(
|
||||
x509.SubjectKeyIdentifier.from_public_key(private_key.public_key()),
|
||||
critical=False,
|
||||
)
|
||||
.add_extension(
|
||||
x509.AuthorityKeyIdentifier.from_issuer_public_key(private_key.public_key()),
|
||||
critical=False,
|
||||
)
|
||||
.sign(private_key, hashes.SHA256())
|
||||
)
|
||||
return private_key, cert
|
||||
|
||||
|
||||
def leaf(ca_key, ca_cert, name, dns_names, ip_names=(), server=True, client=False):
|
||||
private_key = key()
|
||||
subject = x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, name)])
|
||||
usages = []
|
||||
if server:
|
||||
usages.append(ExtendedKeyUsageOID.SERVER_AUTH)
|
||||
if client:
|
||||
usages.append(ExtendedKeyUsageOID.CLIENT_AUTH)
|
||||
builder = (
|
||||
x509.CertificateBuilder()
|
||||
.subject_name(subject)
|
||||
.issuer_name(ca_cert.subject)
|
||||
.public_key(private_key.public_key())
|
||||
.serial_number(x509.random_serial_number())
|
||||
.not_valid_before(datetime.now(timezone.utc) - timedelta(minutes=5))
|
||||
.not_valid_after(datetime.now(timezone.utc) + timedelta(days=365))
|
||||
.add_extension(x509.BasicConstraints(ca=False, path_length=None), critical=True)
|
||||
.add_extension(
|
||||
x509.SubjectAlternativeName(
|
||||
[x509.DNSName(value) for value in dns_names]
|
||||
+ [x509.IPAddress(ipaddress.ip_address(value)) for value in ip_names]
|
||||
),
|
||||
critical=False,
|
||||
)
|
||||
.add_extension(x509.ExtendedKeyUsage(usages), critical=False)
|
||||
.add_extension(
|
||||
x509.SubjectKeyIdentifier.from_public_key(private_key.public_key()),
|
||||
critical=False,
|
||||
)
|
||||
.add_extension(
|
||||
x509.AuthorityKeyIdentifier.from_issuer_public_key(ca_key.public_key()),
|
||||
critical=False,
|
||||
)
|
||||
)
|
||||
cert = builder.sign(ca_key, hashes.SHA256())
|
||||
return private_key, cert
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--force", action="store_true")
|
||||
args = parser.parse_args()
|
||||
required = (
|
||||
"public-ca.crt", "public-ca.key",
|
||||
"public-server.crt", "public-server.key",
|
||||
"internal-ca.crt", "internal-ca.key",
|
||||
"lb.crt", "lb.key", "api.crt", "api.key",
|
||||
"db.crt", "db.key", "s3.crt", "s3.key",
|
||||
"broker.crt", "broker.key", "openbao.crt", "openbao.key",
|
||||
"otel-collector.crt", "otel-collector.key",
|
||||
"loki.crt", "loki.key", "tempo.crt", "tempo.key",
|
||||
"prometheus.crt", "prometheus.key",
|
||||
)
|
||||
if not args.force and all((OUT / name).is_file() for name in required):
|
||||
for name in (
|
||||
"public-server.key", "lb.key", "rogue.key", "api.key",
|
||||
"db.key", "s3.key", "broker.key", "openbao.key",
|
||||
"otel-collector.key", "loki.key", "tempo.key", "prometheus.key",
|
||||
):
|
||||
(OUT / name).chmod(0o644)
|
||||
print("PASS: existing local CA and leaf certificates retained")
|
||||
return
|
||||
|
||||
public_key, public_ca = ca("MTUSI Lab7 Public CA")
|
||||
write_key(OUT / "public-ca.key", public_key)
|
||||
write_cert(OUT / "public-ca.crt", public_ca)
|
||||
public_leaf_key, public_leaf = leaf(
|
||||
public_key,
|
||||
public_ca,
|
||||
"localhost",
|
||||
["localhost", "lb"],
|
||||
["127.0.0.1"],
|
||||
server=True,
|
||||
client=False,
|
||||
)
|
||||
write_key(OUT / "public-server.key", public_leaf_key)
|
||||
write_cert(OUT / "public-server.crt", public_leaf)
|
||||
|
||||
internal_key, internal_ca = ca("MTUSI Lab7 Internal CA")
|
||||
write_key(OUT / "internal-ca.key", internal_key)
|
||||
write_cert(OUT / "internal-ca.crt", internal_ca)
|
||||
|
||||
lb_key, lb_cert = leaf(
|
||||
internal_key, internal_ca, "messenger-lb",
|
||||
["lb", "localhost"], client=True, server=False,
|
||||
)
|
||||
write_key(OUT / "lb.key", lb_key)
|
||||
write_cert(OUT / "lb.crt", lb_cert)
|
||||
|
||||
rogue_key, rogue_cert = leaf(
|
||||
internal_key, internal_ca, "rogue-client",
|
||||
["rogue", "rogue-client"], client=True, server=False,
|
||||
)
|
||||
write_key(OUT / "rogue.key", rogue_key)
|
||||
write_cert(OUT / "rogue.crt", rogue_cert)
|
||||
|
||||
api_key, api_cert = leaf(
|
||||
internal_key, internal_ca, "messenger-api",
|
||||
["api", "messenger-api"], server=True, client=False,
|
||||
)
|
||||
write_key(OUT / "api.key", api_key)
|
||||
write_cert(OUT / "api.crt", api_cert)
|
||||
|
||||
for name in (
|
||||
"db", "s3", "broker", "openbao", "otel-collector",
|
||||
"loki", "tempo", "prometheus",
|
||||
):
|
||||
leaf_key, leaf_cert = leaf(
|
||||
internal_key, internal_ca, name,
|
||||
[name, "localhost"], ["127.0.0.1"],
|
||||
server=True, client=False,
|
||||
)
|
||||
write_key(OUT / f"{name}.key", leaf_key)
|
||||
write_cert(OUT / f"{name}.crt", leaf_cert)
|
||||
|
||||
print("PASS: local public/internal CA and leaf certificates created")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,80 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Provision isolated RabbitMQ API and worker users through verified HTTPS."""
|
||||
import base64
|
||||
import json
|
||||
import os
|
||||
import ssl
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
|
||||
|
||||
def request(path, username, password, context, method="GET", body=None):
|
||||
headers = {
|
||||
"Authorization": "Basic " + base64.b64encode(
|
||||
(username + ":" + password).encode("utf-8")
|
||||
).decode("ascii"),
|
||||
"Content-Type": "application/json",
|
||||
}
|
||||
data = json.dumps(body).encode("utf-8") if body is not None else None
|
||||
req = urllib.request.Request(
|
||||
"https://broker:15671/api" + path,
|
||||
data=data,
|
||||
headers=headers,
|
||||
method=method,
|
||||
)
|
||||
with urllib.request.urlopen(req, context=context, timeout=5) as response:
|
||||
response.read()
|
||||
return response.status
|
||||
|
||||
|
||||
def main():
|
||||
context = ssl.create_default_context(cafile=os.environ["INTERNAL_CA_CERT"])
|
||||
admin_user = os.environ["RABBITMQ_DEFAULT_USER"]
|
||||
admin_password = os.environ["RABBITMQ_DEFAULT_PASS"]
|
||||
for attempt in range(30):
|
||||
try:
|
||||
request("/overview", admin_user, admin_password, context)
|
||||
break
|
||||
except (OSError, urllib.error.URLError):
|
||||
if attempt == 29:
|
||||
raise RuntimeError("RabbitMQ HTTPS management endpoint unavailable") from None
|
||||
time.sleep(2)
|
||||
|
||||
configure = r"^attachment\.jobs(\.v1|\.dlx|\.dead)$"
|
||||
read_main = r"^attachment\.jobs\.v1$"
|
||||
write_main = r"^attachment\.jobs\.v1$"
|
||||
api_write = r"^(attachment\.jobs(\.v1|\.dlx|\.dead)|amq\.default)$"
|
||||
api_read = r"^attachment\.jobs(\.v1|\.dlx|\.dead)$"
|
||||
worker_write = r"^attachment\.jobs(\.v1|\.dlx|\.dead)$"
|
||||
worker_read = r"^attachment\.jobs(\.v1|\.dlx|\.dead)$"
|
||||
for role in ("API", "WORKER"):
|
||||
user = os.environ["BROKER_" + role + "_USER"]
|
||||
password = os.environ["BROKER_" + role + "_PASSWORD"]
|
||||
encoded_user = urllib.parse.quote(user, safe="")
|
||||
request(
|
||||
"/users/" + encoded_user,
|
||||
admin_user,
|
||||
admin_password,
|
||||
context,
|
||||
method="PUT",
|
||||
body={"password": password, "tags": ""},
|
||||
)
|
||||
request(
|
||||
"/permissions/%2F/" + encoded_user,
|
||||
admin_user,
|
||||
admin_password,
|
||||
context,
|
||||
method="PUT",
|
||||
body={
|
||||
"configure": configure,
|
||||
"write": api_write if role == "API" else worker_write,
|
||||
"read": api_read if role == "API" else worker_read,
|
||||
},
|
||||
)
|
||||
print("PASS: RabbitMQ API/worker users have separate queue-scoped permissions")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,76 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Create non-owner database accounts with API and worker table grants."""
|
||||
import os
|
||||
|
||||
import psycopg
|
||||
from psycopg import sql
|
||||
|
||||
|
||||
def main():
|
||||
ca_file = os.environ["INTERNAL_CA_CERT"]
|
||||
conninfo = psycopg.conninfo.make_conninfo(
|
||||
host=os.environ["PGHOST"],
|
||||
port=os.environ.get("PGPORT", "5432"),
|
||||
dbname=os.environ["PGDATABASE"],
|
||||
user=os.environ["PGUSER"],
|
||||
password=os.environ["PGPASSWORD"],
|
||||
sslmode="verify-full",
|
||||
sslrootcert=ca_file,
|
||||
connect_timeout=5,
|
||||
)
|
||||
accounts = (
|
||||
(os.environ["API_DB_USER"], os.environ["API_DB_PASSWORD"]),
|
||||
(os.environ["WORKER_DB_USER"], os.environ["WORKER_DB_PASSWORD"]),
|
||||
)
|
||||
with psycopg.connect(conninfo, autocommit=True) as conn:
|
||||
conn.execute(
|
||||
sql.SQL("REVOKE CREATE ON SCHEMA public FROM PUBLIC")
|
||||
)
|
||||
for username, password in accounts:
|
||||
found = conn.execute(
|
||||
"SELECT 1 FROM pg_roles WHERE rolname = %s",
|
||||
(username,),
|
||||
).fetchone()
|
||||
if found:
|
||||
conn.execute(
|
||||
sql.SQL("ALTER ROLE {} LOGIN PASSWORD {}").format(
|
||||
sql.Identifier(username),
|
||||
sql.Literal(password),
|
||||
)
|
||||
)
|
||||
else:
|
||||
conn.execute(
|
||||
sql.SQL("CREATE ROLE {} LOGIN PASSWORD {}").format(
|
||||
sql.Identifier(username),
|
||||
sql.Literal(password),
|
||||
)
|
||||
)
|
||||
conn.execute(
|
||||
sql.SQL("GRANT CONNECT ON DATABASE {} TO {}").format(
|
||||
sql.Identifier(os.environ["PGDATABASE"]),
|
||||
sql.Identifier(username),
|
||||
)
|
||||
)
|
||||
conn.execute(
|
||||
sql.SQL("GRANT USAGE ON SCHEMA public TO {}").format(
|
||||
sql.Identifier(username),
|
||||
)
|
||||
)
|
||||
|
||||
api_user = sql.Identifier(accounts[0][0])
|
||||
conn.execute(
|
||||
sql.SQL(
|
||||
"GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA public TO {}"
|
||||
).format(api_user)
|
||||
)
|
||||
worker_user = sql.Identifier(accounts[1][0])
|
||||
conn.execute(
|
||||
sql.SQL(
|
||||
"GRANT SELECT, UPDATE ON TABLE attachments, image_jobs TO {}"
|
||||
).format(worker_user)
|
||||
)
|
||||
print("PASS: database service roles provisioned with separate grants")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,49 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Provision separate MinIO application users and bucket-scoped policies."""
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
|
||||
|
||||
MC = "/usr/local/bin/mc"
|
||||
CONFIG = Path("/tmp/mc")
|
||||
|
||||
|
||||
def mc(*args, check=True):
|
||||
result = subprocess.run(
|
||||
[MC, "--config-dir", str(CONFIG), *args],
|
||||
stdout=subprocess.DEVNULL,
|
||||
stderr=subprocess.PIPE,
|
||||
text=True,
|
||||
)
|
||||
if check and result.returncode:
|
||||
detail = result.stderr.strip()
|
||||
raise RuntimeError(
|
||||
"MinIO application identity provisioning failed"
|
||||
+ (": " + detail if detail else "")
|
||||
) from None
|
||||
return result.returncode == 0
|
||||
|
||||
|
||||
def main():
|
||||
ca_file = Path(os.environ["INTERNAL_CA_CERT"])
|
||||
ca_directory = CONFIG / "certs" / "CAs"
|
||||
ca_directory.mkdir(parents=True, exist_ok=True)
|
||||
shutil.copyfile(ca_file, ca_directory / "internal-ca.crt")
|
||||
mc(
|
||||
"alias", "set", "local", os.environ["S3_ENDPOINT"],
|
||||
os.environ["MINIO_ROOT_USER"], os.environ["MINIO_ROOT_PASSWORD"],
|
||||
)
|
||||
|
||||
for prefix in ("API", "WORKER"):
|
||||
user = os.environ["S3_" + prefix + "_ACCESS_KEY"]
|
||||
password = os.environ["S3_" + prefix + "_SECRET_KEY"]
|
||||
if not mc("admin", "user", "info", "local", user, check=False):
|
||||
mc("admin", "user", "add", "local", user, password)
|
||||
mc("admin", "policy", "attach", "local", "readwrite", "--user", user)
|
||||
print("PASS: separate MinIO application users and readwrite policies provisioned")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,10 @@
|
||||
@echo off
|
||||
setlocal
|
||||
set "PROJECT_DIR=%~dp0.."
|
||||
docker compose --project-directory "%PROJECT_DIR%" --env-file "%PROJECT_DIR%\.env" restart db s3 broker
|
||||
docker compose --project-directory "%PROJECT_DIR%" --env-file "%PROJECT_DIR%\.env" up -d --wait db s3 broker
|
||||
docker compose --project-directory "%PROJECT_DIR%" --env-file "%PROJECT_DIR%\.env" restart openbao
|
||||
docker compose --project-directory "%PROJECT_DIR%" --env-file "%PROJECT_DIR%\.env" run --rm s3-init
|
||||
docker compose --project-directory "%PROJECT_DIR%" --env-file "%PROJECT_DIR%\.env" run --rm openbao-bootstrap
|
||||
docker compose --project-directory "%PROJECT_DIR%" --env-file "%PROJECT_DIR%\.env" restart api
|
||||
docker compose --project-directory "%PROJECT_DIR%" --env-file "%PROJECT_DIR%\.env" up -d --wait --scale api=2 api lb
|
||||
@@ -0,0 +1,12 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
|
||||
SCRIPT_DIR=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
|
||||
PROJECT_DIR=$(dirname "$SCRIPT_DIR")
|
||||
|
||||
docker compose --project-directory "$PROJECT_DIR" --env-file "$PROJECT_DIR/.env" restart db s3 broker openbao
|
||||
docker compose --project-directory "$PROJECT_DIR" --env-file "$PROJECT_DIR/.env" up -d --wait db s3 broker openbao
|
||||
docker compose --project-directory "$PROJECT_DIR" --env-file "$PROJECT_DIR/.env" run --rm s3-init
|
||||
docker compose --project-directory "$PROJECT_DIR" --env-file "$PROJECT_DIR/.env" run --rm openbao-bootstrap
|
||||
docker compose --project-directory "$PROJECT_DIR" --env-file "$PROJECT_DIR/.env" restart api worker otel-collector prometheus loki tempo grafana
|
||||
docker compose --project-directory "$PROJECT_DIR" --env-file "$PROJECT_DIR/.env" up -d --wait --scale api=2 api worker otel-collector prometheus loki tempo grafana lb
|
||||
@@ -0,0 +1,13 @@
|
||||
@echo off
|
||||
setlocal
|
||||
if not defined TARGET_INSTANCE_ID exit /b 2
|
||||
set "PROJECT_DIR=%~dp0.."
|
||||
for /f "delims=" %%i in ('docker compose --project-directory "%PROJECT_DIR%" --env-file "%PROJECT_DIR%\.env" ps -q api') do (
|
||||
for /f "delims=" %%h in ('docker inspect --format "{{.Config.Hostname}}" %%i') do (
|
||||
if /i "%%h"=="%TARGET_INSTANCE_ID%" (
|
||||
docker stop %%i >nul
|
||||
exit /b 0
|
||||
)
|
||||
)
|
||||
)
|
||||
exit /b 1
|
||||
@@ -0,0 +1,17 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
|
||||
: "${TARGET_INSTANCE_ID:?test provides the API instance ID}"
|
||||
SCRIPT_DIR=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
|
||||
PROJECT_DIR=$(dirname "$SCRIPT_DIR")
|
||||
|
||||
for container_id in $(docker compose --project-directory "$PROJECT_DIR" --env-file "$PROJECT_DIR/.env" ps -q api); do
|
||||
hostname=$(docker inspect --format '{{.Config.Hostname}}' "$container_id")
|
||||
if [ "$hostname" = "$TARGET_INSTANCE_ID" ]; then
|
||||
docker stop "$container_id" >/dev/null
|
||||
exit 0
|
||||
fi
|
||||
done
|
||||
|
||||
printf '%s\n' 'No running API container matches TARGET_INSTANCE_ID' >&2
|
||||
exit 1
|
||||
Reference in New Issue
Block a user