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.

Canonicalize reporting transport filenames and format errors

rcourtmana490ba2b7e75
diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
index 0dfd7ff7ee..b18c3d3a0e 100644
--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
@@ -189,9 +189,9 @@ routes.
That same API-owned performance-report definition also governs transport-side
validation and attachment naming. Lifecycle-adjacent fleet surfaces may depend
on those downloads, but they must treat allowed formats, multi-resource caps,
-optional metric/title support, default fallback range windows, and filename
-prefixes as API-owned reporting contract rather than mirroring local
-constants.
+optional metric/title support, default fallback range windows, attachment
+filename stems, and invalid-format validation copy as API-owned reporting
+contract rather than mirroring local constants.
That adjacent export contract now also carries canonical Proxmox pool
membership for each VM row. Lifecycle-adjacent install and fleet surfaces may
reuse those current-state facts, but they must still treat the pool column as
diff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.md
index 36dda0dc1d..17fed24ae9 100644
--- a/docs/release-control/v6/internal/subsystems/api-contracts.md
+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md
@@ -267,13 +267,13 @@ That same catalog payload also owns the optional performance-report capability
surface: `supportsMetricFilter` and `supportsCustomTitle` are contract flags,
not UI hints, so frontend consumers and request builders must not render or
emit unsupported metric-filter or custom-title fields from local assumptions.
-The same performance-report catalog definition also owns backend transport
-validation and download semantics. `internal/api/metrics_reporting_handlers.go`
-must derive allowed formats, default format selection, multi-resource limits,
-optional metric/title field emission, canonical default-title fallback,
-default fallback range window, and
-attachment filename prefixes from the canonical reporting definition instead of
-hardcoding a second local contract.
+The same reporting catalog and inventory export definitions also own backend
+transport validation and download semantics. `internal/api/metrics_reporting_handlers.go`
+and `internal/api/reporting_inventory_handlers.go` must derive allowed formats,
+default format selection, multi-resource limits, optional metric/title field
+emission, canonical default-title fallback, default fallback range window,
+attachment filename stems, and invalid-format validation copy from the
+canonical reporting definitions instead of hardcoding a second local contract.
Frontend consumers may still keep a local fallback filename for defensive
download behavior, but when the server returns `Content-Disposition` they must
prefer that attachment filename as the canonical transport output.
diff --git a/docs/release-control/v6/internal/subsystems/storage-recovery.md b/docs/release-control/v6/internal/subsystems/storage-recovery.md
index b7865692f6..2aa2f40fd5 100644
--- a/docs/release-control/v6/internal/subsystems/storage-recovery.md
+++ b/docs/release-control/v6/internal/subsystems/storage-recovery.md
@@ -282,8 +282,9 @@ report/export routes.
That same API-owned performance-report definition also governs transport-side
validation and attachment naming. Storage and recovery flows may consume those
downloads, but they must treat allowed formats, multi-resource caps, optional
-metric/title support, default fallback range windows, and filename prefixes as
-API/reporting contract rather than rebuilding local reporting constants.
+metric/title support, default fallback range windows, attachment filename
+stems, and invalid-format validation copy as API/reporting contract rather than
+rebuilding local reporting constants.
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 48ae3bf586..b1cb6bc938 100644
--- a/internal/api/contract_test.go
+++ b/internal/api/contract_test.go
@@ -555,6 +555,55 @@ func TestContract_PerformanceReportTransportUsesCatalogDefaultRange(t *testing.T
}
}
+func TestContract_ReportingInvalidFormatErrorsUseCatalogDefinitions(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)
+
+ reportReq := httptest.NewRequest(
+ http.MethodGet,
+ "/api/reporting?format=xlsx&resourceType=node&resourceId=node-1",
+ nil,
+ )
+ reportRec := httptest.NewRecorder()
+ handler.HandleGenerateReport(reportRec, reportReq)
+ if reportRec.Code != http.StatusBadRequest {
+ t.Fatalf("expected 400 for invalid performance report format, got %d body=%s", reportRec.Code, reportRec.Body.String())
+ }
+ var reportPayload struct {
+ Error string `json:"error"`
+ }
+ if err := json.NewDecoder(reportRec.Body).Decode(&reportPayload); err != nil {
+ t.Fatalf("decode performance invalid-format response: %v", err)
+ }
+ if reportPayload.Error != reporting.DescribePerformanceReport().InvalidFormatError() {
+ t.Fatalf("expected canonical performance invalid-format error, got %q", reportPayload.Error)
+ }
+
+ inventoryReq := httptest.NewRequest(
+ http.MethodGet,
+ "/api/admin/reports/inventory/vms/export?format=pdf",
+ nil,
+ )
+ inventoryRec := httptest.NewRecorder()
+ handler.HandleExportVMInventory(inventoryRec, inventoryReq)
+ if inventoryRec.Code != http.StatusBadRequest {
+ t.Fatalf("expected 400 for invalid inventory format, got %d body=%s", inventoryRec.Code, inventoryRec.Body.String())
+ }
+ var inventoryPayload struct {
+ Error string `json:"error"`
+ }
+ if err := json.NewDecoder(inventoryRec.Body).Decode(&inventoryPayload); err != nil {
+ t.Fatalf("decode inventory invalid-format response: %v", err)
+ }
+ if inventoryPayload.Error != reporting.DescribeVMInventoryExport().InvalidFormatError() {
+ t.Fatalf("expected canonical inventory invalid-format error, got %q", inventoryPayload.Error)
+ }
+}
+
func TestContract_HostedTenantAISettingsFallbackJSONSnapshot(t *testing.T) {
t.Setenv("PULSE_HOSTED_MODE", "true")
diff --git a/internal/api/metrics_reporting_handlers.go b/internal/api/metrics_reporting_handlers.go
index c982b584f3..130941cd16 100644
--- a/internal/api/metrics_reporting_handlers.go
+++ b/internal/api/metrics_reporting_handlers.go
@@ -3,6 +3,7 @@ package api
import (
"context"
"encoding/json"
+ "errors"
"fmt"
"net/http"
"regexp"
@@ -52,7 +53,7 @@ func normalizePerformanceReportFormat(raw string, definition reporting.Performan
format = definition.DefaultFormat
}
if !definition.SupportsFormat(format) {
- return "", fmt.Errorf("Format must be 'pdf' or 'csv'")
+ return "", errors.New(definition.InvalidFormatError())
}
return format, nil
}
@@ -381,7 +382,7 @@ func (h *ReportingHandlers) HandleGenerateReport(w http.ResponseWriter, r *http.
w.Header().Set("Content-Type", contentType)
// Build safe filename - sanitize resourceID to prevent header injection
safeResourceID := sanitizeFilename(resourceID)
- filename := fmt.Sprintf("%s-%s-%s.%s", definition.SingleFilenamePrefix, safeResourceID, time.Now().Format("20060102"), format)
+ filename := definition.SingleAttachmentFilename(safeResourceID, time.Now().UTC(), format)
w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=\"%s\"", filename))
w.Write(data)
}
@@ -742,7 +743,7 @@ func (h *ReportingHandlers) HandleGenerateMultiReport(w http.ResponseWriter, r *
}
w.Header().Set("Content-Type", contentType)
- filename := fmt.Sprintf("%s-%s.%s", definition.MultiFilenamePrefix, time.Now().Format("20060102"), format)
+ filename := definition.MultiAttachmentFilename(time.Now().UTC(), format)
w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=\"%s\"", filename))
w.Write(data)
}
diff --git a/internal/api/reporting_handlers_test.go b/internal/api/reporting_handlers_test.go
index d178e177de..f33d0266e8 100644
--- a/internal/api/reporting_handlers_test.go
+++ b/internal/api/reporting_handlers_test.go
@@ -317,6 +317,15 @@ func TestReportingHandlers_ExportVMInventory_InvalidFormat(t *testing.T) {
if rr.Code != http.StatusBadRequest {
t.Fatalf("expected status %d, got %d body=%s", http.StatusBadRequest, rr.Code, rr.Body.String())
}
+ var payload struct {
+ Error string `json:"error"`
+ }
+ if err := json.NewDecoder(rr.Body).Decode(&payload); err != nil {
+ t.Fatalf("decode invalid-format response: %v", err)
+ }
+ if payload.Error != reporting.DescribeVMInventoryExport().InvalidFormatError() {
+ t.Fatalf("expected canonical inventory invalid-format error, got %q", payload.Error)
+ }
}
func TestReportingHandlers_GenerateMultiReport_UsesCatalogLimit(t *testing.T) {
diff --git a/internal/api/reporting_inventory_handlers.go b/internal/api/reporting_inventory_handlers.go
index 1e8121d7de..583bdab572 100644
--- a/internal/api/reporting_inventory_handlers.go
+++ b/internal/api/reporting_inventory_handlers.go
@@ -16,12 +16,13 @@ func (h *ReportingHandlers) HandleExportVMInventory(w http.ResponseWriter, r *ht
return
}
+ definition := reporting.DescribeVMInventoryExport()
format := reporting.ReportFormat(r.URL.Query().Get("format"))
if format == "" {
- format = reporting.FormatCSV
+ format = definition.Format
}
- if format != reporting.FormatCSV {
- writeErrorResponse(w, http.StatusBadRequest, "invalid_format", "Format must be 'csv'", nil)
+ if !definition.SupportsFormat(format) {
+ writeErrorResponse(w, http.StatusBadRequest, "invalid_format", definition.InvalidFormatError(), nil)
return
}
@@ -32,8 +33,9 @@ func (h *ReportingHandlers) HandleExportVMInventory(w http.ResponseWriter, r *ht
}
}
+ generatedAt := time.Now().UTC()
data, err := reporting.GenerateVMInventoryCSV(reporting.VMInventoryData{
- GeneratedAt: time.Now().UTC(),
+ GeneratedAt: generatedAt,
Rows: buildVMInventoryRows(snapshot.Resources),
})
if err != nil {
@@ -42,7 +44,7 @@ func (h *ReportingHandlers) HandleExportVMInventory(w http.ResponseWriter, r *ht
}
w.Header().Set("Content-Type", "text/csv; charset=utf-8")
- filename := fmt.Sprintf("vm-inventory-%s.csv", time.Now().Format("20060102"))
+ filename := definition.AttachmentFilename(generatedAt)
w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=\"%s\"", filename))
_, _ = w.Write(data)
}
diff --git a/pkg/reporting/catalog.go b/pkg/reporting/catalog.go
index 5b60a45ef8..ba2057fa36 100644
--- a/pkg/reporting/catalog.go
+++ b/pkg/reporting/catalog.go
@@ -1,6 +1,10 @@
package reporting
-import "time"
+import (
+ "fmt"
+ "strings"
+ "time"
+)
// ReportingFormatDefinition describes one supported output format for an
// operator-facing reporting surface.
@@ -70,6 +74,28 @@ func (d PerformanceReportDefinition) SupportsFormat(format ReportFormat) bool {
return false
}
+// InvalidFormatError returns the canonical validation message for unsupported
+// performance report formats.
+func (d PerformanceReportDefinition) InvalidFormatError() string {
+ allowed := make([]ReportFormat, 0, len(d.Formats))
+ for _, candidate := range d.Formats {
+ allowed = append(allowed, candidate.Value)
+ }
+ return invalidFormatErrorMessage(allowed)
+}
+
+// SingleAttachmentFilename returns the canonical attachment filename for a
+// single-resource performance report download.
+func (d PerformanceReportDefinition) SingleAttachmentFilename(resourceID string, generatedAt time.Time, format ReportFormat) string {
+ return fmt.Sprintf("%s-%s-%s.%s", d.SingleFilenamePrefix, resourceID, reportingDateStamp(generatedAt), format)
+}
+
+// MultiAttachmentFilename returns the canonical attachment filename for a
+// multi-resource performance report download.
+func (d PerformanceReportDefinition) MultiAttachmentFilename(generatedAt time.Time, format ReportFormat) string {
+ return fmt.Sprintf("%s-%s.%s", d.MultiFilenamePrefix, reportingDateStamp(generatedAt), format)
+}
+
// DefaultRangeDuration returns the canonical fallback time window for the
// performance reporting surface.
func (d PerformanceReportDefinition) DefaultRangeDuration() time.Duration {
@@ -81,6 +107,30 @@ func (d PerformanceReportDefinition) DefaultRangeDuration() time.Duration {
return 24 * time.Hour
}
+func invalidFormatErrorMessage(allowed []ReportFormat) string {
+ quoted := make([]string, 0, len(allowed))
+ for _, format := range allowed {
+ if format == "" {
+ continue
+ }
+ quoted = append(quoted, fmt.Sprintf("%q", format))
+ }
+ if len(quoted) == 0 {
+ return "Format is not supported"
+ }
+ if len(quoted) == 1 {
+ return fmt.Sprintf("Format must be %s", quoted[0])
+ }
+ if len(quoted) == 2 {
+ return fmt.Sprintf("Format must be %s or %s", quoted[0], quoted[1])
+ }
+ return fmt.Sprintf("Format must be %s, or %s", strings.Join(quoted[:len(quoted)-1], ", "), quoted[len(quoted)-1])
+}
+
+func reportingDateStamp(generatedAt time.Time) string {
+ return generatedAt.UTC().Format("20060102")
+}
+
// DescribePerformanceReport returns the canonical definition for Pulse's
// historical performance reporting surface.
func DescribePerformanceReport() PerformanceReportDefinition {
diff --git a/pkg/reporting/catalog_test.go b/pkg/reporting/catalog_test.go
index 6c68ac024e..fc883866d6 100644
--- a/pkg/reporting/catalog_test.go
+++ b/pkg/reporting/catalog_test.go
@@ -52,3 +52,41 @@ func TestPerformanceReportDefinition_DefaultRangeDuration(t *testing.T) {
t.Fatalf("default range duration = %s, want %s", got, 24*time.Hour)
}
}
+
+func TestPerformanceReportDefinition_InvalidFormatError(t *testing.T) {
+ definition := DescribePerformanceReport()
+
+ if got := definition.InvalidFormatError(); got != `Format must be "pdf" or "csv"` {
+ t.Fatalf("invalid format error = %q", got)
+ }
+}
+
+func TestPerformanceReportDefinition_AttachmentFilenamesUseUTCDateStamp(t *testing.T) {
+ definition := DescribePerformanceReport()
+ generatedAt := time.Date(2026, 3, 26, 0, 30, 0, 0, time.FixedZone("late", -7*60*60))
+
+ if got := definition.SingleAttachmentFilename("node-1", generatedAt, FormatPDF); got != "report-node-1-20260326.pdf" {
+ t.Fatalf("single attachment filename = %q", got)
+ }
+ if got := definition.MultiAttachmentFilename(generatedAt, FormatCSV); got != "fleet-report-20260326.csv" {
+ t.Fatalf("multi attachment filename = %q", got)
+ }
+}
+
+func TestVMInventoryExportDefinition_FormatContract(t *testing.T) {
+ definition := DescribeVMInventoryExport()
+ generatedAt := time.Date(2026, 3, 26, 23, 30, 0, 0, time.FixedZone("early", 2*60*60))
+
+ if !definition.SupportsFormat(FormatCSV) {
+ t.Fatalf("expected csv inventory export support")
+ }
+ if definition.SupportsFormat(FormatPDF) {
+ t.Fatalf("did not expect pdf inventory export support")
+ }
+ if got := definition.InvalidFormatError(); got != `Format must be "csv"` {
+ t.Fatalf("invalid inventory format error = %q", got)
+ }
+ if got := definition.AttachmentFilename(generatedAt); got != "vm-inventory-20260326.csv" {
+ t.Fatalf("inventory attachment filename = %q", got)
+ }
+}
diff --git a/pkg/reporting/vm_inventory.go b/pkg/reporting/vm_inventory.go
index 1f0f6f3813..2d225ae6e5 100644
--- a/pkg/reporting/vm_inventory.go
+++ b/pkg/reporting/vm_inventory.go
@@ -29,6 +29,24 @@ type VMInventoryExportDefinition struct {
Columns []InventoryExportColumnDefinition `json:"columns"`
}
+// SupportsFormat reports whether the inventory export allows the given output
+// format.
+func (d VMInventoryExportDefinition) SupportsFormat(format ReportFormat) bool {
+ return format == d.Format
+}
+
+// InvalidFormatError returns the canonical validation message for unsupported
+// VM inventory formats.
+func (d VMInventoryExportDefinition) InvalidFormatError() string {
+ return invalidFormatErrorMessage([]ReportFormat{d.Format})
+}
+
+// AttachmentFilename returns the canonical attachment filename for a VM
+// inventory export.
+func (d VMInventoryExportDefinition) AttachmentFilename(generatedAt time.Time) string {
+ return fmt.Sprintf("%s-%s.%s", d.FilenamePrefix, reportingDateStamp(generatedAt), d.Format)
+}
+
// VMInventoryData captures the current-state VM inventory export payload.
type VMInventoryData struct {
GeneratedAt time.Time