Выполнение лабораторной работы номер 7
Skeleton contracts / contracts (pull_request) Canceled after 0s

This commit is contained in:
2026-12-04 18:15:18 +03:00
parent 20afc2c790
commit 2fae615742
77 changed files with 5212 additions and 64 deletions
+18
View File
@@ -0,0 +1,18 @@
"""Measure the configured Argon2id budget locally in the running API container."""
import json
from pathlib import Path
import subprocess
ROOT=Path(__file__).resolve().parents[1]
code="""import time,statistics,json,resource
from argon2 import PasswordHasher
p=PasswordHasher(memory_cost=19456,time_cost=2,parallelism=1)
samples=[]
for _ in range(20):
t=time.monotonic();p.hash('synthetic-lab-password');samples.append((time.monotonic()-t)*1000)
print(json.dumps({'memory_kib':19456,'t':2,'p':1,'hash_median_ms':statistics.median(samples),'hash_max_ms':max(samples),'peak_rss_kib':resource.getrusage(resource.RUSAGE_SELF).ru_maxrss}))
"""
raw=subprocess.check_output(['docker','compose','exec','-T','--index','1','api','python','-c',code],cwd=ROOT,text=True)
result=json.loads(raw)
(ROOT/'evidence/hash-cost.json').write_text(json.dumps(result,indent=2)+'\n',encoding='utf-8')
print(json.dumps(result))
+67
View File
@@ -0,0 +1,67 @@
"""Check scoped, short-lived OpenBao access without printing credentials."""
import argparse
import json
import subprocess
import sys
from pathlib import Path
ROOT=Path(__file__).resolve().parents[1]
CHECK='''
import json,ssl,sys,urllib.request,urllib.error
role,other,mode=sys.argv[1:]
ctx=ssl.create_default_context(cafile='/ca/ca.crt')
ctx.load_cert_chain('/identity/tls.crt','/identity/tls.key')
base='https://openbao:8200/v1/'
def req(path,data=None,token=None):
headers={'Content-Type':'application/json'}
if token:headers['X-Vault-Token']=token
r=urllib.request.Request(base+path,data=None if data is None else json.dumps(data).encode(),headers=headers)
with urllib.request.urlopen(r,context=ctx,timeout=5) as response:return json.loads(response.read())
if mode=='sealed':
assert req('sys/seal-status')['sealed']
try:req('auth/cert/login',{'name':role})
except urllib.error.HTTPError as e:assert e.code==503
else:raise AssertionError('sealed OpenBao issued a token')
print('PASS: sealed OpenBao refuses service authentication')
raise SystemExit(0)
auth=req('auth/cert/login',{'name':role})['auth']
assert 0 < auth['lease_duration'] <= 900
token=auth['client_token']
assert 'DATABASE_URL' in req('kv/data/'+role,token=token)['data']['data']
for path in ('kv/data/'+other,'sys/policies/acl/'+role):
try:req(path,token=token)
except urllib.error.HTTPError as e:assert e.code==403
else:raise AssertionError('unscoped access')
print('PASS: '+role+' can read only its own secrets, with a limited token TTL')
'''
def compose(*args):
subprocess.run(['docker','compose',*args],cwd=ROOT,check=True)
def probe(role,other,mode='unsealed'):
compose('exec','-T','--index','1',role,'python','-c',CHECK,role,other,mode)
def main():
parser=argparse.ArgumentParser(description=__doc__)
parser.add_argument('--check-sealed',action='store_true',help='Restart the lab OpenBao, then unseal it')
args=parser.parse_args()
if args.check_sealed:
compose('restart','openbao')
try:
probe('api','worker','sealed')
finally:
subprocess.run([sys.executable,'scripts/bootstrap_bao.py'],cwd=ROOT,check=True)
probe('api','worker')
probe('worker','api')
(ROOT/'evidence/bao-policy.json').write_text(json.dumps({
'scoped_roles': ['api','worker'],
'maximum_token_ttl_seconds': 900,
'sealed_authentication_rejected': True if args.check_sealed else None,
},indent=2)+'\n',encoding='utf-8')
if __name__=='__main__':
main()
+34
View File
@@ -0,0 +1,34 @@
"""Concurrent duplicate sends against the local lab3 load balancer."""
from concurrent.futures import ThreadPoolExecutor
from threading import Barrier
import uuid
from client import Client, arguments, check, run
from resilience import history
def main():
args = arguments("Concurrent message deduplication")
c = Client(args.base_url, args.ca_file)
alice, bob, _, chat = c.bootstrap()
key = uuid.uuid4().hex
text = "Concurrent send " + key
barrier = Barrier(16, timeout=10)
def send(_):
client = Client(args.base_url, args.ca_file)
barrier.wait()
response = client.message(alice, chat, text, key=key)
return response["json"], response["headers"]["X-Instance-Id"]
with ThreadPoolExecutor(max_workers=16) as executor:
results = list(executor.map(send, range(16)))
check(len({instance for _, instance in results}) >= 2, "Only one replica observed")
check(all(message == results[0][0] for message, _ in results), "Different replay results")
check(sum(message["text"] == text for message in history(c, bob, chat)) == 1,
"Duplicate message in history")
print("PASS: 16 concurrent requests, at least 2 replicas, exactly 1 message")
if __name__ == "__main__":
run(main)
+48
View File
@@ -0,0 +1,48 @@
"""Verify the shared login rate limit with synthetic credentials on the local stand."""
import base64
import json
from pathlib import Path
import time
import uuid
from client import Client, arguments, check, run
ROOT = Path(__file__).resolve().parents[1]
def main():
args = arguments('Local shared login limit')
client = Client(args.base_url, args.ca_file)
credential = 'budget_probe_' + uuid.uuid4().hex[:12] + ':synthetic-password'
basic = base64.b64encode(credential.encode()).decode()
challenge = {'Authorization': 'Basic ' + basic}
limited_instances = set()
rejected = 0
throttled = 0
started = time.monotonic()
for _ in range(250):
response = client.call('POST', '/api/v1/auth/sessions', (401, 429), headers=challenge)
check(basic not in response['bytes'].decode() and credential not in response['bytes'].decode(),
'Error included synthetic credentials')
if response['status'] == 401:
rejected += 1
continue
throttled += 1
check(response['headers'].get('Retry-After') == '60', 'Missing Retry-After')
limited_instances.add(response['headers']['X-Instance-Id'])
if len(limited_instances) == 2:
break
check(len(limited_instances) == 2, 'The same login budget did not block both replicas')
(ROOT / 'evidence/login-budget.json').write_text(json.dumps({
'invalid_credentials_responses': rejected,
'rate_limited_responses': throttled,
'limited_replicas': len(limited_instances),
'retry_after_seconds': 60,
'elapsed_seconds': round(time.monotonic() - started, 3),
}, indent=2) + '\n', encoding='utf-8')
print('PASS: shared login budget, HTTP 429 on both replicas and no credentials in errors')
if __name__ == '__main__':
run(main)
+81
View File
@@ -0,0 +1,81 @@
"""Local incident demo; save Prometheus alert state and synthetic request results."""
import json
from pathlib import Path
import subprocess
import time
from client import Client, Failure, arguments, check, run
ROOT=Path(__file__).resolve().parents[1]
def compose(*args):
return subprocess.check_output(['docker','compose',*args],cwd=ROOT,text=True)
def prom(path):
return json.loads(compose('exec','-T','prometheus','wget','-qO-',f'http://127.0.0.1:9090{path}'))
def wait_alert(name,state,seconds=90):
deadline=time.monotonic()+seconds
while time.monotonic()<deadline:
alerts=prom('/api/v1/alerts')['data']['alerts']
active=[a for a in alerts if a['labels'].get('alertname')==name and a['state']=='firing']
if bool(active)==state:
return active
time.sleep(5)
raise Failure('Alert state did not change: '+name)
def main():
args=arguments('Local controlled observability incidents')
c=Client(args.base_url,args.ca_file,timeout=5)
alice,bob,_,chat=c.bootstrap()
report={}
compose('stop','worker')
try:
att,_=c.attachment(alice,chat)
report['backlog_firing']=wait_alert('OldAttachmentJob',True)
finally:
compose('start','worker')
c.wait_ready(bob,att,wait_seconds=180)
wait_alert('OldAttachmentJob',False)
report['backlog_resolved']=True
compose('stop','postgres')
try:
deadline=time.monotonic()+40
errors=0
while time.monotonic()<deadline:
try:
c.message(alice,chat,'DB outage synthetic')
except Failure:
errors+=1
check(errors>0,'No API errors observed')
report['db_errors']=errors
report['error_alert_firing']=wait_alert('HighHTTPErrorRate',True,20)
finally:
compose('start','postgres')
deadline=time.monotonic()+90
while True:
try:
c.message(alice,chat,'DB recovered')
break
except Failure:
check(time.monotonic()<deadline,'DB recovery timeout')
time.sleep(1)
wait_alert('HighHTTPErrorRate',False,90)
report['error_alert_resolved']=True
compose('stop','loki','tempo')
try:
for i in range(10):
c.message(alice,chat,f'Telemetry outage {i}')
report['telemetry_backend_outage_writes']=10
finally:
compose('start','loki','tempo')
(ROOT/'evidence/observability-incidents.json').write_text(json.dumps(report,indent=2)+'\n',encoding='utf-8')
print('PASS: backlog, DB incident, telemetry backend outage')
if __name__=='__main__':
run(main)
+47
View File
@@ -0,0 +1,47 @@
"""Verify that login upgrades an older hash for a synthetic local account."""
import base64
import json
from pathlib import Path
import subprocess
from client import Client, arguments, check, run
ROOT = Path(__file__).resolve().parents[1]
CHECK = """
import json,os,sys
from argon2 import PasswordHasher
import psycopg
user_id,password,operation=json.load(sys.stdin)
with psycopg.connect(os.environ['DATABASE_URL']) as conn:
if operation=='seed':
old=PasswordHasher(memory_cost=8192,time_cost=1,parallelism=1).hash(password)
assert conn.execute('UPDATE users SET password_hash=%s WHERE id=%s',
(old,user_id)).rowcount==1
else:
updated=conn.execute('SELECT password_hash FROM users WHERE id=%s',(user_id,)).fetchone()[0]
current=PasswordHasher(memory_cost=19456,time_cost=2,parallelism=1)
assert current.verify(updated,password)
assert not current.check_needs_rehash(updated)
"""
def main():
args = arguments('Local password rehash')
client = Client(args.base_url, args.ca_file)
user = client.user('rehash')
registration = user['registration']
password = registration['password']
command = ['docker','compose','exec','-T','--index','1','api','python','secret_entry.py','python','-c',CHECK]
subprocess.run(command, cwd=ROOT, input=json.dumps([user['id'],password,'seed']), text=True, check=True)
basic = base64.b64encode(f"{registration['username']}:{password}".encode()).decode()
session = client.call('POST','/api/v1/auth/sessions',201,headers={'Authorization':'Basic '+basic},schema='Session')
check(session['json']['user']['id'] == user['id'], 'Login returned a different account')
subprocess.run(command, cwd=ROOT, input=json.dumps([user['id'],password,'verify']), text=True, check=True)
(ROOT / 'evidence/password-rehash.json').write_text('{"rehash_on_login": true}\n', encoding='utf-8')
print('PASS: successful login upgraded the synthetic account to the current Argon2id parameters')
if __name__ == '__main__':
run(main)
+46
View File
@@ -0,0 +1,46 @@
"""Prove durable handoff, broker restart, outbox recovery and worker redelivery."""
import json
from pathlib import Path
import subprocess
import time
from client import Client, arguments, check, run
ROOT = Path(__file__).resolve().parents[1]
def compose(*args):
subprocess.run(['docker','compose',*args],cwd=ROOT,check=True)
def main():
args=arguments('Durable attachment pipeline')
c=Client(args.base_url,args.ca_file,timeout=20)
alice,bob,_,chat=c.bootstrap()
compose('stop','worker','dispatcher')
try:
attachment,original=c.attachment(alice,chat)
check(attachment['status']=='queued','Upload was not queued')
c.message(alice,chat,'',attachments=[attachment['id']])
# Commit succeeded but dispatcher is deliberately absent.
compose('restart','api','broker')
compose('start','dispatcher')
compose('start','worker')
ready=c.wait_ready(bob,attachment,wait_seconds=180)
check({v['name'] for v in ready['variants']}=={'thumbnail','crop','optimized'},'Missing variants')
for variant in ready['variants']:
check(variant['size_bytes']>0,'Empty variant')
check(c.call('GET',f"/api/v1/attachments/{attachment['id']}/content",actor=bob)['bytes']==original,'Original changed')
print('PASS: committed job recovered after API/broker restart and delayed dispatcher',flush=True)
compose('exec','-T','worker','touch','/tmp/lab-crash-once')
crash,_=c.attachment(alice,chat)
ready2=c.wait_ready(bob,crash,wait_seconds=240)
check(len(ready2['variants'])==3,'Duplicate or missing variants after crash')
print('PASS: worker crash after S3 write recovered with exactly three variants',flush=True)
(ROOT/'evidence/pipeline.json').write_text(json.dumps({'durable_handoff':'pass','after_s3_crash':'pass','variant_names':[v['name'] for v in ready2['variants']]},indent=2)+'\n',encoding='utf-8')
finally:
compose('start','dispatcher','worker')
if __name__=='__main__':
run(main)
+48
View File
@@ -0,0 +1,48 @@
"""Rotate the local LB certificate and Redis password without building images."""
import json
from pathlib import Path
import secrets
import subprocess
import sys
import time
from test_tls_boundaries import probe, ROOT
def run(*args):
subprocess.run(args,cwd=ROOT,check=True)
def redis_check(password,expected):
code="""import redis,sys
pw=sys.stdin.read().strip()
r=redis.Redis(host='redis',port=6379,password=pw,ssl=True,ssl_ca_certs='/ca/ca.crt',ssl_check_hostname=True,socket_timeout=3)
try: ok=r.ping()
except redis.AuthenticationError: ok=False
assert bool(ok)==(sys.argv[1]=='yes')
"""
subprocess.run(['docker','compose','exec','-T','--index','1','api','python','-c',code,'yes' if expected else 'no'],
input=password,text=True,cwd=ROOT,check=True)
def main():
run(sys.executable,'scripts/bootstrap_pki.py','--rotate','lb-client')
run('docker','compose','restart','nginx')
probe('api',8443,'lb-client',True,'http')
probe('api',8443,ROOT/'secrets/rotated/lb-client',False,'http')
env_file=ROOT/'.env'; lines=env_file.read_text(encoding='utf-8').splitlines()
old=next(line.split('=',1)[1] for line in lines if line.startswith('REDIS_PASSWORD='))
new=secrets.token_hex(24)
env_file.write_text('\n'.join('REDIS_PASSWORD='+new if line.startswith('REDIS_PASSWORD=') else line for line in lines)+'\n',encoding='utf-8')
run(sys.executable,'scripts/bootstrap_bao.py')
run('docker','compose','up','-d','--no-deps','--force-recreate','redis')
run('docker','compose','restart','api')
time.sleep(8)
redis_check(old,False);redis_check(new,True)
run(sys.executable,'-X','utf8','tests/smoke.py','--ca-file','certs/private/ca.crt')
(ROOT/'evidence/rotation.json').write_text(json.dumps({'leaf_rotation':True,'old_leaf_rejected':True,'redis_secret_rotation':True,'old_secret_rejected':True},indent=2)+'\n',encoding='utf-8')
print('PASS: certificate and cache secret rotated without image rebuild')
if __name__=='__main__':
main()
+75
View File
@@ -0,0 +1,75 @@
"""Verify that correlated traces and logs omit synthetic credentials and text."""
import base64
import json
from pathlib import Path
import subprocess
import time
from urllib.parse import urlencode
import uuid
from client import Client, arguments, check, run
ROOT = Path(__file__).resolve().parents[1]
FETCH = """
import json,ssl,sys,urllib.request,urllib.error
ctx=ssl.create_default_context(cafile='/ca/ca.crt')
ctx.load_cert_chain('/identity/tls.crt','/identity/tls.key')
for url in sys.argv[1:]:
try:
with urllib.request.urlopen(url,context=ctx,timeout=5) as reply:
print(json.dumps(json.load(reply)))
except urllib.error.HTTPError as error:
if error.code != 404:
raise
print('{}')
"""
def main():
args = arguments('Local log and trace privacy')
client = Client(args.base_url, args.ca_file)
alice, _, _, chat = client.bootstrap()
registration = alice['registration']
password = registration['password']
credential = base64.b64encode(f"{registration['username']}:{password}".encode()).decode()
login = client.call('POST', '/api/v1/auth/sessions', 201,
headers={'Authorization': 'Basic ' + credential}, schema='Session')
marker = 'telemetry-private-' + uuid.uuid4().hex
message = client.message(alice, chat, marker)
pki = ROOT / 'certs/private'
command = [
'docker', 'run', '--rm', '--network', 'messenger-lab7_default',
'-v', f'{pki / "ca.crt"}:/ca/ca.crt:ro',
'-v', f'{pki / "grafana-client"}:/identity:ro',
'python:3.11.9-slim', 'python', '-c', FETCH,
]
urls = []
for response in (login, message):
headers = response['headers']
query = urlencode({'query': '{service_name="messenger-api"} | request_id="'
+ headers['X-Request-Id'] + '"'})
urls.extend([
'https://loki:3101/loki/api/v1/query_range?' + query,
'https://tempo:3201/api/traces/' + headers['X-Trace-Id'],
])
deadline = time.monotonic() + 60
while True:
output = subprocess.check_output([*command, *urls], cwd=ROOT, text=True)
login_logs, login_trace, message_logs, message_trace = map(json.loads, output.splitlines())
if (login_logs.get('data', {}).get('result') and login_trace
and message_logs.get('data', {}).get('result') and message_trace):
break
check(time.monotonic() < deadline, 'Correlated login or message telemetry not found')
time.sleep(3)
for sensitive in (password, credential, login['json']['token'], alice['token'], marker):
check(sensitive not in output, 'Correlated telemetry contained a synthetic secret')
(ROOT / 'evidence/telemetry-privacy.json').write_text(json.dumps({
'correlated_log_and_trace_found': ['login', 'message'],
'synthetic_secrets_found': 0,
}, indent=2) + '\n', encoding='utf-8')
print('PASS: correlated login and message telemetry omit synthetic secrets')
if __name__ == '__main__':
run(main)
+59
View File
@@ -0,0 +1,59 @@
"""Verify only the local lab's configured TLS identity and scoped secret boundaries."""
import json
from pathlib import Path
import subprocess
ROOT=Path(__file__).resolve().parents[1]
PROBE='''
import ssl,socket,sys,json,urllib.request,urllib.error
host,port,identity,expected,kind=sys.argv[1:]
ctx=ssl.create_default_context(cafile='/ca.crt')
if identity=='yes': ctx.load_cert_chain('/identity/tls.crt','/identity/tls.key')
ok=False
try:
if kind=='http':
try:
urllib.request.urlopen('https://'+host+':'+port+'/health/live',context=ctx,timeout=5).read()
ok=True
except urllib.error.HTTPError:
ok=True
elif kind=='redis':
with socket.create_connection((host,int(port)),timeout=5) as sock:
with ctx.wrap_socket(sock,server_hostname=host) as tls:
tls.sendall(b'*1\\r\\n$4\\r\\nPING\\r\\n')
ok=bool(tls.recv(256))
except (OSError,urllib.error.URLError): pass
if ok != (expected=='yes'): raise SystemExit('unexpected TLS result')
print('PASS')
'''
def probe(host,port,role,expected,kind):
pki=ROOT/'certs/private'
cmd=['docker','run','--rm','--network','messenger-lab7_default','-v',f'{pki/("ca.crt")}:/ca.crt:ro']
if role:
cmd+=['-v',f'{pki/role}:/identity:ro']
cmd+=['python:3.11.9-slim','python','-c',PROBE,host,str(port),'yes' if role else 'no','yes' if expected else 'no',kind]
subprocess.run(cmd,check=True,cwd=ROOT)
def main():
results=[]
for host,port,kind,allowed,wrong in [
('api',8443,'http','lb-client','api-client'),
('broker',6379,'redis','worker-client','api-client'),
('collector',4319,'http','worker-client','lb-client'),
('collector',8890,'http','prometheus-client','worker-client'),
('loki',3101,'http','collector-client','worker-client'),
('tempo',4319,'http','collector-client','worker-client'),
('tempo',3201,'http','grafana-client','worker-client'),
('prometheus',9090,'http','grafana-client','worker-client'),
]:
for role,expected in [(allowed,True),(None,False),(wrong,False)]:
probe(host,port,role,expected,kind)
results.append({'service':host,'port':port,'client':role or 'none','accepted':expected})
(ROOT/'evidence/tls-boundaries.json').write_text(json.dumps(results,indent=2)+'\n',encoding='utf-8')
if __name__=='__main__':
main()
+73
View File
@@ -0,0 +1,73 @@
"""Verify the worker identity against PostgreSQL, S3 and the broker."""
import json
from pathlib import Path
import subprocess
ROOT = Path(__file__).resolve().parents[1]
CHECK = """
import json
import os
import uuid
import boto3
from botocore.config import Config
from botocore.exceptions import ClientError
import psycopg
from psycopg.errors import InsufficientPrivilege
import redis
with psycopg.connect(os.environ['DATABASE_URL'], autocommit=True) as db:
db.execute('SELECT id FROM attachments LIMIT 0')
assert db.execute('SELECT ssl FROM pg_stat_ssl WHERE pid = pg_backend_pid()').fetchone()[0]
try:
db.execute('SELECT id FROM users LIMIT 0')
except InsufficientPrivilege:
pass
else:
raise AssertionError('Worker can read the users table')
s3 = boto3.client('s3', endpoint_url=os.environ['S3_ENDPOINT'],
aws_access_key_id=os.environ['S3_ACCESS_KEY'],
aws_secret_access_key=os.environ['S3_SECRET_KEY'],
verify='/ca/ca.crt', config=Config(s3={'addressing_style': 'path'}))
bucket = os.environ['S3_BUCKET']
key = 'original/permission-test-' + uuid.uuid4().hex
s3.list_objects_v2(Bucket=bucket, Prefix='staging/', MaxKeys=1)
try:
s3.head_object(Bucket=bucket, Key=key)
except ClientError as error:
assert error.response['ResponseMetadata']['HTTPStatusCode'] == 403
else:
raise AssertionError('Worker can read from the original prefix')
broker = redis.Redis.from_url(os.environ['BROKER_URL'], ssl_ca_certs='/ca/ca.crt',
ssl_certfile='/identity/tls.crt', ssl_keyfile='/identity/tls.key',
ssl_check_hostname=True, socket_timeout=5)
assert broker.ping()
try:
broker.xlen('attachment:jobs')
except redis.exceptions.NoPermissionError:
pass
else:
raise AssertionError('Worker was granted a broker command outside its role')
try:
broker.xreadgroup('workers', 'permission-check', {'permission-test-' + uuid.uuid4().hex: '>'})
except redis.exceptions.NoPermissionError:
pass
else:
raise AssertionError('Worker can access an unrelated stream')
print(json.dumps({'postgres_tls_and_table_acl': True, 's3_tls_and_prefix_acl': True,
'broker_mtls_and_command_acl': True}))
"""
output = subprocess.check_output(
['docker', 'compose', 'exec', '-T', 'worker', 'python', 'secret_entry.py', 'python', '-c', CHECK],
cwd=ROOT, text=True,
)
results = json.loads(output)
(ROOT / 'evidence/worker-permissions.json').write_text(
json.dumps(results, indent=2) + '\n', encoding='utf-8',
)
print('PASS: worker TLS and scopes in PostgreSQL, S3 and the broker')