chore(dev): add standalone mock authentication server
Add an isolated development dashboard and illustrative authentication endpoints using mock tokens. This script is not the production identity implementation.
This commit is contained in:
@@ -0,0 +1,536 @@
|
||||
"""Universal Mock Authentication Server.
|
||||
|
||||
A standalone, zero-dependency mock auth service for local development and testing.
|
||||
It accepts ANY authentication request (username/password, Bearer token, Cookie, API key, OAuth2, etc.)
|
||||
and ALWAYS returns HTTP 200 OK with valid user, session, and token objects matching the RAG Phase 1 schema.
|
||||
|
||||
Features:
|
||||
- Handles standard API Catalog routes:
|
||||
- POST /api/v1/auth/login and /auth/login
|
||||
- POST /api/v1/auth/logout and /auth/logout
|
||||
- GET /api/v1/me, /me, /api/v1/auth/me
|
||||
- Handles OAuth2 / OIDC routes:
|
||||
- POST /oauth/token, /token
|
||||
- GET /oauth/userinfo, /userinfo
|
||||
- GET /.well-known/openid-configuration
|
||||
- GET /.well-known/jwks.json
|
||||
- Wildcard Catch-All (/{path:path}):
|
||||
- Any method (GET, POST, PUT, DELETE, PATCH, OPTIONS) to any path returns 200 OK.
|
||||
- Automatically sets `rag_session` cookie and CSRF tokens.
|
||||
- Interactive Dashboard at `http://localhost:<port>/` to monitor requests in real time and test endpoints.
|
||||
- Windows UTF-8 console output safe.
|
||||
|
||||
Usage:
|
||||
.venv\\Scripts\\python scripts/mock_auth_server.py
|
||||
.venv\\Scripts\\python scripts/mock_auth_server.py --port 1321
|
||||
"""
|
||||
|
||||
import argparse
|
||||
from datetime import datetime, timezone, timedelta
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
from typing import Any, Dict, Optional
|
||||
|
||||
# Ensure UTF-8 output on Windows consoles
|
||||
if sys.stdout and hasattr(sys.stdout, "reconfigure"):
|
||||
try:
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||
sys.stderr.reconfigure(encoding="utf-8", errors="replace")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
from fastapi import FastAPI, Request, Response
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
from fastapi.responses import HTMLResponse, JSONResponse
|
||||
import uvicorn
|
||||
|
||||
app = FastAPI(
|
||||
title="Universal Mock Authentication Service",
|
||||
description="Always returns 200 OK for any authentication request",
|
||||
version="1.0.0"
|
||||
)
|
||||
|
||||
# Enable CORS for any client / origin
|
||||
app.add_middleware(
|
||||
CORSMiddleware,
|
||||
allow_origins=["*"],
|
||||
allow_credentials=True,
|
||||
allow_methods=["*"],
|
||||
allow_headers=["*"],
|
||||
)
|
||||
|
||||
# In-memory recent requests log for the dashboard
|
||||
RECENT_REQUESTS = []
|
||||
|
||||
MOCK_USER = {
|
||||
"id": "01000000-0000-4000-8000-000000000001",
|
||||
"username": "demo.admin",
|
||||
"email": "demo.admin@organization.local",
|
||||
"role": "admin",
|
||||
"organization_id": "02000000-0000-4000-8000-000000000001",
|
||||
"is_enabled": True
|
||||
}
|
||||
|
||||
|
||||
def build_auth_payload(custom_username: Optional[str] = None) -> Dict[str, Any]:
|
||||
"""Build a comprehensive auth response payload matching RAG Phase 1 specs."""
|
||||
user = dict(MOCK_USER)
|
||||
if custom_username:
|
||||
user["username"] = custom_username
|
||||
user["email"] = f"{custom_username}@organization.local"
|
||||
|
||||
now = datetime.now(timezone.utc)
|
||||
expires_at = (now + timedelta(hours=24)).strftime("%Y-%m-%dT%H:%M:%SZ")
|
||||
|
||||
return {
|
||||
"status": "ok",
|
||||
"authenticated": True,
|
||||
"user": user,
|
||||
"csrf_token": "mock-csrf-token-f8b1c4e2-9a3d-4c7b-b5e1-8f2a6d4c0e3b",
|
||||
"token": "mock-access-token-01000000-0000-4000-8000-000000000001",
|
||||
"access_token": "mock-access-token-01000000-0000-4000-8000-000000000001",
|
||||
"token_type": "bearer",
|
||||
"expires_in": 86400,
|
||||
"expires_at": expires_at
|
||||
}
|
||||
|
||||
|
||||
def set_auth_cookies(response: Response) -> None:
|
||||
"""Set the standard session cookie used by the Phase 1 backend."""
|
||||
response.set_cookie(
|
||||
key="rag_session",
|
||||
value="mock-session-token-01000000-0000-4000-8000-000000000001",
|
||||
max_age=86400,
|
||||
httponly=True,
|
||||
samesite="lax",
|
||||
secure=False,
|
||||
path="/"
|
||||
)
|
||||
response.set_cookie(
|
||||
key="csrf_token",
|
||||
value="mock-csrf-token-f8b1c4e2-9a3d-4c7b-b5e1-8f2a6d4c0e3b",
|
||||
max_age=86400,
|
||||
httponly=False,
|
||||
samesite="lax",
|
||||
path="/"
|
||||
)
|
||||
|
||||
|
||||
async def log_request(request: Request, body_data: Any = None):
|
||||
"""Log incoming request details for debugging and web dashboard."""
|
||||
req_info = {
|
||||
"time": datetime.now().strftime("%H:%M:%S"),
|
||||
"method": request.method,
|
||||
"path": request.url.path,
|
||||
"client": request.client.host if request.client else "unknown",
|
||||
"headers": dict(request.headers),
|
||||
"query": dict(request.query_params),
|
||||
"body": body_data
|
||||
}
|
||||
RECENT_REQUESTS.insert(0, req_info)
|
||||
if len(RECENT_REQUESTS) > 30:
|
||||
RECENT_REQUESTS.pop()
|
||||
|
||||
print(f"[AUTH MOCK] {request.method} {request.url.path} from {req_info['client']} -> 200 OK")
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# Interactive Dashboard & Web Interface
|
||||
# ============================================================================
|
||||
|
||||
@app.get("/", response_class=HTMLResponse)
|
||||
async def dashboard(request: Request):
|
||||
"""Interactive visual dashboard showing server status and live requests."""
|
||||
return HTMLResponse(content="""<!DOCTYPE html>
|
||||
<html lang="fa" dir="rtl">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>سرویس ماک احراز هویت (Mock Auth Service)</title>
|
||||
<style>
|
||||
:root {
|
||||
--bg: #0b0f19;
|
||||
--surface: #111827;
|
||||
--border: #1f2937;
|
||||
--accent: #10b981;
|
||||
--primary: #4f46e5;
|
||||
--text: #f9fafb;
|
||||
--dim: #9ca3af;
|
||||
}
|
||||
* { box-sizing: border-box; margin: 0; padding: 0; }
|
||||
body {
|
||||
font-family: system-ui, -apple-system, Tahoma, Arial, sans-serif;
|
||||
background: var(--bg);
|
||||
color: var(--text);
|
||||
padding: 2rem;
|
||||
line-height: 1.6;
|
||||
}
|
||||
.container { max-width: 1000px; margin: 0 auto; }
|
||||
header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
margin-bottom: 2rem;
|
||||
padding-bottom: 1rem;
|
||||
border-bottom: 1px solid var(--border);
|
||||
}
|
||||
.badge {
|
||||
background: rgba(16, 185, 129, 0.15);
|
||||
color: var(--accent);
|
||||
border: 1px solid var(--accent);
|
||||
padding: 0.35rem 0.85rem;
|
||||
border-radius: 9999px;
|
||||
font-size: 0.85rem;
|
||||
font-weight: 600;
|
||||
}
|
||||
.card {
|
||||
background: var(--surface);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 12px;
|
||||
padding: 1.5rem;
|
||||
margin-bottom: 1.5rem;
|
||||
}
|
||||
h2 { font-size: 1.15rem; margin-bottom: 1rem; color: #fff; }
|
||||
.endpoints-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
|
||||
gap: 1rem;
|
||||
}
|
||||
.endpoint-item {
|
||||
background: rgba(255,255,255,0.03);
|
||||
border: 1px solid var(--border);
|
||||
padding: 0.85rem;
|
||||
border-radius: 8px;
|
||||
font-size: 0.88rem;
|
||||
}
|
||||
.method {
|
||||
display: inline-block;
|
||||
padding: 0.2rem 0.5rem;
|
||||
border-radius: 4px;
|
||||
font-size: 0.75rem;
|
||||
font-weight: 700;
|
||||
margin-left: 0.5rem;
|
||||
}
|
||||
.method.post { background: #0284c7; color: #fff; }
|
||||
.method.get { background: #16a34a; color: #fff; }
|
||||
.method.any { background: #8b5cf6; color: #fff; }
|
||||
.btn {
|
||||
background: var(--primary);
|
||||
color: #fff;
|
||||
border: none;
|
||||
padding: 0.5rem 1rem;
|
||||
border-radius: 6px;
|
||||
cursor: pointer;
|
||||
font-size: 0.85rem;
|
||||
margin-top: 0.5rem;
|
||||
transition: opacity 0.2s;
|
||||
}
|
||||
.btn:hover { opacity: 0.9; }
|
||||
pre {
|
||||
background: #000;
|
||||
padding: 1rem;
|
||||
border-radius: 8px;
|
||||
overflow-x: auto;
|
||||
direction: ltr;
|
||||
text-align: left;
|
||||
font-size: 0.82rem;
|
||||
color: #38bdf8;
|
||||
margin-top: 0.5rem;
|
||||
}
|
||||
.logs-table {
|
||||
width: 100%;
|
||||
border-collapse: collapse;
|
||||
font-size: 0.85rem;
|
||||
direction: ltr;
|
||||
text-align: left;
|
||||
}
|
||||
.logs-table th, .logs-table td {
|
||||
padding: 0.65rem;
|
||||
border-bottom: 1px solid var(--border);
|
||||
}
|
||||
.logs-table th { color: var(--dim); font-weight: 600; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="container">
|
||||
<header>
|
||||
<div>
|
||||
<h1>سرویس ماک احراز هویت (Mock Auth Service)</h1>
|
||||
<p style="color: var(--dim); font-size: 0.9rem; margin-top: 4px;">هر درخواستی با هر مشخصاتی ارسال شود، تایید شده و ۲۰۲/۲۰۰ اوکی با کاربر ادمین برمیگرداند.</p>
|
||||
</div>
|
||||
<div class="badge">● فعال و آماده (Always 200 OK)</div>
|
||||
</header>
|
||||
|
||||
<div class="card">
|
||||
<h2>تست سریع در مرورگر</h2>
|
||||
<div class="endpoints-grid">
|
||||
<div class="endpoint-item">
|
||||
<span class="method post">POST</span> <code>/api/v1/auth/login</code>
|
||||
<p style="color: var(--dim); font-size: 0.78rem; margin-top: 4px;">ورود با هر نام کاربری و رمز دلخواه</p>
|
||||
<button class="btn" onclick="testLogin()">ارسال درخواست لاگین</button>
|
||||
</div>
|
||||
<div class="endpoint-item">
|
||||
<span class="method get">GET</span> <code>/api/v1/me</code>
|
||||
<p style="color: var(--dim); font-size: 0.78rem; margin-top: 4px;">استعلام هویت کاربر فعلی</p>
|
||||
<button class="btn" onclick="testMe()">دریافت هویت کاربر</button>
|
||||
</div>
|
||||
<div class="endpoint-item">
|
||||
<span class="method any">ANY</span> <code>/* (هر مسیر و متدی)</code>
|
||||
<p style="color: var(--dim); font-size: 0.78rem; margin-top: 4px;">واکنش همگانی برای توکنها، OAuth و غیره</p>
|
||||
<button class="btn" onclick="testWildcard()">تست مسیر دلخواه</button>
|
||||
</div>
|
||||
</div>
|
||||
<div id="resultBox" style="display: none; margin-top: 1rem;">
|
||||
<h3 style="font-size: 0.9rem; color: #a78bfa;">نتیجه دریافتی:</h3>
|
||||
<pre id="resultPre"></pre>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="card">
|
||||
<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 1rem;">
|
||||
<h2>آخرین درخواستهای دریافتی</h2>
|
||||
<button class="btn" style="background: rgba(255,255,255,0.08); padding: 0.3rem 0.7rem;" onclick="location.reload()">بروزرسانی جدول</button>
|
||||
</div>
|
||||
<div id="logsArea">در حال بارگذاری...</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
async function fetchLogs() {
|
||||
try {
|
||||
const res = await fetch('/__logs');
|
||||
const logs = await res.json();
|
||||
if (!logs.length) {
|
||||
document.getElementById('logsArea').innerHTML = '<p style="color: var(--dim);">هنوز درخواستی ارسال نشده است.</p>';
|
||||
return;
|
||||
}
|
||||
let html = '<table class="logs-table"><thead><tr><th>Time</th><th>Method</th><th>Path</th><th>IP</th></tr></thead><tbody>';
|
||||
logs.forEach(l => {
|
||||
html += `<tr><td>${l.time}</td><td><b>${l.method}</b></td><td>${l.path}</td><td>${l.client}</td></tr>`;
|
||||
});
|
||||
html += '</tbody></table>';
|
||||
document.getElementById('logsArea').innerHTML = html;
|
||||
} catch (e) {
|
||||
document.getElementById('logsArea').innerText = 'خطا در بارگذاری لاگها';
|
||||
}
|
||||
}
|
||||
|
||||
async function showResult(res) {
|
||||
const data = await res.json();
|
||||
const box = document.getElementById('resultBox');
|
||||
box.style.display = 'block';
|
||||
document.getElementById('resultPre').innerText = JSON.stringify(data, null, 2);
|
||||
fetchLogs();
|
||||
}
|
||||
|
||||
async function testLogin() {
|
||||
const res = await fetch('/api/v1/auth/login', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ username: 'test_user', password: 'any_password' })
|
||||
});
|
||||
await showResult(res);
|
||||
}
|
||||
|
||||
async function testMe() {
|
||||
const res = await fetch('/api/v1/me');
|
||||
await showResult(res);
|
||||
}
|
||||
|
||||
async function testWildcard() {
|
||||
const res = await fetch('/custom/oauth/token', {
|
||||
method: 'POST',
|
||||
headers: { 'Authorization': 'Bearer test-token' }
|
||||
});
|
||||
await showResult(res);
|
||||
}
|
||||
|
||||
fetchLogs();
|
||||
setInterval(fetchLogs, 3000);
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
""")
|
||||
|
||||
|
||||
@app.get("/__logs")
|
||||
async def get_logs():
|
||||
"""Internal route to feed dashboard with recent requests."""
|
||||
return JSONResponse(content=RECENT_REQUESTS)
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# Standard RAG Phase 1 Authentication Routes
|
||||
# ============================================================================
|
||||
|
||||
@app.post("/api/v1/auth/login")
|
||||
@app.post("/auth/login")
|
||||
@app.post("/login")
|
||||
async def login(request: Request):
|
||||
"""A01: Login with any username/password -> Always succeeds with admin session."""
|
||||
body_data = None
|
||||
custom_username = "demo.admin"
|
||||
try:
|
||||
body_data = await request.json()
|
||||
if isinstance(body_data, dict) and "username" in body_data:
|
||||
custom_username = body_data["username"]
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
await log_request(request, body_data)
|
||||
|
||||
payload = build_auth_payload(custom_username)
|
||||
response = JSONResponse(content=payload, status_code=200)
|
||||
set_auth_cookies(response)
|
||||
return response
|
||||
|
||||
|
||||
@app.post("/api/v1/auth/logout")
|
||||
@app.post("/auth/logout")
|
||||
@app.post("/logout")
|
||||
async def logout(request: Request):
|
||||
"""A02: Logout -> Always succeeds and clears cookies."""
|
||||
await log_request(request)
|
||||
response = Response(status_code=204)
|
||||
response.delete_cookie(key="rag_session", path="/")
|
||||
response.delete_cookie(key="csrf_token", path="/")
|
||||
return response
|
||||
|
||||
|
||||
@app.get("/api/v1/me")
|
||||
@app.get("/me")
|
||||
@app.get("/api/v1/auth/me")
|
||||
@app.get("/auth/me")
|
||||
async def current_user(request: Request):
|
||||
"""A03: Current user identity -> Always returns valid admin profile."""
|
||||
await log_request(request)
|
||||
payload = build_auth_payload()
|
||||
response = JSONResponse(content=payload, status_code=200)
|
||||
set_auth_cookies(response)
|
||||
return response
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# Standard OAuth2 / OpenID Connect Routes
|
||||
# ============================================================================
|
||||
|
||||
@app.post("/oauth/token")
|
||||
@app.post("/token")
|
||||
@app.post("/api/v1/token")
|
||||
async def oauth_token(request: Request):
|
||||
"""OAuth2 token exchange -> Returns Bearer token."""
|
||||
body_data = None
|
||||
try:
|
||||
form = await request.form()
|
||||
body_data = dict(form)
|
||||
except Exception:
|
||||
try:
|
||||
body_data = await request.json()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
await log_request(request, body_data)
|
||||
payload = {
|
||||
"access_token": "mock-access-token-01000000-0000-4000-8000-000000000001",
|
||||
"token_type": "bearer",
|
||||
"expires_in": 86400,
|
||||
"refresh_token": "mock-refresh-token-xyz789",
|
||||
"scope": "read write admin",
|
||||
"user": MOCK_USER
|
||||
}
|
||||
response = JSONResponse(content=payload, status_code=200)
|
||||
set_auth_cookies(response)
|
||||
return response
|
||||
|
||||
|
||||
@app.get("/oauth/userinfo")
|
||||
@app.get("/userinfo")
|
||||
async def userinfo(request: Request):
|
||||
"""OIDC userinfo endpoint."""
|
||||
await log_request(request)
|
||||
return JSONResponse(content={
|
||||
"sub": MOCK_USER["id"],
|
||||
"name": "Demo Admin",
|
||||
"preferred_username": MOCK_USER["username"],
|
||||
"email": MOCK_USER["email"],
|
||||
"email_verified": True,
|
||||
"roles": [MOCK_USER["role"]],
|
||||
"organization_id": MOCK_USER["organization_id"]
|
||||
})
|
||||
|
||||
|
||||
@app.get("/.well-known/openid-configuration")
|
||||
async def openid_configuration(request: Request):
|
||||
"""OIDC discovery endpoint."""
|
||||
base = str(request.base_url).rstrip("/")
|
||||
return JSONResponse(content={
|
||||
"issuer": base,
|
||||
"authorization_endpoint": f"{base}/oauth/authorize",
|
||||
"token_endpoint": f"{base}/oauth/token",
|
||||
"userinfo_endpoint": f"{base}/oauth/userinfo",
|
||||
"jwks_uri": f"{base}/.well-known/jwks.json",
|
||||
"response_types_supported": ["code", "token"],
|
||||
"id_token_signing_alg_values_supported": ["RS256"]
|
||||
})
|
||||
|
||||
|
||||
@app.get("/.well-known/jwks.json")
|
||||
async def jwks(request: Request):
|
||||
"""Mock JWKS endpoint."""
|
||||
return JSONResponse(content={"keys": []})
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# Wildcard Catch-All Handler
|
||||
# Any other endpoint, method, or path -> ALWAYS 200 OK!
|
||||
# ============================================================================
|
||||
|
||||
@app.api_route("/{full_path:path}", methods=["GET", "POST", "PUT", "DELETE", "PATCH", "HEAD", "OPTIONS"])
|
||||
async def catch_all(request: Request, full_path: str):
|
||||
"""Wildcard: Accept ANY path and ANY method, always return 200 OK."""
|
||||
body_data = None
|
||||
try:
|
||||
body_data = await request.json()
|
||||
except Exception:
|
||||
try:
|
||||
body_bytes = await request.body()
|
||||
if body_bytes:
|
||||
body_data = body_bytes.decode("utf-8", errors="replace")[:200]
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
await log_request(request, body_data)
|
||||
|
||||
payload = build_auth_payload()
|
||||
payload["requested_path"] = f"/{full_path}"
|
||||
payload["requested_method"] = request.method
|
||||
|
||||
response = JSONResponse(content=payload, status_code=200)
|
||||
set_auth_cookies(response)
|
||||
return response
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# Main Entrypoint
|
||||
# ============================================================================
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description="Universal Mock Authentication Service")
|
||||
parser.add_argument("--port", type=int, default=int(os.getenv("AUTH_PORT", "1321")), help="Port to listen on (default: 1321)")
|
||||
parser.add_argument("--host", type=str, default="0.0.0.0", help="Host address (default: 0.0.0.0)")
|
||||
args = parser.parse_args()
|
||||
|
||||
print("\n" + "="*65)
|
||||
print(" 🚀 Universal Mock Authentication Server Running")
|
||||
print(f" 🌐 Dashboard & Quick Test: http://localhost:{args.port}/")
|
||||
print(f" 🔑 Login Endpoint: http://localhost:{args.port}/api/v1/auth/login")
|
||||
print(f" 👤 Current User (/me): http://localhost:{args.port}/api/v1/me")
|
||||
print(f" 🔀 Wildcard Fallback: ANY request to ANY path returns 200 OK")
|
||||
print("="*65 + "\n")
|
||||
|
||||
uvicorn.run(app, host=args.host, port=args.port)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user