Get up and running with Kimi, GLM, MiniMax, DeepSeek, gpt-oss, Qwen, Gemma and other models.
openai: clarify Responses authentication errors (#19004)
Eva H8e4dad49f9f5
diff --git a/middleware/openai.go b/middleware/openai.goindex 3f109346e..722373f4e 100644--- a/middleware/openai.go+++ b/middleware/openai.go@@ -542,6 +542,15 @@ func (w *ResponsesWriter) writeResponse(data []byte) (int, error) {func (w *ResponsesWriter) Write(data []byte) (int, error) {code := w.ResponseWriter.Status()+ // Cloud /v1/responses replies bypass this native response writer.+ if code == http.StatusUnauthorized {+ var authorizationError api.AuthorizationError+ if err := json.Unmarshal(data, &authorizationError); err != nil {+ authorizationError.SigninURL = ""+ }+ w.ResponseWriter.Header().Set("Content-Type", "application/json")+ return len(data), json.NewEncoder(w.ResponseWriter).Encode(openai.NewResponsesAuthenticationError(authorizationError.SigninURL))+ }if code != http.StatusOK {return w.writeError(data)}@@ -1110,25 +1119,31 @@ func (w *WebSearchResponsesWriter) writeWebSearchError(err error, usage api.Metrmessage := err.Error()status := http.StatusBadGatewayerrorCode := "api_error"+ signinURL := ""var authorizationError api.AuthorizationErrorvar statusError api.StatusErrorswitch {case errors.As(err, &authorizationError):status = authorizationError.StatusCodeerrorCode = "authentication_error"- if authorizationError.SigninURL != "" {- message += "; sign in at " + authorizationError.SigninURL- }+ message = openai.ResponsesSignInMessage+ signinURL = authorizationError.SigninURLcase errors.As(err, &statusError):status = statusError.StatusCodeif status == http.StatusTooManyRequests {errorCode = "rate_limit_exceeded"+ } else if status == http.StatusUnauthorized {+ errorCode = "authentication_error"+ message = openai.ResponsesSignInMessage}}if !w.inner.stream {w.ResponseWriter.Header().Set("Content-Type", "application/json")w.ResponseWriter.WriteHeader(status)w.done = true+ if errorCode == "authentication_error" {+ return json.NewEncoder(w.ResponseWriter).Encode(openai.NewResponsesAuthenticationError(signinURL))+ }return json.NewEncoder(w.ResponseWriter).Encode(openai.NewError(status, message))}w.ResponseWriter.Header().Set("Content-Type", "text/event-stream")@@ -1142,6 +1157,9 @@ func (w *WebSearchResponsesWriter) writeWebSearchError(err error, usage api.Metr"input_tokens_details": map[string]any{"cached_tokens": optionalIntValue(usage.PromptEvalCachedCount)},},}+ if signinURL != "" {+ response["signin_url"] = signinURL+ }initialEvents := w.inner.converter.Process(api.ChatResponse{})for _, event := range initialEvents {if err := w.inner.writeEvent(event.Event, event.Data); err != nil {diff --git a/middleware/responses_errors_test.go b/middleware/responses_errors_test.gonew file mode 100644index 000000000..a9ca2f10d--- /dev/null+++ b/middleware/responses_errors_test.go@@ -0,0 +1,124 @@+package middleware++import (+ "encoding/json"+ "fmt"+ "net/http"+ "net/http/httptest"+ "strings"+ "testing"++ "github.com/gin-gonic/gin"+ "github.com/ollama/ollama/api"+ "github.com/ollama/ollama/openai"+)++func assertResponsesAuthenticationError(t *testing.T, body string, stream bool, signinURL string) {+ t.Helper()+ data := []byte(body)+ if stream {+ data = nil+ for _, line := range strings.Split(body, "\n") {+ if !strings.HasPrefix(line, "data: ") {+ continue+ }+ var event struct {+ Type string `json:"type"`+ Response json.RawMessage `json:"response"`+ }+ if err := json.Unmarshal([]byte(strings.TrimPrefix(line, "data: ")), &event); err != nil {+ t.Fatal(err)+ }+ if event.Type == "response.completed" {+ t.Fatalf("authentication failure emitted completion: %s", body)+ }+ if event.Type == "response.failed" {+ if data != nil {+ t.Fatalf("multiple terminal failures: %s", body)+ }+ data = event.Response+ }+ }+ }+ var response openai.ResponsesErrorResponse+ if err := json.Unmarshal(data, &response); err != nil {+ t.Fatalf("invalid authentication error: %v: %s", err, body)+ }+ if response.Error.Message != "This model requires an Ollama account. Please sign in to Ollama to use this model." || response.Error.Code == nil || *response.Error.Code != "authentication_error" {+ t.Fatalf("unexpected authentication error: %s", body)+ }+ if response.SigninURL != signinURL {+ t.Fatalf("sign-in metadata = %q, want %q", response.SigninURL, signinURL)+ }+}++func TestResponsesMiddlewareNativeAuthenticationErrors(t *testing.T) {+ gin.SetMode(gin.TestMode)+ const signinURL = "https://ollama.com/connect?key=synthetic-secret"+ for _, test := range []struct {+ name string+ stream, webSearch, afterContent bool+ }{+ {"JSON", false, false, false},+ {"streaming request", true, false, false},+ {"web search JSON", false, true, false},+ {"web search before stream", true, true, false},+ {"web search during stream", true, true, true},+ } {+ t.Run(test.name, func(t *testing.T) {+ router := gin.New()+ router.POST("/v1/responses", ResponsesMiddleware(), func(c *gin.Context) {+ if test.afterContent {+ data, _ := json.Marshal(api.ChatResponse{Message: api.Message{Role: "assistant", Content: "partial answer"}})+ _, _ = c.Writer.Write(data)+ c.Writer.Flush()+ }+ c.JSON(http.StatusUnauthorized, gin.H{"error": "unauthorized", "signin_url": signinURL})+ if test.afterContent {+ _, _ = c.Writer.Write([]byte(`{"done":true}`))+ }+ })+ tools := "[]"+ if test.webSearch {+ tools = `[{"type":"web_search"}]`+ }+ body := fmt.Sprintf(`{"model":"test","input":"hello","stream":%t,"tools":%s}`, test.stream, tools)+ req := httptest.NewRequest(http.MethodPost, "/v1/responses", strings.NewReader(body))+ req.Header.Set("Content-Type", "application/json")+ recorder := httptest.NewRecorder()+ router.ServeHTTP(recorder, req)+ streamError := test.stream && test.webSearch+ wantStatus := http.StatusUnauthorized+ if streamError {+ wantStatus = http.StatusOK+ }+ if recorder.Code != wantStatus {+ t.Fatalf("status = %d, want %d: %s", recorder.Code, wantStatus, recorder.Body.String())+ }+ assertResponsesAuthenticationError(t, recorder.Body.String(), streamError, signinURL)+ if test.afterContent && !strings.Contains(recorder.Body.String(), "partial answer") {+ t.Fatal("previous output was discarded")+ }+ })+ }+}++func TestResponsesMiddlewareDoesNotInferAuthenticationFromMessage(t *testing.T) {+ gin.SetMode(gin.TestMode)+ router := gin.New()+ router.POST("/v1/responses", ResponsesMiddleware(), func(c *gin.Context) {+ c.JSON(http.StatusInternalServerError, gin.H{"error": "unauthorized"})+ })+ req := httptest.NewRequest(http.MethodPost, "/v1/responses", strings.NewReader(`{"model":"test","input":"hello"}`))+ req.Header.Set("Content-Type", "application/json")+ recorder := httptest.NewRecorder()+ router.ServeHTTP(recorder, req)++ var response openai.ErrorResponse+ if err := json.Unmarshal(recorder.Body.Bytes(), &response); err != nil {+ t.Fatal(err)+ }+ if recorder.Code != http.StatusInternalServerError || response.Error.Type != "api_error" || response.Error.Message != "unauthorized" {+ t.Fatalf("non-authentication error was reclassified: status=%d body=%s", recorder.Code, recorder.Body.String())+ }+}diff --git a/middleware/responses_web_search_test.go b/middleware/responses_web_search_test.goindex 92f57ddd6..accab325b 100644--- a/middleware/responses_web_search_test.go+++ b/middleware/responses_web_search_test.go@@ -132,9 +132,7 @@ func TestWebSearchResponsesWriterNonStreamingAuthorizationError(t *testing.T) {if recorder.Code != http.StatusUnauthorized {t.Fatalf("status = %d, want %d", recorder.Code, http.StatusUnauthorized)}- if body := recorder.Body.String(); !strings.Contains(body, "https://ollama.com/signin") {- t.Fatalf("missing sign-in URL: %s", body)- }+ assertResponsesAuthenticationError(t, recorder.Body.String(), false, "https://ollama.com/signin")}func TestWebSearchResponsesWriterStreamingAuthorizationError(t *testing.T) {@@ -154,10 +152,7 @@ func TestWebSearchResponsesWriterStreamingAuthorizationError(t *testing.T) {if recorder.Code != http.StatusOK {t.Fatalf("status = %d, want %d", recorder.Code, http.StatusOK)}- body := recorder.Body.String()- if !strings.Contains(body, "response.failed") || !strings.Contains(body, "https://ollama.com/signin") {- t.Fatalf("missing streaming authorization error: %s", body)- }+ assertResponsesAuthenticationError(t, recorder.Body.String(), true, "https://ollama.com/signin")}func TestWebSearchResponsesWriterStreamingRateLimitError(t *testing.T) {@@ -247,6 +242,9 @@ func TestWebSearchResponsesWriterPreservesFollowUpErrors(t *testing.T) {if recorder.Code != test.status || !strings.Contains(recorder.Body.String(), test.wantInBody) {t.Fatalf("response status=%d body=%s", recorder.Code, recorder.Body.String())}+ if test.status == http.StatusUnauthorized {+ assertResponsesAuthenticationError(t, recorder.Body.String(), false, test.wantInBody)+ }})}}diff --git a/openai/responses_errors.go b/openai/responses_errors.gonew file mode 100644index 000000000..d2938fa57--- /dev/null+++ b/openai/responses_errors.go@@ -0,0 +1,17 @@+package openai++// ResponsesSignInMessage is safe to display without device sign-in details.+const ResponsesSignInMessage = "This model requires an Ollama account. Please sign in to Ollama to use this model."++type ResponsesErrorResponse struct {+ Error Error `json:"error"`+ SigninURL string `json:"signin_url,omitempty"`+}++func NewResponsesAuthenticationError(signinURL string) ResponsesErrorResponse {+ code := "authentication_error"+ return ResponsesErrorResponse{+ Error: Error{Message: ResponsesSignInMessage, Type: code, Code: &code},+ SigninURL: signinURL,+ }+}diff --git a/server/cloud_proxy.go b/server/cloud_proxy.goindex 99954adf8..93b114290 100644--- a/server/cloud_proxy.go+++ b/server/cloud_proxy.go@@ -210,7 +210,7 @@ func proxyCloudRequestWithPath(c *gin.Context, body []byte, path string, disableif err := cloudProxySignRequest(outReq.Context(), outReq); err != nil {slog.Warn("cloud proxy signing failed", "error", err)- writeCloudUnauthorized(c)+ writeCloudUnauthorized(c, path)return}@@ -372,14 +372,23 @@ func hasWebSearchTool(path string, body []byte) bool {return false}-func writeCloudUnauthorized(c *gin.Context) {+func writeCloudUnauthorized(c *gin.Context, path string) {signinURL, err := cloudProxySigninURL()if err != nil {- c.JSON(http.StatusUnauthorized, gin.H{"error": "unauthorized"})+ signinURL = ""+ }+ // Responses passthrough runs before the compatibility writer. Requests+ // routed through /api/chat (including web search) still need native errors.+ if path == "/v1/responses" {+ c.JSON(http.StatusUnauthorized, openai.NewResponsesAuthenticationError(signinURL))return}- c.JSON(http.StatusUnauthorized, gin.H{"error": "unauthorized", "signin_url": signinURL})+ response := gin.H{"error": "unauthorized"}+ if err == nil {+ response["signin_url"] = signinURL+ }+ c.JSON(http.StatusUnauthorized, response)}func signCloudProxyRequest(ctx context.Context, req *http.Request) error {diff --git a/server/routes_cloud_test.go b/server/routes_cloud_test.goindex a5c33df1d..43075c5ee 100644--- a/server/routes_cloud_test.go+++ b/server/routes_cloud_test.go@@ -18,6 +18,7 @@ import ("github.com/ollama/ollama/api"internalcloud "github.com/ollama/ollama/internal/cloud""github.com/ollama/ollama/middleware"+ "github.com/ollama/ollama/openai""github.com/ollama/ollama/version")@@ -1202,6 +1203,160 @@ func TestCloudPassthroughSkipsAnthropicWebSearchLegacySuffix(t *testing.T) {}}+func TestCloudResponsesSigningFailureReturnsStructuredError(t *testing.T) {+ gin.SetMode(gin.TestMode)+ setTestHome(t, t.TempDir())++ originalSignRequest := cloudProxySignRequest+ originalSigninURL := cloudProxySigninURL+ cloudProxySignRequest = func(context.Context, *http.Request) error {+ return errors.New("synthetic signing failure")+ }+ t.Cleanup(func() {+ cloudProxySignRequest = originalSignRequest+ cloudProxySigninURL = originalSigninURL+ })++ s := &Server{}+ router, err := s.GenerateRoutes()+ if err != nil {+ t.Fatal(err)+ }++ const signinURL = "https://ollama.com/connect?name=test&key=synthetic-device-key"+ for _, request := range []struct {+ name string+ path string+ body string+ withSigninURL bool+ }{+ {"non-streaming", "/v1/responses", `{"model":"test:cloud","input":"hello","stream":false}`, true},+ {"streaming", "/v1/responses", `{"model":"test:cloud","input":"hello","stream":true}`, true},+ {"web search", "/v1/responses", `{"model":"test:cloud","input":"hello","stream":false,"tools":[{"type":"web_search"}]}`, true},+ {"compaction", "/v1/responses/compact", `{"model":"test:cloud","input":[{"role":"user","content":"hello"}]}`, true},+ {"triggered compaction", "/v1/responses", `{"model":"test:cloud","stream":true,"input":[{"role":"user","content":"hello"},{"type":"compaction_trigger"}]}`, true},+ {"without sign-in URL", "/v1/responses", `{"model":"test:cloud","input":"hello","stream":false}`, false},+ {"web search without sign-in URL", "/v1/responses", `{"model":"test:cloud","input":"hello","stream":false,"tools":[{"type":"web_search"}]}`, false},+ } {+ t.Run(request.name, func(t *testing.T) {+ cloudProxySigninURL = func() (string, error) {+ if !request.withSigninURL {+ return "", errors.New("synthetic sign-in URL failure")+ }+ return signinURL, nil+ }++ req := httptest.NewRequest(http.MethodPost, request.path, strings.NewReader(request.body))+ req.Header.Set("Content-Type", "application/json")+ recorder := httptest.NewRecorder()+ router.ServeHTTP(recorder, req)++ if recorder.Code != http.StatusUnauthorized {+ t.Fatalf("status = %d, want 401: %s", recorder.Code, recorder.Body.String())+ }+ if got := recorder.Header().Get("Content-Type"); !strings.HasPrefix(got, "application/json") {+ t.Fatalf("content type = %q, want application/json", got)+ }+ var response struct {+ Error openai.Error `json:"error"`+ SigninURL *string `json:"signin_url"`+ }+ if err := json.Unmarshal(recorder.Body.Bytes(), &response); err != nil {+ t.Fatalf("invalid Responses error: %v: %s", err, recorder.Body.String())+ }+ if response.Error.Message != "This model requires an Ollama account. Please sign in to Ollama to use this model." {+ t.Errorf("message = %q, want safe sign-in instructions", response.Error.Message)+ }+ if response.Error.Type != "authentication_error" || response.Error.Code == nil || *response.Error.Code != "authentication_error" {+ t.Errorf("unexpected error type or code: %+v", response.Error)+ }+ if request.withSigninURL {+ if response.SigninURL == nil || *response.SigninURL != signinURL {+ t.Errorf("sign-in URL metadata was not preserved: %s", recorder.Body.String())+ }+ } else if response.SigninURL != nil {+ t.Errorf("unexpected sign-in URL metadata: %s", recorder.Body.String())+ }+ })+ }+}++func TestCloudResponsesPreservesUpstreamResponses(t *testing.T) {+ gin.SetMode(gin.TestMode)+ setTestHome(t, t.TempDir())++ originalBaseURL := cloudProxyBaseURL+ originalSignRequest := cloudProxySignRequest+ cloudProxySignRequest = func(context.Context, *http.Request) error { return nil }+ t.Cleanup(func() {+ cloudProxyBaseURL = originalBaseURL+ cloudProxySignRequest = originalSignRequest+ })++ s := &Server{}+ router, err := s.GenerateRoutes()+ if err != nil {+ t.Fatal(err)+ }++ for _, test := range []struct {+ name string+ status int+ contentType string+ body string+ }{+ {"success", http.StatusOK, "application/json", `{"id":"resp_test","object":"response","output":[]}`},+ {"stream", http.StatusOK, "text/event-stream", "event: response.output_text.delta\ndata: {\"delta\":\"hello\"}\n\n"},+ {"native authentication", http.StatusUnauthorized, "application/json", `{"error":"unauthorized","signin_url":"https://ollama.com/connect?key=upstream-device-key"}`},+ {"Responses authentication", http.StatusUnauthorized, "application/json", `{"error":{"message":"Device key is not linked to an account","type":"authentication_error","code":"authentication_error"},"request_id":"upstream-request"}`},+ {"plain authentication", http.StatusUnauthorized, "text/plain", "Unauthorized\n"},+ {"streamed authentication", http.StatusOK, "text/event-stream", "event: response.failed\ndata: {\"type\":\"response.failed\",\"response\":{\"status\":\"failed\",\"error\":{\"code\":\"authentication_error\",\"message\":\"Device key is not linked to an account\"}}}\n\n"},+ {"subscription", http.StatusForbidden, "application/json", `{"error":{"message":"subscription required","code":"subscription_required"}}`},+ {"rate limit", http.StatusTooManyRequests, "application/json", `{"error":{"message":"too many requests","code":"rate_limit_exceeded"}}`},+ } {+ t.Run(test.name, func(t *testing.T) {+ upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if r.URL.Path != "/v1/responses" {+ t.Errorf("upstream path = %q, want /v1/responses", r.URL.Path)+ }+ if got := r.Header.Get("Accept-Encoding"); got != "gzip" {+ t.Errorf("Accept-Encoding = %q, want gzip", got)+ }+ w.Header().Set("Content-Type", test.contentType)+ w.Header().Set("X-Request-Id", "upstream-request")+ if test.status == http.StatusTooManyRequests {+ w.Header().Set("Retry-After", "30")+ }+ w.WriteHeader(test.status)+ _, _ = io.WriteString(w, test.body)+ }))+ defer upstream.Close()+ cloudProxyBaseURL = upstream.URL++ stream := test.contentType == "text/event-stream"+ body := fmt.Sprintf(`{"model":"test:cloud","input":"hello","stream":%t}`, stream)+ req := httptest.NewRequest(http.MethodPost, "/v1/responses", strings.NewReader(body))+ req.Header.Set("Content-Type", "application/json")+ req.Header.Set("Accept-Encoding", "gzip")+ recorder := httptest.NewRecorder()+ router.ServeHTTP(recorder, req)++ if recorder.Code != test.status || recorder.Body.String() != test.body {+ t.Fatalf("upstream response changed: status = %d, body = %s", recorder.Code, recorder.Body.String())+ }+ if got := recorder.Header().Get("Content-Type"); got != test.contentType {+ t.Errorf("content type = %q, want %q", got, test.contentType)+ }+ if recorder.Header().Get("X-Request-Id") != "upstream-request" {+ t.Error("request ID header was not preserved")+ }+ if test.status == http.StatusTooManyRequests && recorder.Header().Get("Retry-After") != "30" {+ t.Error("Retry-After header was not preserved")+ }+ })+ }+}+func TestCloudPassthroughSigningFailureReturnsUnauthorized(t *testing.T) {gin.SetMode(gin.TestMode)setTestHome(t, t.TempDir())