Skip to content

DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.

fix(codex-auth): route the OAuth callback by state, not by request user

Bingxi Zhao (Frank)7a5102a8cd65
diff --git a/deeptutor/api/routers/auth.py b/deeptutor/api/routers/auth.py
index 0909c5db4..fbda81405 100644
--- a/deeptutor/api/routers/auth.py
+++ b/deeptutor/api/routers/auth.py
@@ -50,7 +50,7 @@ from deeptutor.services.auth import (
set_role,
)
from deeptutor.services.codex_auth.contracts import CodexAuthError
-from deeptutor.services.codex_auth.service import get_codex_oauth_service
+from deeptutor.services.codex_auth.service import deliver_codex_oauth_callback
logger = logging.getLogger(__name__)
@@ -380,7 +380,7 @@ async def receive_codex_oauth_callback(
headers = {"Cache-Control": "no-store"}
try:
callback_state = state if len(request.query_params.getlist("state")) == 1 else None
- await get_codex_oauth_service().receive_callback(code, callback_state, error)
+ await deliver_codex_oauth_callback(code, callback_state, error)
except CodexAuthError as exc:
return HTMLResponse(
(
diff --git a/deeptutor/services/codex_auth/service.py b/deeptutor/services/codex_auth/service.py
index 164df7df2..c9c76eb2c 100644
--- a/deeptutor/services/codex_auth/service.py
+++ b/deeptutor/services/codex_auth/service.py
@@ -284,6 +284,21 @@ class CodexOAuthService:
and (operation.task is None or not operation.task.done())
)
+ def awaits_callback_state(self, state: str | None) -> bool:
+ """Whether this instance holds the active login that owns ``state``.
+
+ Read without the operation lock: the caller only uses this to pick a
+ recipient, and :meth:`receive_callback` revalidates under the lock.
+ """
+ operation = self._operation
+ if operation is None or not self._operation_is_active():
+ return False
+ return oauth_state_matches(state, operation.state_secret)
+
+ def awaits_callback(self) -> bool:
+ """Whether this instance has a login waiting for a browser callback."""
+ return self._operation is not None and self._operation_is_active()
+
async def receive_callback(
self,
code: str | None,
@@ -711,12 +726,48 @@ def get_codex_oauth_service() -> CodexOAuthService:
return service
+async def deliver_codex_oauth_callback(
+ code: str | None,
+ state: str | None,
+ error: str | None,
+) -> None:
+ """Hand a browser OAuth callback to whichever login is awaiting it.
+
+ The browser reaches ``/auth/callback`` on its own loopback address — the
+ far end of the user's tunnel — not on the DeepTutor Web origin, so the
+ request carries no session and the per-user service instance behind
+ :func:`get_codex_oauth_service` cannot be resolved from it. Resolving it
+ anyway would land every callback on the default root and strand every
+ non-administrator mid-login.
+
+ The OAuth ``state`` is the identity instead: it is a secret this process
+ minted for exactly one login, and it is compared in constant time. That is
+ already the trust model the loopback listener uses.
+ """
+ for service in list(_SERVICE_INSTANCES.values()):
+ if service.awaits_callback_state(state):
+ await service.receive_callback(code, state, error)
+ return
+ if any(service.awaits_callback() for service in list(_SERVICE_INSTANCES.values())):
+ raise CodexAuthError(
+ "state_mismatch",
+ "Codex sign-in returned an invalid state.",
+ 400,
+ )
+ raise CodexAuthError(
+ "login_not_active",
+ "Codex sign-in is not waiting for a callback.",
+ 409,
+ )
+
+
__all__ = [
"CODEX_PROFILE_ID",
"MANAGED_BY",
"CatalogSyncResult",
"CodexOAuthService",
"codex_model_id",
+ "deliver_codex_oauth_callback",
"get_codex_oauth_service",
"remove_codex_catalog",
"ssh_forward_command",
diff --git a/tests/api/test_codex_oauth_callback.py b/tests/api/test_codex_oauth_callback.py
index a1f0646a7..4f8783a69 100644
--- a/tests/api/test_codex_oauth_callback.py
+++ b/tests/api/test_codex_oauth_callback.py
@@ -43,7 +43,11 @@ def _client(
monkeypatch: pytest.MonkeyPatch,
service: FakeCodexOAuthService,
) -> TestClient:
- monkeypatch.setattr(auth_router, "get_codex_oauth_service", lambda: service)
+ monkeypatch.setattr(
+ auth_router,
+ "deliver_codex_oauth_callback",
+ service.receive_callback,
+ )
app = FastAPI()
app.include_router(auth_router.router, prefix="/api/v1/auth")
return TestClient(app)
diff --git a/tests/services/codex_auth/test_service.py b/tests/services/codex_auth/test_service.py
index 77d034121..16f455e99 100644
--- a/tests/services/codex_auth/test_service.py
+++ b/tests/services/codex_auth/test_service.py
@@ -603,6 +603,85 @@ async def test_callback_broker_keeps_waiting_after_wrong_state_then_completes(
assert status["operation_state"] == "completed"
+async def test_callback_delivery_finds_the_login_that_owns_the_state(
+ monkeypatch: pytest.MonkeyPatch,
+ tmp_path: Path,
+) -> None:
+ """A callback must reach the account that started the login, not the default root.
+
+ The browser hits ``/auth/callback`` on the far end of its own tunnel, so the
+ request carries no session and cannot name a user. Routing by the OAuth
+ state is what keeps a non-administrator's sign-in from being delivered to
+ the default root instead.
+ """
+ default_root = tmp_path / "user"
+ member_root = tmp_path / "users" / "member"
+ default_root.mkdir(parents=True)
+ member_root.mkdir(parents=True)
+ default_service, *_ = await _oauth_service(default_root)
+ member_service, _callback, _oauth, _catalog, _store, _models = await _oauth_service(member_root)
+ monkeypatch.setattr(
+ service_module,
+ "_SERVICE_INSTANCES",
+ {str(default_root): default_service, str(member_root): member_service},
+ )
+
+ started = await member_service.start_login()
+ member_state = parse_qs(urlsplit(started["authorize_url"]).query)["state"][0]
+
+ await service_module.deliver_codex_oauth_callback(
+ code="authorization-code",
+ state=member_state,
+ error=None,
+ )
+
+ status = await _wait_until_terminal(member_service)
+ assert status["operation_state"] == "completed"
+ assert default_service.public_status()["operation_state"] is None
+
+
+async def test_callback_delivery_rejects_a_state_no_login_owns(
+ monkeypatch: pytest.MonkeyPatch,
+ tmp_path: Path,
+) -> None:
+ service, _callback, _oauth, _catalog, _store, _models = await _oauth_service(tmp_path)
+ monkeypatch.setattr(service_module, "_SERVICE_INSTANCES", {str(tmp_path): service})
+ await service.start_login()
+
+ with pytest.raises(CodexAuthError) as exc_info:
+ await service_module.deliver_codex_oauth_callback(
+ code="do-not-accept",
+ state="wrong-state",
+ error=None,
+ )
+
+ assert exc_info.value.code == "state_mismatch"
+ assert exc_info.value.http_status == 400
+ assert service.public_status()["operation_state"] == "waiting"
+ await service.cancel_login()
+
+
+async def test_callback_delivery_rejects_when_nothing_is_waiting(
+ monkeypatch: pytest.MonkeyPatch,
+ tmp_path: Path,
+) -> None:
+ service, _callback, _oauth, _catalog, _store, _models = await _oauth_service(tmp_path)
+ monkeypatch.setattr(service_module, "_SERVICE_INSTANCES", {str(tmp_path): service})
+
+ with pytest.raises(CodexAuthError) as exc_info:
+ await service_module.deliver_codex_oauth_callback(
+ code="authorization-code",
+ state="untrusted-state",
+ error=None,
+ )
+
+ assert exc_info.value.code == "login_not_active"
+ assert exc_info.value.http_status == 409
+
+
@pytest.mark.asyncio
async def test_callback_broker_rejects_when_no_login_is_active(tmp_path: Path) -> None:
service, _callback, _oauth, _catalog, _store, _models = await _oauth_service(tmp_path)