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.

Reject competing audit webhook destination fields

pulse-triage[bot]3883796a9b4f
diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
index ca50cb0bc7..e2c8f899ea 100644
--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
@@ -4019,6 +4019,15 @@ its intentional clear semantics. `internal/api/audit_selection_validation_test.g
pins read non-execution, selected wire results, tenant isolation and mutation
preservation/clear/restore. Agent operations and storage internals are unchanged.
+Audit webhook destination updates refuse repeated top-level `urls` members,
+including JSON-escaped and case-folded aliases, before URL/DNS validation or
+mutation. One complete object within the existing body bound is required;
+trailing documents or oversized suffixes cannot apply a partial selection.
+Singleton aliases and unknown fields remain compatible. Explicit clear/restore
+and tenant-scoped access/entitlement remain unchanged. The executable controls
+in `internal/api/audit_handlers_test.go` preserve selected destinations after
+rejection; they establish neither receiver delivery nor installed recovery.
+
## Forbidden Paths
1. New install or update continuity behavior hidden only inside broad monitoring ownership.
diff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.md
index 8ec0e85cfa..a3636e7ae7 100644
--- a/docs/release-control/v6/internal/subsystems/api-contracts.md
+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md
@@ -4102,6 +4102,19 @@ forwarding remain unchanged; these controls establish no receiver delivery.
The same test file pins both methods, unchanged state after refusal, deliberate
clear/restore, invalid-URL atomicity and tenant-scoped mutation.
+Audit webhook updates also reject competing top-level `urls` members with
+`400 invalid_request`, before DNS/URL validation or any logger update. JSON
+escapes and the existing case-insensitive key matching (including Unicode
+case folds) identify the same selection: identical duplicates are ambiguous
+too. A singleton alias, well-formed unknown fields and nested metadata remain
+compatible. The bounded body must contain one complete JSON object, followed
+only by whitespace; a second document, junk or an oversized suffix cannot
+silently apply its first selection. Explicit `[]` clear/restore, atomic URL/SSRF
+validation, tenant selection, access/entitlement and best-effort delivery are
+unchanged. `internal/api/audit_handlers_test.go` pins both methods, duplicate
+aliases, preserved destinations, singleton compatibility and complete-body
+bounds. This proves configuration preservation, not external receiver delivery.
+
## Forbidden Paths
1. Handler-local payload shape drift without a contract test
diff --git a/docs/release-control/v6/internal/subsystems/storage-recovery.md b/docs/release-control/v6/internal/subsystems/storage-recovery.md
index d5508509e7..aefc0ab0a4 100644
--- a/docs/release-control/v6/internal/subsystems/storage-recovery.md
+++ b/docs/release-control/v6/internal/subsystems/storage-recovery.md
@@ -2765,6 +2765,15 @@ its intentional clear semantics. `internal/api/audit_selection_validation_test.g
pins read non-execution, selected wire results, tenant isolation and mutation
preservation/clear/restore. Agent operations and storage internals are unchanged.
+Audit webhook destination updates refuse repeated top-level `urls` members,
+including JSON-escaped and case-folded aliases, before URL/DNS validation or
+mutation. One complete object within the existing body bound is required;
+trailing documents or oversized suffixes cannot apply a partial selection.
+Singleton aliases and unknown fields remain compatible. Explicit clear/restore
+and tenant-scoped access/entitlement remain unchanged. The executable controls
+in `internal/api/audit_handlers_test.go` preserve selected destinations after
+rejection; they establish neither receiver delivery nor installed recovery.
+
## Forbidden Paths
1. Reintroducing storage or recovery product logic as ad hoc dashboard-only summaries without a canonical page-surface owner
diff --git a/internal/api/activity_audit_handlers.go b/internal/api/activity_audit_handlers.go
index 9c5146df97..581d601aac 100644
--- a/internal/api/activity_audit_handlers.go
+++ b/internal/api/activity_audit_handlers.go
@@ -4,6 +4,7 @@ import (
"context"
"encoding/json"
"fmt"
+ "io"
"net"
"net/http"
"net/url"
@@ -300,21 +301,15 @@ func (h *AuditHandlers) HandleUpdateWebhooks(w http.ResponseWriter, r *http.Requ
// Limit request body size to prevent memory exhaustion
r.Body = http.MaxBytesReader(w, r.Body, 64*1024) // 64KB max
- var req struct {
- URLs []string `json:"urls"`
- }
- if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
- writeErrorResponse(w, http.StatusBadRequest, "invalid_request", "Invalid request body", nil)
- return
- }
- if req.URLs == nil {
- writeErrorResponse(w, http.StatusBadRequest, "invalid_request", "An explicit urls array is required; use [] to remove all audit webhooks", nil)
+ urls, err := decodeAuditWebhookSelection(r.Body)
+ if err != nil {
+ writeErrorResponse(w, http.StatusBadRequest, "invalid_request", err.Error(), nil)
return
}
// Validate all webhook URLs
- validatedURLs := make([]string, 0, len(req.URLs))
- for _, rawURL := range req.URLs {
+ validatedURLs := make([]string, 0, len(urls))
+ for _, rawURL := range urls {
if err := validateWebhookURL(rawURL); err != nil {
writeErrorResponse(w, http.StatusBadRequest, "invalid_url", fmt.Sprintf("Invalid webhook URL: %s", err.Error()), map[string]string{"url": rawURL})
return
@@ -332,6 +327,55 @@ func (h *AuditHandlers) HandleUpdateWebhooks(w http.ResponseWriter, r *http.Requ
w.WriteHeader(http.StatusNoContent)
}
+// Decode one complete selection before validating URLs or updating destinations.
+// Struct/map decoding would discard repeated members. Match the struct decoder's
+// case-insensitive keys, including JSON escapes, but never choose a last value.
+func decodeAuditWebhookSelection(body io.Reader) ([]string, error) {
+ invalidBody := fmt.Errorf("Invalid request body")
+ decoder := json.NewDecoder(body)
+ opening, err := decoder.Token()
+ if err != nil || opening != json.Delim('{') {
+ return nil, invalidBody
+ }
+
+ var urls []string
+ seenURLs := false
+ for decoder.More() {
+ key, err := decoder.Token()
+ if err != nil {
+ return nil, invalidBody
+ }
+ if name, ok := key.(string); ok && strings.EqualFold(name, "urls") {
+ if seenURLs {
+ return nil, fmt.Errorf("Only one urls array may be supplied")
+ }
+ seenURLs = true
+ if err := decoder.Decode(&urls); err != nil {
+ return nil, invalidBody
+ }
+ } else {
+ // Retain forward-compatible unknown fields without letting a nested
+ // urls member masquerade as a top-level destination selection.
+ var ignored json.RawMessage
+ if err := decoder.Decode(&ignored); err != nil {
+ return nil, invalidBody
+ }
+ }
+ }
+ if closing, err := decoder.Token(); err != nil || closing != json.Delim('}') {
+ return nil, invalidBody
+ }
+ // Do not accept another document, trailing junk, or an oversized suffix.
+ var trailing json.RawMessage
+ if err := decoder.Decode(&trailing); err != io.EOF {
+ return nil, invalidBody
+ }
+ if urls == nil {
+ return nil, fmt.Errorf("An explicit urls array is required; use [] to remove all audit webhooks")
+ }
+ return urls, nil
+}
+
// validateWebhookURL validates a webhook URL for security.
// Returns an error if the URL is invalid or potentially dangerous (SSRF).
func validateWebhookURL(rawURL string) error {
diff --git a/internal/api/audit_handlers_test.go b/internal/api/audit_handlers_test.go
index 022d8075ce..759d4250f1 100644
--- a/internal/api/audit_handlers_test.go
+++ b/internal/api/audit_handlers_test.go
@@ -9,6 +9,7 @@ import (
"net/http"
"net/http/httptest"
"net/url"
+ "reflect"
"strings"
"testing"
"time"
@@ -430,6 +431,102 @@ func TestHandleUpdateWebhooksRejectsNonArrayAndOversizedSelections(t *testing.T)
}
}
+func TestHandleUpdateWebhooksRejectsCompetingSelections(t *testing.T) {
+ previousResolve := resolveWebhookIPs
+ resolveWebhookIPs = func(context.Context, string) ([]net.IPAddr, error) {
+ t.Error("competing selections must be rejected before DNS validation")
+ return []net.IPAddr{{IP: net.ParseIP("8.8.8.8")}}, nil
+ }
+ t.Cleanup(func() { resolveWebhookIPs = previousResolve })
+ for _, method := range []string{http.MethodPost, http.MethodPut} {
+ for name, body := range map[string]string{
+ "clear_overrides_selection": `{"urls":["https://receiver.example/new"],"urls":[]}`,
+ "selection_overrides_clear": `{"urls":[],"urls":["https://receiver.example/new"]}`,
+ "identical": `{"urls":[],"urls":[]}`,
+ "escaped": `{"urls":["https://receiver.example/new"],"\u0075rls":[]}`,
+ "upper_case": `{"urls":["https://receiver.example/new"],"URLS":[]}`,
+ "mixed_case": `{"uRlS":["https://receiver.example/new"],"urls":[]}`,
+ "unicode_fold": `{"urls":["https://receiver.example/new"],"url\u017f":[]}`,
+ "null_before_clear": `{"urls":null,"urls":[]}`,
+ } {
+ t.Run(method+"/"+name, func(t *testing.T) {
+ logger := newAuditSelectionLogger()
+ before := []string{"https://8.8.8.8/original", "https://1.1.1.1/second"}
+ logger.urls = append([]string{}, before...)
+ setAuditLogger(t, logger)
+ rec := httptest.NewRecorder()
+ NewAuditHandlers().HandleUpdateWebhooks(rec, httptest.NewRequest(method,
+ "/api/admin/webhooks/audit", strings.NewReader(body)))
+ var payload APIError
+ if err := json.Unmarshal(rec.Body.Bytes(), &payload); err != nil {
+ t.Fatal(err)
+ }
+ if rec.Code != http.StatusBadRequest || payload.Code != "invalid_request" || payload.ErrorMessage != "Only one urls array may be supplied" {
+ t.Errorf("status/body = %d/%s, want a clear competing-selection error", rec.Code, rec.Body.String())
+ }
+ if logger.updates != 0 || !reflect.DeepEqual(logger.urls, before) {
+ t.Errorf("competing fields changed receivers: updates=%d urls=%v", logger.updates, logger.urls)
+ }
+ })
+ }
+ }
+}
+
+func TestHandleUpdateWebhooksAcceptsSingleSelectionAliases(t *testing.T) {
+ for _, method := range []string{http.MethodPost, http.MethodPut} {
+ for _, key := range []string{"urls", "URLS", "uRlS", `\u0075rls`, `url\u017f`} {
+ t.Run(method+"/"+key, func(t *testing.T) {
+ logger := newAuditSelectionLogger()
+ logger.urls = []string{"https://8.8.8.8/original"}
+ setAuditLogger(t, logger)
+ // Unknown (even repeated) fields remain compatible. Nested urls
+ // are metadata, not competing top-level selections.
+ body := `{"future":{"urls":["ignored"]},"future":true,"` + key + `":["https://8.8.8.8/restored"]} ` + "\n\t"
+ rec := httptest.NewRecorder()
+ NewAuditHandlers().HandleUpdateWebhooks(rec, httptest.NewRequest(method,
+ "/api/admin/webhooks/audit", strings.NewReader(body)))
+ if rec.Code != http.StatusNoContent || logger.updates != 1 || !reflect.DeepEqual(logger.urls, []string{"https://8.8.8.8/restored"}) {
+ t.Fatalf("status/updates/urls = %d/%d/%v: %s", rec.Code, logger.updates, logger.urls, rec.Body.String())
+ }
+ })
+ }
+ }
+}
+
+func TestHandleUpdateWebhooksRequiresCompleteBoundedObject(t *testing.T) {
+ for _, method := range []string{http.MethodPost, http.MethodPut} {
+ for name, body := range map[string]string{
+ "second_object": `{"urls":[]} {"urls":["https://8.8.8.8/unselected"]}`,
+ "trailing_null": `{"urls":[]} null`,
+ "trailing_junk": `{"urls":[]} broken`,
+ "missing_close": `{"urls":[]`,
+ "trailing_comma": `{"urls":[],}`,
+ "non_object": `[{"urls":[]}]`,
+ "nested_only": `{"future":{"urls":[]}}`,
+ "oversized_field": `{"urls":[],"future":"` + strings.Repeat("x", 64*1024) + `"}`,
+ "oversized_suffix": `{"urls":[]}` + strings.Repeat(" ", 64*1024),
+ "malformed_unknown": `{"urls":[],"future":invalid}`,
+ } {
+ t.Run(method+"/"+name, func(t *testing.T) {
+ logger := newAuditSelectionLogger()
+ before := []string{"https://8.8.8.8/original"}
+ logger.urls = append([]string{}, before...)
+ setAuditLogger(t, logger)
+ rec := httptest.NewRecorder()
+ NewAuditHandlers().HandleUpdateWebhooks(rec, httptest.NewRequest(method,
+ "/api/admin/webhooks/audit", strings.NewReader(body)))
+ var payload APIError
+ if err := json.Unmarshal(rec.Body.Bytes(), &payload); err != nil {
+ t.Fatal(err)
+ }
+ if rec.Code != http.StatusBadRequest || payload.Code != "invalid_request" || logger.updates != 0 || !reflect.DeepEqual(logger.urls, before) {
+ t.Fatalf("invalid body changed receivers: status/code/updates/urls = %d/%q/%d/%v", rec.Code, payload.Code, logger.updates, logger.urls)
+ }
+ })
+ }
+ }
+}
+
func TestHandleExportAuditEvents_NotPersistent(t *testing.T) {
setAuditLogger(t, audit.NewConsoleLogger())
handler := NewAuditHandlers()