Files
mtusi2026lab5/student-tests/expiry.py
T
2026-10-25 21:43:03 +03:00

47 lines
2.7 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, make expiry
поднимает его сам). С lab3 он, как и основные реплики, доступен только через балансировщик:
127.0.0.1:8081. База и кэш общие с основным API.
Сценарий: вход -> токен работает (и попадает в кэш Valkey) -> ждём истечения ->
токен отклоняется с 401 и на коротком, и на основном API. Значит, срок жизни — свойство
сессии в PostgreSQL, а кэш не продлевает её.
"""
import datetime as dt
import os
import time
import uuid
from helpers import Client, check, login, run, wait_ready
def main():
short = Client(os.environ.get("BASE_URL_TTL", "http://127.0.0.1:8081"))
main_api = Client()
# Контейнер уже healthy, но балансировщику нужно ещё пару секунд: найти его по DNS
# и пройти 2 проверки готовности. Ждём готовности именно через балансировщик (:8081).
wait_ready(short, seconds=60)
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)