50 lines
2.0 KiB
Python
50 lines
2.0 KiB
Python
#!/usr/bin/env python3
|
|
"""
|
|
Истечение сессии при коротком SESSION_TTL_SECONDS (=2).
|
|
Запускается против отдельного экземпляра API с коротким TTL:
|
|
docker compose --env-file .env --profile ttl up -d api-ttl
|
|
python student-tests/expiry.py --base-url http://localhost:8081
|
|
"""
|
|
import argparse
|
|
import time
|
|
from datetime import datetime, timezone
|
|
|
|
from common import Api, Report
|
|
|
|
|
|
def main():
|
|
ap = argparse.ArgumentParser()
|
|
ap.add_argument("--base-url", default="http://localhost:8081")
|
|
ap.add_argument("--ttl", type=float, default=2)
|
|
args = ap.parse_args()
|
|
api, r = Api(args.base_url), Report()
|
|
# Экземпляр с коротким TTL мог только что стартовать: ждём готовности до 60 с.
|
|
deadline = time.time() + 60
|
|
while True:
|
|
try:
|
|
if api.raw("GET", "/health/ready", timeout=2)[0] == 200:
|
|
break
|
|
except OSError:
|
|
pass
|
|
if time.time() > deadline:
|
|
raise SystemExit("API is not ready at " + args.base_url)
|
|
time.sleep(1)
|
|
|
|
user = api.register("ttl")
|
|
st, sess, _ = api.login(user["username"], user["password"])
|
|
r.check(st == 201, "login -> 201")
|
|
exp = datetime.fromisoformat(sess["expires_at"].replace("Z", "+00:00"))
|
|
left = (exp - datetime.now(timezone.utc)).total_seconds()
|
|
r.check(0 < left <= args.ttl + 1, f"expires_at is about {args.ttl}s ahead (got {left:.2f}s)")
|
|
st, _, _ = api.call("GET", "/api/v1/users/me", token=sess["token"])
|
|
r.check(st == 200, "token works before expiry") # заодно кладёт сессию в кэш Redis
|
|
time.sleep(args.ttl + 1.5)
|
|
st, _, rh = api.call("GET", "/api/v1/users/me", token=sess["token"])
|
|
r.check(st == 401 and rh.get("WWW-Authenticate", "").startswith("Bearer"),
|
|
"expired token -> 401 (cache does not extend the session)")
|
|
r.finish()
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|