ЛР 7: безопасность, mTLS и OpenBao на оценку 3
Skeleton contracts / contracts (pull_request) Blocked by required conditions
Skeleton contracts / contracts (pull_request) Blocked by required conditions
This commit is contained in:
@@ -0,0 +1,86 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Additional checks against the local lab7 HTTPS endpoint."""
|
||||
import base64
|
||||
import os
|
||||
import time
|
||||
import uuid
|
||||
import socket
|
||||
import ssl
|
||||
from urllib.error import HTTPError
|
||||
from urllib.parse import urlparse
|
||||
from urllib.request import Request, urlopen
|
||||
|
||||
from client import Client, arguments, check, run, timestamp
|
||||
from datetime import datetime, timezone
|
||||
|
||||
|
||||
def main():
|
||||
args = arguments("Verify lab7 login limit, body limit, foreign attachment, and optional session expiry",
|
||||
lambda parser: parser.add_argument("--expiry-only", action="store_true"))
|
||||
client = Client(args.base_url, args.ca_file)
|
||||
if args.expiry_only:
|
||||
username = "expiry_" + uuid.uuid4().hex[:12]
|
||||
registration = {"username": username, "display_name": "Expiry", "password": "Пароль-" + uuid.uuid4().hex}
|
||||
client.call("POST", "/api/v1/users", 201, body=registration)
|
||||
auth = base64.b64encode(f"{username}:{registration['password']}".encode()).decode()
|
||||
session = client.call("POST", "/api/v1/auth/sessions", 201, headers={"Authorization": "Basic " + auth}, schema="Session")["json"]
|
||||
actor = {"token": session["token"]}
|
||||
client.call("GET", "/api/v1/users/me", actor=actor, schema="User")
|
||||
until = (timestamp(session["expires_at"]) - datetime.now(timezone.utc)).total_seconds()
|
||||
check(0 < until < 30, "run expiry verification on a stand using SESSION_TTL_SECONDS=8")
|
||||
time.sleep(until + 0.6)
|
||||
client.call("GET", "/api/v1/users/me", 401, actor=actor)
|
||||
print("PASS HTTPS session works before TTL and returns 401 after expiry")
|
||||
return
|
||||
|
||||
context = ssl.create_default_context(cafile=args.ca_file or os.getenv('CA_FILE'))
|
||||
address = urlparse(client.base)
|
||||
try:
|
||||
with socket.create_connection((address.hostname, address.port or 443), timeout=5) as conn:
|
||||
with context.wrap_socket(conn, server_hostname="wrong-name.invalid"):
|
||||
raise AssertionError("incorrect TLS hostname accepted")
|
||||
except ssl.SSLCertVerificationError as exc:
|
||||
check(exc.verify_code == 62, "expected hostname mismatch")
|
||||
print("PASS HTTPS rejects an incorrect hostname with the trusted CA")
|
||||
|
||||
alice, bob, eve, chat = client.bootstrap()
|
||||
attachment, _ = client.attachment(alice, chat)
|
||||
other_chat = client.call("POST", "/api/v1/chats", 201, actor=eve,
|
||||
body={"title": "Another chat", "member_ids": [eve["id"], bob["id"]]},
|
||||
schema="Chat")["json"]
|
||||
client.call("POST", f"/api/v1/chats/{other_chat['id']}/messages", (400, 404),
|
||||
actor=eve, headers={"Idempotency-Key": uuid.uuid4().hex},
|
||||
body={"text": "Foreign attachment", "attachment_ids": [attachment["id"]]})
|
||||
print("PASS attachment cannot be linked into another chat")
|
||||
|
||||
request = Request(client.base + "/api/v1/users", data=b"x" * (10 * 1024**2 + 1), method="POST")
|
||||
try:
|
||||
urlopen(request, context=context, timeout=10)
|
||||
except HTTPError as exc:
|
||||
check(exc.code == 413, "oversize body must return 413")
|
||||
except BrokenPipeError:
|
||||
raise AssertionError("oversize body response was not observed") from None
|
||||
else:
|
||||
raise AssertionError("oversize body was accepted")
|
||||
print("PASS oversized body returns 413")
|
||||
|
||||
auth = base64.b64encode(b"unknown-user:invalid-password").decode()
|
||||
request = Request(client.base + "/api/v1/auth/sessions", method="POST",
|
||||
headers={"Authorization": "Basic " + auth})
|
||||
for _ in range(25):
|
||||
try:
|
||||
urlopen(request, context=context, timeout=5)
|
||||
except HTTPError as exc:
|
||||
with exc:
|
||||
check(exc.code in (401, 429), f"unexpected login status {exc.code}")
|
||||
if exc.code == 429:
|
||||
check(int(exc.headers.get("Retry-After", "0")) >= 1, "missing Retry-After")
|
||||
print("PASS login limit returns 429 with Retry-After")
|
||||
return
|
||||
else:
|
||||
raise AssertionError("login unexpectedly accepted")
|
||||
raise AssertionError("login limiter did not activate")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
Reference in New Issue
Block a user