add level 3

This commit is contained in:
Матвей
2026-11-07 15:00:53 +03:00
parent eafb825657
commit 7b6c10cde9
54 changed files with 1593 additions and 120 deletions
+40
View File
@@ -0,0 +1,40 @@
"""Probe trusted and untrusted TLS plus inaccessible plaintext dependency ports."""
import os
import socket
import ssl
import urllib.error
import urllib.request
ca = os.environ['BAO_CACERT']
for host, port in [('s3', 8333), ('broker', 5671), ('openbao', 8200)]:
trusted = ssl.create_default_context(cafile=ca)
with socket.create_connection((host, port), timeout=5) as raw:
with trusted.wrap_socket(raw, server_hostname=host) as connection:
assert connection.version() in {'TLSv1.2', 'TLSv1.3'}
untrusted = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
try:
with socket.create_connection((host, port), timeout=5) as raw:
with untrusted.wrap_socket(raw, server_hostname=host):
pass
except ssl.SSLCertVerificationError:
pass
else:
raise AssertionError(f'{host}: untrusted CA accepted')
print(f'PASS {host}: verified TLS; untrusted CA rejected')
for host, port in [('s3', 8888), ('s3', 9333), ('s3', 18333), ('broker', 5672), ('broker', 4369), ('broker', 25672), ('broker', 15692), ('loki', 9095), ('tempo', 9095)]:
try:
socket.create_connection((host, port), timeout=3).close()
except ConnectionRefusedError:
pass
else:
raise AssertionError(f'{host}:{port}: unexpected accessible plaintext port')
print('PASS: S3 internal and broker plaintext ports are closed')
request = urllib.request.Request('https://s3:8333/', data=b'', method='POST')
try:
urllib.request.urlopen(request, context=ssl.create_default_context(cafile=ca), timeout=5)
except urllib.error.HTTPError as error:
assert error.code == 403
else:
raise AssertionError('S3 proxy allowed the blocked POST method')
print('PASS: S3 proxy blocks POST')
+67
View File
@@ -0,0 +1,67 @@
"""Offline tests of login throttling and bounded request bodies."""
import asyncio
import sys
import unittest
from pathlib import Path
from types import SimpleNamespace
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from src.login_limit import LoginLimiter
from src.main import app
async def request(chunks, limiter=None):
app.state.settings = SimpleNamespace(instance_id="test")
app.state.login_limiter = limiter or LoginLimiter(attempts=1, window_seconds=60)
app.state.store = object()
messages = [{"type": "http.request", "body": chunk, "more_body": i < len(chunks) - 1}
for i, chunk in enumerate(chunks)]
response = []
async def receive():
if messages:
return messages.pop(0)
await asyncio.Event().wait()
async def send(message):
response.append(message)
scope = {"type": "http", "asgi": {"version": "3.0"}, "http_version": "1.1",
"method": "POST", "scheme": "http", "path": "/api/v1/auth/sessions",
"raw_path": b"/api/v1/auth/sessions", "query_string": b"", "headers": [],
"client": ("127.0.0.1", 1234), "server": ("localhost", 8080), "root_path": ""}
await app(scope, receive, send)
return response
class LimitsTests(unittest.TestCase):
def test_window_and_retry(self):
now = [100.0]
limiter = LoginLimiter(2, 60, lambda: now[0])
self.assertEqual([limiter.retry_after() for _ in range(3)], [0, 0, 60])
now[0] = 159.5
self.assertEqual(limiter.retry_after(), 1)
now[0] = 160
self.assertEqual(limiter.retry_after(), 0)
def test_chunked_oversized_body(self):
result = asyncio.run(request([b"x" * 40000, b"x" * 30000]))
start = result[0]
self.assertEqual(start["status"], 413)
headers = dict(start["headers"])
self.assertIn(b"x-request-id", headers)
self.assertIn(b"x-instance-id", headers)
self.assertIn(b'"payload_too_large"', b"".join(x.get("body", b"") for x in result))
def test_small_body_reaches_route(self):
result = asyncio.run(request([b""]))
self.assertEqual(result[0]["status"], 401)
def test_rate_limit_returns_retry_after(self):
limiter = LoginLimiter(attempts=1, window_seconds=60)
first = asyncio.run(request([b""], limiter))
second = asyncio.run(request([b""], limiter))
self.assertEqual(first[0]["status"], 401)
self.assertEqual(second[0]["status"], 429)
self.assertGreater(int(dict(second[0]["headers"])[b"retry-after"]), 0)
if __name__ == "__main__":
unittest.main()
+49
View File
@@ -0,0 +1,49 @@
"""TLS hostname, cross-chat attachment ACL, and actual session expiry."""
import hashlib
from pathlib import Path
import socket
import ssl
import subprocess
import sys
import time
from urllib.parse import urlsplit
from uuid import uuid4
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / 'tests'))
from client import Client, arguments, run
def main():
args = arguments(__doc__)
client = Client(args.base_url, args.ca_file)
target = urlsplit(client.base)
context = ssl.create_default_context(cafile=args.ca_file)
try:
with socket.create_connection((target.hostname, target.port or 443), timeout=5) as raw:
with context.wrap_socket(raw, server_hostname='wrong-host.invalid'):
pass
except ssl.SSLCertVerificationError:
pass
else:
raise AssertionError('TLS accepted wrong server hostname')
alice, bob, eve, chat = client.bootstrap()
attachment, _ = client.attachment(alice, chat)
other_chat = client.call('POST', '/api/v1/chats', 201, actor=eve,
body={'title': 'Other chat', 'member_ids': [eve['id']]}, schema='Chat')['json']
client.call('POST', '/api/v1/chats/' + other_chat['id'] + '/messages', 404, actor=eve,
body={'text': '', 'attachment_ids': [attachment['id']]},
headers={'Idempotency-Key': uuid4().hex})
client.call('GET', '/api/v1/users/me', actor=alice, schema='User')
digest = hashlib.sha256(alice['token'].encode('ascii')).hexdigest()
sql = "UPDATE sessions SET expires_at=now()+interval '2 seconds' WHERE token_hash='" + digest + "';\n"
result = subprocess.run(['docker', 'compose', 'exec', '-T', 'postgres', 'psql', '-U', 'messenger', '-d', 'messenger', '-q'],
cwd=ROOT, input=sql, text=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, check=True)
del result
time.sleep(3)
client.call('GET', '/api/v1/users/me', 401, actor=alice)
print('PASS: wrong hostname rejected; cross-chat attachment denied; expired session rejected')
if __name__ == '__main__':
run(main)
+31
View File
@@ -0,0 +1,31 @@
"""Run inside the Compose network using temporary test identities."""
import socket
import ssl
def call(host, cert=None):
context = ssl.create_default_context(cafile="/certs/ca.crt")
if cert:
context.load_cert_chain(cert)
with socket.create_connection((host, 8444), timeout=5) as raw:
with context.wrap_socket(raw, server_hostname=host) as conn:
conn.sendall(b"GET /health/ready HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n")
return conn.recv(4096).split(b"\r\n", 1)[0]
for host in ("api-a", "api-b"):
assert b" 200 " in call(host, "/certs/lb.pem"), f"{host}: valid LB certificate rejected"
for certificate in (None, "/certs/foreign.pem"):
try:
result = call(host, certificate)
except (ssl.SSLError, ConnectionResetError, BrokenPipeError):
continue
raise AssertionError(f"{host}: bad certificate unexpectedly received {result!r}")
assert b" 403 " in call(host, "/certs/wrong-role.pem"), f"{host}: wrong role not denied"
try:
socket.create_connection((host, 8080), timeout=3).close()
except ConnectionRefusedError:
pass
else:
raise AssertionError(f"{host}: application port reachable without mTLS")
print(f"PASS {host}: valid identity accepted; no cert, foreign CA and wrong role rejected; direct API closed")
+32
View File
@@ -0,0 +1,32 @@
"""Query Grafana's three TLS-protected datasources without printing telemetry."""
import base64
import json
import os
from pathlib import Path
import ssl
import time
import urllib.parse
import urllib.request
root = Path(__file__).resolve().parents[1]
context = ssl.create_default_context(cafile=str(root / 'secrets/ca.crt'))
password = (root / 'secrets/grafana_password').read_text().strip()
auth = base64.b64encode(('admin:' + password).encode()).decode()
base = os.environ.get('GRAFANA_URL', 'https://localhost:3000').rstrip('/') + '/api/datasources/proxy/uid/'
now = time.time_ns()
paths = {
'prometheus': '/api/v1/query?' + urllib.parse.urlencode({'query': 'up'}),
'loki': '/loki/api/v1/query_range?' + urllib.parse.urlencode({
'query': '{service_name="messenger-api"}', 'start': now - 600_000_000_000,
'end': now, 'limit': 5}),
'tempo': '/api/search?' + urllib.parse.urlencode({'limit': 5, 'start': now // 1_000_000_000 - 120, 'end': now // 1_000_000_000}),
}
for name, path in paths.items():
req = urllib.request.Request(base + name + path, headers={'Authorization': 'Basic ' + auth})
with urllib.request.urlopen(req, context=context, timeout=15) as response:
payload = json.load(response)
values = payload.get('data', {}).get('result', payload.get('traces', []))
assert values, f'{name}: no data returned'
if name == 'prometheus':
assert all(item['value'][1] == '1' for item in values), 'Prometheus scrape target down'
print(f'PASS: Grafana connected to {name}; data present')
+37
View File
@@ -0,0 +1,37 @@
"""Run inside API and worker containers; print only allow/deny outcomes."""
import json
import os
from pathlib import Path
import ssl
import urllib.error
import urllib.request
role = os.environ['BAO_SERVICE_ROLE']
other = {'api': 'worker', 'worker': 'api'}[role]
base = os.environ['BAO_ADDR'].rstrip('/')
context = ssl.create_default_context(cafile=os.environ['BAO_CACERT'])
context.load_cert_chain(os.environ['BAO_CLIENT_CERT'])
def request(path, token=None, body=None):
headers = {'Content-Type': 'application/json'}
if token:
headers['X-Vault-Token'] = token
data = json.dumps(body).encode() if body is not None else None
req = urllib.request.Request(base + '/v1/' + path, data=data, headers=headers,
method='POST' if body is not None else 'GET')
with urllib.request.urlopen(req, context=context, timeout=5) as response:
return json.load(response)
token = request('auth/cert/login', body={'name': role})['auth']['client_token']
assert request('lab/data/' + role, token)['data']['data']
for path, body in [('lab/data/' + other, None), ('sys/policies/acl/forbidden', {'policy': 'path "*" { capabilities = ["read"] }'})]:
try:
request(path, token, body)
except urllib.error.HTTPError as error:
assert error.code == 403, f'unexpected status {error.code}'
else:
raise AssertionError('cross-role read or policy write allowed')
assert not Path('/run/secrets/openbao-operator.json').exists()
print(f'PASS {role}: own path allowed; other path and policy write denied')
+33
View File
@@ -0,0 +1,33 @@
"""Run the persistence hook and record actual service restart timestamps."""
import json
import os
from pathlib import Path
import subprocess
ROOT = Path(__file__).resolve().parents[1]
SERVICES = ('postgres', 's3', 'broker', 'openbao', 'prometheus', 'loki', 'tempo', 'api-a', 'api-b')
def started(service):
container = subprocess.check_output(['docker', 'compose', 'ps', '-q', service], cwd=ROOT, text=True).strip()
if not container:
raise RuntimeError(f'{service} is not running')
return subprocess.check_output(['docker', 'inspect', '--format', '{{.State.StartedAt}}', container], text=True).strip()
before = {service: started(service) for service in SERVICES}
result = subprocess.run(['make', 'test-persistence', 'ACTION_SCRIPT=scripts/restart.sh'], cwd=ROOT,
text=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
print(result.stdout, end='')
if result.returncode:
raise SystemExit(result.returncode)
after = {service: started(service) for service in SERVICES}
for service in SERVICES:
if after[service] <= before[service]:
raise RuntimeError(f'{service} did not restart')
evidence = {'status': 'PASS', 'command': 'make test-persistence ACTION_SCRIPT=scripts/restart.sh',
'services': {service: {'before': before[service], 'after': after[service]} for service in SERVICES},
'test_output': result.stdout.strip()}
path = ROOT / 'evidence' / 'lab7-persistence.json'
path.write_text(json.dumps(evidence, ensure_ascii=False, indent=2) + '\n')
print('PASS: restart timestamps recorded in evidence/lab7-persistence.json')
+47
View File
@@ -0,0 +1,47 @@
"""Execute inside an API container to test the PostgreSQL transport."""
import asyncio
import json
import os
from pathlib import Path
import ssl
import urllib.request
import asyncpg
async def main():
if Path('/run/secrets/database_url').exists():
dsn = Path('/run/secrets/database_url').read_text().strip()
else:
bao_tls = ssl.create_default_context(cafile=os.environ['BAO_CACERT'])
bao_tls.load_cert_chain(os.environ['BAO_CLIENT_CERT'])
base = os.environ['BAO_ADDR'].rstrip('/')
role = os.environ['BAO_SERVICE_ROLE']
request = urllib.request.Request(base + '/v1/auth/cert/login',
data=json.dumps({'name': role}).encode(), headers={'Content-Type': 'application/json'})
with urllib.request.urlopen(request, context=bao_tls) as response:
token = json.load(response)['auth']['client_token']
request = urllib.request.Request(base + '/v1/lab/data/' + role, headers={'X-Vault-Token': token})
with urllib.request.urlopen(request, context=bao_tls) as response:
dsn = json.load(response)['data']['data']['DATABASE_URL']
context = ssl.create_default_context(cafile='/run/secrets/ca_cert')
connection = await asyncpg.connect(dsn, ssl=context)
try:
assert await connection.fetchval('select ssl from pg_stat_ssl where pid=pg_backend_pid()')
finally:
await connection.close()
try:
await asyncpg.connect(dsn, ssl=False)
except asyncpg.InvalidAuthorizationSpecificationError:
pass
else:
raise AssertionError('plaintext PostgreSQL connection was accepted')
try:
await asyncpg.connect(dsn, ssl=ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT))
except ssl.SSLCertVerificationError:
pass
else:
raise AssertionError('untrusted CA was accepted')
print('PASS: PostgreSQL TLS verified, plaintext and untrusted CA rejected')
asyncio.run(main())
+40
View File
@@ -0,0 +1,40 @@
"""Check allowed and denied S3 prefixes using the current service identity."""
import json
import os
import ssl
import urllib.request
from uuid import uuid4
import boto3
from botocore.exceptions import ClientError
role = os.environ['BAO_SERVICE_ROLE']
ctx = ssl.create_default_context(cafile=os.environ['BAO_CACERT'])
ctx.load_cert_chain(os.environ['BAO_CLIENT_CERT'])
base = os.environ['BAO_ADDR'].rstrip('/')
request = urllib.request.Request(base + '/v1/auth/cert/login', data=json.dumps({'name': role}).encode(),
headers={'Content-Type': 'application/json'})
with urllib.request.urlopen(request, context=ctx) as response:
token = json.load(response)['auth']['client_token']
request = urllib.request.Request(base + '/v1/lab/data/' + role, headers={'X-Vault-Token': token})
with urllib.request.urlopen(request, context=ctx) as response:
values = json.load(response)['data']['data']
client = boto3.client('s3', endpoint_url=os.environ['S3_ENDPOINT'], region_name='us-east-1',
aws_access_key_id=values['S3_ACCESS_KEY_ID'],
aws_secret_access_key=values['S3_SECRET_ACCESS_KEY'])
bucket = os.environ['S3_BUCKET']
probe = uuid4().hex
allowed = 'staging/security-probe-' + probe
denied = ('originals/' if role == 'api' else '_bootstrap/') + 'security-probe-' + probe
client.put_object(Bucket=bucket, Key=allowed, Body=b'test')
client.delete_object(Bucket=bucket, Key=allowed)
try:
client.put_object(Bucket=bucket, Key=denied, Body=b'test')
except ClientError as error:
assert error.response['ResponseMetadata']['HTTPStatusCode'] == 403
else:
client.delete_object(Bucket=bucket, Key=denied)
raise AssertionError('disallowed prefix was writable')
finally:
client.close()
print(f'PASS {role}: allowed staging write; forbidden prefix denied')
+55
View File
@@ -0,0 +1,55 @@
"""Check scoped DB and broker permissions from the running service identity."""
import asyncio
import json
import os
import ssl
import urllib.request
import asyncpg
import pika
role = os.environ['BAO_SERVICE_ROLE']
context = ssl.create_default_context(cafile=os.environ['BAO_CACERT'])
context.load_cert_chain(os.environ['BAO_CLIENT_CERT'])
base = os.environ['BAO_ADDR'].rstrip('/')
req = urllib.request.Request(base + '/v1/auth/cert/login', data=json.dumps({'name': role}).encode(),
headers={'Content-Type': 'application/json'})
with urllib.request.urlopen(req, context=context) as response:
token = json.load(response)['auth']['client_token']
req = urllib.request.Request(base + '/v1/lab/data/' + role, headers={'X-Vault-Token': token})
with urllib.request.urlopen(req, context=context) as response:
values = json.load(response)['data']['data']
async def database():
db = await asyncpg.connect(values['DATABASE_URL'], ssl=ssl.create_default_context(cafile=os.environ['DATABASE_CA_FILE']))
try:
assert await db.fetchval('SELECT current_user') == 'messenger_' + role
try:
await db.execute('SELECT password_hash FROM users LIMIT 1' if role == 'worker' else 'CREATE TABLE unauthorized_probe (id integer)')
except asyncpg.InsufficientPrivilegeError:
pass
else:
raise AssertionError('unexpected database privilege')
finally:
await db.close()
asyncio.run(database())
params = pika.URLParameters(values['BROKER_URL'])
params.ssl_options = pika.SSLOptions(ssl.create_default_context(cafile=os.environ['BROKER_CA_FILE']), params.host)
connection = pika.BlockingConnection(params)
try:
channel = connection.channel()
try:
if role == 'api':
channel.basic_get('attachment.process.v1', auto_ack=False)
else:
channel.queue_declare(queue='unauthorized.probe', durable=True)
except pika.exceptions.ChannelClosedByBroker as error:
assert error.reply_code == 403
else:
raise AssertionError('unexpected broker privilege')
finally:
connection.close()
print(f'PASS {role}: DB identity and denied privilege; broker denied unauthorized operation')
+30
View File
@@ -0,0 +1,30 @@
"""Verify the Collector accepts its publisher role and rejects other callers."""
import os
import socket
import ssl
def request(certificate):
ctx = ssl.create_default_context(cafile=os.environ['OTEL_EXPORTER_OTLP_CERTIFICATE'])
if certificate:
ctx.load_cert_chain(certificate)
with socket.create_connection(('otel-collector', 4318), timeout=5) as raw:
with ctx.wrap_socket(raw, server_hostname='otel-collector') as conn:
conn.sendall(b'GET / HTTP/1.1\r\nHost: otel-collector\r\nConnection: close\r\n\r\n')
return conn.recv(1024)
assert b'404' in request(os.environ['OTEL_EXPORTER_OTLP_CLIENT_CERTIFICATE'])
for cert in (None, os.environ['BAO_CLIENT_CERT']):
try:
result = request(cert)
except (ssl.SSLError, ConnectionResetError, BrokenPipeError):
continue
assert not result, 'Collector accepted an unauthorized caller'
try:
socket.create_connection(('otel-collector', 14318), timeout=2).close()
except ConnectionRefusedError:
pass
else:
raise AssertionError('Collector plaintext listener reachable from outside')
print('PASS: Collector publisher accepted; no cert and wrong role rejected; local listener closed')