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.

6.1 KB
Raw Blame
package api

import (
	"archive/zip"
	"bytes"
	"context"
	"encoding/json"
	"io"
	"net/http"
	"net/http/httptest"
	"os"
	"path/filepath"
	"strings"
	"testing"

	"github.com/rcourtman/pulse-go-rewrite/internal/config"
	"github.com/rcourtman/pulse-go-rewrite/internal/logging"
)

type noFlushWriter struct {
	header http.Header
	code   int
	body   bytes.Buffer
}

func (w *noFlushWriter) Header() http.Header {
	if w.header == nil {
		w.header = http.Header{}
	}
	return w.header
}

func (w *noFlushWriter) Write(p []byte) (int, error) {
	return w.body.Write(p)
}

func (w *noFlushWriter) WriteHeader(statusCode int) {
	w.code = statusCode
}

func TestLogHandlers_HandleStreamLogs_RequiresFlusher(t *testing.T) {
	handler := NewLogHandlers(&config.Config{}, nil)
	req := httptest.NewRequest(http.MethodGet, "/api/logs/stream", nil)
	w := &noFlushWriter{}

	handler.HandleStreamLogs(w, req)

	if w.code != http.StatusInternalServerError {
		t.Fatalf("expected status %d, got %d", http.StatusInternalServerError, w.code)
	}
}

func TestLogHandlers_HandleStreamLogs_SendsEvents(t *testing.T) {
	handler := NewLogHandlers(&config.Config{}, nil)

	// The global broadcaster is shared with every concurrently running test,
	// so live-channel delivery cannot be asserted without racing their log
	// traffic (full subscriber channels drop messages). Write the line first
	// and rely on Subscribe's history replay, which the handler performs
	// before its live loop; a pre-cancelled context then makes the handler
	// return synchronously after the replay.
	_, _ = logging.GetBroadcaster().Write([]byte("test-log-line"))

	ctx, cancel := context.WithCancel(context.Background())
	cancel()
	req := httptest.NewRequest(http.MethodGet, "/api/logs/stream", nil).WithContext(ctx)
	rr := httptest.NewRecorder()

	handler.HandleStreamLogs(rr, req)

	body := rr.Body.String()
	if !strings.Contains(body, "data:") {
		t.Fatalf("expected SSE data in response, got %q", body)
	}
	if !strings.Contains(body, "test-log-line") {
		t.Fatalf("expected log line in response, got %q", body)
	}
}

func TestLogHandlers_HandleDownloadBundle(t *testing.T) {
	logFile := filepathWithTemp(t, "pulse.log")
	if err := os.WriteFile(logFile, []byte("log-line"), 0600); err != nil {
		t.Fatalf("write log file: %v", err)
	}

	t.Setenv("TEST_SECRET", "super-secret")

	cfg := &config.Config{
		LogFile:         logFile,
		AuthPass:        "password",
		APIToken:        "token",
		ProxyAuthSecret: "proxy-secret",
		PVEInstances:    []config.PVEInstance{{Password: "pve-pass", TokenValue: "pve-token"}},
		PBSInstances:    []config.PBSInstance{{Password: "pbs-pass", TokenValue: "pbs-token"}},
		PMGInstances:    []config.PMGInstance{{Password: "pmg-pass", TokenValue: "pmg-token"}},
	}

	handler := NewLogHandlers(cfg, nil)
	rr := httptest.NewRecorder()
	req := httptest.NewRequest(http.MethodGet, "/api/logs/bundle", nil)
	handler.HandleDownloadBundle(rr, req)

	if rr.Code != http.StatusOK {
		t.Fatalf("expected status %d, got %d", http.StatusOK, rr.Code)
	}

	zr, err := zip.NewReader(bytes.NewReader(rr.Body.Bytes()), int64(rr.Body.Len()))
	if err != nil {
		t.Fatalf("zip reader: %v", err)
	}

	var haveLog, haveSystem bool
	var systemInfo []byte
	for _, f := range zr.File {
		switch f.Name {
		case "pulse.log", "pulse-tail.log":
			haveLog = true
		case "system-info.json":
			haveSystem = true
			rc, err := f.Open()
			if err != nil {
				t.Fatalf("open system-info.json: %v", err)
			}
			defer rc.Close()
			systemInfo, _ = io.ReadAll(rc)
		}
	}
	if !haveLog {
		t.Fatalf("expected log file in bundle")
	}
	if !haveSystem {
		t.Fatalf("expected system-info.json in bundle")
	}

	var payload struct {
		Config config.Config `json:"Config"`
		Env    []string      `json:"Env"`
	}
	if err := json.Unmarshal(systemInfo, &payload); err != nil {
		t.Fatalf("unmarshal system-info: %v", err)
	}

	// Configuration/environment are an allowlisted diagnostic summary, not a
	// redacted full configuration backup. Unknown environment is absent.
	for _, forbidden := range []string{"super-secret", "password", "proxy-secret", "pve-pass", "pve-token", "pbs-pass", "pbs-token", "pmg-pass", "pmg-token"} {
		if strings.Contains(string(systemInfo), forbidden) {
			t.Fatalf("system-info disclosed a synthetic credential")
		}
	}
	for _, env := range payload.Env {
		if strings.HasPrefix(env, "TEST_SECRET=") {
			t.Fatal("unknown environment must not be copied")
		}
	}

}

func TestLogHandlers_HandleSetLevelAndGetLevel(t *testing.T) {
	originalLevel := logging.GetGlobalLevel()
	t.Cleanup(func() {
		logging.SetGlobalLevel(originalLevel)
	})

	cfg := &config.Config{}
	persistence := config.NewConfigPersistence(t.TempDir())
	if err := persistence.SaveSystemSettings(config.SystemSettings{LogLevel: "info"}); err != nil {
		t.Fatalf("save system settings: %v", err)
	}
	handler := NewLogHandlers(cfg, persistence)

	req := httptest.NewRequest(http.MethodPost, "/api/logs/level", strings.NewReader("{bad"))
	rr := httptest.NewRecorder()
	handler.HandleSetLevel(rr, req)
	if rr.Code != http.StatusBadRequest {
		t.Fatalf("expected status %d, got %d", http.StatusBadRequest, rr.Code)
	}

	req = httptest.NewRequest(http.MethodPost, "/api/logs/level", strings.NewReader(`{"level":"invalid"}`))
	rr = httptest.NewRecorder()
	handler.HandleSetLevel(rr, req)
	if rr.Code != http.StatusBadRequest {
		t.Fatalf("expected status %d, got %d", http.StatusBadRequest, rr.Code)
	}

	req = httptest.NewRequest(http.MethodPost, "/api/logs/level", strings.NewReader(`{"level":"debug"}`))
	rr = httptest.NewRecorder()
	handler.HandleSetLevel(rr, req)
	if rr.Code != http.StatusOK {
		t.Fatalf("expected status %d, got %d", http.StatusOK, rr.Code)
	}
	if cfg.LogLevel != "debug" {
		t.Fatalf("expected config log level updated, got %q", cfg.LogLevel)
	}

	req = httptest.NewRequest(http.MethodGet, "/api/logs/level", nil)
	rr = httptest.NewRecorder()
	handler.HandleGetLevel(rr, req)
	if rr.Code != http.StatusOK {
		t.Fatalf("expected status %d, got %d", http.StatusOK, rr.Code)
	}
	if !strings.Contains(rr.Body.String(), "debug") {
		t.Fatalf("expected response to include debug level, got %q", rr.Body.String())
	}
}

func filepathWithTemp(t *testing.T, name string) string {
	t.Helper()
	return filepath.Join(t.TempDir(), name)
}