Skip to content

armgit / Pulse

Public Imported from GitHub
0

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.

Exercise agent redirect credential boundaries

pulse-triage[bot]3f0f7938de29
diff --git a/cmd/pulse-mcp/main_test.go b/cmd/pulse-mcp/main_test.go
index 859bf58aa7..8627d968e6 100644
--- a/cmd/pulse-mcp/main_test.go
+++ b/cmd/pulse-mcp/main_test.go
@@ -4,6 +4,7 @@ import (
"bytes"
"context"
"encoding/json"
+ "fmt"
"io"
"net/http"
"net/http/httptest"
@@ -12,6 +13,7 @@ import (
"sort"
"strings"
"sync"
+ "sync/atomic"
"testing"
"time"
@@ -22,6 +24,102 @@ import (
unified "github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources"
)
+func TestMCPRedirectBoundaryCoversEveryAuthenticatedTransport(t *testing.T) {
+ for _, operation := range []string{"tools/read", "tools/write", "resources/read", "prompt-activity", "live-notifications"} {
+ t.Run(operation, func(t *testing.T) {
+ var destinationRequests atomic.Int32
+ destination := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ destinationRequests.Add(1)
+ if operation == "live-notifications" {
+ _, _ = io.WriteString(w, "event: finding.created\ndata: {\"findingId\":\"off-origin-marker\"}\n\n")
+ } else {
+ _, _ = io.WriteString(w, `{"marker":"off-origin-marker"}`)
+ }
+ }))
+ defer destination.Close()
+ origin := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ http.Redirect(w, r, destination.URL+"/target", http.StatusTemporaryRedirect)
+ }))
+ defer origin.Close()
+ manifest := agentcapabilities.CanonicalManifest()
+ out := &bytes.Buffer{}
+ server := &mcpServer{baseURL: origin.URL, token: "synthetic-token", manifest: &manifest, http: origin.Client(), out: out}
+ switch operation {
+ case "prompt-activity":
+ server.recordWorkflowPromptActivity(context.Background(), "overnight-triage")
+ case "live-notifications":
+ if err := server.streamSSEOnce(context.Background(), agentcapabilities.AgentEventsPath); err == nil {
+ t.Error("off-origin event stream succeeded")
+ }
+ default:
+ method := "tools/call"
+ params := `{"name":"get_fleet_context","arguments":{}}`
+ if operation == "tools/write" {
+ params = `{"name":"set_operator_state","arguments":{"resourceId":"vm:101","body":{"intentionallyOffline":true,"note":"private-write-marker"}}}`
+ } else if operation == "resources/read" {
+ method = "resources/read"
+ params = `{"uri":"pulse://resource/vm:101"}`
+ }
+ input := fmt.Sprintf("{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":%q,\"params\":%s}\n", method, params)
+ server.serve(strings.NewReader(input), out)
+ var response map[string]any
+ if err := json.Unmarshal(out.Bytes(), &response); err != nil {
+ t.Fatalf("decode stdio response: %v", err)
+ }
+ result, _ := response["result"].(map[string]any)
+ if response["error"] == nil && result["isError"] != true {
+ t.Error("off-origin request did not reach MCP as an error")
+ }
+ }
+ if destinationRequests.Load() != 0 {
+ t.Errorf("off-origin destination received %d requests", destinationRequests.Load())
+ }
+ if strings.Contains(out.String(), "off-origin-marker") {
+ t.Error("off-origin data reached the agent")
+ }
+ })
+ }
+}
+
+func TestMCPSameOriginRedirectPreservesWriteAndEventConsumer(t *testing.T) {
+ var writes, events atomic.Int32
+ origin := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.URL.Path != "/accepted" {
+ http.Redirect(w, r, "/accepted", http.StatusPermanentRedirect)
+ return
+ }
+ if r.Header.Get(agentcapabilities.AgentAPITokenHeader) != "synthetic-token" || r.Header.Get(agentcapabilities.AgentSurfaceHeader) != agentcapabilities.AgentSurfacePulseMCP {
+ t.Error("same-origin redirect lost the token or surface header")
+ }
+ if r.Header.Get("Accept") == agentcapabilities.AgentSSEAccept {
+ events.Add(1)
+ _, _ = io.WriteString(w, "event: finding.created\ndata: {\"findingId\":\"same-origin-marker\"}\n\n")
+ return
+ }
+ body, _ := io.ReadAll(r.Body)
+ if r.Method != http.MethodPut || !strings.Contains(string(body), "private-write-marker") || r.Header.Get("Content-Type") != "application/json" {
+ t.Error("same-origin redirect changed the write")
+ }
+ writes.Add(1)
+ _, _ = io.WriteString(w, `{"accepted":true}`)
+ }))
+ defer origin.Close()
+ manifest := agentcapabilities.CanonicalManifest()
+ out := &bytes.Buffer{}
+ server := &mcpServer{baseURL: origin.URL, token: "synthetic-token", manifest: &manifest, http: origin.Client(), out: out}
+ server.serve(strings.NewReader("{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"tools/call\",\"params\":{\"name\":\"set_operator_state\",\"arguments\":{\"resourceId\":\"vm:101\",\"body\":{\"intentionallyOffline\":true,\"note\":\"private-write-marker\"}}}}\n"), out)
+ if writes.Load() != 1 || !strings.Contains(out.String(), `"accepted":true`) || strings.Contains(out.String(), `"isError":true`) {
+ t.Fatalf("same-origin write did not reach the MCP consumer: %s", out)
+ }
+ out.Reset()
+ if err := server.streamSSEOnce(context.Background(), agentcapabilities.AgentEventsPath); err != nil {
+ t.Fatalf("same-origin stream: %v", err)
+ }
+ if events.Load() != 1 || !strings.Contains(out.String(), "same-origin-marker") {
+ t.Fatalf("same-origin event did not reach the MCP consumer: %s", out)
+ }
+}
+
type httpDoerFunc func(*http.Request) (*http.Response, error)
func (f httpDoerFunc) Do(req *http.Request) (*http.Response, error) {
diff --git a/internal/agentcapabilities/http_test.go b/internal/agentcapabilities/http_test.go
index a16cb2ab86..cc4cba8c72 100644
--- a/internal/agentcapabilities/http_test.go
+++ b/internal/agentcapabilities/http_test.go
@@ -9,9 +9,144 @@ import (
"net/http"
"net/http/httptest"
"strings"
+ "sync/atomic"
"testing"
)
+// These are two independent loopback servers, not real Pulse installations.
+// A redirect must not widen the destination of either the token or write body.
+func TestAgentHTTPRedirectsRejectOtherOrigins(t *testing.T) {
+ for _, status := range []int{301, 302, 303, 307, 308} {
+ for _, method := range []string{http.MethodGet, http.MethodPut} {
+ t.Run(fmt.Sprintf("%d/%s", status, method), func(t *testing.T) {
+ var destinationRequests, tokenRequests, bodyRequests atomic.Int32
+ destination := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ destinationRequests.Add(1)
+ if r.Header.Get(AgentAPITokenHeader) != "" {
+ tokenRequests.Add(1)
+ }
+ body, _ := io.ReadAll(r.Body)
+ if len(body) > 0 {
+ bodyRequests.Add(1)
+ }
+ _, _ = io.WriteString(w, `{"unexpected":true}`)
+ }))
+ defer destination.Close()
+ origin := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ http.Redirect(w, r, destination.URL+"/elsewhere?private=redirect-query-marker", status)
+ }))
+ defer origin.Close()
+
+ args := map[string]any{}
+ if method == http.MethodPut {
+ args["body"] = map[string]any{"note": "private-write-marker"}
+ }
+ response, err := CallCapabilityHTTP(context.Background(), origin.Client(), origin.URL, "synthetic-private-token", Capability{Method: method, Path: "/api/example"}, args)
+ if err == nil {
+ t.Errorf("off-origin redirect returned success: status %d", response.StatusCode)
+ } else if strings.Contains(err.Error(), "redirect-query-marker") {
+ t.Error("redirect rejection exposed the destination query")
+ }
+ if got := destinationRequests.Load(); got != 0 {
+ t.Errorf("off-origin destination received %d requests (%d with token, %d with body)", got, tokenRequests.Load(), bodyRequests.Load())
+ }
+ })
+ }
+ }
+}
+
+type redirectTestTransport func(*http.Request) (*http.Response, error)
+
+func (f redirectTestTransport) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) }
+
+func TestAgentHTTPRedirectOriginPolicy(t *testing.T) {
+ for _, tc := range []struct {
+ name, from, to string
+ allowed bool
+ }{
+ {"relative", "https://pulse.example", "/accepted", true},
+ {"same-origin", "https://pulse.example", "https://pulse.example/accepted", true},
+ {"host-case", "https://pulse.example", "https://PULSE.example/accepted", true},
+ {"default-https-port", "https://pulse.example", "https://pulse.example:443/accepted", true},
+ {"default-http-port", "http://pulse.example:80", "http://pulse.example/accepted", true},
+ {"same-nondefault-port", "https://pulse.example:9443", "https://pulse.example:9443/accepted", true},
+ {"other-host", "https://pulse.example", "https://elsewhere.example/accepted", false},
+ {"subdomain", "https://pulse.example", "https://child.pulse.example/accepted", false},
+ {"other-port", "https://pulse.example", "https://pulse.example:9443/accepted", false},
+ {"downgrade", "https://pulse.example", "http://pulse.example/accepted", false},
+ {"upgrade", "http://pulse.example", "https://pulse.example/accepted", false},
+ {"trailing-dot", "https://pulse.example", "https://pulse.example./accepted", false},
+ {"new-userinfo", "https://pulse.example", "https://name:[email protected]/accepted", false},
+ {"retained-userinfo", "https://name:[email protected]", "/accepted", true},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ requests := 0
+ client := &http.Client{Transport: redirectTestTransport(func(r *http.Request) (*http.Response, error) {
+ requests++
+ if requests == 1 {
+ return &http.Response{StatusCode: http.StatusTemporaryRedirect, Header: http.Header{"Location": {tc.to}}, Body: io.NopCloser(strings.NewReader("")), Request: r}, nil
+ }
+ return &http.Response{StatusCode: http.StatusOK, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(`{"version":"v1"}`)), Request: r}, nil
+ })}
+ _, err := FetchManifest(context.Background(), client, tc.from)
+ if (err == nil) != tc.allowed {
+ t.Errorf("redirect allowed = %v, want %v", err == nil, tc.allowed)
+ }
+ wantRequests := 1
+ if tc.allowed {
+ wantRequests = 2
+ }
+ if requests != wantRequests {
+ t.Errorf("transport requests = %d, want %d", requests, wantRequests)
+ }
+ if err != nil && strings.Contains(err.Error(), "redirect-password-marker") {
+ t.Error("redirect rejection exposed userinfo")
+ }
+ })
+ }
+}
+
+func TestAgentHTTPRedirectsPreserveClientPolicy(t *testing.T) {
+ for _, stop := range []error{errors.New("caller redirect refusal"), http.ErrUseLastResponse} {
+ t.Run(stop.Error(), func(t *testing.T) {
+ var calls atomic.Int32
+ origin := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ http.Redirect(w, r, "/accepted", http.StatusTemporaryRedirect)
+ }))
+ defer origin.Close()
+ client := origin.Client()
+ client.CheckRedirect = func(*http.Request, []*http.Request) error { calls.Add(1); return stop }
+ _, err := FetchManifest(context.Background(), client, origin.URL)
+ if err == nil || (stop != http.ErrUseLastResponse && !errors.Is(err, stop)) {
+ t.Fatalf("caller policy error was lost: %v", err)
+ }
+ if calls.Load() != 1 {
+ t.Fatalf("caller policy calls = %d, want 1", calls.Load())
+ }
+ // The guard must not replace policy on a client it does not own.
+ if got := client.CheckRedirect(nil, nil); got != stop {
+ t.Fatal("caller client was mutated")
+ }
+ })
+ }
+}
+
+func TestAgentHTTPRedirectsRetainDefaultLimit(t *testing.T) {
+ var requests atomic.Int32
+ origin := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ requests.Add(1)
+ http.Redirect(w, r, "/loop", http.StatusTemporaryRedirect)
+ }))
+ defer origin.Close()
+ _, err := FetchManifest(context.Background(), origin.Client(), origin.URL)
+ if err == nil || !strings.Contains(err.Error(), "stopped after 10 redirects") {
+ t.Fatalf("default redirect limit lost: %v", err)
+ }
+ if requests.Load() != 10 {
+ t.Fatalf("redirect requests = %d, want 10", requests.Load())
+ }
+}
+
func TestFetchManifestUsesSharedDiscoveryPath(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != AgentCapabilitiesPath {