Files
mtusi2026lab7/tests/security_grade3.py
T

109 lines
4.2 KiB
Python

#!/usr/bin/env python3
"""Negative API and TLS scenarios for the local Lab 7 stand."""
import base64
from datetime import datetime, timezone
import secrets
import socket
import ssl
import time
from urllib.parse import urlsplit
from client import Client, arguments, check, run, timestamp
LOGIN = '/api/v1/auth/sessions'
def wrong_hostname(c: Client, ca_file: str) -> None:
url = urlsplit(c.base)
context = ssl.create_default_context(cafile=ca_file)
with socket.create_connection((url.hostname, url.port or 443), timeout=5) as conn:
try:
context.wrap_socket(conn, server_hostname='wrong-name.invalid')
except ssl.SSLCertVerificationError as error:
check(error.verify_code == 62, 'TLS verification failed for a different reason')
else:
check(False, 'unexpectedly accepted a wrong hostname')
def expired_session(c: Client) -> None:
actor = c.user('expiry')
credentials = actor['registration']
value = f'{credentials["username"]}:{credentials["password"]}'
headers = {'Authorization': 'Basic ' + base64.b64encode(value.encode()).decode()}
session = c.call('POST', LOGIN, 201, headers=headers, schema='Session')['json']
actor['token'] = session['token']
c.call('GET', '/api/v1/users/me', actor=actor, schema='User')
wait = (timestamp(session['expires_at']) - datetime.now(timezone.utc)).total_seconds()
check(0 < wait <= 10, 'start the expiry profile with SESSION_TTL_SECONDS=5')
time.sleep(wait + 0.35)
c.call('GET', '/api/v1/users/me', 401, actor=actor)
print('PASS: a previously usable session expired')
def access_and_sizes(c: Client) -> None:
alice, bob, eve, chat = c.bootstrap()
attachment, data = c.attachment(alice, chat)
c.wait_ready(bob, attachment)
path = '/api/v1/attachments/' + attachment['id']
c.call('GET', path, 404, actor=eve)
c.call('GET', path + '/content', 404, actor=eve)
other = c.call(
'POST', '/api/v1/chats', 201, actor=alice,
body={'title': 'Другой чат', 'member_ids': [alice['id'], eve['id']]}, schema='Chat',
)['json']
c.call(
'POST', f'/api/v1/chats/{other["id"]}/messages', 404, actor=alice,
body={'text': 'Вложение из другого чата', 'attachment_ids': [attachment['id']]},
headers={'Idempotency-Key': secrets.token_hex(16)},
)
c.call(
'POST', '/api/v1/users', 413, raw=b' ' * (64 * 1024 + 1),
headers={'Content-Type': 'application/json'},
)
upload = f'/api/v1/chats/{chat["id"]}/attachments?filename=fixture.png'
c.call('POST', upload, 415, actor=alice, raw=b'broken', headers={'Content-Type': 'image/png'})
c.call('POST', upload, 415, actor=alice, raw=data, headers={'Content-Type': 'image/jpeg'})
c.call('POST', upload, 413, actor=alice, raw=b'\0' * (10 * 1024 * 1024 + 1),
headers={'Content-Type': 'image/png'})
def login_budget(c: Client, attempts: int) -> None:
value = 'missing-user:' + secrets.token_hex(16)
auth = 'Basic ' + base64.b64encode(value.encode()).decode()
for _ in range(attempts):
response = c.call('POST', LOGIN, [401, 429], headers={'Authorization': auth})
if response['status'] == 429:
break
else:
check(False, 'login limit never returned 429')
check(int(response['headers']['Retry-After']) > 0, 'Retry-After must be positive')
replicas = set()
for n in range(6):
response = c.call('POST', LOGIN, 429, headers={
'Authorization': auth, 'X-Verified-Client-Ip': f'192.0.2.{n + 1}',
})
replicas.add(response['headers']['X-Instance-Id'])
check(len(replicas) == 2, 'both replicas must reject a throttled source')
def main():
def options(parser):
parser.add_argument('--expiry', action='store_true')
parser.add_argument('--max-attempts', type=int, default=50)
args = arguments(__doc__, options)
client = Client(args.base_url, args.ca_file)
if args.expiry:
expired_session(client)
return
wrong_hostname(client, args.ca_file)
access_and_sizes(client)
login_budget(client, args.max_attempts)
print('PASS: hostname, cross-chat attachment access, body limits and shared login budget')
if __name__ == '__main__':
run(main)