DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
fix(codex): let a Docker sign-in finish from the pasted callback address
Bingxi Zhao (Frank)01615d6c9749
diff --git a/deeptutor/api/routers/settings.py b/deeptutor/api/routers/settings.pyindex fac7ee348..69ef55688 100644--- a/deeptutor/api/routers/settings.py+++ b/deeptutor/api/routers/settings.py@@ -796,6 +796,30 @@ async def get_openai_codex_oauth_status() -> dict[str, Any]:raise _codex_http_exception(exc) from None+class CodexOAuthCallbackPayload(BaseModel):+ callback_url: str++[email protected]("/providers/openai-codex/oauth/complete")+async def complete_openai_codex_oauth(payload: CodexOAuthCallbackPayload) -> dict[str, Any]:+ """Finish a waiting Codex login from a callback address the user pasted.++ The provider redirects the browser to a loopback listener. In Docker that+ listener lives in the container and the published ports do not include it,+ so the browser shows a failed page while the sign-in waits forever+ (#1252). This is the way back in without a tunnel: the address is parsed+ for its OAuth result and discarded, and the exchange is the same one the+ listener would have driven.+ """+ _require_codex_oauth_actor()+ try:+ return await get_codex_oauth_service().complete_login_with_callback_url(+ payload.callback_url+ )+ except CodexAuthError as exc:+ raise _codex_http_exception(exc) from None++@router.post("/providers/openai-codex/oauth/cancel")async def cancel_openai_codex_oauth() -> dict[str, Any]:_require_codex_oauth_actor()diff --git a/deeptutor/services/codex_auth/service.py b/deeptutor/services/codex_auth/service.pyindex 1555a905b..ac6ae51a6 100644--- a/deeptutor/services/codex_auth/service.py+++ b/deeptutor/services/codex_auth/service.py@@ -14,6 +14,7 @@ import secretsimport shutilimport timefrom typing import Any+from urllib.parse import parse_qs, urlsplitimport httpx@@ -73,6 +74,56 @@ class _LoginOperation:task: asyncio.Task[None] | None = None+def parse_oauth_callback_url(+ raw: str, expected_redirect_uri: str+) -> tuple[str | None, str | None, str | None]:+ """Read ``code`` / ``state`` / ``error`` out of a pasted callback address.++ The browser lands on the loopback listener's address. Under Docker that+ listener is inside the container and the standard compose file publishes+ only the Web and API ports, so the user can read the address off their+ address bar while the process never receives it (#1252). Pasting it back+ is the recovery path — which makes this string untrusted input that is+ parsed and then dropped. Nothing here fetches the address, stores it, or+ puts it in a reply.++ It must be *this* login's callback address: same scheme, host, port and+ path as the redirect URI this process registered with the provider, so a+ pasted address cannot redirect the exchange anywhere else. A parameter+ given twice is ambiguous rather than merely untidy, and is refused instead+ of silently resolved to one of the two.+ """++ def _fail(message: str) -> CodexAuthError:+ return CodexAuthError("callback_url_invalid", message, 400)++ try:+ pasted = urlsplit(raw.strip())+ expected = urlsplit(expected_redirect_uri)+ except ValueError as exc:+ raise _fail("That does not look like a callback address.") from exc+ if not pasted.scheme or not pasted.netloc:+ raise _fail("Paste the whole address, including http://.")+ same_target = (+ pasted.scheme.lower() == expected.scheme.lower()+ and (pasted.hostname or "").lower() == (expected.hostname or "").lower()+ and pasted.port == expected.port+ and pasted.path.rstrip("/") == expected.path.rstrip("/")+ )+ if not same_target:+ raise _fail("That address is not the callback this sign-in is waiting for.")++ params = parse_qs(pasted.query, keep_blank_values=True)+ if any(len(values) > 1 for values in params.values()):+ raise _fail("That address repeats an OAuth parameter.")+ code = (params.get("code") or [None])[0]+ state = (params.get("state") or [None])[0]+ error = (params.get("error") or [None])[0]+ if not code and not error:+ raise _fail("That address carries no authorization result.")+ return code, state, error++def ssh_forward_command(callback_port: int, forward_port: int) -> str:return f"ssh -N -L {callback_port}:127.0.0.1:{forward_port} <ssh-user>@<server-host>"@@ -468,6 +519,29 @@ class CodexOAuthService:)operation.callback.submit(OAuthCallbackResult(code=code, state=state, error=error))+ async def complete_login_with_callback_url(self, callback_url: str) -> dict[str, Any]:+ """Finish a waiting login from the callback address the user pasted.++ The loopback listener is the normal delivery route; this is the one+ for deployments where the browser can reach the callback address and+ this process cannot. It resolves against *this* account's operation+ rather than every login in the process — the request arrives+ authenticated on the Web origin, so the caller's own pending sign-in+ is the only one they may finish. ``receive_callback`` then applies the+ same state check and hands the code to the same exchange, so PKCE, the+ registered redirect URI and owner binding are unchanged.+ """+ operation = self._operation+ if operation is None or not self._operation_is_active():+ raise CodexAuthError(+ "login_not_active",+ "Codex sign-in is not waiting for a callback.",+ 409,+ )+ code, state, error = parse_oauth_callback_url(callback_url, operation.redirect_uri)+ await self.receive_callback(code, state, error)+ return self.public_status()+async def _run_login(self, operation: _LoginOperation) -> None:try:callback = await operation.callback.wait(diff --git a/tests/services/codex_auth/test_service.py b/tests/services/codex_auth/test_service.pyindex 91a80ea53..b4c7ed540 100644--- a/tests/services/codex_auth/test_service.py+++ b/tests/services/codex_auth/test_service.py@@ -23,6 +23,7 @@ from deeptutor.services.codex_auth.service import (MANAGED_BY,CodexOAuthService,codex_model_id,+ parse_oauth_callback_url,remove_codex_catalog,ssh_forward_command,sync_codex_catalog,@@ -1545,3 +1546,98 @@ async def test_recover_after_unauthorized_forces_refresh_for_next_request(assert oauth.refresh_calls == 1assert store.load_credentials().access_token == "refreshed-access" # type: ignore[union-attr]+++_REDIRECT_URI = "http://localhost:1455/auth/callback"+++ "pasted",+ [+ "http://localhost:1455/auth/callback?code=c&state=s&code=c2",+ "http://localhost:1455/auth/callback?state=s",+ "http://localhost:9999/auth/callback?code=c&state=s",+ "http://evil.example/auth/callback?code=c&state=s",+ "http://localhost:1455/somewhere-else?code=c&state=s",+ "localhost:1455/auth/callback?code=c&state=s",+ "not a url at all",+ ],+)+def test_a_pasted_address_that_is_not_this_logins_callback_is_refused(pasted: str) -> None:+ """The recovery form takes a string off the user's clipboard.++ Anything that is not the callback this process registered — another host,+ another port, another path, a repeated OAuth parameter, or no result at+ all — is refused before the code reaches the exchange.+ """+ with pytest.raises(CodexAuthError) as exc_info:+ parse_oauth_callback_url(pasted, _REDIRECT_URI)++ assert exc_info.value.code == "callback_url_invalid"+ assert exc_info.value.http_status == 400+++def test_a_pasted_callback_yields_its_oauth_result() -> None:+ assert parse_oauth_callback_url(+ f" {_REDIRECT_URI}?code=the-code&state=the-state ", _REDIRECT_URI+ ) == ("the-code", "the-state", None)+ assert parse_oauth_callback_url(f"{_REDIRECT_URI}?error=access_denied", _REDIRECT_URI) == (+ None,+ None,+ "access_denied",+ )+++async def test_a_docker_user_finishes_a_login_by_pasting_the_callback_address(+ tmp_path: Path,+) -> None:+ """#1252: the browser reaches the callback address, the container does not.++ The loopback listener runs inside the container and the standard compose+ file does not publish its port, so the redirect dead-ends in the browser+ and the sign-in waits until it expires. Pasting the address back finishes+ the same exchange, with the same state check.+ """+ service, _callback, _oauth, _catalog, _store, _models = await _oauth_service(tmp_path)+ started = await service.start_login()+ state = parse_qs(urlsplit(started["authorize_url"]).query)["state"][0]++ await service.complete_login_with_callback_url(+ f"{started['redirect_uri']}?code=authorization-code&state={state}"+ )++ assert (await _wait_until_terminal(service))["operation_state"] == "completed"+++async def test_a_callback_for_someone_elses_login_does_not_complete_this_one(+ tmp_path: Path,+) -> None:+ """The endpoint is authenticated, so it finishes the caller's own sign-in.++ A state minted for another account's login is not a credential this+ account may spend, and the address is not fetched to find out whose it is.+ """+ service, _callback, _oauth, _catalog, _store, _models = await _oauth_service(tmp_path)+ started = await service.start_login()++ with pytest.raises(CodexAuthError) as exc_info:+ await service.complete_login_with_callback_url(+ f"{started['redirect_uri']}?code=authorization-code&state=another-accounts-state"+ )++ assert exc_info.value.code == "state_mismatch"+ assert service.public_status()["operation_state"] == "waiting"+ await service.cancel_login()+++async def test_pasting_a_callback_with_no_login_waiting_is_a_conflict(tmp_path: Path) -> None:+ service, _callback, _oauth, _catalog, _store, _models = await _oauth_service(tmp_path)++ with pytest.raises(CodexAuthError) as exc_info:+ await service.complete_login_with_callback_url(f"{_REDIRECT_URI}?code=c&state=s")++ assert exc_info.value.code == "login_not_active"+ assert exc_info.value.http_status == 409diff --git a/web/components/settings/CodexOAuthCard.tsx b/web/components/settings/CodexOAuthCard.tsxindex 06557f747..adc193e9f 100644--- a/web/components/settings/CodexOAuthCard.tsx+++ b/web/components/settings/CodexOAuthCard.tsx@@ -14,6 +14,7 @@ import {CodexOAuthApiError,codexErrorMessageKey,codexStatusMessageKey,+ completeCodexLogin,getCodexStatus,isLoopbackHostname,logoutCodex,@@ -37,6 +38,9 @@ export function CodexOAuthCard() {const [errorKey, setErrorKey] = useState<string | null>(null);const [pollTick, setPollTick] = useState(0);const [loginStart, setLoginStart] = useState<CodexLoginStart | null>(null);+ // Cleared on submit and when the waiting operation ends, so a callback+ // address never outlives the login it belongs to.+ const [callbackUrl, setCallbackUrl] = useState("");const reloadedOperation = useRef<string | null>(null);const statusRequestSequence = useRef(0);const remoteAccess =@@ -51,6 +55,7 @@ export function CodexOAuthCard() {nextStatus.operation_state === "expired" ||nextStatus.operation_state === "failed";if (!terminalOperation) return;+ setCallbackUrl("");setLoginStart((loginStart) =>loginStart && nextStatus.operation_id === loginStart.operation_id? null@@ -307,6 +312,27 @@ export function CodexOAuthCard() {}};+ const submitCallbackUrl = async () => {+ const pasted = callbackUrl.trim();+ if (!pasted) return;+ invalidateStatusRequests();+ setPending(true);+ setErrorKey(null);+ try {+ const nextStatus = await completeCodexLogin(pasted);+ recordStatus(nextStatus);+ setCallbackUrl("");+ } catch (error) {+ setErrorKey(+ codexErrorMessageKey(+ error instanceof CodexOAuthApiError ? error.code : null,+ ),+ );+ } finally {+ setPending(false);+ }+ };+const polling = Boolean(status && shouldPollCodexStatus(status));const connected = status?.connection === "connected";const messageKey =@@ -447,6 +473,44 @@ export function CodexOAuthCard() {</div></div>)}+ {remoteGuidance && (+ <div className="mt-4 rounded-lg border border-[var(--border)] bg-[var(--background)] p-3">+ <p className="text-sm font-medium">+ {t("codex.oauth.callbackRecoveryTitle")}+ </p>+ <p className="mt-2 text-xs text-[var(--muted-foreground)]">+ {t("codex.oauth.callbackRecoveryHint")}+ </p>+ <label+ className="mt-3 block text-xs font-medium"+ htmlFor="codex-callback-url"+ >+ {t("codex.oauth.callbackUrlLabel")}+ </label>+ <input+ id="codex-callback-url"+ type="url"+ inputMode="url"+ autoComplete="off"+ spellCheck={false}+ value={callbackUrl}+ onChange={(event) => setCallbackUrl(event.target.value)}+ placeholder={remoteGuidance.redirect_uri}+ className="mt-1 w-full rounded-md border border-[var(--border)] bg-[var(--card)] px-2 py-1.5 text-xs"+ />+ <div className="mt-3">+ <Button+ type="button"+ size="sm"+ loading={pending}+ disabled={!callbackUrl.trim()}+ onClick={() => void submitCallbackUrl()}+ >+ {t("codex.oauth.completeSignIn")}+ </Button>+ </div>+ </div>+ )}<div className="mt-4 flex flex-wrap gap-2">{!connected && !polling && (<Buttondiff --git a/web/lib/codex-oauth.ts b/web/lib/codex-oauth.tsindex 1d8c745cd..4e6eca1b7 100644--- a/web/lib/codex-oauth.ts+++ b/web/lib/codex-oauth.ts@@ -180,6 +180,23 @@ export function cancelCodexLogin(): Promise<CodexOAuthStatus> {return requestCodex<CodexOAuthStatus>("/oauth/cancel", "POST");}+/**+ * Finish a waiting login from the callback address the browser landed on.+ *+ * The loopback listener normally receives it. Under Docker that listener is+ * inside the container and its port is not published, so the browser reaches+ * an address this process never hears about (#1252). The address is sent once+ * and parsed server-side; it is never stored here.+ */+export function completeCodexLogin(+ callbackUrl: string,+ fetchImpl: typeof apiFetch = apiFetch,+): Promise<CodexOAuthStatus> {+ return requestCodex<CodexOAuthStatus>("/oauth/complete", "POST", fetchImpl, {+ callback_url: callbackUrl,+ });+}+export function refreshCodexModels(): Promise<CodexOAuthStatus> {return requestCodex<CodexOAuthStatus>("/models/refresh", "POST");}@@ -220,6 +237,9 @@ export function codexErrorMessageKey(code: string | null): string {if (code === "callback_unavailable") {return "codex.oauth.callbackUnavailable";}+ if (code === "callback_url_invalid") {+ return "codex.oauth.callbackUrlInvalid";+ }if (code === "invalid_response") return "codex.oauth.invalidResponse";if (code === "reasoning_effort_unsupported") {return "codex.oauth.reasoningUnsupported";diff --git a/web/locales/en/app.json b/web/locales/en/app.jsonindex 5611e5b2f..8a91940f4 100644--- a/web/locales/en/app.json+++ b/web/locales/en/app.json@@ -2500,6 +2500,11 @@"codex.oauth.remoteTitle": "Remote OAuth authorization","codex.oauth.remoteSteps": "First run the command below and keep the SSH tunnel running. Then click Open authorization.","codex.oauth.callbackAddress": "OAuth callback address",+ "codex.oauth.callbackRecoveryTitle": "Finish sign-in from the callback address",+ "codex.oauth.callbackRecoveryHint": "If your browser lands on a page that cannot load — the usual case in Docker, where the callback port is not published — copy that page's whole address and paste it here.",+ "codex.oauth.callbackUrlLabel": "Callback address",+ "codex.oauth.completeSignIn": "Finish sign-in",+ "codex.oauth.callbackUrlInvalid": "That address is not the callback this sign-in is waiting for.","codex.oauth.copyCommand": "Copy command","codex.oauth.commandCopied": "SSH tunnel command copied.","codex.oauth.copyFailed": "Could not copy the SSH tunnel command.",diff --git a/web/locales/zh/app.json b/web/locales/zh/app.jsonindex 5f199113e..d44038055 100644--- a/web/locales/zh/app.json+++ b/web/locales/zh/app.json@@ -2500,6 +2500,11 @@"codex.oauth.remoteTitle": "远程 OAuth 授权","codex.oauth.remoteSteps": "先运行下方命令并保持 SSH 隧道运行,再点击“打开授权页面”。","codex.oauth.callbackAddress": "OAuth 回调地址",+ "codex.oauth.callbackRecoveryTitle": "用回调地址完成登录",+ "codex.oauth.callbackRecoveryHint": "如果浏览器停在一个打不开的页面上——Docker 部署没有发布回调端口时通常如此——把那个页面的完整地址复制过来粘贴到这里。",+ "codex.oauth.callbackUrlLabel": "回调地址",+ "codex.oauth.completeSignIn": "完成登录",+ "codex.oauth.callbackUrlInvalid": "这个地址不是本次登录在等待的回调。","codex.oauth.copyCommand": "复制命令","codex.oauth.commandCopied": "SSH 隧道命令已复制。","codex.oauth.copyFailed": "无法复制 SSH 隧道命令。",