lab7
This commit is contained in:
@@ -0,0 +1,17 @@
|
||||
import os,sys,ssl,json,time,urllib.request
|
||||
ctx=ssl.create_default_context(cafile='/tls/ca.crt')
|
||||
ctx.load_cert_chain('/identity/cert.crt','/identity/cert.key')
|
||||
role=os.environ['BAO_ROLE']; base=os.environ['BAO_ADDR']
|
||||
def call(path,body=None,token=None):
|
||||
headers={'Content-Type':'application/json'}
|
||||
if token: headers['X-Vault-Token']=token
|
||||
req=urllib.request.Request(base+'/v1/'+path,data=json.dumps(body).encode() if body is not None else None,headers=headers)
|
||||
with urllib.request.urlopen(req,context=ctx,timeout=5) as r: return json.load(r)
|
||||
for i in range(120):
|
||||
try:
|
||||
token=call('auth/cert/login',{'name':role})['auth']['client_token']
|
||||
values=call('secret/data/'+role,token=token)['data']['data']; break
|
||||
except Exception:
|
||||
time.sleep(2)
|
||||
else: sys.exit('OpenBao unavailable or access denied')
|
||||
os.environ.update(values); os.execvp(sys.argv[1],sys.argv[1:])
|
||||
@@ -0,0 +1,13 @@
|
||||
import pathlib,subprocess,secrets,json,os
|
||||
root=pathlib.Path('secrets'); root.mkdir(exist_ok=True)
|
||||
def run(*args): subprocess.run(['openssl',*map(str,args)],check=True)
|
||||
if (root/'ca.key').exists(): raise SystemExit('Existing CA; refusing overwrite')
|
||||
run('req','-x509','-newkey','rsa:3072','-nodes','-days','365','-subj','/CN=Lab7 CA','-addext','basicConstraints=critical,CA:TRUE','-addext','keyUsage=critical,keyCertSign,cRLSign','-addext','subjectKeyIdentifier=hash','-keyout',root/'ca.key','-out',root/'ca.crt')
|
||||
for role,cn,san in [('ingress','localhost','DNS:localhost,IP:127.0.0.1'),('lb','lab-lb','DNS:lab-lb'),('api-server','api.internal','DNS:api.internal'),('bao','bao','DNS:bao,DNS:localhost'),('api','api','DNS:api'),('worker','worker','DNS:worker'),('operator','operator','DNS:operator'), ('postgres','postgres','DNS:postgres'), ('broker','broker','DNS:broker'), ('s3','s3','DNS:s3'), ('otel-collector','otel-collector','DNS:otel-collector'), ('prometheus','prometheus','DNS:prometheus'), ('loki','loki','DNS:loki'), ('tempo','tempo','DNS:tempo')]:
|
||||
d=root/role; d.mkdir(); run('req','-new','-newkey','rsa:2048','-nodes','-subj','/CN='+cn,'-keyout',d/'cert.key','-out',d/'cert.csr'); (d/'ext').write_text('subjectAltName='+san+'\nextendedKeyUsage=serverAuth,clientAuth\n'); run('x509','-req','-in',d/'cert.csr','-CA',root/'ca.crt','-CAkey',root/'ca.key','-CAcreateserial','-days','30','-extfile',d/'ext','-out',d/'cert.crt'); os.chmod(d/'cert.key',0o644)
|
||||
values={k:secrets.token_hex(24) for k in ['POSTGRES_PASSWORD','BROKER_PASSWORD','GRAFANA_PASSWORD','S3_SECRET_ACCESS_KEY','DB_API_PASSWORD','DB_WORKER_PASSWORD','BROKER_WORKER_PASSWORD','S3_API_PASSWORD','S3_WORKER_PASSWORD']}; pathlib.Path('.env').write_text(''.join(f'{k}={v}\n' for k,v in values.items())); (root/'s3.json').write_text(json.dumps({'identities':[{'name':'lab','credentials':[{'accessKey':'lab','secretKey':values['S3_SECRET_ACCESS_KEY','DB_API_PASSWORD','DB_WORKER_PASSWORD','BROKER_WORKER_PASSWORD','S3_API_PASSWORD','S3_WORKER_PASSWORD']}],'actions':['Admin','Read','Write','List']}]}))
|
||||
|
||||
import shutil
|
||||
shutil.copyfile(root/'ca.crt', root/'bao'/'ca.crt')
|
||||
run('version')
|
||||
subprocess.run([__import__('sys').executable, 'scripts/setup_s3_roles.py'], check=True)
|
||||
@@ -0,0 +1,17 @@
|
||||
import json,ssl,urllib.request,pathlib,getpass
|
||||
ctx=ssl.create_default_context(cafile='secrets/ca.crt'); token=getpass.getpass('Operator root token: ')
|
||||
def post(path,data):
|
||||
req=urllib.request.Request('https://localhost:8200/v1/'+path,data=json.dumps(data).encode(),headers={'X-Vault-Token':token,'Content-Type':'application/json'}); urllib.request.urlopen(req,context=ctx).close()
|
||||
env=dict(x.split('=',1) for x in pathlib.Path('.env').read_text().splitlines())
|
||||
try:
|
||||
post('sys/auth/cert', {'type': 'cert'})
|
||||
post('sys/mounts/secret', {'type': 'kv', 'options': {'version': '2'}})
|
||||
except urllib.error.HTTPError as e:
|
||||
print(e.read().decode())
|
||||
raise SystemExit(1)
|
||||
for role in ('api','worker','operator'):
|
||||
post('sys/policies/acl/'+role,{'policy':pathlib.Path('infra/openbao/'+role+'.hcl').read_text()}); post('auth/cert/certs/'+role,{'certificate':pathlib.Path('secrets/'+role+'/cert.crt').read_text(),'token_policies':[role],'token_ttl':'10m','token_max_ttl':'30m'}); post('secret/data/'+role,{'data':{'DATABASE_URL':'postgresql://messenger:'+env['POSTGRES_PASSWORD']+'@postgres:5432/messenger?sslmode=verify-full&sslrootcert=/tls/ca.crt','S3_ACCESS_KEY_ID':'lab','S3_SECRET_ACCESS_KEY':env['S3_SECRET_ACCESS_KEY'],'BROKER_URL':'amqps://lab:'+env['BROKER_PASSWORD']+'@broker:5671/%2F'}})
|
||||
|
||||
import subprocess
|
||||
import sys
|
||||
subprocess.run([sys.executable, 'scripts/update_roles_bao.py'], check=True)
|
||||
@@ -0,0 +1,27 @@
|
||||
import os
|
||||
import time
|
||||
import boto3
|
||||
from botocore.config import Config
|
||||
|
||||
client = boto3.client(
|
||||
's3',
|
||||
endpoint_url=os.environ['S3_ENDPOINT'],
|
||||
region_name='us-east-1',
|
||||
aws_access_key_id=os.environ['S3_ACCESS_KEY_ID'],
|
||||
aws_secret_access_key=os.environ['S3_SECRET_ACCESS_KEY'],
|
||||
verify='/tls/ca.crt',
|
||||
config=Config(connect_timeout=3, read_timeout=5, retries={'max_attempts': 1}),
|
||||
)
|
||||
bucket = os.getenv('S3_BUCKET', 'messenger-attachments')
|
||||
for attempt in range(60):
|
||||
try:
|
||||
buckets = [x['Name'] for x in client.list_buckets().get('Buckets', [])]
|
||||
if bucket not in buckets:
|
||||
client.create_bucket(Bucket=bucket)
|
||||
print('Private S3 bucket ready:', bucket)
|
||||
break
|
||||
except Exception as exc:
|
||||
print('Waiting for S3:', str(exc), flush=True)
|
||||
if attempt == 59:
|
||||
raise
|
||||
time.sleep(2)
|
||||
@@ -0,0 +1,8 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
mkdir -p /var/lib/postgresql/tls
|
||||
cp /tls/cert.crt /var/lib/postgresql/tls/server.crt
|
||||
cp /tls/cert.key /var/lib/postgresql/tls/server.key
|
||||
chown postgres:postgres /var/lib/postgresql/tls/server.crt /var/lib/postgresql/tls/server.key
|
||||
chmod 600 /var/lib/postgresql/tls/server.key
|
||||
exec docker-entrypoint.sh "$@"
|
||||
@@ -0,0 +1,28 @@
|
||||
@echo off
|
||||
cd /d "%~dp0.."
|
||||
|
||||
echo Restarting PostgreSQL and S3...
|
||||
docker compose --env-file .env restart postgres s3
|
||||
if errorlevel 1 exit /b 1
|
||||
|
||||
timeout /t 30 /nobreak >nul
|
||||
|
||||
echo Restarting API replicas...
|
||||
docker compose --env-file .env restart api1 api2
|
||||
if errorlevel 1 exit /b 1
|
||||
|
||||
echo Recreating TLS proxies...
|
||||
docker compose --env-file .env up -d --force-recreate --no-deps api1-tls api2-tls s3-tls
|
||||
if errorlevel 1 exit /b 1
|
||||
|
||||
echo Restarting load balancer...
|
||||
docker compose --env-file .env restart lb
|
||||
if errorlevel 1 exit /b 1
|
||||
|
||||
echo Waiting for services...
|
||||
docker compose --env-file .env up -d --wait
|
||||
if errorlevel 1 exit /b 1
|
||||
|
||||
timeout /t 10 /nobreak >nul
|
||||
|
||||
exit /b 0
|
||||
@@ -0,0 +1,24 @@
|
||||
import pathlib
|
||||
import subprocess
|
||||
|
||||
env = dict(x.split('=',1) for x in pathlib.Path('.env').read_text().splitlines() if '=' in x and not x.startswith('#'))
|
||||
|
||||
def run(*args):
|
||||
subprocess.run(['docker','compose','exec','-T','broker','rabbitmqctl',*args],check=True)
|
||||
|
||||
users = subprocess.check_output(
|
||||
['docker','compose','exec','-T','broker','rabbitmqctl','list_users'],
|
||||
text=True
|
||||
)
|
||||
|
||||
if 'messenger_worker' not in users:
|
||||
run('add_user','messenger_worker',env['BROKER_WORKER_PASSWORD'])
|
||||
else:
|
||||
run('change_password','messenger_worker',env['BROKER_WORKER_PASSWORD'])
|
||||
|
||||
run('set_permissions','-p','/','messenger_worker',
|
||||
r'^attachment\.jobs$',
|
||||
r'^(attachment\.jobs|amq\.default)$',
|
||||
r'^attachment\.jobs$')
|
||||
|
||||
print('PASS: RabbitMQ roles configured')
|
||||
@@ -0,0 +1,45 @@
|
||||
import pathlib
|
||||
import secrets
|
||||
import subprocess
|
||||
|
||||
p = pathlib.Path('.env')
|
||||
env = dict(x.split('=', 1) for x in p.read_text().splitlines() if '=' in x and not x.startswith('#'))
|
||||
|
||||
for key in ('DB_API_PASSWORD', 'DB_WORKER_PASSWORD', 'BROKER_WORKER_PASSWORD'):
|
||||
env.setdefault(key, secrets.token_hex(24))
|
||||
|
||||
p.write_text(''.join(f'{k}={v}\n' for k,v in env.items()))
|
||||
|
||||
sql = f"""
|
||||
DO $$
|
||||
BEGIN
|
||||
IF NOT EXISTS (SELECT FROM pg_roles WHERE rolname='messenger_api') THEN
|
||||
CREATE ROLE messenger_api LOGIN;
|
||||
END IF;
|
||||
IF NOT EXISTS (SELECT FROM pg_roles WHERE rolname='messenger_worker') THEN
|
||||
CREATE ROLE messenger_worker LOGIN;
|
||||
END IF;
|
||||
END
|
||||
$$;
|
||||
|
||||
ALTER ROLE messenger_api PASSWORD '{env["DB_API_PASSWORD"]}';
|
||||
ALTER ROLE messenger_worker PASSWORD '{env["DB_WORKER_PASSWORD"]}';
|
||||
|
||||
GRANT CONNECT ON DATABASE messenger TO messenger_api, messenger_worker;
|
||||
GRANT USAGE ON SCHEMA public TO messenger_api, messenger_worker;
|
||||
|
||||
GRANT SELECT, INSERT, UPDATE ON
|
||||
users, chats, chat_members, messages, sessions,
|
||||
message_idempotency, attachments, jobs
|
||||
TO messenger_api;
|
||||
|
||||
GRANT SELECT, UPDATE ON attachments, jobs TO messenger_worker;
|
||||
"""
|
||||
|
||||
subprocess.run(
|
||||
['docker','compose','exec','-T','postgres','psql',
|
||||
'-U','messenger','-d','messenger','-v','ON_ERROR_STOP=1'],
|
||||
input=sql, text=True, check=True
|
||||
)
|
||||
|
||||
print('PASS: PostgreSQL roles configured')
|
||||
@@ -0,0 +1,34 @@
|
||||
import pathlib
|
||||
import secrets
|
||||
import json
|
||||
|
||||
p = pathlib.Path('.env')
|
||||
env = dict(x.split('=',1) for x in p.read_text().splitlines() if '=' in x and not x.startswith('#'))
|
||||
|
||||
for role in ('API', 'WORKER'):
|
||||
env.setdefault('S3_'+role+'_PASSWORD', secrets.token_hex(24))
|
||||
|
||||
p.write_text(''.join(f'{k}={v}\n' for k,v in env.items()))
|
||||
|
||||
config = {
|
||||
'identities': [
|
||||
{
|
||||
'name': 'operator',
|
||||
'credentials': [{'accessKey':'lab','secretKey':env['S3_SECRET_ACCESS_KEY']}],
|
||||
'actions': ['Admin','Read','Write','List']
|
||||
},
|
||||
{
|
||||
'name': 'api',
|
||||
'credentials': [{'accessKey':'messenger_api','secretKey':env['S3_API_PASSWORD']}],
|
||||
'actions': ['Read:messenger-attachments','Write:messenger-attachments','List:messenger-attachments']
|
||||
},
|
||||
{
|
||||
'name': 'worker',
|
||||
'credentials': [{'accessKey':'messenger_worker','secretKey':env['S3_WORKER_PASSWORD']}],
|
||||
'actions': ['Read:messenger-attachments','Write:messenger-attachments','List:messenger-attachments']
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
pathlib.Path('secrets/s3.json').write_text(json.dumps(config))
|
||||
print('PASS: S3 identities configured')
|
||||
@@ -0,0 +1,14 @@
|
||||
@echo off
|
||||
cd /d "%~dp0.."
|
||||
|
||||
if /I "%TARGET_INSTANCE_ID%"=="api1" (
|
||||
docker compose --env-file .env stop api1 >nul 2>&1
|
||||
exit /b %errorlevel%
|
||||
)
|
||||
|
||||
if /I "%TARGET_INSTANCE_ID%"=="api2" (
|
||||
docker compose --env-file .env stop api2 >nul 2>&1
|
||||
exit /b %errorlevel%
|
||||
)
|
||||
|
||||
exit /b 1
|
||||
@@ -0,0 +1,60 @@
|
||||
import ssl
|
||||
import json
|
||||
import urllib.request
|
||||
import urllib.error
|
||||
|
||||
base = "https://localhost:8200/v1/"
|
||||
|
||||
for role in ("api", "worker"):
|
||||
ctx = ssl.create_default_context(cafile="secrets/ca.crt")
|
||||
ctx.load_cert_chain(
|
||||
f"secrets/{role}/cert.crt",
|
||||
f"secrets/{role}/cert.key"
|
||||
)
|
||||
|
||||
req = urllib.request.Request(
|
||||
base + "auth/cert/login",
|
||||
data=json.dumps({"name": role}).encode(),
|
||||
headers={"Content-Type": "application/json"}
|
||||
)
|
||||
|
||||
with urllib.request.urlopen(req, context=ctx) as r:
|
||||
auth = json.load(r)["auth"]
|
||||
|
||||
token = auth["client_token"]
|
||||
print(f"\n{role}: login OK, TTL={auth['lease_duration']}")
|
||||
|
||||
for target in ("api", "worker", "operator"):
|
||||
req = urllib.request.Request(
|
||||
base + "secret/data/" + target,
|
||||
headers={"X-Vault-Token": token}
|
||||
)
|
||||
try:
|
||||
with urllib.request.urlopen(req, context=ctx) as r:
|
||||
print(f"{role} -> {target}: {r.status}")
|
||||
except urllib.error.HTTPError as e:
|
||||
print(f"{role} -> {target}: {e.code}")
|
||||
|
||||
|
||||
|
||||
|
||||
req = urllib.request.Request(
|
||||
base + "auth/token/revoke-self",
|
||||
data=b"{}",
|
||||
headers={"X-Vault-Token": token}
|
||||
)
|
||||
|
||||
with urllib.request.urlopen(req, context=ctx) as r:
|
||||
print(f"{role}: revoke -> {r.status}")
|
||||
|
||||
req = urllib.request.Request(
|
||||
base + "secret/data/" + role,
|
||||
headers={"X-Vault-Token": token}
|
||||
)
|
||||
|
||||
try:
|
||||
urllib.request.urlopen(req, context=ctx)
|
||||
print("FAIL: revoked token still works")
|
||||
except urllib.error.HTTPError as e:
|
||||
print(f"{role}: after revoke -> {e.code}")
|
||||
assert e.code == 403
|
||||
@@ -0,0 +1,36 @@
|
||||
import sys
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
from uuid import UUID
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tests"))
|
||||
|
||||
from client import Client
|
||||
|
||||
c = Client("https://localhost:8443", "secrets/ca.crt")
|
||||
alice, bob, eve, chat = c.bootstrap()
|
||||
|
||||
c.call("GET", "/api/v1/users/me", 200, actor=alice)
|
||||
print("Before expiry: 200 OK")
|
||||
|
||||
user_id = str(UUID(str(alice["id"])))
|
||||
|
||||
sql = (
|
||||
"UPDATE sessions SET expires_at = now() - interval '1 second' "
|
||||
f"WHERE user_id = '{user_id}';"
|
||||
)
|
||||
|
||||
subprocess.run(
|
||||
[
|
||||
"docker", "compose", "exec", "-T", "postgres",
|
||||
"sh", "-c",
|
||||
'psql -v ON_ERROR_STOP=1 -U "$POSTGRES_USER" -d "$POSTGRES_DB"',
|
||||
],
|
||||
input=sql,
|
||||
text=True,
|
||||
check=True,
|
||||
)
|
||||
|
||||
c.call("GET", "/api/v1/users/me", 401, actor=alice)
|
||||
print("After expiry: 401 Unauthorized")
|
||||
print("PASS: expired session rejected")
|
||||
@@ -0,0 +1,36 @@
|
||||
import json
|
||||
import ssl
|
||||
import urllib.request
|
||||
import pathlib
|
||||
import getpass
|
||||
|
||||
ctx = ssl.create_default_context(cafile="secrets/ca.crt")
|
||||
token = getpass.getpass("Operator root token: ")
|
||||
|
||||
for role in ("api", "worker", "operator"):
|
||||
url = "https://localhost:8200/v1/secret/data/" + role
|
||||
headers = {
|
||||
"X-Vault-Token": token,
|
||||
"Content-Type": "application/json"
|
||||
}
|
||||
|
||||
req = urllib.request.Request(url, headers=headers)
|
||||
with urllib.request.urlopen(req, context=ctx) as r:
|
||||
data = json.load(r)["data"]["data"]
|
||||
|
||||
data["DATABASE_URL"] = data["DATABASE_URL"].split("?")[0]
|
||||
data["DATABASE_URL"] += "?sslmode=verify-full&sslrootcert=/tls/ca.crt"
|
||||
data["BROKER_URL"] = data["BROKER_URL"].replace(
|
||||
"amqp://", "amqps://"
|
||||
).replace("@broker:5672", "@broker:5671")
|
||||
|
||||
|
||||
req = urllib.request.Request(
|
||||
url,
|
||||
data=json.dumps({"data": data}).encode(),
|
||||
headers=headers,
|
||||
method="POST"
|
||||
)
|
||||
|
||||
with urllib.request.urlopen(req, context=ctx):
|
||||
print(role + ": updated")
|
||||
@@ -0,0 +1,28 @@
|
||||
import pathlib
|
||||
import json
|
||||
import ssl
|
||||
import urllib.request
|
||||
import getpass
|
||||
|
||||
env = dict(x.split('=',1) for x in pathlib.Path('.env').read_text().splitlines() if '=' in x and not x.startswith('#'))
|
||||
ctx = ssl.create_default_context(cafile='secrets/ca.crt')
|
||||
token = getpass.getpass('Operator root token: ')
|
||||
|
||||
for role in ('api','worker'):
|
||||
values = {
|
||||
'DATABASE_URL': f'postgresql://messenger_{role}:'+env['DB_'+role.upper()+'_PASSWORD']+'@postgres:5432/messenger?sslmode=verify-full&sslrootcert=/tls/ca.crt',
|
||||
'S3_ACCESS_KEY_ID': 'messenger_'+role,
|
||||
'S3_SECRET_ACCESS_KEY': env['S3_'+role.upper()+'_PASSWORD']
|
||||
}
|
||||
|
||||
if role == 'worker':
|
||||
values['BROKER_URL'] = 'amqps://messenger_worker:'+env['BROKER_WORKER_PASSWORD']+'@broker:5671/%2F'
|
||||
|
||||
req = urllib.request.Request(
|
||||
'https://localhost:8200/v1/secret/data/'+role,
|
||||
data=json.dumps({'data':values}).encode(),
|
||||
headers={'X-Vault-Token':token,'Content-Type':'application/json'}
|
||||
)
|
||||
|
||||
with urllib.request.urlopen(req,context=ctx) as response:
|
||||
print(role, response.status)
|
||||
Reference in New Issue
Block a user