Real-time monitoring dashboard for Proxmox VE, PBS, Docker, Kubernetes, TrueNAS and vSphere. Self-hosted, with alerts for failed backups, full disks, unhealthy containers and offline nodes.
Go aialertsdashboarddockerdocker-monitoringgohomelabinfrastructure-monitoringkubernetesmonitoringmspproxmoxproxmox-backup-serverproxmox-mail-gatewayproxmox-veself-hostedtruenastypescriptvspherewebhooks
Restrict Ollama provider outbound transport
rcourtman160d8126f2ba
diff --git a/docs/release-control/v6/internal/subsystems/ai-runtime.md b/docs/release-control/v6/internal/subsystems/ai-runtime.mdindex d7966eb6b4..d516d483e3 100644--- a/docs/release-control/v6/internal/subsystems/ai-runtime.md+++ b/docs/release-control/v6/internal/subsystems/ai-runtime.md@@ -115,6 +115,12 @@ That backend/runtime ownership does not require the Patrol product surface toinherit `AI` as its canonical browser route: the customer-facing shell may use`/patrol` while shared AI transport, provider settings, and payload contractsremain the governed technical boundary behind it.+Operator-configured provider base URLs remain part of that backend transport+boundary. Ollama keeps supporting remote or local instances, but+`internal/ai/providers/ollama.go` must normalize the configured base URL and+route requests through the shared restricted outbound HTTP transport so+metadata, link-local, and redirect-escape paths do not bypass the runtime's+egress guardrails.That same operator-facing vocabulary rule applies to the runtime usage surface:`frontend-modern/src/components/AI/AICostDashboard.tsx` must present providerusage and spend backing Pulse Assistant and Patrol rather than generic `AI`diff --git a/internal/ai/chat/service.go b/internal/ai/chat/service.goindex 759a3aac32..57411f3789 100644--- a/internal/ai/chat/service.go+++ b/internal/ai/chat/service.go@@ -950,7 +950,7 @@ func (s *Service) createProviderForModel(modelStr string) (providers.StreamingPrreturn providers.NewGeminiClient(s.cfg.GeminiAPIKey, modelName, "", timeout), nilcase "ollama":baseURL := s.cfg.GetBaseURLForProvider(config.AIProviderOllama)- return providers.NewOllamaClient(modelName, baseURL, s.cfg.OllamaUsername, s.cfg.OllamaPassword, timeout), nil+ return providers.NewOllamaClient(modelName, baseURL, s.cfg.OllamaUsername, s.cfg.OllamaPassword, timeout)case config.AIProviderQuickstart:// Quickstart uses the hosted proxy — no API key needed.// The licenseID is embedded in the client via orgID.diff --git a/internal/ai/chat/service_explore.go b/internal/ai/chat/service_explore.goindex dbb50aa7da..ffe76bc5b3 100644--- a/internal/ai/chat/service_explore.go+++ b/internal/ai/chat/service_explore.go@@ -247,7 +247,7 @@ func (s *Service) createProviderForExplore(modelStr string) (providers.Streamingreturn providers.NewGeminiClient(s.cfg.GeminiAPIKey, modelName, "", exploreHTTPTimeout), nilcase "ollama":baseURL := s.cfg.GetBaseURLForProvider(config.AIProviderOllama)- return providers.NewOllamaClient(modelName, baseURL, s.cfg.OllamaUsername, s.cfg.OllamaPassword, exploreHTTPTimeout), nil+ return providers.NewOllamaClient(modelName, baseURL, s.cfg.OllamaUsername, s.cfg.OllamaPassword, exploreHTTPTimeout)case config.AIProviderQuickstart:// Quickstart uses the hosted proxy and does not require a BYOK key.// The orgID carries the hosted workspace identity for credit accounting.diff --git a/internal/ai/providers/factory.go b/internal/ai/providers/factory.goindex 8a094a96c9..6dda3cd187 100644--- a/internal/ai/providers/factory.go+++ b/internal/ai/providers/factory.go@@ -81,7 +81,7 @@ func NewForProvider(cfg *config.AIConfig, provider, model string) (Provider, errcase config.AIProviderOllama:baseURL := cfg.GetBaseURLForProvider(config.AIProviderOllama)- return NewOllamaClient(model, baseURL, cfg.OllamaUsername, cfg.OllamaPassword, timeout), nil+ return NewOllamaClient(model, baseURL, cfg.OllamaUsername, cfg.OllamaPassword, timeout)case config.AIProviderGemini:apiKey := cfg.GetAPIKeyForProvider(config.AIProviderGemini)diff --git a/internal/ai/providers/integration_test.go b/internal/ai/providers/integration_test.goindex 7c73afab6e..3b211c91aa 100644--- a/internal/ai/providers/integration_test.go+++ b/internal/ai/providers/integration_test.go@@ -27,8 +27,17 @@ func getOllamaURL() string {return "http://127.0.0.1:11434"}+func newIntegrationOllamaClient(t *testing.T, model string) *providers.OllamaClient {+ t.Helper()+ client, err := providers.NewOllamaClient(model, getOllamaURL(), "", "", 0)+ if err != nil {+ t.Fatalf("NewOllamaClient failed: %v", err)+ }+ return client+}+func TestIntegration_Ollama_TestConnection(t *testing.T) {- client := providers.NewOllamaClient("tinyllama", getOllamaURL(), "", "", 0)+ client := newIntegrationOllamaClient(t, "tinyllama")ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)defer cancel()@@ -41,7 +50,7 @@ func TestIntegration_Ollama_TestConnection(t *testing.T) {}func TestIntegration_Ollama_ListModels(t *testing.T) {- client := providers.NewOllamaClient("tinyllama", getOllamaURL(), "", "", 0)+ client := newIntegrationOllamaClient(t, "tinyllama")ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)defer cancel()@@ -62,7 +71,7 @@ func TestIntegration_Ollama_ListModels(t *testing.T) {}func TestIntegration_Ollama_SimpleChat(t *testing.T) {- client := providers.NewOllamaClient("tinyllama", getOllamaURL(), "", "", 0)+ client := newIntegrationOllamaClient(t, "tinyllama")ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)defer cancel()@@ -87,7 +96,7 @@ func TestIntegration_Ollama_SimpleChat(t *testing.T) {}func TestIntegration_Ollama_SystemPrompt(t *testing.T) {- client := providers.NewOllamaClient("tinyllama", getOllamaURL(), "", "", 0)+ client := newIntegrationOllamaClient(t, "tinyllama")ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)defer cancel()@@ -117,7 +126,7 @@ func TestIntegration_Ollama_SystemPrompt(t *testing.T) {}func TestIntegration_Ollama_MultiTurnConversation(t *testing.T) {- client := providers.NewOllamaClient("tinyllama", getOllamaURL(), "", "", 0)+ client := newIntegrationOllamaClient(t, "tinyllama")ctx, cancel := context.WithTimeout(context.Background(), 120*time.Second)defer cancel()@@ -156,7 +165,7 @@ func TestIntegration_Ollama_MultiTurnConversation(t *testing.T) {}func TestIntegration_Ollama_TokenCounting(t *testing.T) {- client := providers.NewOllamaClient("tinyllama", getOllamaURL(), "", "", 0)+ client := newIntegrationOllamaClient(t, "tinyllama")ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)defer cancel()@@ -184,7 +193,7 @@ func TestIntegration_Ollama_TokenCounting(t *testing.T) {}func TestIntegration_Ollama_ErrorHandling_BadModel(t *testing.T) {- client := providers.NewOllamaClient("nonexistent-model-12345", getOllamaURL(), "", "", 0)+ client := newIntegrationOllamaClient(t, "nonexistent-model-12345")ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)defer cancel()@@ -203,7 +212,7 @@ func TestIntegration_Ollama_ErrorHandling_BadModel(t *testing.T) {}func TestIntegration_Ollama_Timeout(t *testing.T) {- client := providers.NewOllamaClient("tinyllama", getOllamaURL(), "", "", 0)+ client := newIntegrationOllamaClient(t, "tinyllama")// Very short timeout - should failctx, cancel := context.WithTimeout(context.Background(), 1*time.Millisecond)@@ -226,7 +235,7 @@ func TestIntegration_Ollama_Timeout(t *testing.T) {// --- More useful tests below ---func TestIntegration_Ollama_JSONOutput(t *testing.T) {- client := providers.NewOllamaClient("tinyllama", getOllamaURL(), "", "", 0)+ client := newIntegrationOllamaClient(t, "tinyllama")ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)defer cancel()@@ -268,7 +277,7 @@ func TestIntegration_Ollama_JSONOutput(t *testing.T) {}func TestIntegration_Ollama_LongResponse(t *testing.T) {- client := providers.NewOllamaClient("tinyllama", getOllamaURL(), "", "", 0)+ client := newIntegrationOllamaClient(t, "tinyllama")ctx, cancel := context.WithTimeout(context.Background(), 120*time.Second)defer cancel()@@ -293,7 +302,7 @@ func TestIntegration_Ollama_LongResponse(t *testing.T) {}func TestIntegration_Ollama_EmptyMessage(t *testing.T) {- client := providers.NewOllamaClient("tinyllama", getOllamaURL(), "", "", 0)+ client := newIntegrationOllamaClient(t, "tinyllama")ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)defer cancel()@@ -314,7 +323,7 @@ func TestIntegration_Ollama_EmptyMessage(t *testing.T) {}func TestIntegration_Ollama_SpecialCharacters(t *testing.T) {- client := providers.NewOllamaClient("tinyllama", getOllamaURL(), "", "", 0)+ client := newIntegrationOllamaClient(t, "tinyllama")ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)defer cancel()@@ -337,7 +346,7 @@ func TestIntegration_Ollama_SpecialCharacters(t *testing.T) {}func TestIntegration_Ollama_ConcurrentRequests(t *testing.T) {- client := providers.NewOllamaClient("tinyllama", getOllamaURL(), "", "", 0)+ client := newIntegrationOllamaClient(t, "tinyllama")const numRequests = 3results := make(chan error, numRequests)@@ -373,7 +382,7 @@ func TestIntegration_Ollama_ConcurrentRequests(t *testing.T) {func TestIntegration_Ollama_InfrastructureAnalysis(t *testing.T) {// This simulates what Pulse actually does - send infrastructure context- client := providers.NewOllamaClient("tinyllama", getOllamaURL(), "", "", 0)+ client := newIntegrationOllamaClient(t, "tinyllama")ctx, cancel := context.WithTimeout(context.Background(), 90*time.Second)defer cancel()@@ -417,7 +426,7 @@ What should I investigate first?`}func TestIntegration_Ollama_ModelName_Preserved(t *testing.T) {- client := providers.NewOllamaClient("tinyllama", getOllamaURL(), "", "", 0)+ client := newIntegrationOllamaClient(t, "tinyllama")ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)defer cancel()@@ -442,7 +451,7 @@ func TestIntegration_Ollama_ModelName_Preserved(t *testing.T) {}func TestIntegration_Ollama_StopReason(t *testing.T) {- client := providers.NewOllamaClient("tinyllama", getOllamaURL(), "", "", 0)+ client := newIntegrationOllamaClient(t, "tinyllama")ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)defer cancel()@@ -462,7 +471,7 @@ func TestIntegration_Ollama_StopReason(t *testing.T) {}func TestIntegration_Ollama_VeryLongInput(t *testing.T) {- client := providers.NewOllamaClient("tinyllama", getOllamaURL(), "", "", 0)+ client := newIntegrationOllamaClient(t, "tinyllama")ctx, cancel := context.WithTimeout(context.Background(), 120*time.Second)defer cancel()@@ -487,7 +496,7 @@ func TestIntegration_Ollama_VeryLongInput(t *testing.T) {}func TestIntegration_Ollama_RapidFireRequests(t *testing.T) {- client := providers.NewOllamaClient("tinyllama", getOllamaURL(), "", "", 0)+ client := newIntegrationOllamaClient(t, "tinyllama")// Send 5 requests in rapid successionfor i := 0; i < 5; i++ {diff --git a/internal/ai/providers/ollama.go b/internal/ai/providers/ollama.goindex 07974fb3c5..7bde1b2a22 100644--- a/internal/ai/providers/ollama.go+++ b/internal/ai/providers/ollama.go@@ -9,8 +9,18 @@ import ("net/http""strings""time"++ "github.com/rcourtman/pulse-go-rewrite/internal/securityutil")+const defaultOllamaBaseURL = "http://localhost:11434"++var ollamaOutboundHTTPOptions = securityutil.RestrictedOutboundHTTPOptions{+ AllowedSchemes: []string{"http", "https"},+ AllowPrivateIPs: true,+ AllowLoopback: true,+}+// OllamaClient implements the Provider interface for Ollama's local APItype OllamaClient struct {model string@@ -23,36 +33,58 @@ type OllamaClient struct {// NewOllamaClient creates a new Ollama API client// timeout is optional - pass 0 to use the default 5 minute timeout-func NewOllamaClient(model, baseURL, username, password string, timeout time.Duration) *OllamaClient {- if baseURL == "" {- baseURL = "http://localhost:11434"- }- // Normalize the URL: strip trailing slashes and /api suffix- // Users sometimes enter http://host:11434/ or http://host:11434/api- baseURL = strings.TrimSuffix(baseURL, "/")- baseURL = strings.TrimSuffix(baseURL, "/api")- baseURL = strings.TrimSuffix(baseURL, "/") // In case it was /api/+func NewOllamaClient(model, baseURL, username, password string, timeout time.Duration) (*OllamaClient, error) {+ normalizedBaseURL, err := normalizeOllamaBaseURL(baseURL)+ if err != nil {+ return nil, err+ }if timeout <= 0 {timeout = 300 * time.Second // Default 5 minutes}return &OllamaClient{- model: model,- baseURL: baseURL,- username: username,- password: password,- client: &http.Client{- Timeout: timeout,- },- streamClient: &http.Client{- // No Timeout set — http.Client.Timeout covers the entire request lifecycle- // including reading the response body, which kills streaming responses from- // slow models (e.g. CPU-only inference). Context cancellation handles timeouts- // for streaming instead.- Transport: &http.Transport{- ResponseHeaderTimeout: timeout, // Still timeout if server never starts responding- },- },+ model: model,+ baseURL: normalizedBaseURL,+ username: username,+ password: password,+ client: newOllamaHTTPClient(timeout, false),+ streamClient: newOllamaHTTPClient(timeout, true),+ }, nil+}++func normalizeOllamaBaseURL(raw string) (string, error) {+ if strings.TrimSpace(raw) == "" {+ raw = defaultOllamaBaseURL+ }++ baseURL, err := securityutil.NormalizeHTTPBaseURL(raw, "")+ if err != nil {+ return "", fmt.Errorf("normalize Ollama base URL: %w", err)}++ baseURL.Path = strings.TrimSuffix(baseURL.Path, "/")+ baseURL.Path = strings.TrimSuffix(baseURL.Path, "/api")+ baseURL.Path = strings.TrimSuffix(baseURL.Path, "/")+ baseURL.RawPath = ""++ return baseURL.String(), nil+}++func newOllamaHTTPClient(timeout time.Duration, streaming bool) *http.Client {+ clientTimeout := timeout+ if streaming {+ clientTimeout = 0+ }++ client := securityutil.NewRestrictedOutboundHTTPClient(clientTimeout, ollamaOutboundHTTPOptions)+ if streaming {+ if transport, ok := client.Transport.(*http.Transport); ok {+ // Streaming relies on context cancellation instead of a full client timeout,+ // but it should still fail if the server never starts responding.+ transport.ResponseHeaderTimeout = timeout+ }+ }++ return client}func (c *OllamaClient) applyAuth(req *http.Request) {diff --git a/internal/ai/providers/ollama_test.go b/internal/ai/providers/ollama_test.goindex 9f48a88e09..c938dc801e 100644--- a/internal/ai/providers/ollama_test.go+++ b/internal/ai/providers/ollama_test.go@@ -6,11 +6,19 @@ import ("net/http""net/http/httptest""testing"+ "time""github.com/stretchr/testify/assert""github.com/stretchr/testify/require")+func newTestOllamaClient(t *testing.T, model, baseURL, username, password string, timeout time.Duration) *OllamaClient {+ t.Helper()+ client, err := NewOllamaClient(model, baseURL, username, password, timeout)+ require.NoError(t, err)+ return client+}+func TestOllamaClient_ChatStream_Success(t *testing.T) {// Mock Ollama Stream (NDJSON)mockResponse := `{"model":"llama3","created_at":"2023-08-04T08:52:19.385406455-07:00","message":{"role":"assistant","content":"Hello"},"done":false}@@ -35,7 +43,7 @@ func TestOllamaClient_ChatStream_Success(t *testing.T) {}))defer server.Close()- client := NewOllamaClient("llama3", server.URL, "", "", 0)+ client := newTestOllamaClient(t, "llama3", server.URL, "", "", 0)var content stringvar done bool@@ -78,7 +86,7 @@ func TestOllamaClient_ChatStream_ToolCall(t *testing.T) {}))defer server.Close()- client := NewOllamaClient("llama3", server.URL, "", "", 0)+ client := newTestOllamaClient(t, "llama3", server.URL, "", "", 0)var toolsFound []string@@ -111,7 +119,7 @@ func TestOllamaClient_ChatStream_Errors(t *testing.T) {}))defer server.Close()- client := NewOllamaClient("llama3", server.URL, "", "", 0)+ client := newTestOllamaClient(t, "llama3", server.URL, "", "", 0)err := client.ChatStream(context.Background(), ChatRequest{Messages: []Message{{Role: "user"}}}, func(e StreamEvent) {})assert.Error(t, err)@@ -132,7 +140,7 @@ func TestOllamaClient_ListModels(t *testing.T) {}))defer server.Close()- client := NewOllamaClient("llama3", server.URL, "", "", 0)+ client := newTestOllamaClient(t, "llama3", server.URL, "", "", 0)models, err := client.ListModels(context.Background())require.NoError(t, err)@@ -153,11 +161,17 @@ func TestNewOllamaClient_Normalization(t *testing.T) {}for _, tt := range tests {- client := NewOllamaClient("model", tt.input, "", "", 0)+ client := newTestOllamaClient(t, "model", tt.input, "", "", 0)assert.Equal(t, tt.expect, client.baseURL)}}+func TestNewOllamaClient_RejectsCredentialedBaseURL(t *testing.T) {+ _, err := NewOllamaClient("llama3", "http://user:pass@localhost:11434", "", "", 0)+ require.Error(t, err)+ assert.Contains(t, err.Error(), "userinfo is not allowed")+}+func TestOllamaClient_Chat_Success(t *testing.T) {server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {assert.Equal(t, "/api/chat", r.URL.Path)@@ -186,7 +200,7 @@ func TestOllamaClient_Chat_Success(t *testing.T) {}))defer server.Close()- client := NewOllamaClient("llama3", server.URL, "", "", 0)+ client := newTestOllamaClient(t, "llama3", server.URL, "", "", 0)resp, err := client.Chat(context.Background(), ChatRequest{Messages: []Message{{Role: "user", Content: "Hi"}},Tools: []Tool{@@ -233,7 +247,7 @@ func TestOllamaClient_TestConnection(t *testing.T) {}))defer server.Close()- client := NewOllamaClient("llama3", server.URL, "unai", "secret", 0)+ client := newTestOllamaClient(t, "llama3", server.URL, "unai", "secret", 0)err := client.TestConnection(context.Background())require.NoError(t, err)assert.Equal(t, 1, versionHits)@@ -241,12 +255,20 @@ func TestOllamaClient_TestConnection(t *testing.T) {}func TestOllamaClient_SupportsThinking(t *testing.T) {- client := NewOllamaClient("llama3", "http://localhost:11434", "", "", 0)+ client := newTestOllamaClient(t, "llama3", "http://localhost:11434", "", "", 0)if client.SupportsThinking("llama3") {t.Fatal("expected SupportsThinking to be false")}}+func TestOllamaClient_TestConnection_BlocksMetadataServiceHost(t *testing.T) {+ client := newTestOllamaClient(t, "llama3", "http://169.254.169.254:11434", "", "", 0)++ err := client.TestConnection(context.Background())+ require.Error(t, err)+ assert.Contains(t, err.Error(), "metadata service address is not allowed")+}+func TestOllamaClient_TestConnection_ModelUnavailable(t *testing.T) {server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {switch r.URL.Path {@@ -262,7 +284,7 @@ func TestOllamaClient_TestConnection_ModelUnavailable(t *testing.T) {}))defer server.Close()- client := NewOllamaClient("llama3", server.URL, "", "", 0)+ client := newTestOllamaClient(t, "llama3", server.URL, "", "", 0)err := client.TestConnection(context.Background())require.Error(t, err)assert.Contains(t, err.Error(), `model "llama3" is not available`)