Skip to content

Get up and running with Kimi, GLM, MiniMax, DeepSeek, gpt-oss, Qwen, Gemma and other models.

app: harden Codex desktop proxy handling (#18244)

Parth Sareen83ed7d9965b1
diff --git a/app/ui/app/src/components/Settings.tsx b/app/ui/app/src/components/Settings.tsx
index 60a83fac0..1060136b3 100644
--- a/app/ui/app/src/components/Settings.tsx
+++ b/app/ui/app/src/components/Settings.tsx
@@ -150,8 +150,7 @@ export default function Settings() {
const [hasCodexDraftChanges, setHasCodexDraftChanges] = useState(false);
const claudeModelsSettingsRef =
useRef<ClaudeDesktopModelsSettingsHandle>(null);
- const codexModelsSettingsRef =
- useRef<CodexDesktopModelsSettingsHandle>(null);
+ const codexModelsSettingsRef = useRef<CodexDesktopModelsSettingsHandle>(null);
const savedConfirmationTimeoutRef = useRef<number | null>(null);
useBlocker({
shouldBlockFn: () =>
diff --git a/cmd/launch/codex_app.go b/cmd/launch/codex_app.go
index 3822fce25..cc764ffe3 100644
--- a/cmd/launch/codex_app.go
+++ b/cmd/launch/codex_app.go
@@ -5,7 +5,9 @@ import (
"encoding/json"
"errors"
"fmt"
+ "net"
"net/http"
+ "net/url"
"os"
"os/exec"
"path/filepath"
@@ -2286,10 +2288,28 @@ func codexAppRootUsesProxy(config codexParsedConfig) bool {
if modelProvider, ok := config.RootStringOK(codexRootModelProviderKey); ok && modelProvider != "openai" {
return false
}
- return codexNormalizeURL(config.RootString(codexRootOpenAIBaseURLKey)) == codexNormalizeURL(codexAppProxyBaseURL()) &&
+ return codexAppManagedProxyURL(config.RootString(codexRootOpenAIBaseURLKey)) &&
config.RootString(codexRootModelCatalogJSONKey) == catalogPath
}
+func codexAppManagedProxyURL(raw string) bool {
+ u, err := url.Parse(strings.TrimSpace(raw))
+ if err != nil || u.Scheme == "" || u.Host == "" || u.User != nil || u.RawQuery != "" || u.Fragment != "" {
+ return false
+ }
+ if u.Scheme != "http" && u.Scheme != "https" {
+ return false
+ }
+ host := u.Hostname()
+ if !strings.EqualFold(host, "localhost") {
+ ip := net.ParseIP(host)
+ if ip == nil || !ip.IsLoopback() {
+ return false
+ }
+ }
+ return strings.TrimSuffix(u.Path, "/") == proxy.CodexDesktopPathPrefix+"/v1"
+}
+
func codexAppRootReferencesCatalog(text string) bool {
catalogPath, err := codexAppModelCatalogPath()
if err != nil {
diff --git a/cmd/launch/codex_app_test.go b/cmd/launch/codex_app_test.go
index 4786a6a92..44a41001a 100644
--- a/cmd/launch/codex_app_test.go
+++ b/cmd/launch/codex_app_test.go
@@ -1557,6 +1557,87 @@ func TestCodexAppConfigureUsesConnectableHostForUnspecifiedBindAddress(t *testin
}
}
+func TestCodexAppHostChangePreservesRestoreState(t *testing.T) {
+ tmpDir := t.TempDir()
+ setTestHome(t, tmpDir)
+ withCodexAppPlatform(t, "darwin")
+ withCodexAppProcessHooks(t, func() bool { return false }, func() error { return nil }, func() error { return nil })
+
+ configPath := filepath.Join(tmpDir, ".codex", "config.toml")
+ if err := os.MkdirAll(filepath.Dir(configPath), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ original := "" +
+ `model = "gpt-5.6-sol"` + "\n" +
+ `model_provider = "openai"` + "\n" +
+ `openai_base_url = "https://api.openai.com/v1"` + "\n"
+ if err := os.WriteFile(configPath, []byte(original), 0o644); err != nil {
+ t.Fatal(err)
+ }
+
+ t.Setenv("OLLAMA_HOST", "http://127.0.0.1:11434")
+ app := &CodexApp{}
+ if err := app.ConfigureWithModels("llama3.2", testLaunchModels("llama3.2")); err != nil {
+ t.Fatalf("initial ConfigureWithModels returned error: %v", err)
+ }
+
+ // A changed server address must not make the off-switch disappear or cause
+ // the next update to save Ollama's managed root as the user's restore target.
+ t.Setenv("OLLAMA_HOST", "http://127.0.0.1:22434")
+ if !app.OllamaConfigured() {
+ t.Fatal("OllamaConfigured = false after host change, want managed config to remain detectable")
+ }
+ if err := app.ConfigureWithModels("gemma4", testLaunchModels("gemma4")); err != nil {
+ t.Fatalf("updated ConfigureWithModels returned error: %v", err)
+ }
+ if err := app.RestoreFromDesktop(false); err != nil {
+ t.Fatalf("RestoreFromDesktop returned error: %v", err)
+ }
+
+ restored, err := os.ReadFile(configPath)
+ if err != nil {
+ t.Fatal(err)
+ }
+ for key, want := range map[string]string{
+ codexRootModelKey: "gpt-5.6-sol",
+ codexRootModelProviderKey: "openai",
+ codexRootOpenAIBaseURLKey: "https://api.openai.com/v1",
+ } {
+ if got := codexRootStringValue(string(restored), key); got != want {
+ t.Fatalf("restored %s = %q, want %q in:\n%s", key, got, want, restored)
+ }
+ }
+ if got, ok := codexRootStringValueOK(string(restored), codexRootModelCatalogJSONKey); ok {
+ t.Fatalf("restored model catalog = %q, want managed catalog removed in:\n%s", got, restored)
+ }
+ if _, err := os.Stat(codexAppRestoreStatePath()); !os.IsNotExist(err) {
+ t.Fatalf("restore state should be removed after successful restore, err=%v", err)
+ }
+}
+
+func TestCodexAppManagedProxyURLRequiresLoopback(t *testing.T) {
+ for _, tt := range []struct {
+ name string
+ url string
+ want bool
+ }{
+ {name: "IPv4 loopback", url: "http://127.0.0.1:11434/api/codex/v1", want: true},
+ {name: "localhost", url: "http://localhost:22434/api/codex/v1/", want: true},
+ {name: "IPv6 loopback", url: "https://[::1]:11434/api/codex/v1", want: true},
+ {name: "remote hostname", url: "https://example.com/api/codex/v1"},
+ {name: "private address", url: "http://192.168.1.5:11434/api/codex/v1"},
+ {name: "credentials", url: "http://[email protected]:11434/api/codex/v1"},
+ {name: "query", url: "http://127.0.0.1:11434/api/codex/v1?owned=true"},
+ {name: "wrong path", url: "http://127.0.0.1:11434/v1"},
+ } {
+ t.Run(tt.name, func(t *testing.T) {
+ if got := codexAppManagedProxyURL(tt.url); got != tt.want {
+ t.Fatalf("codexAppManagedProxyURL(%q) = %t, want %t", tt.url, got, tt.want)
+ }
+ })
+ }
+}
+
func TestCodexAppConfigureRejectsMalformedTomlBeforeSideEffects(t *testing.T) {
tmpDir := t.TempDir()
setTestHome(t, tmpDir)
diff --git a/internal/proxy/codex_desktop_errors.go b/internal/proxy/codex_desktop_errors.go
index 8b0c015d6..a07ab7545 100644
--- a/internal/proxy/codex_desktop_errors.go
+++ b/internal/proxy/codex_desktop_errors.go
@@ -87,20 +87,22 @@ func (h *CodexDesktop) rewriteAccessErrorJSON(body []byte, status int) ([]byte,
var code, errorType string
_ = json.Unmarshal(fields["code"], &code)
_ = json.Unmarshal(fields["type"], &errorType)
- var rewritten string
+ var rewritten, reason string
switch {
case status == http.StatusUnauthorized || code == "authentication_error" || code == "unauthorized" || errorType == "authentication_error" || strings.EqualFold(strings.TrimSpace(message), "unauthorized"):
rewritten = codexSignInMessage
+ reason = "sign_in"
// Codex displays these errors as plain text, including raw HTTP error
// bodies. Keep device sign-in URLs out of the user-facing response.
delete(payload, "signin_url")
delete(fields, "signin_url")
case strings.Contains(strings.ToLower(message), "this model requires a subscription or extra usage"):
rewritten = codexSubscriptionMessage
+ reason = "subscription"
default:
return body, false
}
- h.logger.Debug("Codex Ollama access error", "status", status, "code", code, "error", message)
+ h.logger.Debug("Codex Ollama access error", "status", status, "reason", reason)
encoded, _ := json.Marshal(rewritten)
if stringError {
payload["error"] = encoded
diff --git a/internal/proxy/codex_desktop_errors_test.go b/internal/proxy/codex_desktop_errors_test.go
index 866b86fea..79961979a 100644
--- a/internal/proxy/codex_desktop_errors_test.go
+++ b/internal/proxy/codex_desktop_errors_test.go
@@ -6,6 +6,7 @@ import (
"encoding/json"
"fmt"
"io"
+ "log/slog"
"net/http"
"net/http/httptest"
"strconv"
@@ -160,6 +161,22 @@ func TestCodexDesktopAccessErrorCopySignInMessage(t *testing.T) {
}
}
+func TestCodexDesktopAccessErrorCopyDoesNotLogSignInSecret(t *testing.T) {
+ var logs bytes.Buffer
+ handler := newTestCodexDesktop(t, "http://localhost", "http://localhost", "unused")
+ handler.logger = slog.New(slog.NewTextHandler(&logs, &slog.HandlerOptions{Level: slog.LevelDebug}))
+ body := []byte(`{"error":{"message":"Sign in: https://ollama.com/connect?name=test&key=test-key","code":"authentication_error","signin_url":"https://ollama.com/connect?name=test&key=test-key"}}`)
+
+ if _, changed := handler.rewriteAccessErrorJSON(body, http.StatusUnauthorized); !changed {
+ t.Fatal("sign-in error was not rewritten")
+ }
+ for _, secret := range []string{"test-key", "https://ollama.com/connect"} {
+ if strings.Contains(logs.String(), secret) {
+ t.Fatalf("debug log contains sign-in secret %q: %s", secret, logs.String())
+ }
+ }
+}
+
func TestCodexAccessErrorStreamFragmentedFrames(t *testing.T) {
body := "event: error\ndata: {\"type\":\"error\",\"code\":\"authentication_error\",\"message\":\"unauthorized\"}\n\n"
handler := newTestCodexDesktop(t, "http://localhost", "http://localhost", "unused")
diff --git a/server/codex_proxy_test.go b/server/codex_proxy_test.go
index fbe7236ee..c23b177bf 100644
--- a/server/codex_proxy_test.go
+++ b/server/codex_proxy_test.go
@@ -1,6 +1,7 @@
package server
import (
+ "net"
"net/http"
"net/http/httptest"
"testing"
@@ -39,3 +40,28 @@ func TestCodexProxyWebSocketUpgradeRequestsHTTPFallback(t *testing.T) {
t.Fatalf("WebSocket fallback response = %d %q, want 426", recorder.Code, recorder.Body.String())
}
}
+
+func TestCodexProxyRemainsLocalOnExposedOllamaListener(t *testing.T) {
+ t.Setenv("HOME", t.TempDir())
+ handler, err := (&Server{addr: &net.TCPAddr{IP: net.IPv4zero, Port: 11434}}).GenerateRoutes()
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ for _, tt := range []struct {
+ path string
+ want int
+ }{
+ {path: "/", want: http.StatusOK},
+ {path: "/api/codex/_health", want: http.StatusForbidden},
+ } {
+ req := httptest.NewRequest(http.MethodGet, "http://192.0.2.1:11434"+tt.path, nil)
+ req.RemoteAddr = "192.0.2.10:1234"
+ recorder := httptest.NewRecorder()
+
+ handler.ServeHTTP(recorder, req)
+ if recorder.Code != tt.want {
+ t.Fatalf("%s status = %d, want %d", tt.path, recorder.Code, tt.want)
+ }
+ }
+}