3ccd94f661
Test Organization: - Create tests/unit/, tests/integration/, tests/system/ directories - Move existing tests into appropriate categories - Add pytest markers (@pytest.mark.unit, @pytest.mark.integration) Shared Fixtures: - Create conftest.py with SQLite engine (for unit tests) - Add PostgreSQL session fixture with transaction rollback - Add TestClient fixture for API tests Configuration: - Update pyproject.toml with asyncio_mode=auto - Add test markers and default addopts - Add aiosqlite dependency for SQLite support E2E Testing: - Initialize Playwright in e2e/ directory - Add playwright.config.ts - Create login flow E2E test Build: - Add test-unit, test-integration, test-system, test-e2e to Makefile - Update test target to run all categories - Add testing documentation to README Note: Some tests have import issues due to missing python-jose package in dev environment. This needs to be addressed separately.
228 lines
7.0 KiB
Python
228 lines
7.0 KiB
Python
from datetime import UTC, datetime, timedelta
|
|
import base64
|
|
|
|
import httpx
|
|
import pytest
|
|
import pytest_asyncio
|
|
from sqlalchemy import text
|
|
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
|
|
|
|
from src.auth.cookies import build_cookie_options
|
|
from src.auth.jwt_service import decode_access_token, mint_access_token
|
|
from src.auth.oidc import build_login_redirect_url, exchange_code_for_tokens, verify_provider_access_token
|
|
from src.auth.refresh_store import create_refresh_token, hash_refresh_token, revoke_refresh_token, rotate_refresh_token
|
|
from src.config import Settings, build_database_url
|
|
from src.models import Base
|
|
from src.models.user import User
|
|
|
|
|
|
n@pytest.mark.integration
|
|
|
|
def test_cookie_options_follow_environment_defaults(monkeypatch) -> None:
|
|
monkeypatch.setenv("APP_ENV", "development")
|
|
dev_settings = Settings()
|
|
dev_options = build_cookie_options(dev_settings)
|
|
|
|
monkeypatch.setenv("APP_ENV", "production")
|
|
prod_settings = Settings()
|
|
prod_options = build_cookie_options(prod_settings)
|
|
|
|
assert dev_options["httponly"] is True
|
|
assert dev_options["secure"] is False
|
|
assert dev_options["samesite"] == "lax"
|
|
assert prod_options["secure"] is True
|
|
assert prod_options["samesite"] == "strict"
|
|
|
|
|
|
n@pytest.mark.integration
|
|
|
|
def test_login_redirect_url_contains_required_oidc_params() -> None:
|
|
settings = Settings()
|
|
|
|
url = build_login_redirect_url(
|
|
settings=settings,
|
|
redirect_uri="http://localhost:8000/auth/callback",
|
|
state="state-123",
|
|
nonce="nonce-123",
|
|
)
|
|
|
|
assert "response_type=code" in url
|
|
assert "client_id=headquarter-web" in url
|
|
assert "scope=openid+profile+email" in url
|
|
assert "state=state-123" in url
|
|
assert "nonce=nonce-123" in url
|
|
|
|
|
|
n@pytest.mark.integration
|
|
|
|
def test_mint_and_decode_internal_access_token_round_trip() -> None:
|
|
settings = Settings()
|
|
expires_at = datetime.now(UTC) + timedelta(minutes=15)
|
|
|
|
token = mint_access_token(
|
|
settings=settings,
|
|
subject="user-123",
|
|
email="dev@headquarter.local",
|
|
name="Dev User",
|
|
expires_at=expires_at,
|
|
)
|
|
|
|
claims = decode_access_token(settings=settings, token=token)
|
|
|
|
assert claims["sub"] == "user-123"
|
|
assert claims["email"] == "dev@headquarter.local"
|
|
assert claims["name"] == "Dev User"
|
|
assert "exp" in claims
|
|
|
|
|
|
n@pytest.mark.integration
|
|
|
|
def test_refresh_token_hash_is_deterministic_and_non_reversible() -> None:
|
|
raw_token = "refresh-token-abc"
|
|
|
|
first_hash = hash_refresh_token(raw_token)
|
|
second_hash = hash_refresh_token(raw_token)
|
|
|
|
assert first_hash == second_hash
|
|
assert first_hash != raw_token
|
|
assert len(first_hash) == 64
|
|
|
|
|
|
n@pytest.mark.integration
|
|
|
|
def test_decode_access_token_rejects_invalid_signature() -> None:
|
|
settings = Settings()
|
|
other_settings = Settings(jwt_secret="different-secret")
|
|
expires_at = datetime.now(UTC) + timedelta(minutes=15)
|
|
|
|
token = mint_access_token(
|
|
settings=other_settings,
|
|
subject="user-123",
|
|
email="dev@headquarter.local",
|
|
name="Dev User",
|
|
expires_at=expires_at,
|
|
)
|
|
|
|
with pytest.raises(Exception):
|
|
decode_access_token(settings=settings, token=token)
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
n@pytest.mark.integration
|
|
|
|
async def test_exchange_code_for_tokens_posts_expected_payload() -> None:
|
|
settings = Settings()
|
|
|
|
def handler(request: httpx.Request) -> httpx.Response:
|
|
assert request.url == httpx.URL(settings.resolved_authentik_token_url)
|
|
payload = dict(httpx.QueryParams(request.content.decode("utf-8")))
|
|
assert payload["grant_type"] == "authorization_code"
|
|
assert payload["code"] == "auth-code"
|
|
assert payload["redirect_uri"] == "http://localhost:8000/auth/callback"
|
|
return httpx.Response(200, json={"access_token": "provider-token", "refresh_token": "provider-refresh"})
|
|
|
|
transport = httpx.MockTransport(handler)
|
|
async with httpx.AsyncClient(transport=transport) as client:
|
|
token_payload = await exchange_code_for_tokens(
|
|
settings=settings,
|
|
code="auth-code",
|
|
redirect_uri="http://localhost:8000/auth/callback",
|
|
client=client,
|
|
)
|
|
|
|
assert token_payload["access_token"] == "provider-token"
|
|
|
|
|
|
n@pytest.mark.integration
|
|
|
|
def test_verify_provider_access_token_with_jwks_oct_key() -> None:
|
|
settings = Settings(authentik_audience="headquarter-web", authentik_issuer="https://authentik.local/")
|
|
shared_secret = b"shared-secret-123"
|
|
jwks = {
|
|
"keys": [
|
|
{
|
|
"kty": "oct",
|
|
"alg": "HS256",
|
|
"k": base64.urlsafe_b64encode(shared_secret).decode("utf-8").rstrip("="),
|
|
"kid": "kid-1",
|
|
}
|
|
]
|
|
}
|
|
|
|
from jose import jwt # type: ignore[import-untyped]
|
|
|
|
token = jwt.encode(
|
|
{
|
|
"sub": "authentik-user",
|
|
"iss": settings.authentik_issuer,
|
|
"aud": settings.authentik_audience,
|
|
"exp": int((datetime.now(UTC) + timedelta(minutes=5)).timestamp()),
|
|
},
|
|
shared_secret,
|
|
algorithm="HS256",
|
|
headers={"kid": "kid-1"},
|
|
)
|
|
|
|
claims = verify_provider_access_token(settings=settings, token=token, jwks=jwks)
|
|
|
|
assert claims["sub"] == "authentik-user"
|
|
|
|
|
|
TEST_DATABASE_URL = build_database_url(
|
|
user="headquarter",
|
|
password="headquarter",
|
|
host="localhost",
|
|
port=5432,
|
|
database="headquarter",
|
|
)
|
|
|
|
|
|
@pytest_asyncio.fixture
|
|
async def db_session() -> AsyncSession:
|
|
engine = create_async_engine(TEST_DATABASE_URL)
|
|
session_factory = async_sessionmaker(engine, expire_on_commit=False)
|
|
|
|
async with engine.begin() as connection:
|
|
await connection.run_sync(Base.metadata.create_all)
|
|
|
|
async with session_factory() as session:
|
|
await session.execute(text("TRUNCATE TABLE refresh_tokens, users RESTART IDENTITY CASCADE"))
|
|
await session.commit()
|
|
yield session
|
|
await session.rollback()
|
|
|
|
await engine.dispose()
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
n@pytest.mark.integration
|
|
|
|
async def test_refresh_store_create_rotate_and_revoke(db_session: AsyncSession) -> None:
|
|
user = User(email="dev-auth@headquarter.local", name="Dev Auth", authentik_id="auth-dev", avatar_url=None)
|
|
db_session.add(user)
|
|
await db_session.commit()
|
|
await db_session.refresh(user)
|
|
|
|
raw_refresh_token, stored_token = await create_refresh_token(
|
|
session=db_session,
|
|
user_id=user.id,
|
|
expires_at=datetime.now(UTC) + timedelta(days=7),
|
|
user_agent="pytest",
|
|
ip_address="127.0.0.1",
|
|
)
|
|
assert raw_refresh_token
|
|
assert stored_token.revoked_at is None
|
|
|
|
rotated_raw, rotated_stored = await rotate_refresh_token(
|
|
session=db_session,
|
|
raw_token=raw_refresh_token,
|
|
user_agent="pytest-rotated",
|
|
ip_address="127.0.0.2",
|
|
)
|
|
assert rotated_raw != raw_refresh_token
|
|
assert rotated_stored.revoked_at is None
|
|
assert stored_token.revoked_at is not None
|
|
|
|
revoked = await revoke_refresh_token(session=db_session, raw_token=rotated_raw)
|
|
assert revoked is True
|