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 scanned request and storage boundaries

rcourtman24b2e40e9276
diff --git a/frontend-modern/src/components/shared/__tests__/Tooltip.test.tsx b/frontend-modern/src/components/shared/__tests__/Tooltip.test.tsx
index 0072a76450..978460ce4e 100644
--- a/frontend-modern/src/components/shared/__tests__/Tooltip.test.tsx
+++ b/frontend-modern/src/components/shared/__tests__/Tooltip.test.tsx
@@ -56,8 +56,9 @@ describe('Tooltip', () => {
if (!tooltip) return;
await waitFor(() => {
- expect(tooltip.textContent).toBe('"unsafe" & 'quoted'');
+ expect(tooltip.textContent).toBe(`<b>"unsafe"</b> & 'quoted'`);
expect(tooltip.innerHTML).not.toContain('<b>');
+ expect(tooltip.innerHTML).toContain('&lt;b&gt;');
});
});
diff --git a/frontend-modern/src/components/shared/tooltipModel.ts b/frontend-modern/src/components/shared/tooltipModel.ts
index 0f2725818a..6ddd8da078 100644
--- a/frontend-modern/src/components/shared/tooltipModel.ts
+++ b/frontend-modern/src/components/shared/tooltipModel.ts
@@ -26,13 +26,12 @@ interface ResolveTooltipPositionOptions extends TooltipOptions {
}
export function sanitizeTooltipContent(content: string): string {
- return content
- .replace(/<[^>]*>/g, '')
- .replace(/&/g, '&amp;')
- .replace(/</g, '&lt;')
- .replace(/>/g, '&gt;')
- .replace(/"/g, '&quot;')
- .replace(/'/g, '&#x27;');
+ return Array.from(content)
+ .filter((char) => {
+ const codePoint = char.codePointAt(0) ?? 0;
+ return char === '\n' || char === '\t' || (codePoint >= 0x20 && codePoint !== 0x7f);
+ })
+ .join('');
}
export function resolveTooltipPosition(options: ResolveTooltipPositionOptions): TooltipPosition {
diff --git a/frontend-modern/src/utils/logger.ts b/frontend-modern/src/utils/logger.ts
index 63c4b64594..2aea0f4d44 100644
--- a/frontend-modern/src/utils/logger.ts
+++ b/frontend-modern/src/utils/logger.ts
@@ -3,7 +3,7 @@ const isDev = import.meta.env.DEV;
export const logger = {
debug: (message: string, data?: unknown) => {
- if (isDev) console.log(`[DEBUG] ${message}`, data ?? '');
+ if (isDev) console.log('%s', `[DEBUG] ${message}`, data ?? '');
},
info: (message: string, data?: unknown) => {
@@ -14,16 +14,16 @@ export const logger = {
message.includes('error') ||
message.includes('failed')
) {
- console.log(`[INFO] ${message}`, data ?? '');
+ console.log('%s', `[INFO] ${message}`, data ?? '');
}
},
warn: (message: string, data?: unknown) => {
- console.warn(`[WARN] ${message}`, data ?? '');
+ console.warn('%s', `[WARN] ${message}`, data ?? '');
},
error: (message: string, error?: unknown) => {
- console.error(`[ERROR] ${message}`, error ?? '');
+ console.error('%s', `[ERROR] ${message}`, error ?? '');
},
};
diff --git a/internal/api/connections_probe.go b/internal/api/connections_probe.go
index a5c4771a5d..517d86b051 100644
--- a/internal/api/connections_probe.go
+++ b/internal/api/connections_probe.go
@@ -286,8 +286,11 @@ func runProbe(ctx context.Context, host string, port int, client *http.Client) (
// probeOne runs a single probe. It returns (candidate, true) only when the
// target's identifyFn confirms the product.
func probeOne(ctx context.Context, host string, target probeTarget, client *http.Client) (ProbeCandidate, bool) {
- endpoint := fmt.Sprintf("%s://%s:%d%s", target.Scheme, host, target.Port, target.Path)
- req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint, nil)
+ endpoint, err := validatedProbeEndpoint(ctx, host, target)
+ if err != nil {
+ return ProbeCandidate{}, false
+ }
+ req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint.String(), nil)
if err != nil {
return ProbeCandidate{}, false
}
@@ -324,8 +327,21 @@ func probeOne(ctx context.Context, host string, target probeTarget, client *http
return ProbeCandidate{
Type: target.Type,
- Host: fmt.Sprintf("%s://%s:%d", target.Scheme, host, target.Port),
+ Host: fmt.Sprintf("%s://%s", target.Scheme, endpoint.Host),
Port: target.Port,
Hints: hints,
}, true
}
+
+func validatedProbeEndpoint(ctx context.Context, host string, target probeTarget) (*url.URL, error) {
+ endpoint := &url.URL{
+ Scheme: target.Scheme,
+ Host: net.JoinHostPort(host, strconv.Itoa(target.Port)),
+ Path: target.Path,
+ }
+ return securityutil.ValidateOutboundFetchURL(ctx, endpoint.String(), securityutil.RestrictedOutboundHTTPOptions{
+ AllowedSchemes: []string{"https"},
+ AllowPrivateIPs: true,
+ AllowLoopback: true,
+ })
+}
diff --git a/internal/api/connections_probe_test.go b/internal/api/connections_probe_test.go
index 8dd3a1c59a..5cc08cadeb 100644
--- a/internal/api/connections_probe_test.go
+++ b/internal/api/connections_probe_test.go
@@ -336,6 +336,21 @@ func TestValidateProbeHostRejectsMetadataService(t *testing.T) {
}
}
+func TestValidatedProbeEndpointRejectsMetadataService(t *testing.T) {
+ _, err := validatedProbeEndpoint(context.Background(), "169.254.169.254", probeTarget{
+ Type: ConnectionTypePVE,
+ Scheme: "https",
+ Port: 8006,
+ Path: "/",
+ })
+ if err == nil {
+ t.Fatal("expected metadata service endpoint to be rejected")
+ }
+ if !strings.Contains(err.Error(), "metadata service") {
+ t.Fatalf("unexpected error: %v", err)
+ }
+}
+
func TestConnectionsHandlersHandleProbeRejectsBlockedAddress(t *testing.T) {
h := NewConnectionsHandlers(nil, nil, nil)
body := strings.NewReader(`{"address":"169.254.169.254"}`)
diff --git a/internal/api/report_schedules.go b/internal/api/report_schedules.go
index 4f236749a4..a034e26eaf 100644
--- a/internal/api/report_schedules.go
+++ b/internal/api/report_schedules.go
@@ -8,7 +8,6 @@ import (
"io"
"net/http"
"os"
- "path/filepath"
"sort"
"strings"
"time"
@@ -542,7 +541,7 @@ func saveGeneratedReport(persistence *config.ConfigPersistence, schedule config.
if err != nil {
return "", err
}
- scheduleDir, err := securityutil.JoinStorageLeaf(generatedDir, schedule.ID)
+ scheduleDir, err := securityutil.JoinStorageLeaf(generatedDir, securityutil.HashedStorageName(schedule.ID))
if err != nil {
return "", err
}
@@ -553,7 +552,10 @@ func saveGeneratedReport(persistence *config.ConfigPersistence, schedule config.
if filename == "" {
filename = "report." + string(report.Format)
}
- path := filepath.Join(scheduleDir, filename)
+ path, err := securityutil.JoinStorageLeaf(scheduleDir, filename)
+ if err != nil {
+ return "", err
+ }
if err := os.WriteFile(path, report.Data, 0o600); err != nil {
return "", fmt.Errorf("write generated report: %w", err)
}
@@ -582,7 +584,11 @@ func pruneGeneratedReports(dir string, retentionCount int) {
if err != nil {
continue
}
- files = append(files, generatedFile{path: filepath.Join(dir, entry.Name()), modTime: info.ModTime()})
+ path, err := securityutil.JoinStorageLeaf(dir, entry.Name())
+ if err != nil {
+ continue
+ }
+ files = append(files, generatedFile{path: path, modTime: info.ModTime()})
}
sort.Slice(files, func(i, j int) bool {
return files[i].modTime.After(files[j].modTime)
diff --git a/internal/api/report_schedules_test.go b/internal/api/report_schedules_test.go
index b26391e36d..d605dc5653 100644
--- a/internal/api/report_schedules_test.go
+++ b/internal/api/report_schedules_test.go
@@ -6,10 +6,13 @@ import (
"encoding/json"
"net/http"
"net/http/httptest"
+ "path/filepath"
+ "strings"
"testing"
"github.com/rcourtman/pulse-go-rewrite/internal/config"
"github.com/rcourtman/pulse-go-rewrite/internal/monitoring"
+ "github.com/rcourtman/pulse-go-rewrite/internal/securityutil"
"github.com/rcourtman/pulse-go-rewrite/pkg/reporting"
)
@@ -170,3 +173,35 @@ func TestRunReportSchedulePersistsFailureStatusWhenEngineUnavailable(t *testing.
t.Fatalf("run status fields = lastRunAt %v lastError %q, want populated", stored.Schedules[0].LastRunAt, stored.Schedules[0].LastError)
}
}
+
+func TestSaveGeneratedReportUsesHashedScheduleDirectory(t *testing.T) {
+ _, persistence := newTestReportingScheduleHandlers(t)
+ schedule := validReportSchedulePayload()
+ schedule.ID = "../tenant-owned-schedule"
+ report := generatedMultiReport{
+ Data: []byte("report"),
+ Filename: "../unsafe-report.pdf",
+ Format: reporting.FormatPDF,
+ }
+
+ path, err := saveGeneratedReport(persistence, schedule, report)
+ if err != nil {
+ t.Fatalf("saveGeneratedReport() error = %v", err)
+ }
+
+ wantDir := filepath.Join(
+ persistence.DataDir(),
+ "reports",
+ "generated",
+ securityutil.HashedStorageName(schedule.ID),
+ )
+ if filepath.Dir(path) != wantDir {
+ t.Fatalf("report dir = %q, want %q", filepath.Dir(path), wantDir)
+ }
+ if strings.Contains(path, schedule.ID) {
+ t.Fatalf("report path leaked raw schedule ID: %q", path)
+ }
+ if strings.ContainsAny(filepath.Base(path), `/\`) {
+ t.Fatalf("report filename still contains a path separator: %q", filepath.Base(path))
+ }
+}
diff --git a/internal/cloudcp/portal/frontend/dev.mjs b/internal/cloudcp/portal/frontend/dev.mjs
index c64f60f989..8828900c42 100644
--- a/internal/cloudcp/portal/frontend/dev.mjs
+++ b/internal/cloudcp/portal/frontend/dev.mjs
@@ -1,7 +1,7 @@
import fs from 'node:fs';
import http from 'node:http';
import path from 'node:path';
-import { createHash } from 'node:crypto';
+import { createHash, randomBytes } from 'node:crypto';
import { context } from 'esbuild';
import { createPortalBuildOptions, frontendRoot } from './build_config.mjs';
@@ -21,6 +21,10 @@ function deepClone(value) {
return JSON.parse(JSON.stringify(value));
}
+function randomPreviewID(prefix) {
+ return prefix + randomBytes(5).toString('hex');
+}
+
function standardSetupTemplates() {
return [{
id: 'standard-client-onboarding',
@@ -456,6 +460,25 @@ function escapeHTML(value) {
.replace(/'/g, '&#39;');
}
+function inlineScriptJSON(value) {
+ return JSON.stringify(value).replace(/[<>&\u2028\u2029]/g, function(char) {
+ switch (char) {
+ case '<':
+ return '\\u003c';
+ case '>':
+ return '\\u003e';
+ case '&':
+ return '\\u0026';
+ case '\u2028':
+ return '\\u2028';
+ case '\u2029':
+ return '\\u2029';
+ default:
+ return char;
+ }
+ });
+}
+
function previewReturnURL(request, scenario, toastMessage) {
const origin = 'http://' + previewHost + ':' + String(previewPort);
const url = new URL('/', origin);
@@ -708,8 +731,8 @@ function buildPreviewWorkspaceHTML(bootstrap, workspaceID, targetPath, scenario,
}
function buildPreviewHTML(assets, bootstrap, previewToast) {
- const bootstrapJSON = JSON.stringify(bootstrap).replace(/</g, '\\u003c');
- const safeToast = previewToast ? JSON.stringify(String(previewToast)) : 'null';
+ const bootstrapJSON = inlineScriptJSON(bootstrap);
+ const safeToast = previewToast ? inlineScriptJSON(String(previewToast)) : 'null';
return '<!DOCTYPE html>' +
'<html lang="en">' +
'<head>' +
@@ -851,7 +874,7 @@ function routeAccountAPI(request, response, url, bootstrap, scenario) {
members.push({
email,
role,
- user_id: 'u_' + Math.random().toString(36).slice(2, 10),
+ user_id: randomPreviewID('u_'),
created_at: iso(new Date()),
});
account.members = members;
@@ -920,7 +943,7 @@ function routeAccountAPI(request, response, url, bootstrap, scenario) {
}
account.workspaces = account.workspaces || [];
const workspace = {
- id: 'ws_' + Math.random().toString(36).slice(2, 10),
+ id: randomPreviewID('ws_'),
display_name: displayName,
state: 'active',
healthy: true,
diff --git a/internal/monitoring/availability_poller.go b/internal/monitoring/availability_poller.go
index 1835755271..1e7d2391d7 100644
--- a/internal/monitoring/availability_poller.go
+++ b/internal/monitoring/availability_poller.go
@@ -6,6 +6,7 @@ import (
"fmt"
"net"
"net/http"
+ "net/url"
"os/exec"
"runtime"
"sort"
@@ -14,6 +15,7 @@ import (
"time"
"github.com/rcourtman/pulse-go-rewrite/internal/config"
+ "github.com/rcourtman/pulse-go-rewrite/internal/securityutil"
"github.com/rcourtman/pulse-go-rewrite/internal/storagehealth"
"github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources"
)
@@ -428,10 +430,12 @@ func probeHTTP(ctx context.Context, target config.AvailabilityTarget, timeout ti
if err != nil {
return err
}
- transport := &http.Transport{
- TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
+ opts := availabilityHTTPOutboundOptions()
+ u, err = securityutil.ValidateOutboundFetchURL(ctx, u.String(), opts)
+ if err != nil {
+ return fmt.Errorf("http availability target URL validation failed: %w", err)
}
- client := http.Client{Timeout: timeout, Transport: transport}
+ client := securityutil.NewRestrictedOutboundHTTPClient(timeout, opts)
req, err := http.NewRequestWithContext(ctx, http.MethodHead, u.String(), nil)
if err != nil {
return fmt.Errorf("build http availability request: %w", err)
@@ -441,7 +445,7 @@ func probeHTTP(ctx context.Context, target config.AvailabilityTarget, timeout ti
if err == nil {
defer resp.Body.Close()
if resp.StatusCode == http.StatusMethodNotAllowed {
- return probeHTTPGet(ctx, client, u.String())
+ return probeHTTPGet(ctx, client, u)
}
if resp.StatusCode >= http.StatusInternalServerError {
return fmt.Errorf("http probe returned %s", resp.Status)
@@ -452,51 +456,23 @@ func probeHTTP(ctx context.Context, target config.AvailabilityTarget, timeout ti
return ctxErr
}
- return probeHTTPViaSystem(ctx, u.String(), target.EffectiveTimeoutMillis())
+ return fmt.Errorf("http probe failed: %w", err)
}
-func probeHTTPViaSystem(ctx context.Context, rawURL string, timeoutMillis int) error {
- timeoutSecs := (timeoutMillis + 999) / 1000
- if timeoutSecs < 1 {
- timeoutSecs = 1
- }
- timeoutStr := strconv.Itoa(timeoutSecs)
-
- args := []string{
- "-s", "-o", "/dev/null",
- "-w", "%{http_code}",
- "--connect-timeout", timeoutStr,
- "--max-time", timeoutStr,
- "-k",
- rawURL,
- }
-
- cmd := exec.CommandContext(ctx, "curl", args...)
- output, err := cmd.CombinedOutput()
- if err != nil {
- if ctxErr := ctx.Err(); ctxErr != nil {
- return ctxErr
- }
- details := strings.TrimSpace(string(output))
- if len(details) > 240 {
- details = details[:240]
- }
- if details == "" {
- return fmt.Errorf("http probe failed: %w", err)
- }
- return fmt.Errorf("http probe failed: %s", details)
- }
-
- statusCode := strings.TrimSpace(string(output))
- code, _ := strconv.Atoi(statusCode)
- if code >= 500 {
- return fmt.Errorf("http probe returned status %s", statusCode)
+func availabilityHTTPOutboundOptions() securityutil.RestrictedOutboundHTTPOptions {
+ return securityutil.RestrictedOutboundHTTPOptions{
+ AllowedSchemes: []string{"http", "https"},
+ AllowPrivateIPs: true,
+ AllowLoopback: true,
+ TLSConfig: &tls.Config{
+ MinVersion: tls.VersionTLS12,
+ InsecureSkipVerify: true, //nolint:gosec // Availability probes must support self-signed operator endpoints.
+ },
}
- return nil
}
-func probeHTTPGet(ctx context.Context, client http.Client, url string) error {
- req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
+func probeHTTPGet(ctx context.Context, client *http.Client, u *url.URL) error {
+ req, err := http.NewRequestWithContext(ctx, http.MethodGet, u.String(), nil)
if err != nil {
return fmt.Errorf("build http availability fallback request: %w", err)
}
diff --git a/internal/monitoring/availability_poller_test.go b/internal/monitoring/availability_poller_test.go
index 59eef22baa..926930b44f 100644
--- a/internal/monitoring/availability_poller_test.go
+++ b/internal/monitoring/availability_poller_test.go
@@ -4,6 +4,7 @@ import (
"context"
"net/http"
"net/http/httptest"
+ "strings"
"testing"
"time"
@@ -54,6 +55,23 @@ func TestProbeAvailabilityTargetHTTPTreatsServerErrorsAsUnavailable(t *testing.T
}
}
+func TestProbeAvailabilityTargetHTTPRejectsMetadataService(t *testing.T) {
+ target := config.NormalizeAvailabilityTarget(config.AvailabilityTarget{
+ Address: "http://169.254.169.254/latest/meta-data",
+ Protocol: config.AvailabilityProbeHTTP,
+ Enabled: true,
+ TimeoutMillis: 1000,
+ })
+
+ err := ProbeAvailabilityTarget(context.Background(), target)
+ if err == nil {
+ t.Fatal("ProbeAvailabilityTarget() error = nil, want metadata-service rejection")
+ }
+ if got := err.Error(); !strings.Contains(got, "metadata service") {
+ t.Fatalf("error = %q, want metadata-service rejection", got)
+ }
+}
+
func TestAvailabilityPollProviderSupplementalRecordsProjectNetworkEndpointIncident(t *testing.T) {
persistence := config.NewConfigPersistence(t.TempDir())
target := config.NormalizeAvailabilityTarget(config.AvailabilityTarget{
diff --git a/internal/notifications/notifications.go b/internal/notifications/notifications.go
index 3cee584b53..d5872ef68e 100644
--- a/internal/notifications/notifications.go
+++ b/internal/notifications/notifications.go
@@ -263,7 +263,7 @@ type webhookRequestOptions struct {
// It exists so tests can disable or inline async behavior without relying on sleeps.
var spawnAsync = func(f func()) { go f() }
-type appriseExecFunc func(ctx context.Context, path string, args []string) ([]byte, error)
+type appriseExecFunc func(ctx context.Context, args []string) ([]byte, error)
// copyEmailConfig returns a defensive copy of EmailConfig including its slices to avoid data races.
func copyEmailConfig(cfg EmailConfig) EmailConfig {
@@ -505,8 +505,8 @@ func NormalizeAppriseConfig(cfg AppriseConfig) AppriseConfig {
return normalized
}
-func defaultAppriseExec(ctx context.Context, path string, args []string) ([]byte, error) {
- cmd := exec.CommandContext(ctx, path, args...)
+func defaultAppriseExec(ctx context.Context, args []string) ([]byte, error) {
+ cmd := exec.CommandContext(ctx, "apprise", args...)
return cmd.CombinedOutput()
}
@@ -1699,21 +1699,21 @@ func (n *NotificationManager) sendAppriseViaCLI(cfg AppriseConfig, title, body s
execFn = defaultAppriseExec
}
- output, err := execFn(ctx, cfg.CLIPath, args)
+ output, err := execFn(ctx, args)
if err != nil {
if len(output) > 0 {
log.Debug().
- Str("cliPath", cfg.CLIPath).
+ Str("cliPath", "apprise").
Strs("targets", cfg.Targets).
Str("output", string(output)).
Msg("apprise CLI output (error)")
}
- return fmt.Errorf("execute apprise CLI %q: %w", cfg.CLIPath, err)
+ return fmt.Errorf("execute apprise CLI %q: %w", "apprise", err)
}
if len(output) > 0 {
log.Debug().
- Str("cliPath", cfg.CLIPath).
+ Str("cliPath", "apprise").
Strs("targets", cfg.Targets).
Str("output", string(output)).
Msg("apprise CLI output")
diff --git a/internal/notifications/notifications_additional_test.go b/internal/notifications/notifications_additional_test.go
index ae4a7adacf..f55815d14a 100644
--- a/internal/notifications/notifications_additional_test.go
+++ b/internal/notifications/notifications_additional_test.go
@@ -19,11 +19,8 @@ func TestSendResolvedAppriseCLI(t *testing.T) {
defer manager.Stop()
var called bool
- manager.appriseExec = func(ctx context.Context, path string, args []string) ([]byte, error) {
+ manager.appriseExec = func(ctx context.Context, args []string) ([]byte, error) {
called = true
- if path != "apprise" {
- t.Fatalf("expected CLI path apprise, got %q", path)
- }
if len(args) == 0 || args[len(args)-1] != "target-1" {
t.Fatalf("expected target to be passed, got %v", args)
}
@@ -545,7 +542,7 @@ func TestSendResolvedNotificationsDirectDispatchesEnabledTargets(t *testing.T) {
})
appriseCalled := false
- manager.appriseExec = func(ctx context.Context, path string, args []string) ([]byte, error) {
+ manager.appriseExec = func(ctx context.Context, args []string) ([]byte, error) {
appriseCalled = true
return nil, nil
}
diff --git a/internal/notifications/notifications_resolved_apprise_test.go b/internal/notifications/notifications_resolved_apprise_test.go
index 5a1d5a189f..b95f0a8265 100644
--- a/internal/notifications/notifications_resolved_apprise_test.go
+++ b/internal/notifications/notifications_resolved_apprise_test.go
@@ -76,7 +76,7 @@ func TestSendResolvedApprise_CLI(t *testing.T) {
nm := NewNotificationManager("")
defer nm.Stop()
- nm.appriseExec = func(ctx context.Context, path string, args []string) ([]byte, error) {
+ nm.appriseExec = func(ctx context.Context, args []string) ([]byte, error) {
return nil, nil
}
diff --git a/internal/notifications/notifications_security_cli_test.go b/internal/notifications/notifications_security_cli_test.go
index 5abf090930..54bc1655d0 100644
--- a/internal/notifications/notifications_security_cli_test.go
+++ b/internal/notifications/notifications_security_cli_test.go
@@ -4,7 +4,6 @@ import (
"context"
"errors"
"testing"
- "time"
)
func TestSendAppriseViaCLINoTargets(t *testing.T) {
@@ -24,7 +23,7 @@ func TestSendAppriseViaCLIExecError(t *testing.T) {
nm := NewNotificationManager("")
defer nm.Stop()
- nm.appriseExec = func(ctx context.Context, path string, args []string) ([]byte, error) {
+ nm.appriseExec = func(ctx context.Context, args []string) ([]byte, error) {
return []byte("boom"), errors.New("exec failed")
}
@@ -42,7 +41,7 @@ func TestSendAppriseViaCLISuccess(t *testing.T) {
nm := NewNotificationManager("")
defer nm.Stop()
- nm.appriseExec = func(ctx context.Context, path string, args []string) ([]byte, error) {
+ nm.appriseExec = func(ctx context.Context, args []string) ([]byte, error) {
return []byte("ok"), nil
}
@@ -60,7 +59,7 @@ func TestSendAppriseViaCLISuccessNoOutput(t *testing.T) {
nm := NewNotificationManager("")
defer nm.Stop()
- nm.appriseExec = func(ctx context.Context, path string, args []string) ([]byte, error) {
+ nm.appriseExec = func(ctx context.Context, args []string) ([]byte, error) {
return nil, nil
}
@@ -73,12 +72,3 @@ func TestSendAppriseViaCLISuccessNoOutput(t *testing.T) {
t.Fatalf("expected success, got %v", err)
}
}
-
-func TestDefaultAppriseExecRunsCommand(t *testing.T) {
- ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
- defer cancel()
-
- if _, err := defaultAppriseExec(ctx, "true", nil); err != nil {
- t.Fatalf("expected defaultAppriseExec to run, got %v", err)
- }
-}
diff --git a/internal/notifications/notifications_test.go b/internal/notifications/notifications_test.go
index 26dbffa063..5a41ab868c 100644
--- a/internal/notifications/notifications_test.go
+++ b/internal/notifications/notifications_test.go
@@ -182,10 +182,7 @@ func TestSendGroupedAppriseInvokesExecutor(t *testing.T) {
done := make(chan struct{}, 1)
var capturedArgs []string
- nm.appriseExec = func(ctx context.Context, path string, args []string) ([]byte, error) {
- if path != "apprise" {
- t.Fatalf("expected CLI path 'apprise', got %q", path)
- }
+ nm.appriseExec = func(ctx context.Context, args []string) ([]byte, error) {
capturedArgs = append([]string(nil), args...)
select {
case done <- struct{}{}:
@@ -846,10 +843,7 @@ func TestSendTestNotificationApprise(t *testing.T) {
var once sync.Once
var capturedArgs []string
- nm.appriseExec = func(ctx context.Context, path string, args []string) ([]byte, error) {
- if path != "apprise" {
- t.Fatalf("expected CLI path 'apprise', got %q", path)
- }
+ nm.appriseExec = func(ctx context.Context, args []string) ([]byte, error) {
capturedArgs = append([]string(nil), args...)
// Use sync.Once to safely close channel even if callback is invoked multiple times
once.Do(func() { close(done) })
@@ -904,10 +898,10 @@ func TestSendTestAppriseWithConfig(t *testing.T) {
done := make(chan struct{})
var once sync.Once
- var cliPath string
+ var called bool
- nm.appriseExec = func(ctx context.Context, path string, args []string) ([]byte, error) {
- cliPath = path
+ nm.appriseExec = func(ctx context.Context, args []string) ([]byte, error) {
+ called = true
// Use sync.Once to safely close channel even if callback is invoked multiple times
once.Do(func() { close(done) })
return []byte("ok"), nil
@@ -928,8 +922,8 @@ func TestSendTestAppriseWithConfig(t *testing.T) {
t.Fatalf("timeout waiting for Apprise test execution")
}
- if cliPath != "apprise" {
- t.Fatalf("expected default CLI path 'apprise', got %q", cliPath)
+ if !called {
+ t.Fatalf("expected Apprise executor to run")
}
}
diff --git a/internal/relay/proxy.go b/internal/relay/proxy.go
index c4d45fa558..7cefd6ef42 100644
--- a/internal/relay/proxy.go
+++ b/internal/relay/proxy.go
@@ -9,6 +9,7 @@ import (
"fmt"
"io"
"net/http"
+ "net/url"
"strings"
"time"
@@ -101,10 +102,11 @@ func (p *HTTPProxy) HandleRequest(payload []byte, apiToken string) ([]byte, erro
return p.errorResponse(req.ID, http.StatusBadRequest, "missing required fields (id, method, path)"), nil
}
- // Ensure path starts with /
- if !strings.HasPrefix(req.Path, "/") {
- req.Path = "/" + req.Path
+ localURL, err := p.localAPIURL(req.Path)
+ if err != nil {
+ return p.errorResponse(req.ID, http.StatusBadRequest, "invalid proxy path"), nil
}
+ req.Path = localURL.RequestURI()
// Decode body if present
var bodyReader io.Reader
@@ -119,11 +121,12 @@ func (p *HTTPProxy) HandleRequest(payload []byte, apiToken string) ([]byte, erro
bodyReader = bytes.NewReader(bodyBytes)
}
- url := fmt.Sprintf("http://%s%s", p.localAddr, req.Path)
- httpReq, err := http.NewRequest(req.Method, url, bodyReader)
+ httpReq, err := http.NewRequest(req.Method, p.localAPIOrigin(), bodyReader)
if err != nil {
return p.errorResponse(req.ID, http.StatusInternalServerError, "failed to create request"), nil
}
+ httpReq.URL.Path = localURL.Path
+ httpReq.URL.RawQuery = localURL.RawQuery
// Allowlist: only forward safe, content-describing headers.
// Everything else is stripped to prevent auth-context leakage
@@ -208,9 +211,12 @@ func (p *HTTPProxy) HandleStreamRequest(ctx context.Context, payload []byte, api
return nil
}
- if !strings.HasPrefix(req.Path, "/") {
- req.Path = "/" + req.Path
+ localURL, err := p.localAPIURL(req.Path)
+ if err != nil {
+ sendFrame(p.errorResponse(req.ID, http.StatusBadRequest, "invalid proxy path"))
+ return nil
}
+ req.Path = localURL.RequestURI()
var bodyReader io.Reader
if req.Body != "" {
@@ -226,12 +232,13 @@ func (p *HTTPProxy) HandleStreamRequest(ctx context.Context, payload []byte, api
bodyReader = bytes.NewReader(bodyBytes)
}
- url := fmt.Sprintf("http://%s%s", p.localAddr, req.Path)
- httpReq, err := http.NewRequestWithContext(ctx, req.Method, url, bodyReader)
+ httpReq, err := http.NewRequestWithContext(ctx, req.Method, p.localAPIOrigin(), bodyReader)
if err != nil {
sendFrame(p.errorResponse(req.ID, http.StatusInternalServerError, "failed to create request"))
return nil
}
+ httpReq.URL.Path = localURL.Path
+ httpReq.URL.RawQuery = localURL.RawQuery
for k, v := range req.Headers {
headerName := strings.TrimSpace(k)
@@ -426,6 +433,51 @@ func allowedProxyHeader(name string) bool {
return allowedProxyHeaders[strings.ToLower(strings.TrimSpace(name))]
}
+func (p *HTTPProxy) localAPIURL(rawPath string) (*url.URL, error) {
+ requestURI, err := normalizeProxyRequestURI(rawPath)
+ if err != nil {
+ return nil, err
+ }
+ return &url.URL{
+ Scheme: "http",
+ Host: p.localAddr,
+ Path: requestURI.Path,
+ RawQuery: requestURI.RawQuery,
+ }, nil
+}
+
+func (p *HTTPProxy) localAPIOrigin() string {
+ return "http://" + p.localAddr
+}
+
+func normalizeProxyRequestURI(rawPath string) (*url.URL, error) {
+ trimmed := strings.TrimSpace(rawPath)
+ if trimmed == "" {
+ return nil, fmt.Errorf("proxy path is required")
+ }
+ parsed, err := url.ParseRequestURI(trimmed)
+ if err != nil && !strings.HasPrefix(trimmed, "/") {
+ parsed, err = url.ParseRequestURI("/" + trimmed)
+ }
+ if err != nil {
+ return nil, fmt.Errorf("invalid proxy path: %w", err)
+ }
+ if parsed.Scheme != "" || parsed.Host != "" || parsed.Opaque != "" {
+ return nil, fmt.Errorf("proxy path must be origin-relative")
+ }
+ if parsed.Path == "" {
+ parsed.Path = "/"
+ }
+ if !strings.HasPrefix(parsed.Path, "/") {
+ parsed.Path = "/" + parsed.Path
+ }
+ if strings.HasPrefix(parsed.Path, "//") {
+ return nil, fmt.Errorf("proxy path must not be network-path relative")
+ }
+ parsed.Fragment = ""
+ return parsed, nil
+}
+
func (p *HTTPProxy) errorResponse(requestID string, status int, message string) []byte {
resp := ProxyResponse{
ID: requestID,
diff --git a/internal/relay/proxy_additional_test.go b/internal/relay/proxy_additional_test.go
index e1cacb5e17..663bbe66ea 100644
--- a/internal/relay/proxy_additional_test.go
+++ b/internal/relay/proxy_additional_test.go
@@ -142,6 +142,29 @@ func TestHTTPProxy_HandleRequest_ErrorBranches(t *testing.T) {
})
}
+func TestNormalizeProxyRequestURIRejectsNonOriginRelativePaths(t *testing.T) {
+ for _, rawPath := range []string{
+ "http://169.254.169.254/latest/meta-data",
+ "//169.254.169.254/latest/meta-data",
+ } {
+ t.Run(rawPath, func(t *testing.T) {
+ if _, err := normalizeProxyRequestURI(rawPath); err == nil {
+ t.Fatalf("expected %q to be rejected", rawPath)
+ }
+ })
+ }
+}
+
+func TestNormalizeProxyRequestURIPreservesLocalPathAndQuery(t *testing.T) {
+ got, err := normalizeProxyRequestURI("api/resources?filter=http%3A%2F%2Fexample.test")
+ if err != nil {
+ t.Fatalf("normalizeProxyRequestURI() error = %v", err)
+ }
+ if got.RequestURI() != "/api/resources?filter=http%3A%2F%2Fexample.test" {
+ t.Fatalf("RequestURI() = %q", got.RequestURI())
+ }
+}
+
func mustHandleRequest(t *testing.T, proxy *HTTPProxy, payload []byte) []byte {
t.Helper()
resp, err := proxy.HandleRequest(payload, "token")
diff --git a/pkg/licensing/activation_store.go b/pkg/licensing/activation_store.go
index 05128502da..5a0401ae63 100644
--- a/pkg/licensing/activation_store.go
+++ b/pkg/licensing/activation_store.go
@@ -32,7 +32,7 @@ func (p *Persistence) LoadOrCreateInstanceFingerprint() (string, error) {
if fingerprint == "" {
return "", fmt.Errorf("instance fingerprint file is empty")
}
- if err := os.Chmod(fingerprintPath, persistencePrivateFilePerm); err != nil {
+ if err := p.SaveInstanceFingerprint(fingerprint); err != nil {
return "", fmt.Errorf("secure instance fingerprint file: %w", err)
}
return fingerprint, nil
diff --git a/pkg/licensing/activation_store_test.go b/pkg/licensing/activation_store_test.go
index bc5a9903ca..bb6709c9be 100644
--- a/pkg/licensing/activation_store_test.go
+++ b/pkg/licensing/activation_store_test.go
@@ -322,6 +322,34 @@ func TestInstanceFingerprintPersistenceSurvivesActivationClear(t *testing.T) {
}
}
+func TestInstanceFingerprintReadHardensExistingFilePermissions(t *testing.T) {
+ tmpDir := t.TempDir()
+ p, err := NewPersistence(tmpDir)
+ if err != nil {
+ t.Fatalf("create persistence: %v", err)
+ }
+
+ fingerprintPath := filepath.Join(tmpDir, InstanceFingerprintFileName)
+ if err := os.WriteFile(fingerprintPath, []byte("existing-fingerprint\n"), 0o644); err != nil {
+ t.Fatalf("write fingerprint file: %v", err)
+ }
+
+ fingerprint, err := p.LoadOrCreateInstanceFingerprint()
+ if err != nil {
+ t.Fatalf("LoadOrCreateInstanceFingerprint: %v", err)
+ }
+ if fingerprint != "existing-fingerprint" {
+ t.Fatalf("fingerprint = %q, want existing-fingerprint", fingerprint)
+ }
+ info, err := os.Stat(fingerprintPath)
+ if err != nil {
+ t.Fatalf("stat fingerprint file: %v", err)
+ }
+ if got := info.Mode().Perm(); got != 0o600 {
+ t.Fatalf("fingerprint file perms = %o, want 600", got)
+ }
+}
+
func TestInstanceFingerprintPersistenceSeedsFromExistingActivationState(t *testing.T) {
tmpDir, err := os.MkdirTemp("", "pulse-fingerprint-seed-test-*")
if err != nil {
diff --git a/tests/integration/tests/09-cloud-billing-lifecycle.spec.ts b/tests/integration/tests/09-cloud-billing-lifecycle.spec.ts
index df075f1b55..de9f190847 100644
--- a/tests/integration/tests/09-cloud-billing-lifecycle.spec.ts
+++ b/tests/integration/tests/09-cloud-billing-lifecycle.spec.ts
@@ -1,4 +1,5 @@
import { expect, test } from '@playwright/test';
+import { randomInt } from 'node:crypto';
import { completeStripeSandboxCheckout } from './stripe-sandbox';
import { sendStripeWebhook } from './stripe-webhooks';
import { preferredPlaywrightRouteBaseURL } from './runtime-defaults';
@@ -48,7 +49,7 @@ function requiredEnv(name: string): string {
}
function signupIdentity() {
- const suffix = `${Date.now()}-${Math.floor(Math.random() * 1_000_000)}`;
+ const suffix = `${Date.now()}-${randomInt(1_000_000)}`;
const domain = (process.env.PULSE_E2E_CLOUD_EMAIL_DOMAIN || 'example.com').trim() || 'example.com';
return {
email: `cloud-lifecycle-${suffix}@${domain}`,