forked from mtusi2026/mtusi2026lab3
solution
This commit is contained in:
@@ -0,0 +1,90 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Проверка срока жизни сессии, выхода и неверного пароля на запущенном API.
|
||||
|
||||
python scripts/check_expiry.py --base-url http://localhost:8081 --ttl 3
|
||||
|
||||
API должен работать с SESSION_TTL_SECONDS, равным --ttl.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import base64
|
||||
import json
|
||||
import sys
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
import uuid
|
||||
from datetime import datetime, timezone
|
||||
|
||||
|
||||
def http(base, method, path, body=None, headers=None):
|
||||
"""HTTP-запрос: (статус, заголовки, тело)."""
|
||||
data = json.dumps(body).encode() if body is not None else None
|
||||
request = urllib.request.Request(base + path, data=data, method=method, headers=dict(headers or {}))
|
||||
if data is not None:
|
||||
request.add_header("Content-Type", "application/json")
|
||||
try:
|
||||
with urllib.request.urlopen(request, timeout=10) as reply:
|
||||
return reply.status, reply.headers, reply.read()
|
||||
except urllib.error.HTTPError as error:
|
||||
return error.code, error.headers, error.read()
|
||||
|
||||
|
||||
def step(text, ok):
|
||||
"""Напечатать результат шага; при неудаче завершить с кодом 1."""
|
||||
print(("OK " if ok else "FAIL ") + text, flush=True)
|
||||
if not ok:
|
||||
sys.exit(1)
|
||||
|
||||
|
||||
def main():
|
||||
"""Выполнить проверку."""
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--base-url", default="http://localhost:8081")
|
||||
parser.add_argument("--ttl", type=float, default=3)
|
||||
args = parser.parse_args()
|
||||
base = args.base_url.rstrip("/")
|
||||
|
||||
username, password = "ttl_" + uuid.uuid4().hex[:8], "Expiry-" + uuid.uuid4().hex
|
||||
basic = {"Authorization": "Basic " + base64.b64encode((username + ":" + password).encode()).decode()}
|
||||
status, _, _ = http(base, "POST", "/api/v1/users",
|
||||
{"username": username, "display_name": "TTL", "password": password})
|
||||
step("регистрация -> %d" % status, status == 201)
|
||||
|
||||
status, _, raw = http(base, "POST", "/api/v1/auth/sessions", headers=basic)
|
||||
session = json.loads(raw)
|
||||
expires = datetime.fromisoformat(session["expires_at"].replace("Z", "+00:00"))
|
||||
left = (expires - datetime.now(timezone.utc)).total_seconds()
|
||||
step("вход -> %d, expires_at через %.1f с (TTL=%g)" % (status, left, args.ttl),
|
||||
status == 201 and 0 < left <= args.ttl + 1)
|
||||
bearer = {"Authorization": "Bearer " + session["token"]}
|
||||
for n in range(3):
|
||||
status, _, _ = http(base, "GET", "/api/v1/users/me", headers=bearer)
|
||||
step("GET /users/me #%d до истечения -> %d" % (n + 1, status), status == 200)
|
||||
|
||||
time.sleep(args.ttl + 1)
|
||||
status, headers, raw = http(base, "GET", "/api/v1/users/me", headers=bearer)
|
||||
step("GET /users/me после TTL+1 с -> %d, WWW-Authenticate: %s, code=%s"
|
||||
% (status, headers.get("WWW-Authenticate"), json.loads(raw)["error"]["code"]),
|
||||
status == 401 and headers.get("WWW-Authenticate") == 'Bearer realm="messenger"')
|
||||
|
||||
status, _, raw = http(base, "POST", "/api/v1/auth/sessions", headers=basic)
|
||||
bearer = {"Authorization": "Bearer " + json.loads(raw)["token"]}
|
||||
step("новый вход -> %d" % status, status == 201)
|
||||
status, _, _ = http(base, "DELETE", "/api/v1/auth/sessions/current", headers=bearer)
|
||||
step("logout -> %d" % status, status == 204)
|
||||
status, _, _ = http(base, "GET", "/api/v1/users/me", headers=bearer)
|
||||
step("GET /users/me после logout -> %d" % status, status == 401)
|
||||
status, _, _ = http(base, "DELETE", "/api/v1/auth/sessions/current", headers=bearer)
|
||||
step("повторный logout -> %d" % status, status == 401)
|
||||
|
||||
wrong = {"Authorization": "Basic " + base64.b64encode((username + ":wrong-password-123").encode()).decode()}
|
||||
status, headers, _ = http(base, "POST", "/api/v1/auth/sessions", headers=wrong)
|
||||
step("вход с неверным паролем -> %d, WWW-Authenticate: %s" % (status, headers.get("WWW-Authenticate")),
|
||||
status == 401 and headers.get("WWW-Authenticate", "").startswith("Basic"))
|
||||
print("PASS: expiry (TTL=%g с), logout и неверный пароль на запущенном API" % args.ttl)
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
Reference in New Issue
Block a user