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.

Dispatch relay proxy requests to the local API in-process

rcourtmand746731c75f2
diff --git a/internal/api/router.go b/internal/api/router.go
index 6f955ede34..1c2ead7ea0 100644
--- a/internal/api/router.go
+++ b/internal/api/router.go
@@ -3439,7 +3439,13 @@ func (r *Router) StartRelay(ctx context.Context) {
config.Mu.Unlock()
return ok
},
- LocalAddr: localAddr,
+ LocalAddr: localAddr,
+ // Dispatch proxied requests to our own handler chain in-process.
+ // The main listener may serve TLS (HTTPS_ENABLED) or bind a
+ // non-loopback address, so dialing localAddr is not reliable.
+ LocalHandler: http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
+ r.Handler().ServeHTTP(w, req)
+ }),
ServerVersion: r.serverVersion,
IdentityPubKey: cfg.IdentityPublicKey,
IdentityPrivateKey: cfg.IdentityPrivateKey,
diff --git a/internal/relay/client.go b/internal/relay/client.go
index 99a68b727a..c917bd89ce 100644
--- a/internal/relay/client.go
+++ b/internal/relay/client.go
@@ -122,6 +122,7 @@ type ClientDeps struct {
LicenseTokenFunc func() string // returns the raw license JWT
TokenValidator TokenValidator // validates API tokens from CHANNEL_OPEN
LocalAddr string // e.g. "127.0.0.1:7655"
+ LocalHandler http.Handler // in-process local API dispatch; when set, LocalAddr is never dialed (required when the listener serves TLS or binds a non-loopback address)
ServerVersion string // Pulse version for ClientVersion in REGISTER
IdentityPubKey string // base64-encoded Ed25519 public key for MITM prevention
IdentityPrivateKey string // base64-encoded Ed25519 private key for signing KEY_EXCHANGE
@@ -175,7 +176,7 @@ func NewClient(cfg Config, deps ClientDeps, logger zerolog.Logger) *Client {
return &Client{
config: cfg,
deps: deps,
- proxy: NewHTTPProxy(deps.LocalAddr, logger),
+ proxy: NewHTTPProxyWithLocalHandler(deps.LocalAddr, deps.LocalHandler, logger),
logger: logger,
channels: make(map[uint32]*channelState),
startupErr: startupErr,
diff --git a/internal/relay/local_transport.go b/internal/relay/local_transport.go
new file mode 100644
index 0000000000..9b784c4937
--- /dev/null
+++ b/internal/relay/local_transport.go
@@ -0,0 +1,146 @@
+package relay
+
+import (
+ "fmt"
+ "io"
+ "net/http"
+ "sync"
+)
+
+// handlerTransport dispatches proxied relay requests to the local Pulse HTTP
+// handler in-process instead of dialing the main listener over loopback. The
+// relay client runs inside the Pulse server process, and a loopback dial is
+// not faithful to that listener: with HTTPS_ENABLED the listener serves TLS
+// (a plaintext dial gets a bare 400), and with a non-loopback BIND_ADDRESS
+// the 127.0.0.1 dial cannot connect at all. Serving the handler directly
+// traverses the exact middleware chain the real listener serves.
+type handlerTransport struct {
+ handler http.Handler
+}
+
+func newHandlerTransport(handler http.Handler) *handlerTransport {
+ return &handlerTransport{handler: handler}
+}
+
+func (t *handlerTransport) RoundTrip(req *http.Request) (*http.Response, error) {
+ if t == nil || t.handler == nil {
+ return nil, fmt.Errorf("relay local handler transport is not configured")
+ }
+
+ outReq := req.Clone(req.Context())
+ // Server-side requests carry a RequestURI; some handlers read it.
+ outReq.RequestURI = req.URL.RequestURI()
+ if outReq.RemoteAddr == "" {
+ // Match the loopback dial this transport replaces so address-keyed
+ // middleware (rate limits, lockouts, audit logs) behaves the same.
+ outReq.RemoteAddr = "127.0.0.1:0"
+ }
+ if outReq.Body == nil {
+ outReq.Body = http.NoBody
+ }
+
+ pr, pw := io.Pipe()
+ rw := newPipeResponseWriter(pw)
+
+ go func() {
+ defer func() {
+ if recovered := recover(); recovered != nil {
+ rw.abort(fmt.Errorf("relay local handler panicked: %v", recovered))
+ return
+ }
+ rw.finish()
+ }()
+ t.handler.ServeHTTP(rw, outReq)
+ }()
+
+ select {
+ case <-rw.committed():
+ case <-req.Context().Done():
+ _ = pr.CloseWithError(req.Context().Err())
+ return nil, req.Context().Err()
+ }
+
+ status, header := rw.committedResponse()
+ return &http.Response{
+ Status: fmt.Sprintf("%d %s", status, http.StatusText(status)),
+ StatusCode: status,
+ Proto: "HTTP/1.1",
+ ProtoMajor: 1,
+ ProtoMinor: 1,
+ Header: header,
+ Body: pr,
+ ContentLength: -1,
+ Request: req,
+ }, nil
+}
+
+// pipeResponseWriter adapts an http.Handler response onto an io.Pipe so the
+// proxy's http.Client sees headers as soon as the handler commits them and
+// body bytes as the handler writes them (required for SSE streaming).
+//
+// Header/WriteHeader/Write/Flush and finish/abort are only called from the
+// handler goroutine; committedResponse is only read after the commit channel
+// closes, which orders it after the commit writes.
+type pipeResponseWriter struct {
+ pw *io.PipeWriter
+
+ header http.Header
+
+ commitOnce sync.Once
+ commitCh chan struct{}
+ status int
+ snapshot http.Header
+}
+
+func newPipeResponseWriter(pw *io.PipeWriter) *pipeResponseWriter {
+ return &pipeResponseWriter{
+ pw: pw,
+ header: make(http.Header),
+ commitCh: make(chan struct{}),
+ }
+}
+
+func (w *pipeResponseWriter) Header() http.Header {
+ return w.header
+}
+
+func (w *pipeResponseWriter) WriteHeader(status int) {
+ w.commitOnce.Do(func() {
+ w.status = status
+ w.snapshot = w.header.Clone()
+ close(w.commitCh)
+ })
+}
+
+func (w *pipeResponseWriter) Write(b []byte) (int, error) {
+ w.WriteHeader(http.StatusOK)
+ return w.pw.Write(b)
+}
+
+// Flush satisfies http.Flusher for SSE handlers; pipe writes are already
+// delivered to the reader synchronously, so there is nothing to flush.
+func (w *pipeResponseWriter) Flush() {
+ w.WriteHeader(http.StatusOK)
+}
+
+func (w *pipeResponseWriter) finish() {
+ w.WriteHeader(http.StatusOK)
+ _ = w.pw.Close()
+}
+
+func (w *pipeResponseWriter) abort(err error) {
+ w.commitOnce.Do(func() {
+ w.status = http.StatusInternalServerError
+ w.snapshot = w.header.Clone()
+ close(w.commitCh)
+ })
+ _ = w.pw.CloseWithError(err)
+}
+
+func (w *pipeResponseWriter) committed() <-chan struct{} {
+ return w.commitCh
+}
+
+func (w *pipeResponseWriter) committedResponse() (int, http.Header) {
+ return w.status, w.snapshot
+}
diff --git a/internal/relay/local_transport_test.go b/internal/relay/local_transport_test.go
new file mode 100644
index 0000000000..5313fd6bd6
--- /dev/null
+++ b/internal/relay/local_transport_test.go
@@ -0,0 +1,201 @@
+package relay
+
+import (
+ "encoding/base64"
+ "encoding/json"
+ "fmt"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/rs/zerolog"
+)
+
+func decodeProxyResponseBody(t *testing.T, resp ProxyResponse) string {
+ t.Helper()
+ if resp.Body == "" {
+ return ""
+ }
+ body, err := base64.StdEncoding.DecodeString(resp.Body)
+ if err != nil {
+ t.Fatalf("failed to decode proxy response body: %v", err)
+ }
+ return string(body)
+}
+
+// TestLocalHandlerDispatchWithTLSListener pins the regression that broke
+// Remote Access sync on HTTPS-enabled instances: the main listener serves
+// TLS, so the old loopback dial to http://localAddr got a bare
+// "Client sent an HTTP request to an HTTPS server" 400 for every proxied
+// request. With in-process dispatch the listener's scheme is irrelevant.
+func TestLocalHandlerDispatchWithTLSListener(t *testing.T) {
+ handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Type", "application/json")
+ fmt.Fprintf(w, `{"uri":%q}`, r.URL.RequestURI())
+ })
+ tlsListener := httptest.NewTLSServer(handler)
+ defer tlsListener.Close()
+ localAddr := strings.TrimPrefix(tlsListener.URL, "https://")
+
+ // Old behavior (no handler): plaintext dial against the TLS listener
+ // yields the bare 400 the mobile app surfaced as "alerts: HTTP 400".
+ dialProxy := NewHTTPProxy(localAddr, zerolog.Nop())
+ payload, _ := json.Marshal(ProxyRequest{ID: "r1", Method: "GET", Path: "/api/actions?view=pending&limit=100"})
+ respBytes, err := dialProxy.HandleRequest(payload, "token")
+ if err != nil {
+ t.Fatalf("HandleRequest returned error: %v", err)
+ }
+ if resp := decodeProxyResponse(t, respBytes); resp.Status != http.StatusBadRequest {
+ t.Fatalf("expected plaintext dial against TLS listener to fail with 400, got %d", resp.Status)
+ }
+
+ // New behavior: in-process dispatch reaches the same handler regardless
+ // of the listener's scheme.
+ handlerProxy := NewHTTPProxyWithLocalHandler(localAddr, handler, zerolog.Nop())
+ for _, path := range []string{
+ "/api/ai/patrol/findings?limit=20",
+ "/api/actions?view=pending&limit=100",
+ } {
+ payload, _ := json.Marshal(ProxyRequest{ID: "r2", Method: "GET", Path: path})
+ respBytes, err := handlerProxy.HandleRequest(payload, "token")
+ if err != nil {
+ t.Fatalf("HandleRequest(%s) returned error: %v", path, err)
+ }
+ resp := decodeProxyResponse(t, respBytes)
+ if resp.Status != http.StatusOK {
+ t.Fatalf("expected 200 for %s via local handler dispatch, got %d (%s)", path, resp.Status, decodeProxyResponseBody(t, resp))
+ }
+ if got, want := decodeProxyResponseBody(t, resp), fmt.Sprintf(`{"uri":%q}`, path); got != want {
+ t.Fatalf("expected handler to observe %q, got %s", path, got)
+ }
+ }
+}
+
+func TestLocalHandlerDispatchForwardsRequestDetails(t *testing.T) {
+ var seen struct {
+ method string
+ requestURI string
+ remoteAddr string
+ apiToken string
+ body string
+ }
+ handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ seen.method = r.Method
+ seen.requestURI = r.RequestURI
+ seen.remoteAddr = r.RemoteAddr
+ seen.apiToken = r.Header.Get("X-API-Token")
+ bodyBytes := make([]byte, 64)
+ n, _ := r.Body.Read(bodyBytes)
+ seen.body = string(bodyBytes[:n])
+ w.WriteHeader(http.StatusCreated)
+ })
+ proxy := NewHTTPProxyWithLocalHandler("127.0.0.1:1", handler, zerolog.Nop())
+
+ payload, _ := json.Marshal(ProxyRequest{
+ ID: "r1",
+ Method: "POST",
+ Path: "/api/ai/patrol/acknowledge",
+ Body: base64.StdEncoding.EncodeToString([]byte(`{"finding_id":"f1"}`)),
+ })
+ respBytes, err := proxy.HandleRequest(payload, "secret-token")
+ if err != nil {
+ t.Fatalf("HandleRequest returned error: %v", err)
+ }
+ if resp := decodeProxyResponse(t, respBytes); resp.Status != http.StatusCreated {
+ t.Fatalf("expected 201, got %d", resp.Status)
+ }
+ if seen.method != http.MethodPost {
+ t.Errorf("expected POST, got %q", seen.method)
+ }
+ if seen.requestURI != "/api/ai/patrol/acknowledge" {
+ t.Errorf("unexpected RequestURI %q", seen.requestURI)
+ }
+ if seen.remoteAddr != "127.0.0.1:0" {
+ t.Errorf("expected loopback RemoteAddr, got %q", seen.remoteAddr)
+ }
+ if seen.apiToken != "secret-token" {
+ t.Errorf("expected injected API token, got %q", seen.apiToken)
+ }
+ if seen.body != `{"finding_id":"f1"}` {
+ t.Errorf("unexpected body %q", seen.body)
+ }
+}
+
+func TestLocalHandlerDispatchStreamsSSE(t *testing.T) {
+ handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ flusher, ok := w.(http.Flusher)
+ if !ok {
+ t.Error("response writer does not implement http.Flusher")
+ http.Error(w, "no flusher", http.StatusInternalServerError)
+ return
+ }
+ w.Header().Set("Content-Type", "text/event-stream")
+ w.WriteHeader(http.StatusOK)
+ for i := 0; i < 3; i++ {
+ fmt.Fprintf(w, "data: chunk-%d\n\n", i)
+ flusher.Flush()
+ }
+ })
+ proxy := NewHTTPProxyWithLocalHandler("127.0.0.1:1", handler, zerolog.Nop())
+
+ payload, _ := json.Marshal(ProxyRequest{ID: "s1", Method: "GET", Path: "/api/ai/chat/stream"})
+ frames := make([][]byte, 0, 8)
+ done := make(chan error, 1)
+ go func() {
+ done <- proxy.HandleStreamRequest(t.Context(), payload, "token", func(frame []byte) {
+ frames = append(frames, frame)
+ })
+ }()
+ select {
+ case err := <-done:
+ if err != nil {
+ t.Fatalf("HandleStreamRequest returned error: %v", err)
+ }
+ case <-time.After(10 * time.Second):
+ t.Fatal("timed out waiting for stream to complete")
+ }
+
+ if len(frames) < 3 {
+ t.Fatalf("expected header, data, and done frames, got %d", len(frames))
+ }
+ head := decodeProxyResponse(t, frames[0])
+ if head.Status != http.StatusOK || !head.Stream || head.Headers["Content-Type"] != "text/event-stream" {
+ t.Fatalf("unexpected stream header frame: %+v", head)
+ }
+ var streamed strings.Builder
+ sawDone := false
+ for _, frame := range frames[1:] {
+ resp := decodeProxyResponse(t, frame)
+ streamed.WriteString(decodeProxyResponseBody(t, resp))
+ if resp.StreamDone {
+ sawDone = true
+ }
+ }
+ if !sawDone {
+ t.Error("expected a stream_done frame")
+ }
+ for i := 0; i < 3; i++ {
+ if want := fmt.Sprintf("data: chunk-%d", i); !strings.Contains(streamed.String(), want) {
+ t.Errorf("streamed output missing %q: %q", want, streamed.String())
+ }
+ }
+}
+
+func TestLocalHandlerDispatchRecoversFromHandlerPanic(t *testing.T) {
+ handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ panic("boom")
+ })
+ proxy := NewHTTPProxyWithLocalHandler("127.0.0.1:1", handler, zerolog.Nop())
+
+ payload, _ := json.Marshal(ProxyRequest{ID: "p1", Method: "GET", Path: "/api/health"})
+ respBytes, err := proxy.HandleRequest(payload, "token")
+ if err != nil {
+ t.Fatalf("HandleRequest returned error: %v", err)
+ }
+ resp := decodeProxyResponse(t, respBytes)
+ if resp.Status != http.StatusBadGateway && resp.Status != http.StatusInternalServerError {
+ t.Fatalf("expected 502 or 500 after handler panic, got %d", resp.Status)
+ }
+}
diff --git a/internal/relay/proxy.go b/internal/relay/proxy.go
index 7cefd6ef42..de99905e4e 100644
--- a/internal/relay/proxy.go
+++ b/internal/relay/proxy.go
@@ -68,10 +68,24 @@ func (p *HTTPProxy) Close() {
// NewHTTPProxy creates a proxy that forwards requests to the given local address.
func NewHTTPProxy(localAddr string, logger zerolog.Logger) *HTTPProxy {
+ return NewHTTPProxyWithLocalHandler(localAddr, nil, logger)
+}
+
+// NewHTTPProxyWithLocalHandler creates a proxy that dispatches requests to the
+// given handler in-process. localAddr is retained for request URL construction
+// and as the dial target when handler is nil. Passing the handler is the
+// correct mode inside the Pulse server: the main listener may serve TLS or
+// bind a non-loopback address, so a loopback dial is not a faithful hop.
+func NewHTTPProxyWithLocalHandler(localAddr string, handler http.Handler, logger zerolog.Logger) *HTTPProxy {
+ var transport http.RoundTripper
+ if handler != nil {
+ transport = newHandlerTransport(handler)
+ }
return &HTTPProxy{
localAddr: localAddr,
client: &http.Client{
- Timeout: proxyRequestTimeout,
+ Timeout: proxyRequestTimeout,
+ Transport: transport,
CheckRedirect: func(req *http.Request, via []*http.Request) error {
return http.ErrUseLastResponse
},
@@ -79,6 +93,7 @@ func NewHTTPProxy(localAddr string, logger zerolog.Logger) *HTTPProxy {
streamClient: &http.Client{
// No Timeout — streaming responses are long-lived.
// Cancellation is handled via context.
+ Transport: transport,
CheckRedirect: func(req *http.Request, via []*http.Request) error {
return http.ErrUseLastResponse
},