forked from mtusi2026/mtusi2026lab7
61 lines
2.6 KiB
Python
61 lines
2.6 KiB
Python
"""Run via the opt-in Compose probe. Never print credentials or bodies."""
|
|
import http.client
|
|
import json
|
|
import socket
|
|
import ssl
|
|
import urllib.error
|
|
import urllib.request
|
|
from pathlib import Path
|
|
|
|
root = Path('/probe')
|
|
def context(role=None):
|
|
ctx = ssl.create_default_context(cafile=root/'ca.crt')
|
|
if role:
|
|
ctx.load_cert_chain(root/role/'cert.pem',root/role/'key.pem')
|
|
return ctx
|
|
|
|
def exchange(ip, role):
|
|
# Establish TCP separately: an absent replica must fail the test.
|
|
raw = socket.create_connection((ip,8443),timeout=4)
|
|
with raw, context(role).wrap_socket(raw,server_hostname='api') as conn:
|
|
conn.sendall(b'GET /health/ready HTTP/1.1\r\nHost: api\r\nConnection: close\r\n\r\n')
|
|
response = http.client.HTTPResponse(conn)
|
|
response.begin()
|
|
return response.status
|
|
|
|
ips = sorted({a[4][0] for a in socket.getaddrinfo('api',8443,type=socket.SOCK_STREAM)})
|
|
assert len(ips)>=2, 'Restore both replicas before the test'
|
|
for ip in ips:
|
|
assert exchange(ip,'lb')==200
|
|
for role in [None,'foreign','worker']:
|
|
try:
|
|
status = exchange(ip,role)
|
|
except (ssl.SSLError,ConnectionResetError,http.client.RemoteDisconnected):
|
|
continue
|
|
raise AssertionError('Forbidden identity reached HTTP on '+ip+' status '+str(status))
|
|
print('PASS: all',len(ips),'API replicas accepted LB and rejected three invalid clients')
|
|
def bao(role,path,body=None,token=None,expected=200):
|
|
req = urllib.request.Request('https://openbao:8200/v1/'+path,
|
|
data=json.dumps(body).encode() if body is not None else None,
|
|
headers={'X-Vault-Token':token} if token else {})
|
|
try:
|
|
res=urllib.request.urlopen(req,context=context(role),timeout=5)
|
|
except urllib.error.HTTPError as err:
|
|
assert err.code == expected, (path,err.code,expected)
|
|
return
|
|
with res:
|
|
assert res.status==expected,(path,res.status,expected)
|
|
data=res.read()
|
|
return json.loads(data) if data else None
|
|
|
|
for role,other in [('api','worker'),('worker','api')]:
|
|
auth=bao(role,'auth/cert/login',{'name':role})['auth']
|
|
token=auth['client_token']
|
|
assert 0<auth['lease_duration']<=300
|
|
assert bao(role,'messenger/data/'+role,token=token)['data']['data']['DB_USERNAME']==role
|
|
bao(role,'messenger/data/'+other,token=token,expected=403)
|
|
bao(role,'sys/policies/acl/probe-denied',{'policy':'path "probe" { capabilities = ["read"] }'},token,403)
|
|
bao(role,'auth/token/revoke-self',{},token,204)
|
|
bao(role,'messenger/data/'+role,token=token,expected=403)
|
|
print('PASS: scoped KV, denied policy mutation and token revocation for both roles')
|