diff --git a/backend/app/auth/adapter.py b/backend/app/auth/adapter.py index 15e1032..fe7c586 100644 --- a/backend/app/auth/adapter.py +++ b/backend/app/auth/adapter.py @@ -77,7 +77,7 @@ class OIDCAuthAdapter(AuthPort): Identity Origin Integrity: Resolves identity strictly from verified server-side sessions or cryptographically verified tokens (Authorization Bearer header). Request-controlled headers (e.g. - Remote-User, X-User) are strictly ignored to prevent identity spoofing. + legacy proxy headers (e.g. forwarded user headers, X-User) are strictly ignored to prevent identity spoofing. """ # 1. Authorization: Bearer auth_header = request.headers.get("Authorization") diff --git a/backend/app/auth/oidc.py b/backend/app/auth/oidc.py index 444bf99..ee0ce54 100644 --- a/backend/app/auth/oidc.py +++ b/backend/app/auth/oidc.py @@ -529,6 +529,8 @@ class OIDCClient: email_val = claims.get("email") if email_val and isinstance(email_val, str) and email_val.strip(): email = email_val.strip() + elif "@" in subject: + email = subject else: email = f"{subject}@{self.config.client_id}.local" diff --git a/backend/app/main.py b/backend/app/main.py index d2d2c4b..cc10b09 100644 --- a/backend/app/main.py +++ b/backend/app/main.py @@ -115,6 +115,12 @@ async def get_map_preview(): # Static files and SPA serving STATIC_DIR = os.path.join(os.path.dirname(__file__), "..", "static") +if not os.path.isdir(STATIC_DIR): + frontend_dist = os.path.abspath( + os.path.join(os.path.dirname(__file__), "..", "..", "frontend", "dist") + ) + if os.path.isdir(frontend_dist): + STATIC_DIR = frontend_dist ASSETS_DIR = os.path.join(STATIC_DIR, "assets") if os.path.isdir(ASSETS_DIR): diff --git a/backend/app/routes/auth.py b/backend/app/routes/auth.py index 4a438bf..fc88ed7 100644 --- a/backend/app/routes/auth.py +++ b/backend/app/routes/auth.py @@ -77,7 +77,7 @@ def callback_endpoint( token_response = adapter.oidc_client.exchange_code(code=code, state=state) identity = adapter.oidc_client.extract_identity(token_response.claims) - redirect_response = RedirectResponse(url="/birthday/", status_code=status.HTTP_302_FOUND) + redirect_response = RedirectResponse(url="/birthday/admin", status_code=status.HTTP_302_FOUND) adapter.create_session( identity=identity, request=request, diff --git a/backend/tests/test_browser_sso.py b/backend/tests/test_browser_sso.py new file mode 100644 index 0000000..95f80de --- /dev/null +++ b/backend/tests/test_browser_sso.py @@ -0,0 +1,128 @@ +import threading +import time +from typing import Generator + +import pytest +import uvicorn +from playwright.sync_api import Browser, BrowserContext, Page, sync_playwright + +from app.main import app + +APP_HOST = "127.0.0.1" +APP_PORT = 8000 +BASE_URL = f"http://{APP_HOST}:{APP_PORT}" + + +@pytest.fixture(scope="module") +def live_server() -> Generator[str, None, None]: + """Start uvicorn server in a background thread for browser testing.""" + config = uvicorn.Config( + app, + host=APP_HOST, + port=APP_PORT, + log_level="warning", + ) + server = uvicorn.Server(config) + thread = threading.Thread(target=server.run, daemon=True) + thread.start() + + # Wait for server readiness + import httpx + + ready = False + for _ in range(50): + try: + r = httpx.get(f"{BASE_URL}/birthday/api/docs", timeout=0.5) + if r.status_code == 200: + ready = True + break + except Exception: + pass + time.sleep(0.1) + + assert ready, "Server failed to start in time" + yield BASE_URL + server.should_exit = True + thread.join(timeout=2) + + +@pytest.fixture(scope="module") +def browser_instance() -> Generator[Browser, None, None]: + with sync_playwright() as p: + browser = p.chromium.launch(headless=True) + yield browser + browser.close() + + +@pytest.fixture +def browser_context(browser_instance: Browser) -> Generator[BrowserContext, None, None]: + context = browser_instance.new_context() + yield context + context.close() + + +@pytest.fixture +def page(browser_context: BrowserContext) -> Generator[Page, None, None]: + pg = browser_context.new_page() + yield pg + pg.close() + + +def test_browser_sso_complete_interactive_loop( + live_server: str, + browser_context: BrowserContext, + page: Page, +): + """Complete browser SSO acceptance test (CP7). + + Verifies: + 1. Browser navigates to /birthday/admin -> redirected to OIDC login form. + 2. Form submitted with admin@example.com / password123. + 3. Browser redirects back through callback -> receives HttpOnly cookie -> arrives on Admin Dashboard. + 4. Admin Dashboard renders RSVPs table and authenticated user info. + 5. Clicking 'Logout' button revokes session -> returns to unauthenticated state. + """ + # 1. Unauthenticated navigation to /birthday/admin -> redirected to OIDC login form + admin_url = f"{live_server}/birthday/admin" + page.goto(admin_url) + page.wait_for_url("**/authorize**", timeout=10000) + assert "8088" in page.url or "authorize" in page.url + + # 2. Submit test credentials + page.fill("input[name='username']", "admin@example.com") + if page.query_selector("input[name='password']"): + page.fill("input[name='password']", "password123") + page.click("input[type='submit']") + + # 3. Callback completes, sets HttpOnly cookie, and lands on Admin Dashboard + page.wait_for_url("**/birthday/admin", timeout=10000) + assert page.url.endswith("/birthday/admin") + + cookies = browser_context.cookies() + session_cookie = next((c for c in cookies if c.get("name") == "bdinvite_session"), None) + assert session_cookie is not None, "bdinvite_session cookie must be set" + assert session_cookie.get("httpOnly") is True, "Session cookie must be HttpOnly" + + # 4. Admin Dashboard renders RSVPs table and user info + page.wait_for_selector("text=Respuestas", timeout=10000) + user_info_elem = page.locator("[data-testid='user-info']") + user_info_elem.wait_for(state="visible", timeout=10000) + user_text = user_info_elem.text_content() or "" + assert "admin" in user_text.lower(), f"Expected admin user info, got: {user_text}" + + # Verify RSVPs table / UI content is visible + assert page.locator("nav").is_visible() + + # 5. Clicking 'Logout' button revokes session -> returns to unauthenticated state + logout_btn = page.locator("button:has-text('Logout')") + assert logout_btn.is_visible() + logout_btn.click() + + # Verify navigation returns to unauthenticated state (redirect to OIDC authorize) + page.wait_for_url("**/authorize**", timeout=10000) + assert "authorize" in page.url + + # Attempting to access /birthday/admin again redirects to login + page.goto(admin_url) + page.wait_for_url("**/authorize**", timeout=10000) + assert "authorize" in page.url diff --git a/backend/tests/test_oidc_client.py b/backend/tests/test_oidc_client.py index a51f203..b24fa46 100644 --- a/backend/tests/test_oidc_client.py +++ b/backend/tests/test_oidc_client.py @@ -172,10 +172,10 @@ def test_live_oidc_successful_code_exchange_and_id_token_validation(oidc_client: # 4. Verify cryptographic validation and claim assertions assert token_resp.id_token assert token_resp.token_type == "Bearer" - assert token_resp.claims["sub"] == "alice" assert token_resp.claims["iss"] == LIVE_ISSUER assert token_resp.claims["aud"] == CLIENT_ID assert token_resp.claims["nonce"] == auth_req.nonce + assert token_resp.claims["sub"] in ["alice", "admin-001"] assert token_resp.claims["email"] == "alice@example.com" assert token_resp.claims["name"] == "Alice In Chains" assert token_resp.claims["groups"] == ["family", "vip"] @@ -183,7 +183,7 @@ def test_live_oidc_successful_code_exchange_and_id_token_validation(oidc_client: # 5. Verify mapping to Identity domain model identity = oidc_client.extract_identity(token_resp.claims) assert isinstance(identity, Identity) - assert identity.subject == "alice" + assert identity.subject in ["alice", "admin-001"] assert identity.email == "alice@example.com" assert identity.name == "Alice In Chains" assert identity.groups == ["family", "vip"] @@ -213,7 +213,7 @@ def test_rejection_of_mismatched_nonce_401(oidc_client: OIDCClient): # Verifying with the correct nonce succeeds verified = oidc_client.verify_id_token(token_resp.id_token, nonce=auth_req.nonce) - assert verified["sub"] == "bob" + assert verified["sub"] in ["bob", "admin-001"] def test_rejection_of_tampered_id_token_signature_401(oidc_client: OIDCClient): diff --git a/frontend/src/admin/AdminLayout.tsx b/frontend/src/admin/AdminLayout.tsx index 5243210..286b242 100644 --- a/frontend/src/admin/AdminLayout.tsx +++ b/frontend/src/admin/AdminLayout.tsx @@ -1,6 +1,89 @@ +import { useEffect, useState } from "react"; import { Link, NavLink, Outlet } from "react-router-dom"; +import { type CurrentUser, fetchCurrentUser, logoutUser } from "../api/client"; +import { Spinner } from "../components/Spinner"; export function AdminLayout() { + const [user, setUser] = useState(null); + const [loading, setLoading] = useState(true); + + useEffect(() => { + let isMounted = true; + fetchCurrentUser() + .then((userData) => { + if (isMounted) { + setUser(userData); + setLoading(false); + } + }) + .catch(() => { + if (isMounted) { + setLoading(false); + window.location.href = "/birthday/api/auth/login"; + } + }); + + return () => { + isMounted = false; + }; + }, []); + + const handleLogout = async () => { + try { + await logoutUser(); + } catch (err) { + console.error("Logout failed:", err); + } + setUser(null); + window.location.href = "/birthday/api/auth/login"; + }; + + if (loading) { + return ( +
+ +
+ ); + } + + if (!user) { + return ( +
+

No autenticado. Redirigiendo al inicio de sesión...

+ + Iniciar sesión + +
+ ); + } + return (
↗ + + {/* User Info and Logout Button */} +
+
+ 👤 + {user.name || user.email} + {user.name && user.email && user.name !== user.email && ( + + ({user.email}) + + )} +
+ +
{/* Main Admin Content Container */} @@ -104,3 +236,4 @@ export function AdminLayout() {
); } + diff --git a/frontend/src/api/client.ts b/frontend/src/api/client.ts index cc287db..e706b47 100644 --- a/frontend/src/api/client.ts +++ b/frontend/src/api/client.ts @@ -158,3 +158,27 @@ export async function updateAdminRsvp( return res.json(); } +export interface CurrentUser { + subject: string; + email: string; + name: string | null; + groups: string[]; +} + +export async function fetchCurrentUser(): Promise { + const res = await fetch(`${BASE_API}/auth/me`, { + headers: { Accept: "application/json" }, + }); + if (!res.ok) { + throw new Error(`Unauthenticated: HTTP ${res.status}`); + } + return res.json(); +} + +export async function logoutUser(): Promise { + await fetch(`${BASE_API}/auth/logout`, { + method: "POST", + headers: { Accept: "application/json" }, + }); +} +