74 lines
2.4 KiB
Python
74 lines
2.4 KiB
Python
"""P4.5a: jti/ver, 15-мин admin-access, refresh/revoke при 2FA."""
|
|
import importlib
|
|
import os
|
|
import sys
|
|
import time
|
|
|
|
import pytest
|
|
|
|
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
|
if ROOT not in sys.path:
|
|
sys.path.insert(0, ROOT)
|
|
|
|
|
|
@pytest.fixture()
|
|
def env(tmp_path, monkeypatch):
|
|
monkeypatch.setenv("DB_PATH", str(tmp_path / "t.db"))
|
|
monkeypatch.setenv("SESSION_SECRET", "test-secret")
|
|
monkeypatch.setenv("AI_BACKEND", "claude")
|
|
monkeypatch.chdir(ROOT)
|
|
import auth
|
|
import db
|
|
import main
|
|
for m in (auth, db, main):
|
|
importlib.reload(m)
|
|
db.init_db()
|
|
db.create_user("boss@x", auth.hash_password("Passw0rd!ok"), role="admin")
|
|
db.admin_verify_user("boss@x")
|
|
return auth, db
|
|
|
|
|
|
def test_admin_access_15m_and_session(env):
|
|
auth, db = env
|
|
db.create_auth_session("j1", "boss@x", "admin", time.time() + 900, ver=0)
|
|
token = auth._make_token("boss@x", "admin", jti="j1", ver=0)
|
|
payload = auth.jwt.decode(token, auth.SECRET, algorithms=["HS256"])
|
|
assert payload["exp"] - int(time.time()) <= 900
|
|
assert auth.verify_token(token) == "boss@x"
|
|
db.revoke_auth_session("j1")
|
|
assert auth.verify_token(token) is None
|
|
|
|
|
|
def test_refresh_revoked_and_version(env):
|
|
auth, db = env
|
|
token = auth.authenticate("boss@x", "Passw0rd!ok")
|
|
jti, ver = auth.get_token_jti_ver(token)
|
|
assert jti and ver == 0
|
|
refresh = auth._make_refresh_token("boss@x", "admin", jti, ver)
|
|
assert auth.refresh_access_token(refresh)
|
|
db.revoke_auth_session(jti)
|
|
assert auth.refresh_access_token(refresh) is None
|
|
|
|
token2 = auth.authenticate("boss@x", "Passw0rd!ok")
|
|
jti2, ver2 = auth.get_token_jti_ver(token2)
|
|
with db._conn() as c:
|
|
c.execute("UPDATE users SET token_version = token_version + 1 WHERE email='boss@x'")
|
|
assert auth.refresh_access_token(
|
|
auth._make_refresh_token("boss@x", "admin", jti2, ver2)) is None
|
|
|
|
|
|
def test_legacy_token_without_jti_still_works_without_2fa(env):
|
|
auth, db = env
|
|
token = auth._make_token("boss@x", "admin")
|
|
assert auth.verify_token(token) == "boss@x"
|
|
|
|
|
|
def test_2fa_enabled_rejects_legacy_tokens(env):
|
|
auth, db = env
|
|
with db._conn() as c:
|
|
c.execute("UPDATE users SET totp_enabled = 1 WHERE email='boss@x'")
|
|
old = auth._make_token("boss@x", "admin")
|
|
assert auth.verify_token(old) is None
|
|
old_refresh = auth._make_refresh_token("boss@x", "admin")
|
|
assert auth.refresh_access_token(old_refresh) is None
|