Files
mtusi2026lab2/student-tests/expiry.py
T
ng14 994c3a9b7a
Skeleton contracts / contracts (pull_request) Canceled after 0s
ЛР2
2026-10-09 13:44:23 +03:00

43 lines
2.2 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Проверка истечения сессии при коротком TTL (уровень 4). Запуск: make expiry
Нужен второй экземпляр API с SESSION_TTL_SECONDS=2 (сервис api-short-ttl на порту 8081,
make expiry поднимает его сам). База общая с основным API.
Сценарий: вход -> токен работает (и попадает в кэш Valkey) -> ждём истечения ->
токен отклоняется с 401 и на коротком, и на основном API. Значит, срок жизни — свойство
сессии в PostgreSQL, а кэш не продлевает её.
"""
import datetime as dt
import os
import time
import uuid
from helpers import Client, check, login, run
def main():
short = Client(os.environ.get("BASE_URL_TTL", "http://127.0.0.1:8081"))
main_api = Client()
body = {"username": "ttl_" + uuid.uuid4().hex[:12], "display_name": "TTL", "password": "Ttl-password-123"}
short.call("POST", "/api/v1/users", 201, body=body, schema="User")
session = login(short, body["username"], body["password"])
auth = {"Authorization": "Bearer " + session["token"]}
expires_at = dt.datetime.fromisoformat(session["expires_at"].replace("Z", "+00:00"))
ttl = (expires_at - dt.datetime.now(dt.timezone.utc)).total_seconds()
print(f"session issued by short-TTL API, expires in {ttl:.2f}s")
check(0 < ttl <= 3, "short-TTL instance must issue ~2 second sessions")
for api in (short, short, main_api): # два раза подряд: второй ответ уже из кэша
api.call("GET", "/api/v1/users/me", 200, headers=auth, schema="User")
print("before expiry: GET /users/me -> 200 (short API twice, main API once)")
time.sleep(max(0.0, (expires_at - dt.datetime.now(dt.timezone.utc)).total_seconds()) + 1.0)
for api in (short, main_api):
api.call("GET", "/api/v1/users/me", 401, headers=auth) # клиент проверяет WWW-Authenticate: Bearer
print("after expiry: GET /users/me -> 401 on both instances")
print("PASS: session expired after SESSION_TTL_SECONDS; cache did not extend it")
if __name__ == "__main__":
run(main)