From a54a474d435412ab0aa77a9f61c584203f1faaaa Mon Sep 17 00:00:00 2001 From: kiskaadee Date: Fri, 2 Oct 2026 22:48:13 -0500 Subject: [PATCH] feat(auth): define AuthPort protocol and Identity domain model - Establish typed Identity domain model with origin integrity validation - Define AuthPort protocol establishing current_identity, login, and logout contracts - Add unit tests verifying AuthPort protocol conformance and Identity domain invariants --- backend/app/auth/__init__.py | 4 + backend/app/auth/identity.py | 36 ++++++++ backend/app/auth/port.py | 32 +++++++ backend/tests/test_auth_port.py | 154 ++++++++++++++++++++++++++++++++ 4 files changed, 226 insertions(+) create mode 100644 backend/app/auth/__init__.py create mode 100644 backend/app/auth/identity.py create mode 100644 backend/app/auth/port.py create mode 100644 backend/tests/test_auth_port.py diff --git a/backend/app/auth/__init__.py b/backend/app/auth/__init__.py new file mode 100644 index 0000000..346171f --- /dev/null +++ b/backend/app/auth/__init__.py @@ -0,0 +1,4 @@ +from .identity import Identity +from .port import AuthPort + +__all__ = ["AuthPort", "Identity"] diff --git a/backend/app/auth/identity.py b/backend/app/auth/identity.py new file mode 100644 index 0000000..261404c --- /dev/null +++ b/backend/app/auth/identity.py @@ -0,0 +1,36 @@ +from dataclasses import dataclass, field +from typing import Optional + + +@dataclass(frozen=True) +class Identity: + """Domain model representing a validated authenticated principal. + + Identity Origin Integrity: + Instances of Identity must only represent verified authentication results produced + by an authentication adapter or port, and must never be constructed directly from + raw unvalidated client headers or requests. + """ + + subject: str + email: str + name: Optional[str] = None + groups: list[str] = field(default_factory=list) + + def __post_init__(self) -> None: + if not isinstance(self.subject, str) or not self.subject.strip(): + raise ValueError("Identity subject must be a non-empty string") + if not isinstance(self.email, str) or not self.email.strip(): + raise ValueError("Identity email must be a non-empty string") + if self.name is not None and not isinstance(self.name, str): + raise TypeError("Identity name must be a string or None") + if not isinstance(self.groups, (list, tuple)): + raise TypeError("Identity groups must be a list of strings") + for g in self.groups: + if not isinstance(g, str): + raise TypeError("Identity groups items must be strings") + object.__setattr__(self, "groups", list(self.groups)) + + def has_group(self, group: str) -> bool: + """Check if the identity belongs to a specific group.""" + return group in self.groups diff --git a/backend/app/auth/port.py b/backend/app/auth/port.py new file mode 100644 index 0000000..3d2f28e --- /dev/null +++ b/backend/app/auth/port.py @@ -0,0 +1,32 @@ +from typing import Optional, Protocol, runtime_checkable + +from fastapi import Request, Response + +from .identity import Identity + + +@runtime_checkable +class AuthPort(Protocol): + """Hexagonal Port for Authentication and Identity Management. + + Establishes the boundary between application domain logic and concrete authentication + mechanisms (such as OIDC, OAuth, ForwardAuth, or session providers). + """ + + def current_identity(self, request: Request) -> Optional[Identity]: + """Resolve the validated identity associated with the incoming request. + + Returns None if the request is unauthenticated or credentials/session are invalid. + """ + ... + + def login(self, request: Request) -> Response: + """Initiate the login flow (e.g. redirect to identity provider or challenge response).""" + ... + + def logout(self, request: Request) -> Response: + """Terminate the session or logout flow (e.g. invalidate session cookie or IdP logout redirect).""" + ... + + +__all__ = ["AuthPort", "Identity"] diff --git a/backend/tests/test_auth_port.py b/backend/tests/test_auth_port.py new file mode 100644 index 0000000..27dd548 --- /dev/null +++ b/backend/tests/test_auth_port.py @@ -0,0 +1,154 @@ +from dataclasses import FrozenInstanceError +from typing import Optional + +import pytest +from fastapi import Request, Response +from fastapi.responses import RedirectResponse +from starlette.datastructures import Headers + +from app.auth import AuthPort, Identity + + +class MockAuthAdapter: + """Mock implementation of AuthPort for testing hexagonal boundary compliance.""" + + def __init__(self, current_user: Optional[Identity] = None): + self._current_user = current_user + + def current_identity(self, request: Request) -> Optional[Identity]: + return self._current_user + + def login(self, request: Request) -> Response: + return RedirectResponse(url="/auth/login", status_code=302) + + def logout(self, request: Request) -> Response: + return RedirectResponse(url="/auth/logout", status_code=302) + + +class IncompleteAuthAdapter: + """Non-conforming class missing login and logout methods.""" + + def current_identity(self, request: Request) -> Optional[Identity]: + return None + + +def create_dummy_request(headers: dict[str, str] | None = None) -> Request: + raw_headers = [ + (k.lower().encode("latin-1"), v.encode("latin-1")) + for k, v in (headers or {}).items() + ] + scope = { + "type": "http", + "method": "GET", + "path": "/test", + "headers": raw_headers, + } + return Request(scope) + + +def test_identity_creation_full(): + identity = Identity( + subject="user-123", + email="test@example.com", + name="Test User", + groups=["admin", "family"], + ) + assert identity.subject == "user-123" + assert identity.email == "test@example.com" + assert identity.name == "Test User" + assert identity.groups == ["admin", "family"] + assert identity.has_group("admin") is True + assert identity.has_group("stranger") is False + + +def test_identity_creation_defaults(): + identity = Identity( + subject="user-456", + email="minimal@example.com", + ) + assert identity.subject == "user-456" + assert identity.email == "minimal@example.com" + assert identity.name is None + assert identity.groups == [] + assert identity.has_group("admin") is False + + +def test_identity_immutability(): + identity = Identity( + subject="user-789", + email="immutable@example.com", + ) + with pytest.raises(FrozenInstanceError): + identity.subject = "new-subject" # type: ignore[misc] + + with pytest.raises(FrozenInstanceError): + identity.email = "new@example.com" # type: ignore[misc] + + +def test_identity_validation_subject(): + with pytest.raises(ValueError, match="subject must be a non-empty string"): + Identity(subject="", email="test@example.com") + + with pytest.raises(ValueError, match="subject must be a non-empty string"): + Identity(subject=" ", email="test@example.com") + + +def test_identity_validation_email(): + with pytest.raises(ValueError, match="email must be a non-empty string"): + Identity(subject="user-1", email="") + + with pytest.raises(ValueError, match="email must be a non-empty string"): + Identity(subject="user-1", email=" ") + + +def test_identity_validation_name(): + with pytest.raises(TypeError, match="name must be a string or None"): + Identity(subject="user-1", email="test@example.com", name=123) # type: ignore[arg-type] + + +def test_identity_validation_groups(): + with pytest.raises(TypeError, match="groups must be a list of strings"): + Identity(subject="user-1", email="test@example.com", groups="not-a-list") # type: ignore[arg-type] + + with pytest.raises(TypeError, match="groups items must be strings"): + Identity(subject="user-1", email="test@example.com", groups=[123]) # type: ignore[list-item] + + +def test_auth_port_protocol_conformance(): + adapter = MockAuthAdapter() + assert isinstance(adapter, AuthPort) + + +def test_auth_port_protocol_non_conformance(): + incomplete = IncompleteAuthAdapter() + assert not isinstance(incomplete, AuthPort) + + +def test_auth_port_current_identity_resolution(): + expected_identity = Identity( + subject="admin-1", + email="admin@example.com", + name="Admin", + groups=["admin"], + ) + authenticated_port: AuthPort = MockAuthAdapter(current_user=expected_identity) + unauthenticated_port: AuthPort = MockAuthAdapter(current_user=None) + + req = create_dummy_request() + assert authenticated_port.current_identity(req) == expected_identity + assert unauthenticated_port.current_identity(req) is None + + +def test_auth_port_login_logout_contract(): + port: AuthPort = MockAuthAdapter() + req = create_dummy_request() + + login_resp = port.login(req) + assert isinstance(login_resp, Response) + assert login_resp.status_code == 302 + assert login_resp.headers["location"] == "/auth/login" + + logout_resp = port.logout(req) + assert isinstance(logout_resp, Response) + assert logout_resp.status_code == 302 + assert logout_resp.headers["location"] == "/auth/logout"