Проверить уровень 3, устойчивость и отрицательные сценарии, оформить отчёт

This commit is contained in:
2026-12-04 07:15:24 +03:00
parent d4f64bed85
commit 06459d3eed
54 changed files with 1934 additions and 126 deletions
+15
View File
@@ -0,0 +1,15 @@
"""KDF measured within the app's 0.5 CPU / 512MiB limit."""
import json
import statistics
import time
from argon2 import PasswordHasher
hasher=PasswordHasher(time_cost=2,memory_cost=19456,parallelism=1)
hashes=[];values=[]
for _ in range(12):
started=time.perf_counter();encoded=hasher.hash('synthetic-benchmark-input');hasher.verify(encoded,'synthetic-benchmark-input')
values.append((time.perf_counter()-started)*1000);hashes.append(encoded)
assert len(set(hashes))==12
print(json.dumps({'algorithm':'argon2id','memory_kib':19456,'time_cost':2,'parallelism':1,'samples':12,
'cpu_limit':.5,'memory_limit_mib':512,'operation':'hash + verify','min_ms':round(min(values),2),
'median_ms':round(statistics.median(values),2),'max_ms':round(max(values),2),'distinct_salts':True},indent=2))
+36
View File
@@ -0,0 +1,36 @@
"""Accepted queued upload survives worker stop; real broker redelivery and dedupe."""
from pathlib import Path
import subprocess
import sys
import time
ROOT=Path(__file__).resolve().parents[1]
sys.path.insert(0,str(ROOT/'tests'));sys.path.insert(0,str(ROOT/'scripts'))
from client import Client
from manage import env
def compose(*args):subprocess.run(['docker','compose',*args],cwd=ROOT,check=True)
def main():
client=Client('https://localhost:'+env()['HTTPS_PORT'],str(ROOT/'secrets/ca.crt'))
alice,bob,eve,chat=client.bootstrap()
try:
compose('stop','-t','5','worker')
attachment,content=client.attachment(alice,chat)
assert attachment['status']=='queued'
compose('run','--rm','verifier','python','/checks/redelivery.py','redeliver')
finally:
compose('start','worker')
ready=client.wait_ready(alice,attachment)
assert client.call('GET','/api/v1/attachments/'+ready['id']+'/content',actor=bob)['bytes']==content
assert len(ready['variants'])==1 and ready['variants'][0]['name']=='thumbnail'
compose('run','--rm','verifier','python','/checks/redelivery.py','duplicate',ready['id'])
time.sleep(3)
after=client.call('GET','/api/v1/attachments/'+ready['id'],actor=bob,schema='Attachment')['json']
assert after==ready
print('PASS accepted202 during worker stop -> ready with exact original/one thumbnail; no-ack redelivery and completed-job duplicate did not duplicate effects')
if __name__=='__main__':main()
+153
View File
@@ -0,0 +1,153 @@
"""Run in the verifier profile. Real TLS, identity and authorization probes."""
import json
import socket
import ssl
import urllib.request
import urllib.error
import uuid
import time
from urllib.parse import urlparse
import boto3
import pika
import psycopg
from botocore.exceptions import ClientError
def context(identity=None):
ctx=ssl.create_default_context(cafile='/probe/lb/ca.crt')
if identity:
ctx.load_cert_chain('/probe/'+identity+'/cert.crt','/probe/'+identity+'/key.key')
return ctx
def http(host,port,path,identity=None,method='GET',body=None,token=None):
headers={'Content-Type':'application/json'}
if token:headers['X-Vault-Token']=token
req=urllib.request.Request(f'https://{host}:{port}'+path,data=json.dumps(body).encode() if body is not None else None,
headers=headers,method=method)
try:
with urllib.request.urlopen(req,context=context(identity),timeout=5) as response:
return response.status,response.read()
except urllib.error.HTTPError as error:
return error.code,error.read()
def denied_tls(host,port,path,identity):
try:
status,_=http(host,port,path,identity)
except (ssl.SSLError, ConnectionResetError, __import__('http.client',fromlist=['RemoteDisconnected']).RemoteDisconnected):
return
except urllib.error.URLError as error:
assert isinstance(error.reason,(ssl.SSLError,ConnectionResetError)),type(error.reason).__name__
return
raise AssertionError('TLS authorization unexpectedly returned HTTP '+str(status))
def plaintext_closed(host,port):
try:
with socket.create_connection((host,port),timeout=2):pass
except ConnectionRefusedError:return
raise AssertionError('Plaintext bypass reachable '+host)
def wait_http(host,port,path,identity):
deadline=time.monotonic()+60
while True:
status,_=http(host,port,path,identity)
if status==200:return
assert time.monotonic()<deadline,(host,'not ready',status)
time.sleep(1)
def bao(role,identity=None):
status,data=http('openbao',8200,'/v1/auth/cert/login',identity or role,'POST',{'name':role})
assert status==200,('certificate login',role,status)
auth=json.loads(data)['auth']
assert 0<auth['lease_duration']<=300
token=auth['client_token']
own='api' if role=='api2' else role
status,data=http('openbao',8200,'/v1/secret/data/'+own,identity or role,token=token)
assert status==200
for path,method,body in [('/v1/secret/data/'+('worker' if own=='api' else 'api'),'GET',None),
('/v1/sys/policies/acl/escalation','PUT',{'policy':'path "*" { capabilities=["root"] }'}),
('/v1/secret/data/'+own,'POST',{'data':{'overwritten':True}})]:
assert http('openbao',8200,path,identity or role,method,body,token)[0]==403
print('PASS OpenBao',role,'cert auth; TTL<=300; own read=200; foreign read/policy write/KV write=403')
return json.loads(data)['data']['data']
def main():
for host in ('api1','api2'):
for identity in (None,'foreign','probe'):
denied_tls(host,8443,'/health/ready',identity)
assert http(host,8443,'/health/ready','lb')[0]==200
plaintext_closed(host,8080)
print('PASS',host,'no cert / foreign CA / trusted wrong identity rejected; lb=200; port8080 closed')
secrets={role:bao(role, 'api1' if role=='api' else role) for role in ('api','api2','worker','dispatcher','cleaner')}
assert http('openbao',8200,'/v1/auth/cert/login','probe','POST',{'name':'api'})[0] in (400,403)
for role in ('api','worker','dispatcher','cleaner'):
with psycopg.connect(secrets[role]['DATABASE_URL']) as conn:
assert conn.execute('SELECT ssl FROM pg_stat_ssl WHERE pid=pg_backend_pid()').fetchone()[0]
assert conn.execute('SELECT current_user').fetchone()[0]==role
try:
with psycopg.connect(secrets[role]['DATABASE_URL'].replace('sslmode=verify-full','sslmode=disable')):pass
except psycopg.OperationalError:pass
else:raise AssertionError('DB accepted plaintext')
if role=='worker':
try:
with psycopg.connect(secrets[role]['DATABASE_URL']) as conn:conn.execute('SELECT * FROM users LIMIT 1')
except psycopg.errors.InsufficientPrivilege:pass
else:raise AssertionError('worker can read user credentials')
print('PASS PostgreSQL',role,'verify-full, server TLS observed; plaintext rejected')
for role in ('api','worker','cleaner'):
s3=boto3.client('s3',endpoint_url='https://s3:9000',verify='/probe/s3/ca.crt',region_name='us-east-1',
aws_access_key_id=secrets[role]['S3_ACCESS_KEY'],aws_secret_access_key=secrets[role]['S3_SECRET_KEY'])
try:s3.list_buckets()
except ClientError as error:assert error.response['ResponseMetadata']['HTTPStatusCode']==403
else:raise AssertionError('S3 identity has admin listing')
if role in ('api','cleaner'):s3.list_objects_v2(Bucket='attachments',Prefix='staging/',MaxKeys=1)
if role=='worker':
try:s3.put_object(Bucket='attachments',Key='staging/denied-'+uuid.uuid4().hex,Body=b'denied')
except ClientError as error:assert error.response['ResponseMetadata']['HTTPStatusCode']==403
else:raise AssertionError('worker can write API staging')
print('PASS S3',role,'TLS; administrative bucket listing denied; scoped permissions')
for role in ('worker','dispatcher'):
params=pika.URLParameters(secrets[role]['BROKER_URL'])
params.ssl_options=pika.SSLOptions(context(),'broker')
connection=pika.BlockingConnection(params)
channel=connection.channel();channel.queue_declare('attachment.process.v1',durable=True)
try:
if role=='worker':
channel.confirm_delivery();channel.basic_publish('','attachment.process.v1',b'{}')
else:channel.basic_get('attachment.process.v1')
except pika.exceptions.ChannelClosedByBroker as error:assert error.reply_code==403
else:raise AssertionError('broker ACL did not reject wrong operation')
connection.close()
print('PASS RabbitMQ',role,'TLS; wrong producer/consumer operation=403')
plaintext_closed('broker',5672)
assert http('otel-collector',4318,'/v1/traces','api1','POST',{})[0]==200
denied_tls('otel-collector',4318,'/v1/traces',None)
print('PASS Collector TLS authenticated ingest; no-certificate rejected')
for host,path in [('prometheus','/-/ready'),('loki','/ready'),('tempo','/ready')]:
wait_http(host,9443,path,'grafana')
denied_tls(host,9443,path,'probe')
plaintext_closed(host,{'prometheus':9090,'loki':3100,'tempo':3200}[host])
print('PASS backend',host,'Grafana mTLS; wrong identity rejected; plaintext closed')
assert http('tempo',9444,'/v1/traces','otel-collector','POST',{})[0]==200
payload={'resourceLogs':[{'resource':{'attributes':[{'key':'service.name','value':{'stringValue':'security-probe'}}]},
'scopeLogs':[{'logRecords':[{'timeUnixNano':str(time.time_ns()),'body':{'stringValue':'tls.authorization.probe'},'severityNumber':9}]}]}]}
status,_=http('loki',9443,'/otlp/v1/logs','otel-collector','POST',payload)
assert status in (200,204),('Loki OTLP valid record',status)
assert http('prometheus',9443,'/-/ready','otel-collector')[0]==200
print('PASS Collector -> all backends mTLS')
# Assert hostname rejection, distinct from network timeout/refusal.
with socket.create_connection(('s3',9000),timeout=3) as raw:
try:context().wrap_socket(raw,server_hostname='wrong.invalid')
except ssl.SSLCertVerificationError:pass
else:raise AssertionError('wrong hostname accepted')
print('PASS internal wrong hostname rejected by certificate verifier')
if __name__=='__main__':
main()
+55
View File
@@ -0,0 +1,55 @@
"""Broker no-ack redelivery and duplicate completed job, using scoped identities."""
import json
import sys
import time
import pika
import psycopg
from internal import context,http
def credentials(role):
status,data=http('openbao',8200,'/v1/auth/cert/login',role,'POST',{'name':role})
assert status==200
token=json.loads(data)['auth']['client_token']
status,data=http('openbao',8200,'/v1/secret/data/'+role,role,token=token)
assert status==200
return json.loads(data)['data']['data']
def connect(role):
params=pika.URLParameters(credentials(role)['BROKER_URL'])
params.ssl_options=pika.SSLOptions(context(),'broker')
return pika.BlockingConnection(params)
def main():
if sys.argv[1]=='redeliver':
bodies=[]
for attempt in range(2):
conn=connect('worker');channel=conn.channel()
deadline=time.monotonic()+15
while True:
method,properties,body=channel.basic_get('attachment.process.v1',auto_ack=False)
if method:break
assert time.monotonic()<deadline,'Job not present in durable broker queue'
time.sleep(.2)
assert properties.delivery_mode==2 and len(body)<4096
assert 'job_id' in json.loads(body)
if attempt:assert method.redelivered and body==bodies[0]
bodies.append(body)
conn.close() # No ack: broker MUST redeliver the same durable body.
print('PASS durable broker job delivered, disconnected without ack, redelivered=True; left queued for real worker')
else:
secrets=credentials('worker')
with psycopg.connect(secrets['DATABASE_URL']) as conn:
row=conn.execute('SELECT id,attachment_id,pipeline_version,attempt,created_at FROM attachment_jobs WHERE attachment_id=%s AND state=\'ready\'',(sys.argv[2],)).fetchone()
assert row
body={'schema_version':1,'job_id':str(row[0]),'type':'attachment.process.v1','attachment_id':str(row[1]),
'pipeline_version':row[2],'attempt':row[3],'created_at':row[4].isoformat(timespec='microseconds').replace('+00:00','Z')}
conn=connect('dispatcher');channel=conn.channel();channel.confirm_delivery()
channel.basic_publish('','attachment.process.v1',json.dumps(body).encode(),properties=pika.BasicProperties(delivery_mode=2),mandatory=True)
conn.close()
print('PASS completed job duplicate published with broker confirm')
if __name__=='__main__':main()
+70
View File
@@ -0,0 +1,70 @@
"""Host business security, limits and a real two-second session expiry."""
import base64
import json
import os
from pathlib import Path
import ssl
import subprocess
import sys
import time
import urllib.request
import uuid
ROOT=Path(__file__).resolve().parents[1]
sys.path.insert(0,str(ROOT/'tests'))
sys.path.insert(0,str(ROOT/'scripts'))
from client import Client, check
from manage import env,ready
def main():
c=Client('https://localhost:'+env()['HTTPS_PORT'],str(ROOT/'secrets/ca.crt'))
alice,bob,eve,chat=c.bootstrap()
attachment,original=c.attachment(alice,chat)
attachment=c.wait_ready(alice,attachment)
other=c.call('POST','/api/v1/chats',201,actor=eve,body={'title':'Other','member_ids':[eve['id']]},schema='Chat')['json']
c.call('POST','/api/v1/chats/'+other['id']+'/messages',404,actor=eve,
body={'text':'','attachment_ids':[attachment['id']]},headers={'Idempotency-Key':uuid.uuid4().hex})
for suffix in ('','/content','/content?variant=thumbnail'):
c.call('GET','/api/v1/attachments/'+attachment['id']+suffix,404,actor=eve)
me=c.call('GET','/api/v1/users/me',actor=alice,headers={'X-User-Id':eve['id']},schema='User')['json']
assert me['id']==alice['id']
c.call('DELETE','/api/v1/auth/sessions/current',204,actor=alice)
c.call('GET','/api/v1/users/me',401,actor=alice)
print('PASS attachment ACL, foreign-chat attach=404, spoofed identity ignored, logout=401')
name='limited_'+uuid.uuid4().hex[:12]
bad='Basic '+base64.b64encode((name+':synthetic-invalid').encode()).decode()
for _ in range(10):c.call('POST','/api/v1/auth/sessions',401,headers={'Authorization':bad})
response=c.call('POST','/api/v1/auth/sessions',429,headers={'Authorization':bad})
assert int(response['headers']['Retry-After'])>0
print('PASS login limit: 10 allowed attempts, 11th=429 with Retry-After')
c.call('POST','/api/v1/users',413,raw=b'x'*65537,headers={'Content-Type':'application/json'})
c.call('POST','/api/v1/chats/'+chat['id']+'/attachments?filename=large.png',413,actor=bob,
raw=b'x'*(10485760+1),headers={'Content-Type':'image/png'})
# urllib uses chunked transfer for an iterable without Content-Length.
c.call('POST','/api/v1/users',413,raw=iter([b'x'*40000,b'x'*30000]),headers={'Content-Type':'application/json'})
print('PASS JSON 64KiB, upload 10MiB and actual chunked stream limits=413')
ctx=ssl.create_default_context(cafile=str(ROOT/'secrets/ca.crt'))
import socket
with socket.create_connection(('127.0.0.1',int(env()['HTTPS_PORT'])),timeout=3) as raw:
try:ctx.wrap_socket(raw,server_hostname='wrong.invalid')
except ssl.SSLCertVerificationError:pass
else:raise AssertionError('external wrong hostname accepted')
print('PASS external wrong hostname rejected by certificate verifier')
temporary=dict(os.environ,SESSION_TTL_SECONDS='2')
try:
subprocess.run(['docker','compose','up','-d','api1','api2'],cwd=ROOT,env=temporary,check=True,stdout=subprocess.DEVNULL)
ready()
# Ensure BOTH new replicas are ready and serving before making a session.
time.sleep(3)
actor=c.user('expiry')
c.call('GET','/api/v1/users/me',actor=actor,schema='User')
time.sleep(3)
c.call('GET','/api/v1/users/me',401,actor=actor)
print('PASS configured SESSION_TTL_SECONDS=2: valid before expiry, 401 after expiry')
finally:
subprocess.run(['docker','compose','up','-d','api1','api2'],cwd=ROOT,check=True,stdout=subprocess.DEVNULL)
ready()
if __name__=='__main__':main()
+85
View File
@@ -0,0 +1,85 @@
"""Observe real signals through authenticated Grafana HTTPS datasource proxy."""
import base64
import json
from pathlib import Path
import ssl
import subprocess
import sys
import time
import urllib.request
import urllib.parse
ROOT=Path(__file__).resolve().parents[1]
sys.path.insert(0,str(ROOT/'scripts'))
from manage import env
def get(path):
credential=base64.b64encode(('admin:'+(ROOT/'secrets/grafana_password').read_text().strip()).encode()).decode()
request=urllib.request.Request('https://localhost:'+env()['GRAFANA_PORT']+path,headers={'Authorization':'Basic '+credential})
ctx=ssl.create_default_context(cafile=str(ROOT/'secrets/ca.crt'))
with urllib.request.urlopen(request,context=ctx,timeout=15) as response:
return json.load(response)
def query(source,path,**params):
return get('/api/datasources/proxy/uid/'+source+path+'?'+urllib.parse.urlencode(params))
def secret_values():
values=[]
def walk(v):
if isinstance(v,dict):
for item in v.values():walk(item)
elif isinstance(v,list):
for item in v:walk(item)
elif isinstance(v,str) and len(v)>=20 and '\n' not in v and not v.startswith(('-----','^')):
values.append(v)
for file in (ROOT/'secrets').glob('*'):
if not file.is_file() or file.suffix in ('.crt','.yaml'):continue
data=file.read_text()
try:walk(json.loads(data))
except ValueError:
if len(data.strip())>=20:values.append(data.strip())
operator=ROOT/'secrets/operator/bao-init.json'
if operator.exists():walk(json.loads(operator.read_text()))
return values
def main():
dashboard=get('/api/dashboards/uid/messenger')['dashboard']
assert len(dashboard['panels'])>=6
result={}
result['metrics']=query('prometheus','/api/v1/query',query='messenger_http_requests_total')
assert result['metrics']['data']['result'],'No HTTP counters stored'
result['jobs']=query('prometheus','/api/v1/query',query='messenger_jobs_total')
assert result['jobs']['data']['result'],'No worker metrics stored'
result['logs']=query('loki','/loki/api/v1/query_range',query='{service_name=~"messenger-api|messenger-worker"}',limit=1000,
start=str(time.time_ns()-3600*10**9),end=str(time.time_ns()))
assert result['logs']['data']['result'],'No API or worker logs stored'
services=set(stream['stream'].get('service_name') for stream in result['logs']['data']['result'])
assert {'messenger-api','messenger-worker'}<=services,services
trace_counts={}
for service in ('messenger-api','messenger-worker'):
traces=query('tempo','/api/search',q='{resource.service.name="'+service+'"}',limit=20)
assert traces.get('traces'),('No stored traces',service)
trace_counts[service]=len(traces['traces'])
trace_id=traces['traces'][0]['traceID']
result['trace_'+service]=get('/api/datasources/proxy/uid/tempo/api/traces/'+trace_id)
# Inspect returned records, not only Collector configuration.
payload=json.dumps(result)
for value in secret_values():
assert value not in payload,'Credential found in stored telemetry'
assert base64.b64encode(value.encode()).decode() not in payload,'Encoded credential found in telemetry'
assert 'BEGIN PRIVATE KEY' not in payload
# Container logs are scanned in memory and never saved as raw evidence.
logs=subprocess.check_output(['docker','compose','logs','--no-color'],cwd=ROOT).decode(errors='replace')
for value in secret_values():assert value not in logs,'Credential found in container logs'
summary={'grafana_https':True,'provisioned_panels':len(dashboard['panels']),
'http_metric_series':len(result['metrics']['data']['result']),'job_metric_series':len(result['jobs']['data']['result']),
'log_services':sorted(services),'trace_counts':trace_counts,'credential_scan':'PASS; returned telemetry and container logs'}
(ROOT/'evidence/telemetry.json').write_text(json.dumps(summary,indent=2),encoding='utf-8')
print(json.dumps(summary,indent=2))
if __name__=='__main__':main()