"""The operator's own UI can join Infonet without an admin-key login. The frontend proxy presents an HMAC of the admin key in X-SB-Operator-Client. The backend accepts that token only where require_operator_client is used, and a missing or wrong token still falls back to the admin-key check. """ import hmac import hashlib import pytest from fastapi import Depends, FastAPI from fastapi.testclient import TestClient import auth ADMIN_KEY = "test-admin-key-for-operator-client" @pytest.fixture def client(monkeypatch): monkeypatch.setattr(auth, "_current_admin_key", lambda: ADMIN_KEY) app = FastAPI() @app.post("/join", dependencies=[Depends(auth.require_operator_client)]) def join(): return {"ok": True} @app.post("/admin-only", dependencies=[Depends(auth.require_local_operator)]) def admin_only(): return {"ok": True} return TestClient(app, client=("203.0.113.9", 50000)) def _expected_token() -> str: return hmac.new(ADMIN_KEY.encode(), b"shadowbroker-operator-client-v1", hashlib.sha256).hexdigest() def test_token_matches_the_proxy_formula(): assert auth.operator_client_token(ADMIN_KEY) == _expected_token() def test_no_token_and_no_key_is_refused(client): assert client.post("/join").status_code == 403 def test_wrong_token_is_refused(client): resp = client.post("/join", headers={auth.OPERATOR_CLIENT_HEADER: "0" * 64}) assert resp.status_code == 403 def test_proxy_token_is_accepted(client): resp = client.post("/join", headers={auth.OPERATOR_CLIENT_HEADER: _expected_token()}) assert resp.status_code == 200 def test_admin_key_still_works(client): assert client.post("/join", headers={"X-Admin-Key": ADMIN_KEY}).status_code == 200 def test_foreign_origin_without_the_token_is_refused(client): resp = client.post( "/join", headers={"Origin": "https://evil.example", "Sec-Fetch-Site": "cross-site"}, ) assert resp.status_code == 403 def test_token_stands_for_the_proxys_origin_check(client): # The proxy attaches the token only after its own same-origin check # (frontend requestOrigin.ts) passed, for the page's real origin on any # port. The browser's Origin header then need not be on the backend's # fixed localhost:3000 list. resp = client.post( "/join", headers={auth.OPERATOR_CLIENT_HEADER: _expected_token(), "Origin": "http://localhost:3301"}, ) assert resp.status_code == 200 def test_token_does_not_unlock_admin_routes(client): resp = client.post("/admin-only", headers={auth.OPERATOR_CLIENT_HEADER: _expected_token()}) assert resp.status_code == 403 def test_no_token_without_an_admin_key(monkeypatch): monkeypatch.setattr(auth, "_current_admin_key", lambda: "") assert auth.operator_client_token() == "" def test_join_route_uses_the_operator_client_check(): from routers import wormhole route = next(r for r in wormhole.router.routes if getattr(r, "path", "") == "/api/wormhole/join") calls = {d.call for d in route.dependant.dependencies} assert auth.require_operator_client in calls