feat(ui): integrate browser SSO authentication and admin logout
- Update AdminLayout to verify session state via fetchCurrentUser (/auth/me) and redirect unauthenticated visits to login - Display authenticated user name/email badge and add interactive Logout button in admin header - Implement client API bindings for fetchCurrentUser and logoutUser in client.ts - Redirect successful OIDC callback to /birthday/admin instead of root - Support serving frontend assets from frontend/dist fallback in main.py - Refine email claim fallback in OIDCClient when subject contains email format - Update test_oidc_client assertions to accommodate mock admin identities - Add Playwright browser acceptance test (test_browser_sso.py) verifying the complete end-to-end SSO loop: unauthenticated redirect, credential submission, HttpOnly session cookie issuance, dashboard rendering, and logout session invalidation
This commit is contained in:
1 parent
b0dea63c3f
commit
d9b589ccda
8 files changed
+298
-5
No files matched your search
@@ -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 <token>
|
||||
auth_header = request.headers.get("Authorization")
|
||||
|
||||
@@ -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"
|
||||
|
||||
|
||||
@@ -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):
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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
|
||||
@@ -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):
|
||||
|
||||
@@ -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<CurrentUser | null>(null);
|
||||
const [loading, setLoading] = useState<boolean>(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 (
|
||||
<div
|
||||
style={{
|
||||
minHeight: "100vh",
|
||||
backgroundColor: "#0f0f10",
|
||||
color: "#f0f0f0",
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
}}
|
||||
>
|
||||
<Spinner size={36} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (!user) {
|
||||
return (
|
||||
<div
|
||||
style={{
|
||||
minHeight: "100vh",
|
||||
backgroundColor: "#0f0f10",
|
||||
color: "#f0f0f0",
|
||||
fontFamily: "var(--font-body)",
|
||||
display: "flex",
|
||||
flexDirection: "column",
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
gap: "1rem",
|
||||
}}
|
||||
>
|
||||
<p>No autenticado. Redirigiendo al inicio de sesión...</p>
|
||||
<a
|
||||
href="/birthday/api/auth/login"
|
||||
style={{
|
||||
color: "var(--color-gold-light, #e0be75)",
|
||||
textDecoration: "underline",
|
||||
}}
|
||||
>
|
||||
Iniciar sesión
|
||||
</a>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
style={{
|
||||
@@ -89,6 +172,55 @@ export function AdminLayout() {
|
||||
<span>↗</span>
|
||||
</Link>
|
||||
</nav>
|
||||
|
||||
{/* User Info and Logout Button */}
|
||||
<div style={{ display: "flex", alignItems: "center", gap: "1.2rem", flexWrap: "wrap" }}>
|
||||
<div
|
||||
style={{
|
||||
fontSize: "0.85rem",
|
||||
color: "rgba(255, 255, 255, 0.8)",
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
gap: "0.4rem",
|
||||
}}
|
||||
>
|
||||
<span style={{ color: "var(--color-gold, #c5a059)" }}>👤</span>
|
||||
<span data-testid="user-info">{user.name || user.email}</span>
|
||||
{user.name && user.email && user.name !== user.email && (
|
||||
<span
|
||||
data-testid="user-email"
|
||||
style={{ fontSize: "0.8rem", color: "rgba(255, 255, 255, 0.5)" }}
|
||||
>
|
||||
({user.email})
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleLogout}
|
||||
style={{
|
||||
background: "transparent",
|
||||
border: "1px solid rgba(255, 255, 255, 0.2)",
|
||||
color: "#f0f0f0",
|
||||
padding: "0.35rem 0.75rem",
|
||||
borderRadius: "4px",
|
||||
cursor: "pointer",
|
||||
fontSize: "0.82rem",
|
||||
fontWeight: 500,
|
||||
transition: "all 0.2s ease",
|
||||
}}
|
||||
onMouseOver={(e) => {
|
||||
e.currentTarget.style.borderColor = "rgba(255, 255, 255, 0.4)";
|
||||
e.currentTarget.style.backgroundColor = "rgba(255, 255, 255, 0.05)";
|
||||
}}
|
||||
onMouseOut={(e) => {
|
||||
e.currentTarget.style.borderColor = "rgba(255, 255, 255, 0.2)";
|
||||
e.currentTarget.style.backgroundColor = "transparent";
|
||||
}}
|
||||
>
|
||||
Logout
|
||||
</button>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
{/* Main Admin Content Container */}
|
||||
@@ -104,3 +236,4 @@ export function AdminLayout() {
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -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<CurrentUser> {
|
||||
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<void> {
|
||||
await fetch(`${BASE_API}/auth/logout`, {
|
||||
method: "POST",
|
||||
headers: { Accept: "application/json" },
|
||||
});
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user