From b50c920bfc30323427d3966d4a53b7a8af4a699b Mon Sep 17 00:00:00 2001 From: amirhosein mazaheri Date: Thu, 8 Oct 2026 13:00:13 +0330 Subject: [PATCH] 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. --- scripts/mock_auth_server.py | 536 ++++++++++++++++++++++++++++++++++++ 1 file changed, 536 insertions(+) create mode 100644 scripts/mock_auth_server.py diff --git a/scripts/mock_auth_server.py b/scripts/mock_auth_server.py new file mode 100644 index 0000000..59b9135 --- /dev/null +++ b/scripts/mock_auth_server.py @@ -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:/` 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=""" + + + + + سرویس ماک احراز هویت (Mock Auth Service) + + + +
+
+
+

سرویس ماک احراز هویت (Mock Auth Service)

+

هر درخواستی با هر مشخصاتی ارسال شود، تایید شده و ۲۰۲/۲۰۰ اوکی با کاربر ادمین برمی‌گرداند.

+
+
● فعال و آماده (Always 200 OK)
+
+ +
+

تست سریع در مرورگر

+
+
+ POST /api/v1/auth/login +

ورود با هر نام کاربری و رمز دلخواه

+ +
+
+ GET /api/v1/me +

استعلام هویت کاربر فعلی

+ +
+
+ ANY /* (هر مسیر و متدی) +

واکنش همگانی برای توکن‌ها، OAuth و غیره

+ +
+
+ +
+ +
+
+

آخرین درخواست‌های دریافتی

+ +
+
در حال بارگذاری...
+
+
+ + + + +""") + + +@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()