Forward final lab3 session security and validation fixes
This commit is contained in:
@@ -0,0 +1,130 @@
|
||||
import base64
|
||||
import http.client
|
||||
import json
|
||||
import os
|
||||
import uuid
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
base = urlsplit(os.environ.get("BASE_URL", "http://127.0.0.1:18084"))
|
||||
seen = set()
|
||||
checks = []
|
||||
password = "Пароль-проверки-01"
|
||||
|
||||
|
||||
def call(method, path, body=None, headers=None, status=200):
|
||||
request_id = "validation-wire"
|
||||
assert base.hostname
|
||||
conn = http.client.HTTPConnection(base.hostname, base.port, timeout=12)
|
||||
head = {"X-Request-Id": request_id, "Content-Type": "application/json", **(headers or {})}
|
||||
conn.request(method, path, None if body is None else json.dumps(body).encode(), head)
|
||||
response = conn.getresponse()
|
||||
data = response.read()
|
||||
instance = response.getheader("X-Instance-Id")
|
||||
assert response.status == status, (method, path, response.status, status)
|
||||
assert instance
|
||||
assert response.getheader("X-Request-Id") == request_id
|
||||
seen.add(instance)
|
||||
result = json.loads(data) if data else None
|
||||
if status >= 400:
|
||||
assert result is not None
|
||||
assert result["error"]["request_id"] == request_id
|
||||
if status == 401:
|
||||
assert response.getheader("WWW-Authenticate") == (
|
||||
'Basic realm="messenger", charset="UTF-8"'
|
||||
if path == "/api/v1/auth/sessions"
|
||||
else 'Bearer realm="messenger"'
|
||||
)
|
||||
conn.close()
|
||||
return result, instance
|
||||
|
||||
|
||||
def basic(name, secret=password):
|
||||
return {"Authorization": "Basic " + base64.b64encode(f"{name}:{secret}".encode()).decode()}
|
||||
|
||||
|
||||
def enroll():
|
||||
name = "wire_" + uuid.uuid4().hex[:15]
|
||||
user, _ = call(
|
||||
"POST",
|
||||
"/api/v1/users",
|
||||
{"username": name, "password": password, "display_name": "Алиса 👋"},
|
||||
status=201,
|
||||
)
|
||||
login, _ = call("POST", "/api/v1/auth/sessions", headers=basic(name), status=201)
|
||||
return user, {"Authorization": "Bearer " + login["token"]}
|
||||
|
||||
|
||||
user, auth = enroll()
|
||||
wrong, _ = call(
|
||||
"POST", "/api/v1/auth/sessions", headers=basic(user["username"], "wrong-password"), status=401
|
||||
)
|
||||
for raw in [b"Basic \x80", b"Basic \xff", b"Basic \xc3\xa9", b"Basic YWxpY2U6c2VjcmV0\xff"]:
|
||||
result, instance = call(
|
||||
"POST", "/api/v1/auth/sessions", headers={"Authorization": raw}, status=401
|
||||
)
|
||||
assert result == wrong
|
||||
checks.append(
|
||||
{"case": "non_ascii_basic", "raw_hex": raw.hex(), "status": 401, "instance": instance}
|
||||
)
|
||||
for text in ["\x00", "\x00abc", "abc\x00def", "abc\x00"]:
|
||||
result, instance = call("POST", "/api/v1/auth/sessions", headers=basic(text), status=401)
|
||||
assert result == wrong
|
||||
body = {"username": "wire_" + uuid.uuid4().hex[:15], "password": password, "display_name": text}
|
||||
call("POST", "/api/v1/users", body, status=400)
|
||||
call("POST", "/api/v1/users", {**body, "display_name": "Алиса 👋"}, status=201)
|
||||
call("POST", "/api/v1/chats", {"title": text, "member_ids": [user["id"]]}, auth, status=400)
|
||||
chats, _ = call("GET", "/api/v1/chats", headers=auth)
|
||||
assert not chats["items"]
|
||||
checks.append(
|
||||
{
|
||||
"case": "nul_basic_display_title",
|
||||
"position": repr(text),
|
||||
"status": [401, 400, 201, 400],
|
||||
"instance": instance,
|
||||
}
|
||||
)
|
||||
chat, _ = call(
|
||||
"POST", "/api/v1/chats", {"title": "Проверка 👋", "member_ids": [user["id"]]}, auth, status=201
|
||||
)
|
||||
path = f"/api/v1/chats/{chat['id']}/messages"
|
||||
messages = []
|
||||
for text in ["\x00", "\x00abc", "abc\x00def", "abc\x00"]:
|
||||
headers = {**auth, "Idempotency-Key": uuid.uuid4().hex}
|
||||
call("POST", path, {"text": text}, headers, status=400)
|
||||
page, _ = call("GET", path, headers=auth)
|
||||
assert page["items"] == messages
|
||||
first, one = call("POST", path, {"text": "Исправлено\tбез потерь\n👋"}, headers, status=201)
|
||||
again, two = call("POST", path, {"text": first["text"]}, headers, status=201)
|
||||
assert first == again and one != two
|
||||
messages.append(first)
|
||||
page, _ = call("GET", path, headers=auth)
|
||||
assert page["items"] == messages
|
||||
checks.append(
|
||||
{
|
||||
"case": "nul_message_corrected_retry",
|
||||
"position": repr(text),
|
||||
"instances": [one, two],
|
||||
"status": [400, 201, 201],
|
||||
"copies": 1,
|
||||
}
|
||||
)
|
||||
_, outsider = enroll()
|
||||
for target in [chat["id"], str(uuid.uuid4())]:
|
||||
call(
|
||||
"POST",
|
||||
f"/api/v1/chats/{target}/messages",
|
||||
{"text": "abc\x00def"},
|
||||
{**outsider, "Idempotency-Key": uuid.uuid4().hex},
|
||||
status=404,
|
||||
)
|
||||
checks.append({"case": "nul_access", "status": [404, 404]})
|
||||
call("DELETE", "/api/v1/auth/sessions/current", headers=auth, status=204)
|
||||
for _ in range(4):
|
||||
call("GET", "/api/v1/users/me", headers=auth, status=401)
|
||||
checks.append({"case": "logout_across_replicas", "status": [204, 401, 401, 401, 401]})
|
||||
assert len(seen) >= 2
|
||||
print(
|
||||
json.dumps(
|
||||
{"checks": checks, "instances": sorted(seen), "pass": True}, ensure_ascii=False, indent=2
|
||||
)
|
||||
)
|
||||
@@ -0,0 +1,43 @@
|
||||
import http.client
|
||||
import json
|
||||
import sys
|
||||
import time
|
||||
|
||||
status = int(sys.argv[1])
|
||||
path = {502: "/bad", 503: "/none", 504: "/slow"}[status]
|
||||
if status != 503:
|
||||
for _ in range(60):
|
||||
conn = http.client.HTTPConnection("lb", 8080, timeout=2)
|
||||
conn.request("GET", "/health/ready")
|
||||
response = conn.getresponse()
|
||||
response.read()
|
||||
conn.close()
|
||||
if response.status == 200:
|
||||
break
|
||||
time.sleep(1)
|
||||
else:
|
||||
raise RuntimeError("Backend never became ready")
|
||||
else:
|
||||
time.sleep(5)
|
||||
for value in ['a"b', "a\\b", "a\tb", "x" * 200]:
|
||||
conn = http.client.HTTPConnection("lb", 8080, timeout=20)
|
||||
start = time.monotonic()
|
||||
conn.request("GET", path, headers={"X-Request-Id": value})
|
||||
response = conn.getresponse()
|
||||
payload = json.loads(response.read())
|
||||
assert response.status == status, response.status
|
||||
assert response.getheader("X-Request-Id") == value
|
||||
assert payload["error"]["request_id"] == value
|
||||
print(
|
||||
json.dumps(
|
||||
{
|
||||
"status": status,
|
||||
"request_id": value,
|
||||
"json_valid": True,
|
||||
"echo_matches": True,
|
||||
"seconds": round(time.monotonic() - start, 3),
|
||||
}
|
||||
),
|
||||
flush=True,
|
||||
)
|
||||
conn.close()
|
||||
@@ -0,0 +1,25 @@
|
||||
services:
|
||||
lb:
|
||||
image: haproxy:3.2.26-alpine@sha256:5893840576071e6217cd52ebdcc14f454c6f7a631056fa6f4e0f40d3cac4215b
|
||||
volumes: [../../../infra/haproxy/haproxy.cfg:/usr/local/etc/haproxy/haproxy.cfg:ro]
|
||||
init: true
|
||||
deploy:
|
||||
resources:
|
||||
limits: {cpus: "0.5", memory: 128m}
|
||||
api:
|
||||
image: ${API_IMAGE:?Set the image built by the lab4 stack}
|
||||
entrypoint: [python, /fixture/server.py]
|
||||
volumes: [./:/fixture:ro]
|
||||
init: true
|
||||
deploy:
|
||||
resources:
|
||||
limits: {cpus: "0.5", memory: 128m}
|
||||
probe:
|
||||
image: ${API_IMAGE:?Set the image built by the lab4 stack}
|
||||
entrypoint: [python, /fixture/client.py]
|
||||
volumes: [./:/fixture:ro]
|
||||
profiles: [probe]
|
||||
init: true
|
||||
deploy:
|
||||
resources:
|
||||
limits: {cpus: "0.5", memory: 128m}
|
||||
@@ -0,0 +1,20 @@
|
||||
import socketserver
|
||||
import time
|
||||
|
||||
|
||||
class Handler(socketserver.StreamRequestHandler):
|
||||
def handle(self) -> None:
|
||||
request = self.rfile.readline(8192)
|
||||
while self.rfile.readline(8192) not in {b"\r\n", b""}:
|
||||
pass
|
||||
path = request.split(b" ")[1]
|
||||
if path == b"/bad":
|
||||
self.wfile.write(b"NOT-HTTP\r\n\r\n")
|
||||
elif path == b"/slow":
|
||||
time.sleep(12)
|
||||
else:
|
||||
self.wfile.write(b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nOK")
|
||||
|
||||
|
||||
with socketserver.ThreadingTCPServer(("0.0.0.0", 8080), Handler) as server:
|
||||
server.serve_forever()
|
||||
Reference in New Issue
Block a user