Spaces:
Running on Zero
Running on Zero
feat(backend): security hardening, payment integrity, daily content word filter, and HF space stability
e4fde90 Download tests/test_superadmin_auth_architecture.py from sahihislam/superadmin: direct link, hf CLI and curl.
- Browser
- Download file 13.5 kB
-
https://huggingface.co/spaces/sahihislam/superadmin/resolve/main/tests/test_superadmin_auth_architecture.py
- Command line
-
hf download hf://spaces/sahihislam/superadmin/tests/test_superadmin_auth_architecture.py
-
curl -L -o test_superadmin_auth_architecture.py https://huggingface.co/spaces/sahihislam/superadmin/resolve/main/tests/test_superadmin_auth_architecture.py
13.5 kB
| """ | |
| Comprehensive Superadmin Authentication Architecture & HTTP 401 Elimination Tests | |
| ================================================================================ | |
| Verifies permanent fixes for: | |
| 1. Whitelisted SuperAdmin with NO Mongo Record (Auto-provisioning, returns 200, role="SUPERADMIN", is_superadmin=True). | |
| 2. Whitelisted SuperAdmin found via Email (re-anchoring UID & elevating). | |
| 3. Expired token strictly raises HTTP 401 Unauthorized with WWW-Authenticate: Bearer. | |
| 4. Missing Authorization header on /admin/* strictly raises HTTP 401 (Never synthesizes locust user or causes 403 alerts). | |
| 5. Non-superadmin user attempting /admin/finance/* or /admin/statistics receives HTTP 403 Forbidden. | |
| 6. Active employee staff member allowed access to permitted tabs, blocked from restricted tabs. | |
| 7. Whitelist resolution properly includes default immutable code anchors (admin@sahihislam.com, zainshafibhat@gmail.com, etc.). | |
| """ | |
| import os | |
| import asyncio | |
| from unittest.mock import AsyncMock, patch, MagicMock | |
| from datetime import datetime | |
| import pytest | |
| from fastapi import HTTPException, Request | |
| from app.auth_deps import ( | |
| get_current_user, | |
| _load_user, | |
| DEFAULT_SUPERADMIN_EMAILS, | |
| is_superadmin_email, | |
| invalidate_user_cache, | |
| ) | |
| from app.superadmin_routes import ( | |
| require_superadmin, | |
| get_superadmin_whitelist, | |
| get_staff_permissions_for_user, | |
| require_portal_access, | |
| ) | |
| def run_async(coro): | |
| return asyncio.run(coro) | |
| def make_mock_request(path: str = "/admin/statistics", method: str = "GET", headers: dict = None) -> Request: | |
| raw_headers = [] | |
| if headers: | |
| for k, v in headers.items(): | |
| raw_headers.append((k.lower().encode("latin-1"), v.encode("latin-1"))) | |
| req = Request( | |
| scope={ | |
| "type": "http", | |
| "method": method, | |
| "path": path, | |
| "raw_path": path.encode("latin-1"), | |
| "query_string": b"", | |
| "headers": raw_headers, | |
| } | |
| ) | |
| return req | |
| # ============================================================================== | |
| # 1. WHITELIST & IMMUTABLE ANCHOR RESOLUTION TESTS | |
| # ============================================================================== | |
| def test_default_superadmin_emails_present(): | |
| """Confirms all authoritative developer & production administrative emails are anchored.""" | |
| assert "admin@sahihislam.com" in DEFAULT_SUPERADMIN_EMAILS | |
| assert "zainshafibhat@gmail.com" in DEFAULT_SUPERADMIN_EMAILS | |
| assert "suhaileng.bhat@gmail.com" in DEFAULT_SUPERADMIN_EMAILS | |
| assert "zainshafibhat2@gmail.com" in DEFAULT_SUPERADMIN_EMAILS | |
| def test_is_superadmin_email_case_insensitivity(): | |
| """Confirms email whitelist matching is strictly case-insensitive and trims whitespace.""" | |
| assert is_superadmin_email(" ADMIN@sahihislam.com ") is True | |
| assert is_superadmin_email("ZainShafiBhat@GMAIL.COM") is True | |
| assert is_superadmin_email("intruder@evil.org") is False | |
| assert is_superadmin_email(None) is False | |
| assert is_superadmin_email("") is False | |
| def test_get_superadmin_whitelist_always_includes_anchors(): | |
| """Confirms get_superadmin_whitelist() retains core anchors even if env var is empty.""" | |
| with patch.dict(os.environ, {"SUPERADMIN_EMAILS": ""}): | |
| wl = get_superadmin_whitelist(force_refresh=True) | |
| assert "admin@sahihislam.com" in wl | |
| assert "zainshafibhat@gmail.com" in wl | |
| # ============================================================================== | |
| # 2. LOAD USER & AUTO-PROVISIONING TESTS (FIXING ROOT CAUSE 1) | |
| # ============================================================================== | |
| def test_load_user_auto_provisions_superadmin_when_mongo_doc_missing(): | |
| """ | |
| Codex NEW-001 VERIFICATION: | |
| If a whitelisted SuperAdmin authenticates via Firebase, but has no record in MongoDB, | |
| _load_user MUST NOT auto-provision! It must strictly raise 401 (signup required). | |
| SuperAdmins must be explicitly bootstrapped or provisioned via admin control plane. | |
| """ | |
| mock_uid = "firebase_super_uid_1001" | |
| mock_email = "admin@sahihislam.com" | |
| mock_collection = MagicMock() | |
| mock_collection.find_one = AsyncMock(return_value=None) | |
| mock_collection.update_one = AsyncMock() | |
| run_async(invalidate_user_cache(mock_uid)) | |
| with patch("app.auth_deps.users_collection", mock_collection): | |
| with pytest.raises(HTTPException) as exc_info: | |
| run_async(_load_user(mock_uid, email=mock_email, email_verified=True)) | |
| assert exc_info.value.status_code == 401 | |
| assert "complete signup first" in exc_info.value.detail.lower() | |
| mock_collection.update_one.assert_not_called() | |
| def test_load_user_reanchors_uid_when_found_by_email(): | |
| """ | |
| If user document exists in MongoDB with matching email but missing or different UID, | |
| it must re-anchor the UID and return the account without 401. | |
| """ | |
| new_uid = "new_firebase_uid_555" | |
| admin_email = "zainshafibhat@gmail.com" | |
| existing_doc = { | |
| "_id": "mongo_id_999", | |
| "uid": "old_legacy_uid", | |
| "email": admin_email, | |
| "role": "USER", | |
| } | |
| mock_collection = MagicMock() | |
| # find_one: first call with {"uid": new_uid} returns None, second call with {"email": admin_email} returns existing_doc | |
| mock_collection.find_one = AsyncMock(side_effect=[None, existing_doc]) | |
| mock_collection.update_one = AsyncMock(return_value=MagicMock(acknowledged=True)) | |
| run_async(invalidate_user_cache(new_uid)) | |
| with patch("app.auth_deps.users_collection", mock_collection): | |
| user = run_async(_load_user(new_uid, email=admin_email, email_verified=True)) | |
| assert user is not None | |
| assert user["uid"] == new_uid | |
| assert user["email"] == admin_email | |
| # Verify update_one was called to update UID | |
| mock_collection.update_one.assert_called_once() | |
| def test_load_user_unprovisioned_ordinary_user_raises_401(): | |
| """ | |
| Ordinary users without MongoDB documents must still receive 401 | |
| so the app knows to prompt signup. | |
| """ | |
| ordinary_uid = "random_unregistered_uid" | |
| ordinary_email = "regular_person@gmail.com" | |
| mock_collection = MagicMock() | |
| mock_collection.find_one = AsyncMock(return_value=None) | |
| run_async(invalidate_user_cache(ordinary_uid)) | |
| with patch("app.auth_deps.users_collection", mock_collection): | |
| with pytest.raises(HTTPException) as exc_info: | |
| run_async(_load_user(ordinary_uid, email=ordinary_email)) | |
| assert exc_info.value.status_code == 401 | |
| assert "complete signup first" in exc_info.value.detail.lower() | |
| # ============================================================================== | |
| # 3. GET_CURRENT_USER ENDPOINT & SYNTHETIC ROUTE GUARDS (ROOT CAUSE 2) | |
| # ============================================================================== | |
| def test_admin_path_with_missing_auth_header_strictly_returns_401(): | |
| """ | |
| ROOT CAUSE 2 VERIFICATION: | |
| Administrative routes (/admin/*) MUST NEVER generate synthetic 'locust_...' virtual users | |
| when headers are missing. They must strictly reject with HTTP 401 Unauthorized. | |
| """ | |
| mock_req = make_mock_request(path="/admin/finance/summary", method="GET") | |
| with pytest.raises(HTTPException) as exc_info: | |
| run_async(get_current_user(request=mock_req, authorization=None, x_firebase_token=None)) | |
| assert exc_info.value.status_code == 401 | |
| assert "Authorization header" in exc_info.value.detail | |
| assert exc_info.value.headers.get("WWW-Authenticate") == "Bearer" | |
| def test_admin_path_with_valid_superadmin_token_elevates_privileges(): | |
| """ | |
| When a valid Firebase token belonging to a whitelisted SuperAdmin is provided, | |
| get_current_user elevates role to SUPERADMIN and grants all tabs. | |
| """ | |
| mock_req = make_mock_request(path="/admin/statistics", method="GET") | |
| valid_superadmin_claims = { | |
| "uid": "suhail_uid_777", | |
| "email": "suhaileng.bhat@gmail.com", | |
| "email_verified": True, | |
| } | |
| user_db_doc = { | |
| "uid": "suhail_uid_777", | |
| "email": "suhaileng.bhat@gmail.com", | |
| "email_verified": True, | |
| "role": "SUPERADMIN", | |
| "is_superadmin": True, | |
| } | |
| mock_collection = MagicMock() | |
| mock_collection.find_one = AsyncMock(return_value=user_db_doc) | |
| run_async(invalidate_user_cache("suhail_uid_777")) | |
| with patch("app.auth_deps._verify_token", return_value=valid_superadmin_claims), \ | |
| patch("app.auth_deps.users_collection", mock_collection): | |
| user = run_async( | |
| get_current_user( | |
| request=mock_req, | |
| authorization="Bearer valid_superadmin_token", | |
| ) | |
| ) | |
| assert user["is_superadmin"] is True | |
| assert user["role"] == "SUPERADMIN" | |
| assert user["allowed_tabs"] == ["*"] | |
| assert user["_verified_token_email"] == "suhaileng.bhat@gmail.com" | |
| # ============================================================================== | |
| # 4. REQUIRE_SUPERADMIN DEPENDENCY & FEATURE TAB AUTHORIZATION | |
| # ============================================================================== | |
| def test_require_superadmin_grants_access_to_whitelisted_superadmin(): | |
| """Verifies require_superadmin dependency passes for whitelisted SuperAdmin.""" | |
| mock_req = make_mock_request(path="/admin/statistics") | |
| user = { | |
| "uid": "super_uid_1", | |
| "email": "admin@sahihislam.com", | |
| "role": "SUPERADMIN", | |
| "is_superadmin": True, | |
| "_verified_token_email": "admin@sahihislam.com", | |
| "_verified_token_email_verified": True, | |
| } | |
| res = run_async(require_superadmin(request=mock_req, user=user)) | |
| assert res["is_superadmin"] is True | |
| assert res["allowed_tabs"] == ["*"] | |
| def test_require_superadmin_rejects_ordinary_user_with_403(): | |
| """Ordinary authenticated user must be strictly rejected with HTTP 403 Forbidden.""" | |
| mock_req = make_mock_request(path="/admin/finance/summary") | |
| ordinary_user = { | |
| "uid": "regular_user_123", | |
| "email": "regular@domain.com", | |
| "_verified_token_email": "regular@domain.com", | |
| "role": "USER", | |
| } | |
| with pytest.raises(HTTPException) as exc_info: | |
| run_async(require_superadmin(request=mock_req, user=ordinary_user)) | |
| assert exc_info.value.status_code == 403 | |
| assert "SuperAdmin access denied" in exc_info.value.detail or "Portal access denied" in exc_info.value.detail | |
| def test_require_superadmin_blocks_employee_from_superadmin_only_tabs(): | |
| """ | |
| Employees with assigned staff tabs (e.g. users, hadiths) MUST NOT access | |
| strictly superadmin-only tabs like /admin/finance/* or /admin/system/*. | |
| """ | |
| mock_req = make_mock_request(path="/admin/finance/transactions") | |
| staff_user = { | |
| "uid": "staff_emp_001", | |
| "email": "moderator@sahihislam.com", | |
| "_verified_token_email": "moderator@sahihislam.com", | |
| "role": "STAFF", | |
| "is_staff": True, | |
| "allowed_tabs": ["hadiths", "users"], | |
| } | |
| with pytest.raises(HTTPException) as exc_info: | |
| run_async(require_superadmin(request=mock_req, user=staff_user)) | |
| assert exc_info.value.status_code == 403 | |
| assert "restricted to SuperAdmin accounts" in exc_info.value.detail | |
| def test_require_superadmin_allows_employee_on_permitted_tab(): | |
| """ | |
| Employees with active permission for a tab (e.g. 'hadiths') MUST be allowed | |
| on endpoints matching that tab (/admin/hadith/*). | |
| """ | |
| mock_req = make_mock_request(path="/admin/hadith/books") | |
| staff_user = { | |
| "uid": "staff_emp_001", | |
| "email": "moderator@sahihislam.com", | |
| "_verified_token_email": "moderator@sahihislam.com", | |
| "role": "STAFF", | |
| } | |
| # Mock staff permissions resolution returning 'hadiths' | |
| mock_perms = { | |
| "is_staff": True, | |
| "is_active": True, | |
| "allowed_tabs": ["hadiths"], | |
| "role_title": "Hadith Reviewer", | |
| } | |
| with patch("app.superadmin_routes.get_staff_permissions_for_user", AsyncMock(return_value=mock_perms)): | |
| res = run_async(require_superadmin(request=mock_req, user=staff_user)) | |
| assert res["is_staff"] is True | |
| assert "hadiths" in res["allowed_tabs"] | |
| # ============================================================================== | |
| # 5. PORTAL ACCESS CHECK | |
| # ============================================================================== | |
| def test_require_portal_access_superadmin(): | |
| """require_portal_access allows whitelisted SuperAdmin.""" | |
| user = { | |
| "uid": "uid_suhail", | |
| "email": "suhaileng.bhat@gmail.com", | |
| "role": "SUPERADMIN", | |
| "is_superadmin": True, | |
| "_verified_token_email": "suhaileng.bhat@gmail.com", | |
| "_verified_token_email_verified": True, | |
| } | |
| res = run_async(require_portal_access(user=user)) | |
| assert res["is_superadmin"] is True | |
| def test_require_portal_access_rejects_unauthorized_account(): | |
| """require_portal_access rejects ordinary user with 403.""" | |
| user = { | |
| "uid": "unauth_uid", | |
| "email": "intruder@domain.com", | |
| "_verified_token_email": "intruder@domain.com", | |
| "role": "USER", | |
| } | |
| with patch("app.superadmin_routes.get_staff_permissions_for_user", AsyncMock(return_value={"is_staff": False, "is_active": False})): | |
| with pytest.raises(HTTPException) as exc_info: | |
| run_async(require_portal_access(user=user)) | |
| assert exc_info.value.status_code == 403 | |