Get up and running with Kimi, GLM, MiniMax, DeepSeek, gpt-oss, Qwen, Gemma and other models.
proxy: pass through ChatGPT upstream access errors (#19007)
Eva H7fb46364908a
diff --git a/internal/proxy/codex_desktop.go b/internal/proxy/codex_desktop.goindex e2d1d677c..7f976db79 100644--- a/internal/proxy/codex_desktop.go+++ b/internal/proxy/codex_desktop.go@@ -390,11 +390,6 @@ func (h *CodexDesktop) modifyResponse(resp *http.Response) error {h.chatGPTRequests.Add(1)}}- if state.routed {- if err := h.rewriteAccessErrors(resp); err != nil {- return err- }- }if !state.autoReview.buffersResponse(resp.StatusCode) {return nil}diff --git a/internal/proxy/codex_desktop_errors.go b/internal/proxy/codex_desktop_errors.godeleted file mode 100644index a07ab7545..000000000--- a/internal/proxy/codex_desktop_errors.go+++ /dev/null@@ -1,208 +0,0 @@-package proxy--import (- "bufio"- "bytes"- "encoding/json"- "io"- "net/http"- "strings"-)--const (- codexSubscriptionMessage = "This model requires a subscription or extra usage credits. Please upgrade at https://ollama.com/upgrade or add extra usage at https://ollama.com/settings to use this model."- codexSignInMessage = "This model requires an Ollama account. Please sign in to Ollama to use this model."-)--// rewriteAccessErrors changes only Ollama access-error messages. Successful-// events and unrelated errors retain their original bytes and status codes.-func (h *CodexDesktop) rewriteAccessErrors(resp *http.Response) error {- if encoding := resp.Header.Get("Content-Encoding"); encoding != "" && encoding != "identity" {- return nil- }- if strings.HasPrefix(strings.ToLower(resp.Header.Get("Content-Type")), "text/event-stream") {- resp.Body = &codexAccessErrorStream{- ReadCloser: resp.Body,- reader: bufio.NewReader(resp.Body),- rewrite: func(body []byte) ([]byte, bool) { return h.rewriteAccessErrorJSON(body, resp.StatusCode) },- limit: h.maxBodyBytes,- }- resp.ContentLength = -1- resp.Header.Del("Content-Length")- return nil- }- if resp.StatusCode < http.StatusBadRequest {- return nil- }- body, err := io.ReadAll(io.LimitReader(resp.Body, h.maxBodyBytes+1))- if err != nil {- return err- }- if int64(len(body)) > h.maxBodyBytes {- resp.Body = struct {- io.Reader- io.Closer- }{io.MultiReader(bytes.NewReader(body), resp.Body), resp.Body}- return nil- }- resp.Body.Close()- rewritten, changed := h.rewriteAccessErrorJSON(body, resp.StatusCode)- resp.Body = io.NopCloser(bytes.NewReader(rewritten))- if changed {- resp.ContentLength = int64(len(rewritten))- resp.Header.Del("Content-Length")- }- return nil-}--func (h *CodexDesktop) rewriteAccessErrorJSON(body []byte, status int) ([]byte, bool) {- var payload map[string]json.RawMessage- if json.Unmarshal(body, &payload) != nil || payload == nil {- return body, false- }- var kind string- _ = json.Unmarshal(payload["type"], &kind)- if kind == "response.failed" {- rewritten, changed := h.rewriteAccessErrorJSON(payload["response"], status)- if !changed {- return body, false- }- payload["response"] = rewritten- } else {- var message string- var fields map[string]json.RawMessage- stringError := json.Unmarshal(payload["error"], &message) == nil- flatError := false- if !stringError {- if _, nested := payload["error"]; !nested && kind == "error" {- fields = payload- flatError = true- } else if json.Unmarshal(payload["error"], &fields) != nil || fields == nil {- return body, false- }- if json.Unmarshal(fields["message"], &message) != nil {- return body, false- }- }- var code, errorType string- _ = json.Unmarshal(fields["code"], &code)- _ = json.Unmarshal(fields["type"], &errorType)- 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, "reason", reason)- encoded, _ := json.Marshal(rewritten)- if stringError {- payload["error"] = encoded- } else {- fields["message"] = encoded- if !flatError {- payload["error"], _ = json.Marshal(fields)- }- }- }- rewritten, err := json.Marshal(payload)- if err != nil {- return body, false- }- return rewritten, true-}--// Buffer one SSE frame, not the whole response. Oversized frames fall back to-// passthrough so cosmetic error changes cannot interrupt a valid model stream.-type codexAccessErrorStream struct {- io.ReadCloser- reader *bufio.Reader- rewrite func([]byte) ([]byte, bool)- limit int64- pending []byte- err error- passthrough bool-}--func (s *codexAccessErrorStream) Read(p []byte) (int, error) {- if len(p) == 0 {- return 0, nil- }- if len(s.pending) == 0 {- if s.err != nil {- return 0, s.err- }- if s.passthrough {- return s.reader.Read(p)- }- }- if len(s.pending) == 0 && s.err == nil {- var frame []byte- partialLine := false- for {- line, err := s.reader.ReadSlice('\n')- frame = append(frame, line...)- if err != nil && err != bufio.ErrBufferFull {- s.err = err- }- if int64(len(frame)) > s.limit {- s.passthrough = true- break- }- if s.err != nil {- break- }- if !partialLine && (bytes.Equal(line, []byte("\n")) || bytes.Equal(line, []byte("\r\n"))) {- break- }- partialLine = err == bufio.ErrBufferFull- }- s.pending = frame- if !s.passthrough {- s.pending = rewriteCodexErrorFrame(frame, s.rewrite)- }- }- if len(s.pending) > 0 {- n := copy(p, s.pending)- s.pending = s.pending[n:]- return n, nil- }- return 0, s.err-}--func rewriteCodexErrorFrame(frame []byte, rewrite func([]byte) ([]byte, bool)) []byte {- lines := bytes.SplitAfter(frame, []byte("\n"))- var data [][]byte- for _, line := range lines {- if value, ok := bytes.CutPrefix(line, []byte("data:")); ok {- data = append(data, bytes.TrimSpace(value))- }- }- rewritten, changed := rewrite(bytes.Join(data, []byte("\n")))- if !changed {- return frame- }- var result bytes.Buffer- written := false- for _, line := range lines {- if bytes.HasPrefix(line, []byte("data:")) {- if !written {- result.WriteString("data: ")- result.Write(rewritten)- result.WriteByte('\n')- written = true- }- } else {- result.Write(line)- }- }- return result.Bytes()-}diff --git a/internal/proxy/codex_desktop_errors_test.go b/internal/proxy/codex_desktop_errors_test.goindex 79961979a..cba38f6e3 100644--- a/internal/proxy/codex_desktop_errors_test.go+++ b/internal/proxy/codex_desktop_errors_test.go@@ -1,90 +1,27 @@package proxyimport (- "bufio"- "bytes"- "encoding/json""fmt""io"- "log/slog""net/http""net/http/httptest""strconv""strings""testing"- "testing/iotest""time")-const (- testCodexSubscriptionError = "this model requires a subscription or extra usage, upgrade for access at https://ollama.com/upgrade or add extra usage at https://ollama.com/settings (ref: test-reference)"- testCodexSubscriptionCopy = "This model requires a subscription or extra usage credits. Please upgrade at https://ollama.com/upgrade or add extra usage at https://ollama.com/settings to use this model."- testCodexSignInCopy = "This model requires an Ollama account. Please sign in to Ollama to use this model."-)--func TestCodexDesktopAccessErrorCopy(t *testing.T) {+func TestCodexDesktopPreservesUpstreamErrors(t *testing.T) {for _, tt := range []struct {name stringstatus intcontentType stringbody string- want string}{- {- name: "subscription JSON", status: http.StatusForbidden, contentType: "application/json",- body: fmt.Sprintf(`{"error":{"message":%q,"type":"permission_error","code":"subscription_required"},"request_id":"keep-me"}`, testCodexSubscriptionError),- want: testCodexSubscriptionCopy,- },- {- name: "unauthorized JSON", status: http.StatusUnauthorized, contentType: "application/json",- body: `{"error":"unauthorized","signin_url":"https://ollama.com/connect?name=test&key=test-key"}`,- want: testCodexSignInCopy,- },- {- name: "unauthorized JSON with embedded sign-in URL", status: http.StatusUnauthorized, contentType: "application/json",- body: `{"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"}}`,- want: testCodexSignInCopy,- },- {- name: "subscription stream", status: http.StatusOK, contentType: "text/event-stream; charset=utf-8",- body: fmt.Sprintf("event: response.failed\ndata: {\"type\":\"response.failed\",\"sequence_number\":4,\"response\":{\"id\":\"resp_test\",\"status\":\"failed\",\"error\":{\"code\":\"api_error\",\"message\":%q}}}\n\n", testCodexSubscriptionError),- want: testCodexSubscriptionCopy,- },- {- name: "unauthorized stream", status: http.StatusOK, contentType: "text/event-stream",- body: "event: response.failed\ndata: {\"type\":\"response.failed\",\"response\":{\"status\":\"failed\",\"error\":{\"code\":\"authentication_error\",\"message\":\"Sign in: https://ollama.com/connect?name=test&key=test-key\"},\"signin_url\":\"https://ollama.com/connect?name=test&key=test-key\"}}\n\n",- want: testCodexSignInCopy,- },- {- name: "nested SSE error", status: http.StatusOK, contentType: "text/event-stream",- body: "event: error\ndata: {\"type\":\"error\",\"error\":{\"type\":\"authentication_error\",\"message\":\"unauthorized\",\"signin_url\":\"https://ollama.com/connect?name=test&key=test-key\"}}\n\n",- want: testCodexSignInCopy,- },- {- name: "multiline stream with CRLF", status: http.StatusOK, contentType: "text/event-stream",- body: "id: keep-me\r\nevent: error\r\ndata: {\"type\":\"error\",\r\ndata: \"code\":\"authentication_error\",\"message\":\"unauthorized\",\"signin_url\":\"https://ollama.com/connect?name=test&key=test-key\"}\r\n\r\n",- want: testCodexSignInCopy,- },- {- name: "unrelated forbidden error", status: http.StatusForbidden, contentType: "application/json",- body: `{"error":{"message":"cloud is disabled","code":"cloud_disabled"}}`,- },- {- name: "rate limit", status: http.StatusTooManyRequests, contentType: "application/json",- body: `{"error":{"message":"too many requests","code":"rate_limit_exceeded"}}`,- },- {- name: "successful JSON", status: http.StatusOK, contentType: "application/json",- body: `{"status":"completed","output":[{"text":"unauthorized"}]}`,- },- {- name: "successful stream mentioning error text", status: http.StatusOK, contentType: "text/event-stream",- body: fmt.Sprintf("event: response.output_text.delta\ndata: {\"type\":\"response.output_text.delta\",\"delta\":%q}\n\n: heartbeat\n\ndata: [DONE]\n\n", testCodexSubscriptionError),- },- {- name: "malformed error", status: http.StatusForbidden, contentType: "application/json",- body: `{"error":`,- },+ {"sign in", http.StatusUnauthorized, "application/json", `{"error":{"message":"Please sign in to Ollama.","type":"authentication_error","code":"authentication_error"},"signin_url":"https://ollama.com/connect?key=test-key"}`},+ {"subscription", http.StatusPaymentRequired, "application/json", `{"error":{"message":"this model requires a subscription or extra usage","code":"subscription_required"},"request_id":"keep-me"}`},+ {"rate limit", http.StatusTooManyRequests, "application/json", `{"error":{"message":"too many requests","code":"rate_limit_exceeded"}}`},+ {"stream failure", http.StatusOK, "text/event-stream", "event: response.failed\ndata: {\"type\":\"response.failed\",\"response\":{\"status\":\"failed\",\"error\":{\"code\":\"authentication_error\",\"message\":\"Please sign in to Ollama.\"},\"signin_url\":\"https://ollama.com/connect?key=test-key\"}}\n\n"},} {t.Run(tt.name, func(t *testing.T) {upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {@@ -98,7 +35,6 @@ func TestCodexDesktopAccessErrorCopy(t *testing.T) {handler := newTestCodexDesktop(t, upstream.URL, upstream.URL, writeCatalog(t, "test:cloud"))endpoint := httptest.NewServer(handler)defer endpoint.Close()-for _, model := range []string{"test:cloud", "gpt-native"} {req, err := http.NewRequest(http.MethodPost, endpoint.URL+CodexDesktopPathPrefix+"/v1/responses", strings.NewReader(fmt.Sprintf(`{"model":%q,"stream":true}`, model)))if err != nil {@@ -115,108 +51,18 @@ func TestCodexDesktopAccessErrorCopy(t *testing.T) {if err != nil {t.Fatal(err)}- if resp.StatusCode != tt.status || resp.Header.Get("X-Request-ID") != "keep-me" {- t.Errorf("status/headers changed: %d %v", resp.StatusCode, resp.Header)- }- if model == "gpt-native" || tt.want == "" {- if string(body) != tt.body {- t.Errorf("%s response changed: %s", model, body)- }- continue+ if resp.StatusCode != tt.status || resp.Header.Get("Content-Type") != tt.contentType || resp.Header.Get("X-Request-ID") != "keep-me" {+ t.Fatalf("%s status/headers changed: %d %v", model, resp.StatusCode, resp.Header)}- if !strings.Contains(string(body), tt.want) {- t.Errorf("body = %s, want copy %q", body, tt.want)- }- if tt.want == testCodexSignInCopy {- for _, unwanted := range []string{"signin_url", "https://ollama.com/connect", "ollama://connect", "test-key"} {- if strings.Contains(string(body), unwanted) {- t.Errorf("device sign-in link is still visible: %s", body)- }- }- }- if tt.want == testCodexSubscriptionCopy && strings.Contains(string(body), "test-reference") {- t.Errorf("old subscription message is still visible: %s", body)- }- if strings.Contains(tt.contentType, "event-stream") {- if !strings.Contains(string(body), "event:") {- t.Errorf("SSE framing was lost: %s", body)- }- } else if !json.Valid(body) {- t.Errorf("invalid JSON response: %s", body)+ if string(body) != tt.body {+ t.Fatalf("%s body = %q, want %q", model, body, tt.body)}}})}}-func TestCodexDesktopAccessErrorCopySignInMessage(t *testing.T) {- handler := newTestCodexDesktop(t, "http://localhost", "http://localhost", "unused")- body, changed := handler.rewriteAccessErrorJSON([]byte(`{"error":"unauthorized"}`), http.StatusUnauthorized)- want, err := json.Marshal(map[string]string{"error": testCodexSignInCopy})- if err != nil {- t.Fatal(err)- }- if !changed || !bytes.Equal(body, want) {- t.Fatalf("error = %s, want only the short sign-in message %s", body, want)- }-}--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")- upstream := io.NopCloser(iotest.OneByteReader(strings.NewReader(body)))- stream := &codexAccessErrorStream{- ReadCloser: upstream,- reader: bufio.NewReader(upstream),- rewrite: func(body []byte) ([]byte, bool) { return handler.rewriteAccessErrorJSON(body, http.StatusOK) },- limit: defaultMaxBodyBytes,- }- defer stream.Close()- got, err := io.ReadAll(stream)- if err != nil {- t.Fatal(err)- }- if !strings.Contains(string(got), testCodexSignInCopy) || !bytes.HasSuffix(got, []byte("\n\n")) {- t.Fatalf("fragmented event = %s, want rewritten message and intact SSE framing", got)- }-}--func TestCodexAccessErrorStreamOversizedFramePassesThrough(t *testing.T) {- body := "data: " + strings.Repeat("x", 8192) + "\n\n: heartbeat\n\n"- upstream := io.NopCloser(strings.NewReader(body))- stream := &codexAccessErrorStream{- ReadCloser: upstream,- reader: bufio.NewReader(upstream),- rewrite: func([]byte) ([]byte, bool) {- t.Error("oversized frame should not be rewritten")- return nil, false- },- limit: 4096,- }- defer stream.Close()- got, err := io.ReadAll(stream)- if err != nil || string(got) != body {- t.Fatalf("large event was not passed through unchanged: length=%d, error=%v", len(got), err)- }-}--func TestCodexDesktopAccessErrorCopyDoesNotBufferSuccessfulStream(t *testing.T) {+func TestCodexDesktopDoesNotBufferSuccessfulStream(t *testing.T) {first := "event: response.output_text.delta\ndata: {\"type\":\"response.output_text.delta\",\"delta\":\"hello\"}\n\n"release := make(chan struct{})upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {