Skip to content

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

app: sign model recommendation endpoint (#17919)

Parth Sareen124e9af9d281
diff --git a/app/cmd/app/app_darwin.go b/app/cmd/app/app_darwin.go
index 9c4cd1e7c..6f5fd3f08 100644
--- a/app/cmd/app/app_darwin.go
+++ b/app/cmd/app/app_darwin.go
@@ -31,6 +31,7 @@ import (
appui "github.com/ollama/ollama/app/ui"
"github.com/ollama/ollama/app/updater"
"github.com/ollama/ollama/app/version"
+ ollamaAuth "github.com/ollama/ollama/auth"
"github.com/ollama/ollama/cmd/launch"
"github.com/ollama/ollama/envconfig"
"github.com/ollama/ollama/internal/modelref"
@@ -92,9 +93,7 @@ var (
claudeRecommendationsEndpoint = func() string {
return strings.TrimRight(appui.OllamaDotCom, "/") + "/api/experimental/model-recommendations?app=claude-desktop"
}
- claudeDownloadEndpoint = func() string {
- return claudeDesktopDownloadEndpoint(appui.OllamaDotCom)
- }
+ signOllamaData = ollamaAuth.Sign
claudeModelsLoader = loadClaudeDesktopModels
claudeAvailableModels []proxy.ClaudeDesktopModel
claudeModelSource string
@@ -462,7 +461,12 @@ func preserveClaudeDesktopEntitlements(fallback, previous []proxy.ClaudeDesktopM
}
func loadClaudeDesktopModels(ctx context.Context) ([]proxy.ClaudeDesktopModel, string) {
- models, err := proxy.FetchClaudeDesktopModels(ctx, claudeRecommendationsClient, claudeRecommendationsEndpoint())
+ req, err := newSignedOllamaRequest(ctx, http.MethodGet, claudeRecommendationsEndpoint())
+ if err != nil {
+ slog.Debug("could not prepare Claude Desktop model recommendations request", "error", err)
+ return proxy.UnverifyClaudeDesktopCloudEntitlements(proxy.DefaultClaudeDesktopModels()), "fallback"
+ }
+ models, err := proxy.FetchClaudeDesktopModels(claudeRecommendationsClient, req)
if err == nil {
return models, "endpoint"
}
@@ -1066,9 +1070,36 @@ func claudeDesktopDownloadEndpoint(baseURL string) string {
return strings.TrimRight(baseURL, "/") + "/download-app?app=claude-desktop&type=mac-zip"
}
-//export ClaudeDesktopDownloadURL
-func ClaudeDesktopDownloadURL() *C.char {
- return C.CString(claudeDownloadEndpoint())
+func newSignedOllamaRequest(ctx context.Context, method, endpoint string) (*http.Request, error) {
+ req, err := http.NewRequestWithContext(ctx, method, endpoint, nil)
+ if err != nil {
+ return nil, err
+ }
+ query := req.URL.Query()
+ query.Set("ts", strconv.FormatInt(time.Now().Unix(), 10))
+ req.URL.RawQuery = query.Encode()
+ signature, err := signOllamaData(ctx, []byte(fmt.Sprintf("%s,%s", req.Method, req.URL.RequestURI())))
+ if err != nil {
+ return nil, fmt.Errorf("sign request: %w", err)
+ }
+ req.Header.Set("Authorization", signature)
+ return req, nil
+}
+
+//export ClaudeDesktopDownloadRequest
+func ClaudeDesktopDownloadRequest(authorization **C.char) *C.char {
+ if authorization == nil {
+ return nil
+ }
+ *authorization = nil
+
+ req, err := newSignedOllamaRequest(context.Background(), http.MethodGet, claudeDesktopDownloadEndpoint(appui.OllamaDotCom))
+ if err != nil {
+ slog.Warn("failed to prepare Claude Desktop download request", "error", err)
+ return nil
+ }
+ *authorization = C.CString(req.Header.Get("Authorization"))
+ return C.CString(req.URL.String())
}
//export InstallClaudeDesktopArchive
diff --git a/app/cmd/app/app_darwin.h b/app/cmd/app/app_darwin.h
index da3098fdf..f1f526351 100644
--- a/app/cmd/app/app_darwin.h
+++ b/app/cmd/app/app_darwin.h
@@ -65,5 +65,5 @@ enum ClaudeInstallResult
ClaudeInstallFailed,
};
enum ClaudeInstallResult installClaudeDesktop(void);
-char *ClaudeDesktopDownloadURL(void);
+char *ClaudeDesktopDownloadRequest(char **authorization);
bool InstallClaudeDesktopArchive(const char *archivePath);
diff --git a/app/cmd/app/app_darwin.m b/app/cmd/app/app_darwin.m
index 4e8546fc0..d76a6bd61 100644
--- a/app/cmd/app/app_darwin.m
+++ b/app/cmd/app/app_darwin.m
@@ -768,6 +768,29 @@ static NSImage *ollamaApplicationIcon(void) {
return ClaudeInstallCancelled;
}
+ char *downloadAuthorization = NULL;
+ char *downloadURL = ClaudeDesktopDownloadRequest(&downloadAuthorization);
+ NSString *downloadURLString = downloadURL == NULL
+ ? nil
+ : [NSString stringWithUTF8String:downloadURL];
+ NSString *authorization = downloadAuthorization == NULL
+ ? nil
+ : [NSString stringWithUTF8String:downloadAuthorization];
+ free(downloadURL);
+ free(downloadAuthorization);
+ NSURL *url = downloadURLString == nil
+ ? nil
+ : [NSURL URLWithString:downloadURLString];
+ if (url == nil || authorization.length == 0) {
+ NSError *error = [NSError
+ errorWithDomain:@"com.ollama.app"
+ code:3
+ userInfo:@{NSLocalizedDescriptionKey:
+ @"Ollama could not authenticate the download request."}];
+ [self showClaudeDownloadFailure:error];
+ return ClaudeInstallFailed;
+ }
+
[self.claudeAppRow setInactiveStatusText:@"Downloading Claude…"];
[self.claudeAppRow.integrationSwitch setEnabled:NO];
@@ -797,13 +820,10 @@ static NSImage *ollamaApplicationIcon(void) {
sessionWithConfiguration:configuration
delegate:self
delegateQueue:[NSOperationQueue mainQueue]];
- char *downloadURL = ClaudeDesktopDownloadURL();
- NSString *downloadURLString = downloadURL == NULL
- ? nil
- : [NSString stringWithUTF8String:downloadURL];
- free(downloadURL);
+ NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
+ [request setValue:authorization forHTTPHeaderField:@"Authorization"];
self.claudeDownloadTask = [self.claudeDownloadSession
- downloadTaskWithURL:[NSURL URLWithString:downloadURLString]];
+ downloadTaskWithRequest:request];
[NSApp activateIgnoringOtherApps:YES];
[self.claudeDownloadTask resume];
@@ -822,6 +842,22 @@ static NSImage *ollamaApplicationIcon(void) {
return ClaudeInstallCancelled;
}
+- (void)URLSession:(NSURLSession *)session
+ task:(NSURLSessionTask *)task
+willPerformHTTPRedirection:(NSHTTPURLResponse *)response
+ newRequest:(NSURLRequest *)request
+ completionHandler:(void (^)(NSURLRequest * _Nullable))completionHandler {
+ (void)response;
+ if (session != self.claudeDownloadSession ||
+ task != self.claudeDownloadTask) {
+ completionHandler(request);
+ return;
+ }
+ NSMutableURLRequest *redirect = [request mutableCopy];
+ [redirect setValue:nil forHTTPHeaderField:@"Authorization"];
+ completionHandler(redirect);
+}
+
- (void)URLSession:(NSURLSession *)session
downloadTask:(NSURLSessionDownloadTask *)downloadTask
didWriteData:(int64_t)bytesWritten
diff --git a/app/cmd/app/app_darwin_test.go b/app/cmd/app/app_darwin_test.go
index aac1a489b..ea1398ae1 100644
--- a/app/cmd/app/app_darwin_test.go
+++ b/app/cmd/app/app_darwin_test.go
@@ -44,10 +44,17 @@ func TestMain(m *testing.M) {
}
func TestLoadClaudeDesktopModelsUsesAppEndpoint(t *testing.T) {
+ useTestOllamaRequestSigner(t)
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/api/experimental/model-recommendations" || r.URL.Query().Get("app") != "claude-desktop" {
t.Fatalf("request URL = %q", r.URL.String())
}
+ if r.URL.Query().Get("ts") == "" {
+ t.Fatal("model recommendations request is missing its signed timestamp")
+ }
+ if r.Header.Get("Authorization") != "test-public-key:test-signature" {
+ t.Fatal("model recommendations request is missing public-key identity")
+ }
_, _ = w.Write([]byte(`{"recommendations":[{"model":"glm-5.2:cloud","description":"Cloud model","max_output_tokens":262144,"required_plan":"pro"},{"model":"gemma4:26b","description":"Local model","max_output_tokens":262144}]}`))
}))
defer server.Close()
@@ -70,12 +77,94 @@ func TestLoadClaudeDesktopModelsUsesAppEndpoint(t *testing.T) {
}
func TestClaudeDesktopDownloadEndpointUsesTypedZipContract(t *testing.T) {
- endpoint := claudeDesktopDownloadEndpoint("http://127.0.0.1:18080/")
- if endpoint != "http://127.0.0.1:18080/download-app?app=claude-desktop&type=mac-zip" {
- t.Fatalf("endpoint = %q", endpoint)
+ useTestOllamaRequestSigner(t)
+ req, err := newSignedOllamaRequest(context.Background(), http.MethodGet, claudeDesktopDownloadEndpoint("http://127.0.0.1:18080/"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if got, want := req.URL.Path, "/download-app"; got != want {
+ t.Fatalf("path = %q, want %q", got, want)
+ }
+ if query := req.URL.Query(); query.Get("app") != "claude-desktop" || query.Get("type") != "mac-zip" || query.Get("ts") == "" {
+ t.Fatalf("query = %q", req.URL.RawQuery)
+ }
+ if req.Header.Get("Authorization") != "test-public-key:test-signature" {
+ t.Fatal("Claude Desktop download request is missing public-key identity")
+ }
+}
+
+func TestClaudeEndpointRequestsSignCompleteRequestURI(t *testing.T) {
+ previousSigner := signOllamaData
+ t.Cleanup(func() {
+ signOllamaData = previousSigner
+ })
+
+ for _, endpoint := range []string{
+ "https://ollama.com/api/experimental/model-recommendations?app=claude-desktop",
+ "https://ollama.com/download-app?app=claude-desktop&type=mac-zip",
+ } {
+ var challenge string
+ signOllamaData = func(_ context.Context, data []byte) (string, error) {
+ challenge = string(data)
+ return "test-public-key:test-signature", nil
+ }
+ req, err := newSignedOllamaRequest(context.Background(), http.MethodGet, endpoint)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if want := http.MethodGet + "," + req.URL.RequestURI(); challenge != want {
+ t.Fatalf("challenge = %q, want %q", challenge, want)
+ }
+ }
+}
+
+func TestClaudeEndpointRequestsAreNotSentUnsigned(t *testing.T) {
+ previousSigner := signOllamaData
+ signOllamaData = func(context.Context, []byte) (string, error) {
+ return "", errors.New("signing unavailable")
+ }
+ t.Cleanup(func() {
+ signOllamaData = previousSigner
+ })
+
+ called := false
+ server := httptest.NewServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {
+ called = true
+ }))
+ defer server.Close()
+ previousClient := claudeRecommendationsClient
+ previousEndpoint := claudeRecommendationsEndpoint
+ claudeRecommendationsClient = server.Client()
+ claudeRecommendationsEndpoint = func() string {
+ return server.URL + "/api/experimental/model-recommendations?app=claude-desktop"
+ }
+ t.Cleanup(func() {
+ claudeRecommendationsClient = previousClient
+ claudeRecommendationsEndpoint = previousEndpoint
+ })
+
+ if _, source := loadClaudeDesktopModels(context.Background()); source != "fallback" {
+ t.Fatalf("model source = %q, want fallback", source)
+ }
+ if called {
+ t.Fatal("model recommendations request was sent without identity")
+ }
+ if _, err := newSignedOllamaRequest(context.Background(), http.MethodGet, claudeDesktopDownloadEndpoint(server.URL)); err == nil {
+ t.Fatal("Claude Desktop download request succeeded without identity")
}
}
+func useTestOllamaRequestSigner(t *testing.T) {
+ t.Helper()
+ previous := signOllamaData
+ signOllamaData = func(context.Context, []byte) (string, error) {
+ return "test-public-key:test-signature", nil
+ }
+ t.Cleanup(func() {
+ signOllamaData = previous
+ })
+}
+
func TestResolveClaudeDesktopCatalogUsesPersistedSelection(t *testing.T) {
t.Setenv("HOME", t.TempDir())
@@ -526,6 +615,7 @@ func TestClaudeDesktopIntegrationHistoryPersists(t *testing.T) {
}
func TestLoadClaudeDesktopModelsFallsBackWithoutMLX(t *testing.T) {
+ useTestOllamaRequestSigner(t)
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
http.Error(w, "unavailable", http.StatusServiceUnavailable)
}))
diff --git a/internal/proxy/claude_desktop_models.go b/internal/proxy/claude_desktop_models.go
index c1978f400..648db0014 100644
--- a/internal/proxy/claude_desktop_models.go
+++ b/internal/proxy/claude_desktop_models.go
@@ -1,7 +1,6 @@
package proxy
import (
- "context"
"encoding/json"
"errors"
"fmt"
@@ -52,15 +51,15 @@ func (m ClaudeDesktopModel) GatewayID() string {
return m.gateway.ID
}
-// FetchClaudeDesktopModels fetches the public app-aware recommendation
-// contract. Callers are responsible for falling back when this fails.
-func FetchClaudeDesktopModels(ctx context.Context, client *http.Client, endpoint string) ([]ClaudeDesktopModel, error) {
+// FetchClaudeDesktopModels fetches the app-aware recommendation contract.
+// Callers own request construction and are responsible for falling back when
+// the request or response fails.
+func FetchClaudeDesktopModels(client *http.Client, req *http.Request) ([]ClaudeDesktopModel, error) {
if client == nil {
return nil, errors.New("Claude Desktop recommendation client is required")
}
- req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint, nil)
- if err != nil {
- return nil, fmt.Errorf("create Claude Desktop recommendation request: %w", err)
+ if req == nil {
+ return nil, errors.New("Claude Desktop recommendation request is required")
}
resp, err := client.Do(req)
if err != nil {
diff --git a/internal/proxy/claude_desktop_models_test.go b/internal/proxy/claude_desktop_models_test.go
index 5507be1ba..ac183dd62 100644
--- a/internal/proxy/claude_desktop_models_test.go
+++ b/internal/proxy/claude_desktop_models_test.go
@@ -1,7 +1,6 @@
package proxy
import (
- "context"
"encoding/json"
"net/http"
"net/http/httptest"
@@ -28,7 +27,11 @@ func TestFetchClaudeDesktopModelsUsesAppAwareContract(t *testing.T) {
}))
defer server.Close()
- models, err := FetchClaudeDesktopModels(context.Background(), server.Client(), server.URL+"/api/experimental/model-recommendations?app=claude-desktop")
+ req, err := http.NewRequest(http.MethodGet, server.URL+"/api/experimental/model-recommendations?app=claude-desktop", nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ models, err := FetchClaudeDesktopModels(server.Client(), req)
if err != nil {
t.Fatal(err)
}
@@ -60,7 +63,11 @@ func TestFetchClaudeDesktopModelsRejectsInvalidResponses(t *testing.T) {
_, _ = w.Write([]byte(test.body))
}))
defer server.Close()
- if _, err := FetchClaudeDesktopModels(context.Background(), server.Client(), server.URL); err == nil {
+ req, err := http.NewRequest(http.MethodGet, server.URL, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err := FetchClaudeDesktopModels(server.Client(), req); err == nil {
t.Fatal("FetchClaudeDesktopModels succeeded")
}
})
diff --git a/server/model_recommendations.go b/server/model_recommendations.go
index 46708d2c2..bca8e896e 100644
--- a/server/model_recommendations.go
+++ b/server/model_recommendations.go
@@ -199,6 +199,9 @@ func (c *modelRecommendationsCache) refresh(ctx context.Context) error {
return err
}
req.Header.Set("Accept", "application/json")
+ if err := cloudProxySignRequest(reqCtx, req); err != nil {
+ return fmt.Errorf("sign model recommendations request: %w", err)
+ }
resp, err := c.client.Do(req)
if err != nil {
diff --git a/server/model_recommendations_test.go b/server/model_recommendations_test.go
index 67e0d6f46..6e003fbb7 100644
--- a/server/model_recommendations_test.go
+++ b/server/model_recommendations_test.go
@@ -2,7 +2,11 @@ package server
import (
"context"
+ "crypto/ed25519"
+ "crypto/rand"
+ "encoding/base64"
"encoding/json"
+ "encoding/pem"
"errors"
"io"
"net/http"
@@ -20,6 +24,7 @@ import (
"github.com/ollama/ollama/api"
"github.com/ollama/ollama/envconfig"
"github.com/ollama/ollama/format"
+ "golang.org/x/crypto/ssh"
)
func TestModelRecommendationsDefaultOrder(t *testing.T) {
@@ -55,9 +60,13 @@ func TestModelRecommendationsCacheRefreshAppliesServerSideChanges(t *testing.T)
if req.Method != http.MethodGet {
t.Fatalf("method = %q, want GET", req.Method)
}
- if req.URL.String() != modelRecommendationsURL {
- t.Fatalf("url = %q, want %q", req.URL.String(), modelRecommendationsURL)
+ if got := req.URL.Scheme + "://" + req.URL.Host + req.URL.Path; got != modelRecommendationsURL {
+ t.Fatalf("url = %q, want %q", got, modelRecommendationsURL)
}
+ if query := req.URL.Query(); len(query) != 1 || query.Get("ts") == "" {
+ t.Fatalf("query does not contain only the signed timestamp: %q", req.URL.RawQuery)
+ }
+ verifySignedOllamaRequest(t, req)
calls++
payload := api.ModelRecommendationsResponse{Recommendations: first}
@@ -106,6 +115,38 @@ func TestModelRecommendationsCacheRefreshAppliesServerSideChanges(t *testing.T)
}
}
+func TestModelRecommendationsCacheSigningFailurePreservesCurrentData(t *testing.T) {
+ setupModelRecommendationsTestEnv(t, "")
+
+ previousSigner := cloudProxySignRequest
+ cloudProxySignRequest = func(context.Context, *http.Request) error {
+ return errors.New("signing unavailable")
+ }
+ t.Cleanup(func() {
+ cloudProxySignRequest = previousSigner
+ })
+
+ called := false
+ cache := newModelRecommendationsCache()
+ stable := []api.ModelRecommendation{{Model: "stable-local", Description: "stable desc", VRAMBytes: 2 * format.GigaByte}}
+ cache.set(stable)
+ cache.client = &http.Client{Transport: roundTripFunc(func(*http.Request) (*http.Response, error) {
+ called = true
+ return jsonHTTPResponse(http.StatusOK, `{"recommendations":[{"model":"unexpected","description":"unexpected"}]}`), nil
+ })}
+
+ err := cache.refresh(context.Background())
+ if err == nil || !strings.Contains(err.Error(), "signing unavailable") {
+ t.Fatalf("refresh error = %v, want signing failure", err)
+ }
+ if called {
+ t.Fatal("model recommendations request was sent unsigned")
+ }
+ if got := cache.Get(); !slices.Equal(got, stable) {
+ t.Fatalf("recommendations changed on signing failure: got %#v, want %#v", got, stable)
+ }
+}
+
func TestModelRecommendationsCacheRefreshErrorCasesPreserveCurrentData(t *testing.T) {
cases := []struct {
name string
@@ -550,6 +591,7 @@ func setupModelRecommendationsTestEnv(t *testing.T, noCloudEnv string) {
t.Setenv("USERPROFILE", home)
t.Setenv("HOMEDRIVE", filepath.VolumeName(home))
t.Setenv("HOMEPATH", strings.TrimPrefix(home, filepath.VolumeName(home)))
+ writeTestOllamaPrivateKey(t, home)
// Use explicit false rather than empty to avoid platform/env ambiguity.
if noCloudEnv == "" {
@@ -560,6 +602,49 @@ func setupModelRecommendationsTestEnv(t *testing.T, noCloudEnv string) {
t.Cleanup(envconfig.ReloadServerConfig)
}
+func writeTestOllamaPrivateKey(t *testing.T, home string) {
+ t.Helper()
+ _, privateKey, err := ed25519.GenerateKey(rand.Reader)
+ if err != nil {
+ t.Fatal(err)
+ }
+ privateKeyBlock, err := ssh.MarshalPrivateKey(privateKey, "")
+ if err != nil {
+ t.Fatal(err)
+ }
+ keyPath := filepath.Join(home, ".ollama", "id_ed25519")
+ if err := os.MkdirAll(filepath.Dir(keyPath), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(keyPath, pem.EncodeToMemory(privateKeyBlock), 0o600); err != nil {
+ t.Fatal(err)
+ }
+}
+
+func verifySignedOllamaRequest(t *testing.T, req *http.Request) {
+ t.Helper()
+ parts := strings.Split(req.Header.Get("Authorization"), ":")
+ if len(parts) != 2 {
+ t.Fatal("model recommendations request is missing public-key identity")
+ }
+ publicKeyData, err := base64.StdEncoding.DecodeString(parts[0])
+ if err != nil {
+ t.Fatal("model recommendations request contains an invalid public key")
+ }
+ publicKey, err := ssh.ParsePublicKey(publicKeyData)
+ if err != nil {
+ t.Fatal("model recommendations request contains an invalid public key")
+ }
+ signatureData, err := base64.StdEncoding.DecodeString(parts[1])
+ if err != nil {
+ t.Fatal("model recommendations request contains an invalid signature")
+ }
+ challenge := []byte(req.Method + "," + req.URL.RequestURI())
+ if err := publicKey.Verify(challenge, &ssh.Signature{Format: publicKey.Type(), Blob: signatureData}); err != nil {
+ t.Fatal("model recommendations signature does not cover its complete request URI")
+ }
+}
+
func withModelRecommendationsReadRefreshCooldown(t *testing.T, d time.Duration) {
t.Helper()
old := modelRecommendationsReadRefreshCooldown