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.

Harden reporting transport validation

rcourtman7adc4d9b5514
diff --git a/docs/API.md b/docs/API.md
index 3f194c5f10..229d29b9d4 100644
--- a/docs/API.md
+++ b/docs/API.md
@@ -417,18 +417,16 @@ Triggers a test alert to all configured channels.
Validation and limits:
- `start` and `end` must be RFC3339 when provided.
-- Malformed `start`/`end` values, or `end` earlier than `start`, return `400 invalid_time_range`.
-- `start` must be before `end`.
-- Maximum report window is 366 days.
-- `metricType` must match `[a-zA-Z0-9._:-]+` and be <= 64 chars.
-- `title` must be <= 256 chars.
-- Multi-report body max size is 1MB and rejects trailing payload or unknown JSON fields.
+- Malformed `start`/`end` values, `end` not strictly after `start`, or report windows over 366 days return `400 invalid_time_range`.
+- `metricType` must match `[a-zA-Z0-9._:-]+` and be <= 64 chars, otherwise `400 invalid_metric_type`.
+- `title` must be <= 256 chars, otherwise `400 invalid_title`.
+- Multi-report body max size is 1MB; oversized payloads return `400 body_too_large`.
+- Multi-report bodies reject trailing payload and unknown JSON fields with `400 invalid_body`.
- VM inventory export only accepts `csv`.
Common reporting error codes:
- `invalid_format`, `missing_params`, `invalid_resource_type`, `invalid_resource_id`
-- `invalid_metric_type`, `invalid_title`
-- `invalid_start`, `invalid_end`, `invalid_range`, `range_too_large`
+- `invalid_metric_type`, `invalid_title`, `invalid_time_range`
- `no_resources`, `too_many_resources`, `body_too_large`, `invalid_body`
### Queue and Dead-Letter Tools
diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
index 0384722119..f9613e9dbc 100644
--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
@@ -290,6 +290,10 @@ handoff, or scheduled lifecycle flow that triggers performance reports must
treat reporting `start`/`end` values as optional RFC3339 fields owned by the
API contract, with malformed or inverted ranges rejected as
`400 invalid_time_range` rather than silently drifting to a fallback window.
+Those same lifecycle-triggered reporting calls must also stay inside the
+API-owned `metricType`/`title` limits and the strict multi-report JSON body
+rules instead of assuming the backend will coerce malformed payloads into a
+best-effort report.
The direct Proxmox fallback workspace now also lives explicitly inside this
lifecycle boundary: `InfrastructureWorkspace.tsx`,
`infrastructureWorkspaceModel.ts`,
diff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.md
index 5857bb9b0c..ac24f2ddfb 100644
--- a/docs/release-control/v6/internal/subsystems/api-contracts.md
+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md
@@ -294,6 +294,12 @@ Reporting time windows follow the same rule: `start` and `end` stay optional,
but when present they must parse as RFC3339 and `end` must not be earlier than
`start`; invalid values are a `400 invalid_time_range` transport failure, not a
silent fallback to the default reporting window.
+The same transport contract also owns reporting-field and body validation:
+`metricType` must stay within the governed character set/length, `title` must
+stay within the governed length cap, and the multi-report JSON body must remain
+strictly parsed with the canonical size ceiling, unknown-field rejection, and
+no trailing payload tolerance instead of accepting malformed operator input and
+drifting onward.
The catalog route itself is intentionally metadata-readable without the
`advanced_reporting` feature gate so locked admin surfaces can present the same
canonical reporting definition before upsell, while report generation and
diff --git a/docs/release-control/v6/internal/subsystems/storage-recovery.md b/docs/release-control/v6/internal/subsystems/storage-recovery.md
index 783c6c8fa3..35972c6b16 100644
--- a/docs/release-control/v6/internal/subsystems/storage-recovery.md
+++ b/docs/release-control/v6/internal/subsystems/storage-recovery.md
@@ -306,6 +306,11 @@ field limits and multi-report request parsing. Storage and recovery consumers
must treat `metricType`, `title`, request-body size, unknown JSON fields, and
trailing payload rejection as API-owned validation semantics rather than
counting on permissive backend coercion.
+Those same transport rules now also carry explicit failure modes that adjacent
+storage and recovery automation must preserve: bad or oversized multi-report
+payloads fail as `invalid_body` or `body_too_large`, and overlong report
+windows or invalid optional fields fail through the API-owned reporting
+validation contract instead of being clipped or normalized locally.
That adjacent export contract now also includes canonical Proxmox pool
membership for each VM row. Storage and recovery flows may use those current-
state facts when they need fleet context, but they must consume the API-owned
diff --git a/internal/api/contract_test.go b/internal/api/contract_test.go
index 701d979644..fda3bccccc 100644
--- a/internal/api/contract_test.go
+++ b/internal/api/contract_test.go
@@ -592,6 +592,41 @@ func TestContract_PerformanceReportTransportRejectsInvalidTimeRange(t *testing.T
}
}
+func TestContract_PerformanceReportTransportRejectsOversizedMultiBody(t *testing.T) {
+ engine := &stubReportingEngine{data: []byte("report"), contentType: "application/pdf"}
+ original := reporting.GetEngine()
+ reporting.SetEngine(engine)
+ t.Cleanup(func() { reporting.SetEngine(original) })
+
+ handler := NewReportingHandlers(nil, nil)
+ padding := strings.Repeat("x", reportingMultiReportBodyMax)
+ req := httptest.NewRequest(
+ http.MethodPost,
+ "/api/reporting/generate-multi",
+ strings.NewReader(fmt.Sprintf(`{"resources":[{"resourceType":"vm","resourceId":"vm-1"}],"format":"pdf","title":"%s"}`, padding)),
+ )
+ rec := httptest.NewRecorder()
+
+ handler.HandleGenerateMultiReport(rec, req)
+
+ if rec.Code != http.StatusBadRequest {
+ t.Fatalf("expected 400, got %d body=%s", rec.Code, rec.Body.String())
+ }
+ var payload struct {
+ Code string `json:"code"`
+ Error string `json:"error"`
+ }
+ if err := json.NewDecoder(rec.Body).Decode(&payload); err != nil {
+ t.Fatalf("decode oversized-body response: %v", err)
+ }
+ if payload.Code != "body_too_large" {
+ t.Fatalf("expected body_too_large code, got %q", payload.Code)
+ }
+ if payload.Error != "Request body must be 1MB or less" {
+ t.Fatalf("expected canonical oversized-body message, got %q", payload.Error)
+ }
+}
+
func TestContract_ReportingInvalidFormatErrorsUseCatalogDefinitions(t *testing.T) {
engine := &stubReportingEngine{data: []byte("report"), contentType: "application/pdf"}
original := reporting.GetEngine()
diff --git a/internal/api/metrics_reporting_handlers.go b/internal/api/metrics_reporting_handlers.go
index 6d5abe0fc9..b33d3eec87 100644
--- a/internal/api/metrics_reporting_handlers.go
+++ b/internal/api/metrics_reporting_handlers.go
@@ -5,6 +5,7 @@ import (
"encoding/json"
"errors"
"fmt"
+ "io"
"net/http"
"regexp"
"strings"
@@ -20,6 +21,14 @@ import (
// validResourceID matches safe resource identifiers (includes colon for guest IDs like "instance:node:vmid")
var validResourceID = regexp.MustCompile(`^[a-zA-Z0-9._:-]+$`)
+var validReportingMetricType = regexp.MustCompile(`^[a-zA-Z0-9._:-]+$`)
+
+const (
+ reportingMaxMetricTypeLength = 64
+ reportingMaxTitleLength = 256
+ reportingMaxRangeDuration = 366 * 24 * time.Hour
+ reportingMultiReportBodyMax = 1 << 20
+)
func normalizeReportResourceType(raw string) (string, error) {
trimmed := strings.TrimSpace(raw)
@@ -62,18 +71,24 @@ func normalizePerformanceReportOptionalFields(
definition reporting.PerformanceReportDefinition,
metricType string,
title string,
-) (string, string) {
+) (string, string, error) {
normalizedMetricType := strings.TrimSpace(metricType)
normalizedTitle := strings.TrimSpace(title)
if !definition.SupportsMetricFilter {
normalizedMetricType = ""
+ } else if normalizedMetricType != "" {
+ if len(normalizedMetricType) > reportingMaxMetricTypeLength || !validReportingMetricType.MatchString(normalizedMetricType) {
+ return "", "", fmt.Errorf("metricType must match [a-zA-Z0-9._:-]+ and be <= %d chars", reportingMaxMetricTypeLength)
+ }
}
if !definition.SupportsCustomTitle {
normalizedTitle = ""
+ } else if len(normalizedTitle) > reportingMaxTitleLength {
+ return "", "", fmt.Errorf("title must be <= %d chars", reportingMaxTitleLength)
}
- return normalizedMetricType, normalizedTitle
+ return normalizedMetricType, normalizedTitle, nil
}
func normalizePerformanceReportTimeRange(
@@ -100,13 +115,43 @@ func normalizePerformanceReportTimeRange(
start = parsed
}
- if end.Before(start) {
+ if !end.After(start) {
return time.Time{}, time.Time{}, fmt.Errorf("end must be after start")
}
+ if end.Sub(start) > reportingMaxRangeDuration {
+ return time.Time{}, time.Time{}, fmt.Errorf("report window must be %d days or less", int(reportingMaxRangeDuration/(24*time.Hour)))
+ }
return start, end, nil
}
+func decodeMultiReportRequestBody(w http.ResponseWriter, r *http.Request) (multiReportRequestBody, bool) {
+ r.Body = http.MaxBytesReader(w, r.Body, reportingMultiReportBodyMax)
+
+ var body multiReportRequestBody
+ decoder := json.NewDecoder(r.Body)
+ decoder.DisallowUnknownFields()
+ if err := decoder.Decode(&body); err != nil {
+ var maxBytesErr *http.MaxBytesError
+ if errors.As(err, &maxBytesErr) {
+ writeErrorResponse(w, http.StatusBadRequest, "body_too_large", "Request body must be 1MB or less", nil)
+ return multiReportRequestBody{}, false
+ }
+ writeErrorResponse(w, http.StatusBadRequest, "invalid_body", "Invalid request body", nil)
+ return multiReportRequestBody{}, false
+ }
+ if decoder.More() {
+ writeErrorResponse(w, http.StatusBadRequest, "invalid_body", "Invalid request body", nil)
+ return multiReportRequestBody{}, false
+ }
+ if err := decoder.Decode(&struct{}{}); err != io.EOF {
+ writeErrorResponse(w, http.StatusBadRequest, "invalid_body", "Invalid request body", nil)
+ return multiReportRequestBody{}, false
+ }
+
+ return body, true
+}
+
type reportingEnrichmentSnapshot struct {
Nodes []models.Node
VMs []models.VM
@@ -352,11 +397,19 @@ func (h *ReportingHandlers) HandleGenerateReport(w http.ResponseWriter, r *http.
return
}
- metricType, title := normalizePerformanceReportOptionalFields(
+ metricType, title, err := normalizePerformanceReportOptionalFields(
definition,
q.Get("metricType"),
q.Get("title"),
)
+ if err != nil {
+ code := "invalid_metric_type"
+ if strings.HasPrefix(err.Error(), "title ") {
+ code = "invalid_title"
+ }
+ writeErrorResponse(w, http.StatusBadRequest, code, err.Error(), nil)
+ return
+ }
start, end, err := normalizePerformanceReportTimeRange(
definition,
@@ -676,9 +729,8 @@ func (h *ReportingHandlers) HandleGenerateMultiReport(w http.ResponseWriter, r *
}
definition := performanceReportDefinition()
- var body multiReportRequestBody
- if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
- writeErrorResponse(w, http.StatusBadRequest, "invalid_body", "Invalid request body", nil)
+ body, ok := decodeMultiReportRequestBody(w, r)
+ if !ok {
return
}
@@ -697,7 +749,15 @@ func (h *ReportingHandlers) HandleGenerateMultiReport(w http.ResponseWriter, r *
writeErrorResponse(w, http.StatusBadRequest, "invalid_format", err.Error(), nil)
return
}
- metricType, title := normalizePerformanceReportOptionalFields(definition, body.MetricType, body.Title)
+ metricType, title, err := normalizePerformanceReportOptionalFields(definition, body.MetricType, body.Title)
+ if err != nil {
+ code := "invalid_metric_type"
+ if strings.HasPrefix(err.Error(), "title ") {
+ code = "invalid_title"
+ }
+ writeErrorResponse(w, http.StatusBadRequest, code, err.Error(), nil)
+ return
+ }
start, end, err := normalizePerformanceReportTimeRange(definition, body.Start, body.End, time.Now())
if err != nil {
diff --git a/internal/api/reporting_handlers_test.go b/internal/api/reporting_handlers_test.go
index d79f595daa..55ad5b3553 100644
--- a/internal/api/reporting_handlers_test.go
+++ b/internal/api/reporting_handlers_test.go
@@ -444,6 +444,11 @@ func TestReportingHandlers_GenerateReport_RejectsInvalidTimeRange(t *testing.T)
url: "/api/reporting?format=pdf&resourceType=node&resourceId=node-1&start=2026-03-25T12:00:00Z&end=2026-03-25T11:00:00Z",
wantMessage: "end must be after start",
},
+ {
+ name: "range too large",
+ url: "/api/reporting?format=pdf&resourceType=node&resourceId=node-1&start=2025-03-24T12:00:00Z&end=2026-03-25T12:00:01Z",
+ wantMessage: "report window must be 366 days or less",
+ },
}
for _, tc := range tests {
@@ -466,6 +471,61 @@ func TestReportingHandlers_GenerateReport_RejectsInvalidTimeRange(t *testing.T)
}
}
+func TestReportingHandlers_GenerateReport_RejectsInvalidOptionalFields(t *testing.T) {
+ engine := &stubReportingEngine{data: []byte("report"), contentType: "application/pdf"}
+ original := reporting.GetEngine()
+ reporting.SetEngine(engine)
+ t.Cleanup(func() { reporting.SetEngine(original) })
+
+ handler := NewReportingHandlers(nil, nil)
+ longTitle := strings.Repeat("x", reportingMaxTitleLength+1)
+ tests := []struct {
+ name string
+ url string
+ wantCode string
+ wantMessage string
+ }{
+ {
+ name: "invalid metric type characters",
+ url: "/api/reporting?format=pdf&resourceType=node&resourceId=node-1&metricType=" + url.QueryEscape("cpu usage"),
+ wantCode: "invalid_metric_type",
+ wantMessage: "metricType must match [a-zA-Z0-9._:-]+ and be <= 64 chars",
+ },
+ {
+ name: "title too long",
+ url: "/api/reporting?format=pdf&resourceType=node&resourceId=node-1&title=" + url.QueryEscape(longTitle),
+ wantCode: "invalid_title",
+ wantMessage: "title must be <= 256 chars",
+ },
+ }
+
+ for _, tc := range tests {
+ t.Run(tc.name, func(t *testing.T) {
+ req := httptest.NewRequest(http.MethodGet, tc.url, nil)
+ rr := httptest.NewRecorder()
+
+ handler.HandleGenerateReport(rr, req)
+
+ if rr.Code != http.StatusBadRequest {
+ t.Fatalf("expected status %d, got %d body=%s", http.StatusBadRequest, rr.Code, rr.Body.String())
+ }
+ var payload struct {
+ Code string `json:"code"`
+ Error string `json:"error"`
+ }
+ if err := json.NewDecoder(rr.Body).Decode(&payload); err != nil {
+ t.Fatalf("decode error payload: %v", err)
+ }
+ if payload.Code != tc.wantCode || payload.Error != tc.wantMessage {
+ t.Fatalf("unexpected payload: %+v", payload)
+ }
+ if engine.lastReq.ResourceID != "" {
+ t.Fatalf("expected engine not to be called, got %+v", engine.lastReq)
+ }
+ })
+ }
+}
+
func TestReportingHandlers_GenerateMultiReport_RejectsInvalidTimeRange(t *testing.T) {
engine := &stubReportingEngine{data: []byte("report"), contentType: "application/pdf"}
original := reporting.GetEngine()
@@ -494,6 +554,11 @@ func TestReportingHandlers_GenerateMultiReport_RejectsInvalidTimeRange(t *testin
body: `{"resources":[{"resourceType":"vm","resourceId":"vm-1"}],"format":"pdf","start":"2026-03-25T12:00:00Z","end":"2026-03-25T11:00:00Z"}`,
wantMessage: "end must be after start",
},
+ {
+ name: "range too large",
+ body: `{"resources":[{"resourceType":"vm","resourceId":"vm-1"}],"format":"pdf","start":"2025-03-24T12:00:00Z","end":"2026-03-25T12:00:01Z"}`,
+ wantMessage: "report window must be 366 days or less",
+ },
}
for _, tc := range tests {
@@ -516,6 +581,143 @@ func TestReportingHandlers_GenerateMultiReport_RejectsInvalidTimeRange(t *testin
}
}
+func TestReportingHandlers_GenerateMultiReport_RejectsInvalidOptionalFields(t *testing.T) {
+ engine := &stubReportingEngine{data: []byte("report"), contentType: "application/pdf"}
+ original := reporting.GetEngine()
+ reporting.SetEngine(engine)
+ t.Cleanup(func() { reporting.SetEngine(original) })
+
+ handler := NewReportingHandlers(nil, nil)
+ longTitle := strings.Repeat("x", reportingMaxTitleLength+1)
+ tests := []struct {
+ name string
+ body string
+ wantCode string
+ wantMessage string
+ }{
+ {
+ name: "invalid metric type characters",
+ body: `{"resources":[{"resourceType":"vm","resourceId":"vm-1"}],"format":"pdf","metricType":"cpu usage"}`,
+ wantCode: "invalid_metric_type",
+ wantMessage: "metricType must match [a-zA-Z0-9._:-]+ and be <= 64 chars",
+ },
+ {
+ name: "title too long",
+ body: `{"resources":[{"resourceType":"vm","resourceId":"vm-1"}],"format":"pdf","title":"` + longTitle + `"}`,
+ wantCode: "invalid_title",
+ wantMessage: "title must be <= 256 chars",
+ },
+ }
+
+ for _, tc := range tests {
+ t.Run(tc.name, func(t *testing.T) {
+ req := httptest.NewRequest(http.MethodPost, "/api/reporting/generate-multi", strings.NewReader(tc.body))
+ rr := httptest.NewRecorder()
+
+ handler.HandleGenerateMultiReport(rr, req)
+
+ if rr.Code != http.StatusBadRequest {
+ t.Fatalf("expected status %d, got %d body=%s", http.StatusBadRequest, rr.Code, rr.Body.String())
+ }
+ var payload struct {
+ Code string `json:"code"`
+ Error string `json:"error"`
+ }
+ if err := json.NewDecoder(rr.Body).Decode(&payload); err != nil {
+ t.Fatalf("decode error payload: %v", err)
+ }
+ if payload.Code != tc.wantCode || payload.Error != tc.wantMessage {
+ t.Fatalf("unexpected payload: %+v", payload)
+ }
+ if len(engine.lastMulti.Resources) != 0 {
+ t.Fatalf("expected engine not to be called, got %+v", engine.lastMulti)
+ }
+ })
+ }
+}
+
+func TestReportingHandlers_GenerateMultiReport_RejectsInvalidBody(t *testing.T) {
+ engine := &stubReportingEngine{data: []byte("report"), contentType: "application/pdf"}
+ original := reporting.GetEngine()
+ reporting.SetEngine(engine)
+ t.Cleanup(func() { reporting.SetEngine(original) })
+
+ handler := NewReportingHandlers(nil, nil)
+ tests := []struct {
+ name string
+ body string
+ wantCode string
+ }{
+ {
+ name: "unknown field",
+ body: `{"resources":[{"resourceType":"vm","resourceId":"vm-1"}],"format":"pdf","extra":true}`,
+ wantCode: "invalid_body",
+ },
+ {
+ name: "trailing payload",
+ body: `{"resources":[{"resourceType":"vm","resourceId":"vm-1"}],"format":"pdf"}{"extra":true}`,
+ wantCode: "invalid_body",
+ },
+ }
+
+ for _, tc := range tests {
+ t.Run(tc.name, func(t *testing.T) {
+ req := httptest.NewRequest(http.MethodPost, "/api/reporting/generate-multi", strings.NewReader(tc.body))
+ rr := httptest.NewRecorder()
+
+ handler.HandleGenerateMultiReport(rr, req)
+
+ if rr.Code != http.StatusBadRequest {
+ t.Fatalf("expected status %d, got %d body=%s", http.StatusBadRequest, rr.Code, rr.Body.String())
+ }
+ var payload struct {
+ Code string `json:"code"`
+ }
+ if err := json.NewDecoder(rr.Body).Decode(&payload); err != nil {
+ t.Fatalf("decode error payload: %v", err)
+ }
+ if payload.Code != tc.wantCode {
+ t.Fatalf("expected code %q, got %+v", tc.wantCode, payload)
+ }
+ if len(engine.lastMulti.Resources) != 0 {
+ t.Fatalf("expected engine not to be called, got %+v", engine.lastMulti)
+ }
+ })
+ }
+}
+
+func TestReportingHandlers_GenerateMultiReport_RejectsOversizedBody(t *testing.T) {
+ engine := &stubReportingEngine{data: []byte("report"), contentType: "application/pdf"}
+ original := reporting.GetEngine()
+ reporting.SetEngine(engine)
+ t.Cleanup(func() { reporting.SetEngine(original) })
+
+ handler := NewReportingHandlers(nil, nil)
+ padding := strings.Repeat("x", reportingMultiReportBodyMax)
+ body := fmt.Sprintf(`{"resources":[{"resourceType":"vm","resourceId":"vm-1"}],"format":"pdf","title":"%s"}`, padding)
+ req := httptest.NewRequest(http.MethodPost, "/api/reporting/generate-multi", strings.NewReader(body))
+ rr := httptest.NewRecorder()
+
+ handler.HandleGenerateMultiReport(rr, req)
+
+ if rr.Code != http.StatusBadRequest {
+ t.Fatalf("expected status %d, got %d body=%s", http.StatusBadRequest, rr.Code, rr.Body.String())
+ }
+ var payload struct {
+ Code string `json:"code"`
+ Error string `json:"error"`
+ }
+ if err := json.NewDecoder(rr.Body).Decode(&payload); err != nil {
+ t.Fatalf("decode error payload: %v", err)
+ }
+ if payload.Code != "body_too_large" || payload.Error != "Request body must be 1MB or less" {
+ t.Fatalf("unexpected payload: %+v", payload)
+ }
+ if len(engine.lastMulti.Resources) != 0 {
+ t.Fatalf("expected engine not to be called, got %+v", engine.lastMulti)
+ }
+}
+
func TestReportingHandlers_ExportVMInventory_EmptySnapshotStillReturnsCSVHeader(t *testing.T) {
handler := NewReportingHandlers(nil, nil)
req := httptest.NewRequest(http.MethodGet, "/api/admin/reports/inventory/vms/export", nil)