51 lines
1.4 KiB
Python
51 lines
1.4 KiB
Python
from pathlib import Path
|
|
import sys
|
|
import time
|
|
|
|
import pytest
|
|
from fastapi import HTTPException
|
|
|
|
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
|
|
|
from app.core.auth import decode_access_token, issue_access_token # noqa: E402
|
|
|
|
|
|
def test_issue_and_decode_access_token_round_trip():
|
|
token = issue_access_token(
|
|
website_id=42,
|
|
role="student",
|
|
wp_user_id="wp-1001",
|
|
expires_in_seconds=3600,
|
|
)
|
|
auth = decode_access_token(token)
|
|
assert auth.website_id == 42
|
|
assert auth.role == "student"
|
|
assert auth.wp_user_id == "wp-1001"
|
|
|
|
|
|
def test_decode_access_token_rejects_tampered_signature():
|
|
token = issue_access_token(
|
|
website_id=7,
|
|
role="admin",
|
|
wp_user_id=None,
|
|
expires_in_seconds=3600,
|
|
)
|
|
payload, signature = token.split(".", 1)
|
|
tampered_token = f"{payload}.{'A' if signature[0] != 'A' else 'B'}{signature[1:]}"
|
|
with pytest.raises(HTTPException) as exc_info:
|
|
decode_access_token(tampered_token)
|
|
assert exc_info.value.status_code == 401
|
|
|
|
|
|
def test_decode_access_token_rejects_expired_token():
|
|
token = issue_access_token(
|
|
website_id=9,
|
|
role="student",
|
|
wp_user_id="u-1",
|
|
expires_in_seconds=-1,
|
|
)
|
|
time.sleep(0.01)
|
|
with pytest.raises(HTTPException) as exc_info:
|
|
decode_access_token(token)
|
|
assert exc_info.value.status_code == 401
|