forked from mtusi2026/mtusi2026lab7
all for 3
This commit is contained in:
@@ -0,0 +1,60 @@
|
||||
"""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')
|
||||
@@ -0,0 +1,45 @@
|
||||
import socket
|
||||
import ssl
|
||||
import time
|
||||
import uuid
|
||||
from urllib.parse import urlsplit
|
||||
from client import Client, arguments, check, run
|
||||
|
||||
def main():
|
||||
def configure(p):
|
||||
p.add_argument('--expiry',action='store_true',help='Requires a stack with SESSION_TTL_SECONDS=5')
|
||||
args=arguments('Application security checks',configure)
|
||||
c=Client(args.base_url,args.ca_file)
|
||||
if args.expiry:
|
||||
actor=c.user('expiry')
|
||||
c.call('GET','/api/v1/users/me',actor=actor,schema='User')
|
||||
time.sleep(6)
|
||||
c.call('GET','/api/v1/users/me',401,actor=actor)
|
||||
print('PASS: a previously accepted bearer expired')
|
||||
return
|
||||
url=urlsplit(c.base)
|
||||
c.call('GET','/health/ready',schema='Health')
|
||||
ctx=ssl.create_default_context(cafile=args.ca_file)
|
||||
with socket.create_connection((url.hostname,url.port or 443),timeout=5) as raw:
|
||||
try:
|
||||
ctx.wrap_socket(raw,server_hostname='wrong.invalid')
|
||||
except ssl.SSLCertVerificationError as e:
|
||||
check(e.verify_code==62,'expected hostname mismatch')
|
||||
else:
|
||||
raise AssertionError('Wrong hostname accepted')
|
||||
alice,bob,eve,chat=c.bootstrap()
|
||||
att,_=c.attachment(alice,chat)
|
||||
other=c.call('POST','/api/v1/chats',201,actor=eve,body={'title':'Other','member_ids':[eve['id'],bob['id']]},schema='Chat')['json']
|
||||
c.call('POST','/api/v1/chats/'+other['id']+'/messages',404,actor=eve,
|
||||
headers={'X-User-Id':alice['id'],'Idempotency-Key':uuid.uuid4().hex},
|
||||
body={'text':'','attachment_ids':[att['id']]})
|
||||
for _ in range(80):
|
||||
r=c.call('POST','/api/v1/auth/sessions',[401,429])
|
||||
if r['status']==429:
|
||||
check(int(r['headers']['Retry-After'])>0,'missing Retry-After')
|
||||
break
|
||||
else:
|
||||
raise AssertionError('Login throttle did not activate')
|
||||
print('PASS: hostname, foreign attachment and ingress rate limit')
|
||||
if __name__=='__main__':
|
||||
run(main)
|
||||
Reference in New Issue
Block a user