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 remaining CodeQL security boundaries

rcourtman042e7ef96692
diff --git a/.github/codeql/extensions/pulse-security-models/models/go-storage.yml b/.github/codeql/extensions/pulse-security-models/models/go-storage.yml
index 2ab7361711..78d675c72c 100644
--- a/.github/codeql/extensions/pulse-security-models/models/go-storage.yml
+++ b/.github/codeql/extensions/pulse-security-models/models/go-storage.yml
@@ -7,8 +7,10 @@ extensions:
- ["github.com/rcourtman/pulse-go-rewrite/internal/securityutil", "", false, "JoinStorageLeaf", "", "", "ReturnValue[0]", "path-injection", "manual"]
- ["github.com/rcourtman/pulse-go-rewrite/internal/securityutil", "", false, "NormalizeStorageDir", "", "", "ReturnValue[0]", "path-injection", "manual"]
- ["github.com/rcourtman/pulse-go-rewrite/internal/securityutil", "", false, "ValidateOutboundFetchURL", "", "", "ReturnValue[0]", "request-forgery", "manual"]
+ - ["github.com/rcourtman/pulse-go-rewrite/internal/api", "", false, "normalizeConfiguredSSOFilePath", "", "", "ReturnValue[0]", "path-injection", "manual"]
- addsTo:
pack: codeql/go-all
extensible: barrierGuardModel
data:
- ["github.com/rcourtman/pulse-go-rewrite/internal/config", "", false, "isValidOrgID", "", "", "Argument[0]", "true", "path-injection", "manual"]
+ - ["github.com/rcourtman/pulse-go-rewrite/internal/api", "", false, "isValidTenantOrgID", "", "", "Argument[0]", "true", "path-injection", "manual"]
diff --git a/cmd/pulse-control-plane/provider_msp_proof.go b/cmd/pulse-control-plane/provider_msp_proof.go
index 14a6bfedb2..c757a7bd69 100644
--- a/cmd/pulse-control-plane/provider_msp_proof.go
+++ b/cmd/pulse-control-plane/provider_msp_proof.go
@@ -29,6 +29,7 @@ import (
agentshost "github.com/rcourtman/pulse-go-rewrite/pkg/agents/host"
internalauth "github.com/rcourtman/pulse-go-rewrite/pkg/auth"
pkglicensing "github.com/rcourtman/pulse-go-rewrite/pkg/licensing"
+ "github.com/rcourtman/pulse-go-rewrite/pkg/securityutil"
"github.com/spf13/cobra"
)
@@ -358,9 +359,11 @@ func normalizeProviderMSPProofOptions(opts providerMSPProofOptions) (providerMSP
if opts.TargetPath == "" {
opts.TargetPath = "/settings/infrastructure?add=linux-host"
}
- if !strings.HasPrefix(opts.TargetPath, "/") || strings.HasPrefix(opts.TargetPath, "//") {
+ normalizedTargetPath, err := securityutil.NormalizeLocalRedirectPath(opts.TargetPath)
+ if err != nil {
return opts, fmt.Errorf("--target-path must be a local absolute path")
}
+ opts.TargetPath = normalizedTargetPath
return opts, nil
}
diff --git a/cmd/pulse-control-plane/provider_msp_proof_test.go b/cmd/pulse-control-plane/provider_msp_proof_test.go
index c1d34e6ba3..d81786bb45 100644
--- a/cmd/pulse-control-plane/provider_msp_proof_test.go
+++ b/cmd/pulse-control-plane/provider_msp_proof_test.go
@@ -39,6 +39,23 @@ func TestNormalizeProviderMSPProofOptionsRequiresIsolationWorkspaceCount(t *test
}
}
+func TestNormalizeProviderMSPProofOptionsRejectsCrossOriginTargetPaths(t *testing.T) {
+ base := providerMSPProofOptions{
+ AccountName: "Acme MSP",
+ OwnerEmail: "[email protected]",
+ WorkspacePrefix: "Provider MSP Proof",
+ WorkspaceCount: 2,
+ InstallType: "pve",
+ }
+ for _, targetPath := range []string{"//evil.example/path", `/\\evil.example/path`, "/%2f%2fevil.example/path", "https://evil.example/path"} {
+ opts := base
+ opts.TargetPath = targetPath
+ if _, err := normalizeProviderMSPProofOptions(opts); err == nil {
+ t.Errorf("target path %q was accepted", targetPath)
+ }
+ }
+}
+
func TestProviderMSPProofRequiresLicenseBackedPlanSourceByDefault(t *testing.T) {
cfg := testProviderMSPProofConfig(t)
cfg.ProviderMSPPlanSource = cloudcp.ProviderMSPPlanSourceEnvFallback
diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
index cebdf83179..4eba5817f9 100644
--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
@@ -1623,6 +1623,13 @@ Agent` secondary handoff against the live setup wizard instead of relying
## Current State
+Deploy fan-out concurrency is one shared protocol contract in
+`internal/agentexec`: server request normalization and host-agent semaphore
+allocation both cap `max_parallel` at the same bound, including payloads that
+bypass the normal API producer. Shared local-redirect validation in
+`pkg/securityutil/httpurl.go` likewise rejects scheme-relative and backslash
+authority forms before agent-adjacent handoff or proof flows consume them.
+
Denied Patrol investigation-fix approvals passing through shared
`internal/api/` handlers are adjacent AI-runtime/action-governance state only.
The `fix_rejected` finding outcome records that an operator declined a proposed
diff --git a/docs/release-control/v6/internal/subsystems/ai-runtime.md b/docs/release-control/v6/internal/subsystems/ai-runtime.md
index 6522a7abaa..1006efb23c 100644
--- a/docs/release-control/v6/internal/subsystems/ai-runtime.md
+++ b/docs/release-control/v6/internal/subsystems/ai-runtime.md
@@ -3456,6 +3456,13 @@ query...`, and `Reading storage...` before streamed tool arguments are
## Current State
+AI provider model-cache identity must never expose reusable credential material
+or deterministic unkeyed credential hashes. `internal/ai/service.go` derives
+cache-only credential identities with a process-local random HMAC key, so an
+unchanged configuration remains cacheable during the process lifetime while
+credential rotation invalidates the cache without creating an offline
+credential verifier.
+
The canonical findings store must present one active Patrol issue per real
problem. When the model reports an equivalent active sibling under a different
finding ID, key, or severity for the same resource, `internal/ai/findings.go`
diff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.md
index b44ee55baa..f699a133c2 100644
--- a/docs/release-control/v6/internal/subsystems/api-contracts.md
+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md
@@ -3161,6 +3161,14 @@ a new API state machine, queue contract, or verification-accounting field.
## Current State
+Browser authentication cookies now consume one request-derived policy in
+`internal/api/auth.go`; session, CSRF, organization, magic-link, SAML, and cloud
+handoff flows must not materialize independent `Secure` or `SameSite` policy.
+SSO certificate/key file reads are privileged operator configuration and must
+pass the bounded non-symlink regular-file boundary in
+`internal/api/sso_outbound.go`. Cloud handoff redirects consume the shared
+host-local redirect validator rather than carrying route-local prefix checks.
+
Alert delivery diagnosis is a read-only monitoring API contract.
`GET /api/alerts/delivery-diagnosis?alertIdentifier=<id>` returns the alert
manager's current delivery-policy projection for one active alert, including
diff --git a/docs/release-control/v6/internal/subsystems/cloud-paid.md b/docs/release-control/v6/internal/subsystems/cloud-paid.md
index 06f169f9fd..921f497434 100644
--- a/docs/release-control/v6/internal/subsystems/cloud-paid.md
+++ b/docs/release-control/v6/internal/subsystems/cloud-paid.md
@@ -1209,6 +1209,11 @@ hands-on Patrol modes, issue investigation, verified fixes, and longer history`.
## Current State
+Hosted handoff target paths are normalized by the shared host-local redirect
+validator at token minting, exchange, and provider-proof boundaries. Absolute,
+scheme-relative, backslash-authority, encoded-separator, and control-character
+targets are rejected before they can reach a browser redirect.
+
Primary nav moved to platform-first on 2026-05-16 through
`frontend-modern/src/App.tsx`, `frontend-modern/src/AppLayout.tsx`, and
`frontend-modern/src/pages/RuntimeHome.tsx`. The authenticated-runtime landing
diff --git a/docs/release-control/v6/internal/subsystems/deployment-installability.md b/docs/release-control/v6/internal/subsystems/deployment-installability.md
index d61cbd959e..cdeb5ed521 100644
--- a/docs/release-control/v6/internal/subsystems/deployment-installability.md
+++ b/docs/release-control/v6/internal/subsystems/deployment-installability.md
@@ -883,6 +883,11 @@ TLS floor in the dynamic config.
## Current State
+The provider MSP proof command validates its handoff target with the same
+host-local redirect contract as runtime token minting and exchange. Proof input
+must reject absolute, scheme-relative, backslash-authority, encoded-separator,
+and control-character targets before constructing the handoff request.
+
The active stable `v6.0.5` cut sets the repo-root `VERSION`,
repo-root `docker-compose.yml` image default, `scripts/install-docker.sh`
fallback, and Helm chart release metadata to the same `6.0.5` release
diff --git a/docs/release-control/v6/internal/subsystems/monitoring.md b/docs/release-control/v6/internal/subsystems/monitoring.md
index fbfe8c846f..006c29a17a 100644
--- a/docs/release-control/v6/internal/subsystems/monitoring.md
+++ b/docs/release-control/v6/internal/subsystems/monitoring.md
@@ -451,6 +451,14 @@ resource health.
## Current State
+HTTP availability probes consume the shared explicitly unverified,
+parseable-peer-certificate capture
+boundary used by connection discovery, so support for operator self-signed
+endpoints does not create independent skip-verification configurations.
+Direct mock-node generation also clamps its allocation count to the canonical
+fixture bound even when called below the normal configuration-normalization
+entry point.
+
The monitoring-owned storage metrics runtime must preserve store-backed storage
chart continuity during resolver warm-up. `syncUnifiedStorageMetrics` must
prefer the resolver's canonical storage metrics target when it exists, but must
diff --git a/docs/release-control/v6/internal/subsystems/performance-and-scalability.md b/docs/release-control/v6/internal/subsystems/performance-and-scalability.md
index 2a4d0f8c3a..f0b2dc9267 100644
--- a/docs/release-control/v6/internal/subsystems/performance-and-scalability.md
+++ b/docs/release-control/v6/internal/subsystems/performance-and-scalability.md
@@ -756,6 +756,10 @@ shell clickable behind another overlay.
## Current State
+The router's shared browser-cookie writer is request-local security policy. It
+must not add per-request persistence reads, network work, or background fan-out;
+all login and CSRF call sites consume the already-derived in-memory policy.
+
Workload and host drawer discovery-tab Suspense fallbacks now compose the
frontend-primitives `DiscoveryLoadingFallback` template. `GuestDrawer`,
`NodeDrawer`, and Docker host drawer consumers own tab availability and target
diff --git a/docs/release-control/v6/internal/subsystems/security-privacy.md b/docs/release-control/v6/internal/subsystems/security-privacy.md
index 4cab48700b..924d2e093c 100644
--- a/docs/release-control/v6/internal/subsystems/security-privacy.md
+++ b/docs/release-control/v6/internal/subsystems/security-privacy.md
@@ -416,6 +416,19 @@ the `white_label` branding entitlement.
## Current State
+The browser-auth boundary now owns one request-derived cookie policy for every
+session, CSRF, organization, SAML, magic-link, and cloud-handoff cookie. Secure
+requests use Secure cookies and host-prefixed session names; explicitly
+supported non-TLS self-hosted requests retain the bounded compatibility path
+without allowing individual handlers to choose weaker attributes. Audit
+backends persist events through `Logger.Record`; realtime projections omit raw
+actor/IP identity and redact free-form details, keeping queryable audit storage
+distinct from process logs. Certificate discovery and availability probing use
+the single `tlsutil.PeerCertificateCaptureTLSConfig` TOFU boundary, while
+fingerprint-pinned clients continue to require exact leaf-certificate identity;
+the capture helper's `Unverified` name makes the pre-trust boundary explicit to
+callers and static analysis.
+
The multi-tenant authorization boundary now also owns default-org token
scoping. An org-bound API token is a client-scoped credential: it must be
denied implicit access to the default org so a token that leaks from a client
diff --git a/docs/release-control/v6/internal/subsystems/storage-recovery.md b/docs/release-control/v6/internal/subsystems/storage-recovery.md
index 75d974e7cd..c62475ea13 100644
--- a/docs/release-control/v6/internal/subsystems/storage-recovery.md
+++ b/docs/release-control/v6/internal/subsystems/storage-recovery.md
@@ -1612,6 +1612,11 @@ must not treat starter
## Current State
+Authentication-cookie, SSO configured-file, deployment concurrency, and cloud
+handoff redirect hardening in shared `internal/api/` routes is adjacent
+API/security work only. It creates no storage-health, recovery-point, backup,
+restore-authorization, or provider-coverage semantics.
+
Denied Patrol investigation-fix approvals passing through shared
`internal/api/` handlers are adjacent AI-runtime/action-governance state only.
The `fix_rejected` finding outcome means an operator declined a proposed Patrol
diff --git a/internal/agentexec/types.go b/internal/agentexec/types.go
index 46df39575c..2a4976dfa4 100644
--- a/internal/agentexec/types.go
+++ b/internal/agentexec/types.go
@@ -138,6 +138,20 @@ type ConnectedAgent struct {
// --- Deploy protocol payloads ---
+const MaxDeployParallel = 10
+
+// NormalizeDeployMaxParallel applies the shared server/agent concurrency
+// contract before the value reaches worker or channel allocation boundaries.
+func NormalizeDeployMaxParallel(value, defaultValue int) int {
+ if value <= 0 {
+ value = defaultValue
+ }
+ if value > MaxDeployParallel {
+ return MaxDeployParallel
+ }
+ return value
+}
+
// DeployPreflightPayload is sent by the server to request SSH preflight checks
// against cluster peer nodes.
type DeployPreflightPayload struct {
diff --git a/internal/ai/service.go b/internal/ai/service.go
index a9418e8b87..fddf60f662 100644
--- a/internal/ai/service.go
+++ b/internal/ai/service.go
@@ -2,6 +2,8 @@ package ai
import (
"context"
+ "crypto/hmac"
+ cryptorand "crypto/rand"
"crypto/sha256"
"encoding/hex"
"fmt"
@@ -37,6 +39,26 @@ import (
"github.com/rs/zerolog/log"
)
+var modelsCacheCredentialKey = newModelsCacheCredentialKey()
+
+func newModelsCacheCredentialKey() []byte {
+ key := make([]byte, 32)
+ if _, err := cryptorand.Read(key); err != nil {
+ panic(fmt.Sprintf("initialize AI models cache credential key: %v", err))
+ }
+ return key
+}
+
+func credentialCacheDigest(values ...string) string {
+ mac := hmac.New(sha256.New, modelsCacheCredentialKey)
+ for _, value := range values {
+ _, _ = io.WriteString(mac, strconv.Itoa(len(value)))
+ _, _ = io.WriteString(mac, ":")
+ _, _ = io.WriteString(mac, value)
+ }
+ return hex.EncodeToString(mac.Sum(nil))
+}
+
// StateProvider is a type alias for models.SnapshotProvider.
// Kept for local convenience; all new code should use models.SnapshotProvider directly.
type StateProvider = models.SnapshotProvider
@@ -4491,8 +4513,7 @@ func buildModelsCacheKey(cfg *config.AIConfig) string {
b.WriteString(cfg.OllamaBaseURL)
b.WriteString("|ollama_auth=")
if cfg.OllamaUsername != "" || cfg.OllamaPassword != "" {
- sum := sha256.Sum256([]byte(cfg.OllamaUsername + "\n" + cfg.OllamaPassword))
- b.WriteString(hex.EncodeToString(sum[:]))
+ b.WriteString(credentialCacheDigest(cfg.OllamaUsername, cfg.OllamaPassword))
}
return b.String()
@@ -4507,8 +4528,7 @@ func aiCredentialCacheSignature(cfg *config.AIConfig) string {
b.WriteString(providerName)
b.WriteString("=")
if key := cfg.GetAPIKeyForProvider(providerName); key != "" {
- sum := sha256.Sum256([]byte(key))
- b.WriteString(hex.EncodeToString(sum[:]))
+ b.WriteString(credentialCacheDigest(providerName, key))
}
b.WriteString(";")
}
diff --git a/internal/ai/service_extended_test.go b/internal/ai/service_extended_test.go
index 54c1767cb7..6875c427a2 100644
--- a/internal/ai/service_extended_test.go
+++ b/internal/ai/service_extended_test.go
@@ -1511,6 +1511,23 @@ func TestBuildModelsCacheKey_OllamaAuthFingerprint(t *testing.T) {
}
}
+func TestBuildModelsCacheKey_UsesKeyedCredentialIdentity(t *testing.T) {
+ cfg := &config.AIConfig{Enabled: true, OpenAIAPIKey: "provider-secret"}
+ first := buildModelsCacheKey(cfg)
+ second := buildModelsCacheKey(cfg)
+ if first != second {
+ t.Fatal("expected unchanged credentials to retain one cache identity")
+ }
+ if strings.Contains(first, cfg.OpenAIAPIKey) {
+ t.Fatal("cache key must not contain raw provider credentials")
+ }
+
+ cfg.OpenAIAPIKey = "rotated-secret"
+ if rotated := buildModelsCacheKey(cfg); rotated == first {
+ t.Fatal("expected credential rotation to invalidate the models cache")
+ }
+}
+
// Note: ListModelsWithCache does not handle nil persistence gracefully (panics)
// This is acceptable as NewService should always be called with a valid persistence
diff --git a/internal/api/access_tenant_provider.go b/internal/api/access_tenant_provider.go
index ceda777a2b..01124728a7 100644
--- a/internal/api/access_tenant_provider.go
+++ b/internal/api/access_tenant_provider.go
@@ -8,6 +8,7 @@ import (
"regexp"
"sync"
+ "github.com/rcourtman/pulse-go-rewrite/internal/securityutil"
"github.com/rcourtman/pulse-go-rewrite/pkg/auth"
)
@@ -119,22 +120,36 @@ func (p *TenantRBACProvider) ManagerCount() int {
}
func (p *TenantRBACProvider) resolveDataDir(orgID string) (string, error) {
+ baseDataDir, err := securityutil.NormalizeStorageDir(p.baseDataDir)
+ if err != nil {
+ return "", fmt.Errorf("invalid RBAC data directory: %w", err)
+ }
if orgID == "default" {
- return p.baseDataDir, nil
+ return baseDataDir, nil
}
if !isValidTenantOrgID(orgID) {
return "", fmt.Errorf("invalid organization ID: %s", orgID)
}
- orgDir := filepath.Join(p.baseDataDir, "orgs", orgID)
- stat, err := os.Stat(orgDir)
+ orgsDir, err := securityutil.JoinStorageLeaf(baseDataDir, "orgs")
+ if err != nil {
+ return "", fmt.Errorf("resolve organization storage root: %w", err)
+ }
+ orgDir, err := securityutil.JoinStorageLeaf(orgsDir, orgID)
+ if err != nil {
+ return "", fmt.Errorf("resolve organization directory: %w", err)
+ }
+ stat, err := os.Lstat(orgDir)
if err != nil {
if os.IsNotExist(err) {
return "", fmt.Errorf("organization directory does not exist: %s", orgID)
}
return "", fmt.Errorf("failed to read organization directory for %s: %w", orgID, err)
}
+ if stat.Mode()&os.ModeSymlink != 0 {
+ return "", fmt.Errorf("organization path must not be a symlink: %s", orgID)
+ }
if !stat.IsDir() {
return "", fmt.Errorf("organization path is not a directory: %s", orgID)
}
diff --git a/internal/api/audit_handlers_test.go b/internal/api/audit_handlers_test.go
index ab193c5119..55dc0189bb 100644
--- a/internal/api/audit_handlers_test.go
+++ b/internal/api/audit_handlers_test.go
@@ -32,7 +32,7 @@ type testAuditLogger struct {
lastCount audit.QueryFilter
}
-func (l *testAuditLogger) Log(event audit.Event) error {
+func (l *testAuditLogger) Record(event audit.Event) error {
l.events = append(l.events, event)
return nil
}
@@ -81,7 +81,7 @@ type testAuditLoggerNoVerify struct {
events []audit.Event
}
-func (l *testAuditLoggerNoVerify) Log(event audit.Event) error {
+func (l *testAuditLoggerNoVerify) Record(event audit.Event) error {
l.events = append(l.events, event)
return nil
}
diff --git a/internal/api/auth.go b/internal/api/auth.go
index 66868d5583..9cbdaa1b08 100644
--- a/internal/api/auth.go
+++ b/internal/api/auth.go
@@ -310,6 +310,20 @@ func isWebSocketUpgrade(r *http.Request) bool {
// Secure is still set automatically based on the actual connection state
// (TLS, or X-Forwarded-Proto: https from a trusted proxy).
func getCookieSettings(r *http.Request) (secure bool, sameSite http.SameSite) {
+ policy := getBrowserCookiePolicy(r)
+ return policy.secure, policy.sameSite
+}
+
+type browserCookiePolicy struct {
+ secure bool
+ sameSite http.SameSite
+}
+
+func getBrowserCookiePolicy(r *http.Request) browserCookiePolicy {
+ if r == nil {
+ return browserCookiePolicy{}
+ }
+
isProxied := detectProxy(r)
isSecure := isConnectionSecure(r)
@@ -325,7 +339,22 @@ func getCookieSettings(r *http.Request) (secure bool, sameSite http.SameSite) {
Msg("Proxy/tunnel detected - cookies use Lax SameSite")
}
- return isSecure, http.SameSiteLaxMode
+ return browserCookiePolicy{
+ secure: isSecure,
+ sameSite: http.SameSiteLaxMode,
+ }
+}
+
+// set writes a browser cookie using the one request-derived policy shared by
+// every authentication flow. Plain HTTP remains limited to the supported
+// loopback/self-hosted boundary; public deployments receive Secure cookies.
+func (p browserCookiePolicy) set(w http.ResponseWriter, cookie *http.Cookie) {
+ if w == nil || cookie == nil {
+ return
+ }
+ cookie.Secure = p.secure
+ cookie.SameSite = p.sameSite
+ http.SetCookie(w, cookie)
}
// Cookie name constants. The session cookie uses the __Host- prefix when served
@@ -564,6 +593,9 @@ func CheckProxyAuth(cfg *config.Config, r *http.Request) (bool, string, bool) {
return true, username, isAdmin
}
+// responseCapture tracks whether authentication selected an explicit HTTP
+// status. Body writes flow through the embedded ResponseWriter unchanged; auth
+// paths only emit fixed response bodies after selecting a status.
type responseCapture struct {
http.ResponseWriter
wrote bool
@@ -576,11 +608,6 @@ func (rc *responseCapture) WriteHeader(statusCode int) {
}
}
-func (rc *responseCapture) Write(b []byte) (int, error) {
- rc.wrote = true
- return rc.ResponseWriter.Write(b)
-}
-
func wantsJSONAuthResponse(r *http.Request) bool {
if r == nil {
return false
@@ -866,11 +893,11 @@ func checkAuth(cfg *config.Config, w http.ResponseWriter, r *http.Request, write
csrfToken := generateCSRFToken(token)
// Get appropriate cookie settings based on proxy detection
- isSecure, sameSitePolicy := getCookieSettings(r)
+ cookiePolicy := getBrowserCookiePolicy(r)
// Debug logging for Cloudflare tunnel issues
sameSiteName := "Default"
- switch sameSitePolicy {
+ switch cookiePolicy.sameSite {
case http.SameSiteNoneMode:
sameSiteName = "None"
case http.SameSiteLaxMode:
@@ -880,31 +907,27 @@ func checkAuth(cfg *config.Config, w http.ResponseWriter, r *http.Request, write
}
log.Debug().
- Bool("secure", isSecure).
+ Bool("secure", cookiePolicy.secure).
Str("same_site", sameSiteName).
Str("token", safePrefixForLog(token, 8)+"...").
Str("remote_addr", r.RemoteAddr).
Msg("Setting session cookie after successful login")
- // Set session cookie
- http.SetCookie(w, &http.Cookie{
- Name: sessionCookieName(isSecure),
+ // Set session cookie
+ cookiePolicy.set(w, &http.Cookie{
+ Name: sessionCookieName(cookiePolicy.secure),
Value: token,
Path: "/",
HttpOnly: true,
- Secure: isSecure,
- SameSite: sameSitePolicy,
MaxAge: 86400, // 24 hours
})
// Set CSRF cookie (not HttpOnly so JS can read it)
- http.SetCookie(w, &http.Cookie{
- Name: CookieNameCSRF,
- Value: csrfToken,
- Path: "/",
- Secure: isSecure,
- SameSite: sameSitePolicy,
- MaxAge: 86400, // 24 hours
+ cookiePolicy.set(w, &http.Cookie{
+ Name: CookieNameCSRF,
+ Value: csrfToken,
+ Path: "/",
+ MaxAge: 86400, // 24 hours
})
// Audit log successful login
diff --git a/internal/api/auth_helpers_test.go b/internal/api/auth_helpers_test.go
index 02ee1c617a..a42ae395bb 100644
--- a/internal/api/auth_helpers_test.go
+++ b/internal/api/auth_helpers_test.go
@@ -335,6 +335,48 @@ func TestGetCookieSettings(t *testing.T) {
}
}
+func TestBrowserCookiePolicyAppliesRequestSecurity(t *testing.T) {
+ tests := []struct {
+ name string
+ secure bool
+ wantSecure bool
+ }{
+ {name: "plain self-hosted HTTP", secure: false, wantSecure: false},
+ {name: "HTTPS", secure: true, wantSecure: true},
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ req := httptest.NewRequest(http.MethodGet, "http://pulse.local/", nil)
+ if tt.secure {
+ req.TLS = &tls.ConnectionState{}
+ }
+ rec := httptest.NewRecorder()
+ getBrowserCookiePolicy(req).set(rec, &http.Cookie{
+ Name: CookieNameCSRF,
+ Value: "token",
+ Path: "/",
+ HttpOnly: true,
+ })
+
+ cookies := rec.Result().Cookies()
+ if len(cookies) != 1 {
+ t.Fatalf("cookies = %d, want 1", len(cookies))
+ }
+ cookie := cookies[0]
+ if cookie.Secure != tt.wantSecure {
+ t.Fatalf("Secure = %v, want %v", cookie.Secure, tt.wantSecure)
+ }
+ if cookie.SameSite != http.SameSiteLaxMode {
+ t.Fatalf("SameSite = %v, want Lax", cookie.SameSite)
+ }
+ if !cookie.HttpOnly {
+ t.Fatal("cookie-specific attributes must be preserved")
+ }
+ })
+ }
+}
+
func TestGenerateSessionToken(t *testing.T) {
// Test that tokens are generated
token := generateSessionToken()
diff --git a/internal/api/cloud_handoff.go b/internal/api/cloud_handoff.go
index a7435a13df..a25b9a4282 100644
--- a/internal/api/cloud_handoff.go
+++ b/internal/api/cloud_handoff.go
@@ -114,33 +114,27 @@ func HandleCloudHandoff(dataPath string) http.HandlerFunc {
TrackUserSession(authz.UserID, sessionToken)
csrfToken := generateCSRFToken(sessionToken)
- isSecure, sameSitePolicy := getCookieSettings(r)
+ cookiePolicy := getBrowserCookiePolicy(r)
cookieMaxAge := int(sessionDuration.Seconds())
- http.SetCookie(w, &http.Cookie{
- Name: sessionCookieName(isSecure),
+ cookiePolicy.set(w, &http.Cookie{
+ Name: sessionCookieName(cookiePolicy.secure),
Value: sessionToken,
Path: "/",
HttpOnly: true,
- Secure: isSecure,
- SameSite: sameSitePolicy,
MaxAge: cookieMaxAge,
})
- http.SetCookie(w, &http.Cookie{
- Name: CookieNameCSRF,
- Value: csrfToken,
- Path: "/",
- Secure: isSecure,
- SameSite: sameSitePolicy,
- MaxAge: cookieMaxAge,
+ cookiePolicy.set(w, &http.Cookie{
+ Name: CookieNameCSRF,
+ Value: csrfToken,
+ Path: "/",
+ MaxAge: cookieMaxAge,
})
- http.SetCookie(w, &http.Cookie{
- Name: CookieNameOrgID,
- Value: tenantID,
- Path: "/",
- Secure: isSecure,
- SameSite: sameSitePolicy,
- MaxAge: cookieMaxAge,
+ cookiePolicy.set(w, &http.Cookie{
+ Name: CookieNameOrgID,
+ Value: tenantID,
+ Path: "/",
+ MaxAge: cookieMaxAge,
})
log.Info().
diff --git a/internal/api/cloud_handoff_handlers.go b/internal/api/cloud_handoff_handlers.go
index 68e3f35b2f..55cebc6d4a 100644
--- a/internal/api/cloud_handoff_handlers.go
+++ b/internal/api/cloud_handoff_handlers.go
@@ -17,6 +17,7 @@ import (
"github.com/golang-jwt/jwt/v5"
"github.com/rcourtman/pulse-go-rewrite/internal/config"
"github.com/rcourtman/pulse-go-rewrite/internal/models"
+ pkgsecurityutil "github.com/rcourtman/pulse-go-rewrite/pkg/securityutil"
_ "modernc.org/sqlite"
)
@@ -405,33 +406,27 @@ func HandleHandoffExchange(configDir string) http.HandlerFunc {
TrackUserSession(authz.UserID, sessionToken)
csrfToken := generateCSRFToken(sessionToken)
- isSecure, sameSitePolicy := getCookieSettings(r)
+ cookiePolicy := getBrowserCookiePolicy(r)
cookieMaxAge := int(sessionDuration.Seconds())
- http.SetCookie(w, &http.Cookie{
- Name: sessionCookieName(isSecure),
+ cookiePolicy.set(w, &http.Cookie{
+ Name: sessionCookieName(cookiePolicy.secure),
Value: sessionToken,
Path: "/",
HttpOnly: true,
- Secure: isSecure,
- SameSite: sameSitePolicy,
MaxAge: cookieMaxAge,
})
- http.SetCookie(w, &http.Cookie{
- Name: CookieNameCSRF,
- Value: csrfToken,
- Path: "/",
- Secure: isSecure,
- SameSite: sameSitePolicy,
- MaxAge: cookieMaxAge,
+ cookiePolicy.set(w, &http.Cookie{
+ Name: CookieNameCSRF,
+ Value: csrfToken,
+ Path: "/",
+ MaxAge: cookieMaxAge,
})
- http.SetCookie(w, &http.Cookie{
- Name: CookieNameOrgID,
- Value: tenantID,
- Path: "/",
- Secure: isSecure,
- SameSite: sameSitePolicy,
- MaxAge: cookieMaxAge,
+ cookiePolicy.set(w, &http.Cookie{
+ Name: CookieNameOrgID,
+ Value: tenantID,
+ Path: "/",
+ MaxAge: cookieMaxAge,
})
if strings.Contains(r.Header.Get("Accept"), "application/json") || r.URL.Query().Get("format") == "json" {
@@ -463,18 +458,11 @@ func HandleHandoffExchange(configDir string) http.HandlerFunc {
}
func sanitizeCloudHandoffTargetPath(raw string) string {
- raw = strings.TrimSpace(raw)
- if raw == "" || !strings.HasPrefix(raw, "/") || strings.HasPrefix(raw, "//") {
- return ""
- }
- if strings.IndexFunc(raw, func(r rune) bool { return r < 0x20 || r == 0x7f }) >= 0 {
- return ""
- }
- parsed, err := url.Parse(raw)
- if err != nil || parsed.IsAbs() || parsed.Host != "" || parsed.Path == "" || !strings.HasPrefix(parsed.Path, "/") {
+ targetPath, err := pkgsecurityutil.NormalizeLocalRedirectPath(raw)
+ if err != nil {
return ""
}
- return parsed.String()
+ return targetPath
}
func authorizeHandoffOrganizationMembership(configDir, tenantID, userID, email, role string) (*handoffAuthorization, error) {
diff --git a/internal/api/connections_probe.go b/internal/api/connections_probe.go
index 517d86b051..a0737b646c 100644
--- a/internal/api/connections_probe.go
+++ b/internal/api/connections_probe.go
@@ -3,7 +3,6 @@ package api
import (
"context"
"crypto/sha256"
- "crypto/tls"
"encoding/hex"
"fmt"
"io"
@@ -17,6 +16,7 @@ import (
"time"
"github.com/rcourtman/pulse-go-rewrite/internal/securityutil"
+ "github.com/rcourtman/pulse-go-rewrite/pkg/tlsutil"
)
// Probe budget. Per-candidate and whole-request ceilings are kept tight to
@@ -203,10 +203,7 @@ func probeHTTPClient() *http.Client {
AllowedSchemes: []string{"https"},
AllowPrivateIPs: true,
AllowLoopback: true,
- TLSConfig: &tls.Config{
- MinVersion: tls.VersionTLS12,
- InsecureSkipVerify: true, //nolint:gosec // Probing intentionally accepts untrusted certificates for fingerprint capture.
- },
+ TLSConfig: tlsutil.UnverifiedPeerCertificateCaptureTLSConfig(),
})
}
diff --git a/internal/api/connections_probe_test.go b/internal/api/connections_probe_test.go
index 5cc08cadeb..e0b0036b29 100644
--- a/internal/api/connections_probe_test.go
+++ b/internal/api/connections_probe_test.go
@@ -52,6 +52,22 @@ func TestParseProbeAddress_Shapes(t *testing.T) {
}
}
+func TestProbeHTTPClientUsesSharedPeerCertificateCapture(t *testing.T) {
+ server := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+ w.WriteHeader(http.StatusNoContent)
+ }))
+ defer server.Close()
+
+ resp, err := probeHTTPClient().Get(server.URL)
+ if err != nil {
+ t.Fatalf("probe client rejected parseable self-signed peer certificate: %v", err)
+ }
+ defer resp.Body.Close()
+ if resp.StatusCode != http.StatusNoContent {
+ t.Fatalf("probe status = %d, want %d", resp.StatusCode, http.StatusNoContent)
+ }
+}
+
func TestTargetsForPort_ExplicitNarrowsToMatching(t *testing.T) {
targets := targetsForPort(8006)
seen := map[ConnectionType]bool{}
diff --git a/internal/api/contract_test.go b/internal/api/contract_test.go
index d69fd85195..f68b848dc7 100644
--- a/internal/api/contract_test.go
+++ b/internal/api/contract_test.go
@@ -8615,8 +8615,7 @@ func TestContract_HandoffExchangeTargetPathIsSignedAndLocalOnly(t *testing.T) {
"TargetPath string `json:\"target_path,omitempty\"`",
"sanitizeCloudHandoffTargetPath(claims.TargetPath)",
"http.Redirect(w, r, targetPath, http.StatusTemporaryRedirect)",
- "strings.HasPrefix(raw, \"//\")",
- "parsed.IsAbs() || parsed.Host != \"\"",
+ "pkgsecurityutil.NormalizeLocalRedirectPath(raw)",
} {
if !strings.Contains(text, required) {
t.Fatalf("cloud handoff exchange must preserve signed local target-path contract: missing %q", required)
diff --git a/internal/api/deploy_handlers.go b/internal/api/deploy_handlers.go
index 5e80a88dac..993a055f8e 100644
--- a/internal/api/deploy_handlers.go
+++ b/internal/api/deploy_handlers.go
@@ -265,13 +265,7 @@ func (h *DeployHandlers) HandleCreatePreflight(w http.ResponseWriter, r *http.Re
// Build deploy targets from requested node IDs.
now := time.Now().UTC()
jobID := generateID("pf")
- maxParallel := req.MaxParallel
- if maxParallel <= 0 {
- maxParallel = 2
- }
- if maxParallel > 10 {
- maxParallel = 10
- }
+ maxParallel := agentexec.NormalizeDeployMaxParallel(req.MaxParallel, 2)
job := &deploy.Job{
ID: jobID,
@@ -1114,13 +1108,7 @@ func (h *DeployHandlers) HandleCreateJob(w http.ResponseWriter, r *http.Request)
// Create deploy job.
now := time.Now().UTC()
jobID := generateID("dep")
- maxParallel := req.MaxParallel
- if maxParallel <= 0 {
- maxParallel = 2
- }
- if maxParallel > 10 {
- maxParallel = 10
- }
+ maxParallel := agentexec.NormalizeDeployMaxParallel(req.MaxParallel, 2)
retryMax := 3
if req.RetryPolicy != nil && req.RetryPolicy.MaxAttempts > 0 {
diff --git a/internal/api/magic_link_handlers.go b/internal/api/magic_link_handlers.go
index 88f3b3011b..b0500143c8 100644
--- a/internal/api/magic_link_handlers.go
+++ b/internal/api/magic_link_handlers.go
@@ -192,35 +192,29 @@ func (h *MagicLinkHandlers) HandlePublicMagicLinkVerify(w http.ResponseWriter, r
TrackUserSession(principal.UserID, sessionToken)
csrfToken := generateCSRFToken(sessionToken)
- isSecure, sameSitePolicy := getCookieSettings(r)
+ cookiePolicy := getBrowserCookiePolicy(r)
cookieMaxAge := int(sessionDuration.Seconds())
- http.SetCookie(w, &http.Cookie{
- Name: sessionCookieName(isSecure),
+ cookiePolicy.set(w, &http.Cookie{
+ Name: sessionCookieName(cookiePolicy.secure),
Value: sessionToken,
Path: "/",
HttpOnly: true,
- Secure: isSecure,
- SameSite: sameSitePolicy,
MaxAge: cookieMaxAge,
})
- http.SetCookie(w, &http.Cookie{
- Name: CookieNameCSRF,
- Value: csrfToken,
- Path: "/",
- Secure: isSecure,
- SameSite: sameSitePolicy,
- MaxAge: cookieMaxAge,
+ cookiePolicy.set(w, &http.Cookie{
+ Name: CookieNameCSRF,
+ Value: csrfToken,
+ Path: "/",
+ MaxAge: cookieMaxAge,
})
// Org cookie is intentionally NOT HttpOnly — the frontend reads/writes it to
// synchronize org context for WebSocket connections (which cannot send custom headers).
- http.SetCookie(w, &http.Cookie{
- Name: CookieNameOrgID,
- Value: token.OrgID,
- Path: "/",
- Secure: isSecure,
- SameSite: sameSitePolicy,
- MaxAge: cookieMaxAge,
+ cookiePolicy.set(w, &http.Cookie{
+ Name: CookieNameOrgID,
+ Value: token.OrgID,
+ Path: "/",
+ MaxAge: cookieMaxAge,
})
if strings.Contains(r.Header.Get("Accept"), "application/json") || r.URL.Query().Get("format") == "json" {
diff --git a/internal/api/router.go b/internal/api/router.go
index c9fa2515e1..8e50a35852 100644
--- a/internal/api/router.go
+++ b/internal/api/router.go
@@ -4215,14 +4215,11 @@ func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request) {
if csrfErr != nil {
// Session exists but no CSRF cookie - issue one
csrfToken := generateCSRFToken(sessionCookie.Value)
- isSecure, sameSitePolicy := getCookieSettings(req)
- http.SetCookie(w, &http.Cookie{
- Name: CookieNameCSRF,
- Value: csrfToken,
- Path: "/",
- Secure: isSecure,
- SameSite: sameSitePolicy,
- MaxAge: 86400,
+ getBrowserCookiePolicy(req).set(w, &http.Cookie{
+ Name: CookieNameCSRF,
+ Value: csrfToken,
+ Path: "/",
+ MaxAge: 86400,
})
}
}
@@ -4978,25 +4975,21 @@ func (r *Router) establishSession(w http.ResponseWriter, req *http.Request, user
}
csrfToken := generateCSRFToken(token)
- isSecure, sameSitePolicy := getCookieSettings(req)
+ cookiePolicy := getBrowserCookiePolicy(req)
- http.SetCookie(w, &http.Cookie{
- Name: sessionCookieName(isSecure),
+ cookiePolicy.set(w, &http.Cookie{
+ Name: sessionCookieName(cookiePolicy.secure),
Value: token,
Path: "/",
HttpOnly: true,
- Secure: isSecure,
- SameSite: sameSitePolicy,
MaxAge: 86400,
})
- http.SetCookie(w, &http.Cookie{
- Name: CookieNameCSRF,
- Value: csrfToken,
- Path: "/",
- Secure: isSecure,
- SameSite: sameSitePolicy,
- MaxAge: 86400,
+ cookiePolicy.set(w, &http.Cookie{
+ Name: CookieNameCSRF,
+ Value: csrfToken,
+ Path: "/",
+ MaxAge: 86400,
})
return nil
@@ -5019,25 +5012,21 @@ func (r *Router) establishRecoverySession(w http.ResponseWriter, req *http.Reque
GetSessionStore().CreateRecoverySession(token, 24*time.Hour, userAgent, clientIP, username)
csrfToken := generateCSRFToken(token)
- isSecure, sameSitePolicy := getCookieSettings(req)
+ cookiePolicy := getBrowserCookiePolicy(req)
- http.SetCookie(w, &http.Cookie{
- Name: sessionCookieName(isSecure),
+ cookiePolicy.set(w, &http.Cookie{
+ Name: sessionCookieName(cookiePolicy.secure),
Value: token,
Path: "/",
HttpOnly: true,
- Secure: isSecure,
- SameSite: sameSitePolicy,
MaxAge: 86400,
})
- http.SetCookie(w, &http.Cookie{
- Name: CookieNameCSRF,
- Value: csrfToken,
- Path: "/",
- Secure: isSecure,
- SameSite: sameSitePolicy,
- MaxAge: 86400,
+ cookiePolicy.set(w, &http.Cookie{
+ Name: CookieNameCSRF,
+ Value: csrfToken,
+ Path: "/",
+ MaxAge: 86400,
})
return nil
@@ -5064,25 +5053,21 @@ func (r *Router) establishOIDCSession(w http.ResponseWriter, req *http.Request,
}
csrfToken := generateCSRFToken(token)
- isSecure, sameSitePolicy := getCookieSettings(req)
+ cookiePolicy := getBrowserCookiePolicy(req)
- http.SetCookie(w, &http.Cookie{
- Name: sessionCookieName(isSecure),
+ cookiePolicy.set(w, &http.Cookie{
+ Name: sessionCookieName(cookiePolicy.secure),
Value: token,
Path: "/",
HttpOnly: true,
- Secure: isSecure,
- SameSite: sameSitePolicy,
MaxAge: 86400,
})
- http.SetCookie(w, &http.Cookie{
- Name: CookieNameCSRF,
- Value: csrfToken,
- Path: "/",
- Secure: isSecure,
- SameSite: sameSitePolicy,
- MaxAge: 86400,
+ cookiePolicy.set(w, &http.Cookie{
+ Name: CookieNameCSRF,
+ Value: csrfToken,
+ Path: "/",
+ MaxAge: 86400,
})
return nil
@@ -5193,30 +5178,26 @@ func (r *Router) handleLogin(w http.ResponseWriter, req *http.Request) {
csrfToken := generateCSRFToken(token)
// Get appropriate cookie settings based on proxy detection
- isSecure, sameSitePolicy := getCookieSettings(req)
+ cookiePolicy := getBrowserCookiePolicy(req)
// Set cookie MaxAge to match session duration
cookieMaxAge := int(sessionDuration.Seconds())
// Set session cookie
- http.SetCookie(w, &http.Cookie{
- Name: sessionCookieName(isSecure),
+ cookiePolicy.set(w, &http.Cookie{
+ Name: sessionCookieName(cookiePolicy.secure),
Value: token,
Path: "/",
HttpOnly: true,
- Secure: isSecure,
- SameSite: sameSitePolicy,
MaxAge: cookieMaxAge,
})
// Set CSRF cookie (not HttpOnly so JS can read it)
- http.SetCookie(w, &http.Cookie{
- Name: CookieNameCSRF,
- Value: csrfToken,
- Path: "/",
- Secure: isSecure,
- SameSite: sameSitePolicy,
- MaxAge: cookieMaxAge,
+ cookiePolicy.set(w, &http.Cookie{
+ Name: CookieNameCSRF,
+ Value: csrfToken,
+ Path: "/",
+ MaxAge: cookieMaxAge,
})
// Audit log successful login
diff --git a/internal/api/saml_handlers.go b/internal/api/saml_handlers.go
index 5b9adfa82f..72d2d5b08d 100644
--- a/internal/api/saml_handlers.go
+++ b/internal/api/saml_handlers.go
@@ -522,25 +522,21 @@ func (r *Router) establishSAMLSession(w http.ResponseWriter, req *http.Request,
}
csrfToken := generateCSRFToken(token)
- isSecure, sameSitePolicy := getCookieSettings(req)
+ cookiePolicy := getBrowserCookiePolicy(req)
- http.SetCookie(w, &http.Cookie{
- Name: sessionCookieName(isSecure),
+ cookiePolicy.set(w, &http.Cookie{
+ Name: sessionCookieName(cookiePolicy.secure),
Value: token,
Path: "/",
HttpOnly: true,
- Secure: isSecure,
- SameSite: sameSitePolicy,
MaxAge: 86400,
})
- http.SetCookie(w, &http.Cookie{
- Name: CookieNameCSRF,
- Value: csrfToken,
- Path: "/",
- Secure: isSecure,
- SameSite: sameSitePolicy,
- MaxAge: 86400,
+ cookiePolicy.set(w, &http.Cookie{
+ Name: CookieNameCSRF,
+ Value: csrfToken,
+ Path: "/",
+ MaxAge: 86400,
})
return nil
@@ -568,7 +564,7 @@ func (r *Router) getSAMLSessionInfo(req *http.Request) *SAMLSessionInfo {
// clearSession clears the current session - properly invalidates server-side session
// and clears both pulse_session and pulse_csrf cookies
func (r *Router) clearSession(w http.ResponseWriter, req *http.Request) {
- isSecure, sameSitePolicy := getCookieSettings(req)
+ cookiePolicy := getBrowserCookiePolicy(req)
// Invalidate server-side session first
if cookie, err := readSessionCookie(req); err == nil && cookie.Value != "" {
@@ -588,25 +584,21 @@ func (r *Router) clearSession(w http.ResponseWriter, req *http.Request) {
// Clear both session cookie variants (prefixed and unprefixed)
for _, name := range []string{cookieNameSession, cookieNameSessionSecure} {
- http.SetCookie(w, &http.Cookie{
+ cookiePolicy.set(w, &http.Cookie{
Name: name,
Value: "",
Path: "/",
MaxAge: -1,
HttpOnly: true,
- Secure: isSecure,
- SameSite: sameSitePolicy,
})
}
// Clear pulse_csrf cookie
- http.SetCookie(w, &http.Cookie{
- Name: CookieNameCSRF,
- Value: "",
- Path: "/",
- MaxAge: -1,
- Secure: isSecure,
- SameSite: sameSitePolicy,
+ cookiePolicy.set(w, &http.Cookie{
+ Name: CookieNameCSRF,
+ Value: "",
+ Path: "/",
+ MaxAge: -1,
})
}
diff --git a/internal/api/security.go b/internal/api/security.go
index a2661a88cf..b1953006c9 100644
--- a/internal/api/security.go
+++ b/internal/api/security.go
@@ -132,19 +132,12 @@ func clearCSRFCookie(w http.ResponseWriter, r *http.Request) {
if w == nil {
return
}
- var secure bool
- var sameSite http.SameSite
- if r != nil {
- secure, sameSite = getCookieSettings(r)
- }
- http.SetCookie(w, &http.Cookie{
+ getBrowserCookiePolicy(r).set(w, &http.Cookie{
Name: CookieNameCSRF,
Value: "",
Path: "/",
MaxAge: -1,
HttpOnly: false,
- Secure: secure,
- SameSite: sameSite,
})
}
@@ -157,15 +150,11 @@ func issueNewCSRFCookie(w http.ResponseWriter, r *http.Request, sessionID string
}
newToken := generateCSRFToken(sessionID)
- secure, sameSite := getCookieSettings(r)
-
- http.SetCookie(w, &http.Cookie{
- Name: CookieNameCSRF,
- Value: newToken,
- Path: "/",
- Secure: secure,
- SameSite: sameSite,
- MaxAge: 86400,
+ getBrowserCookiePolicy(r).set(w, &http.Cookie{
+ Name: CookieNameCSRF,
+ Value: newToken,
+ Path: "/",
+ MaxAge: 86400,
})
return newToken
}
diff --git a/internal/api/security_additional_coverage_test.go b/internal/api/security_additional_coverage_test.go
index 501d27c212..34f05197a6 100644
--- a/internal/api/security_additional_coverage_test.go
+++ b/internal/api/security_additional_coverage_test.go
@@ -16,7 +16,7 @@ type auditCaptureLogger struct {
events []audit.Event
}
-func (l *auditCaptureLogger) Log(event audit.Event) error {
+func (l *auditCaptureLogger) Record(event audit.Event) error {
l.mu.Lock()
defer l.mu.Unlock()
l.events = append(l.events, event)
@@ -51,7 +51,7 @@ func (l *auditCaptureLogger) Close() error {
type auditErrorLogger struct{}
-func (l *auditErrorLogger) Log(event audit.Event) error { return errors.New("log failed") }
+func (l *auditErrorLogger) Record(event audit.Event) error { return errors.New("log failed") }
func (l *auditErrorLogger) Query(filter audit.QueryFilter) ([]audit.Event, error) {
return nil, errors.New("query failed")
}
diff --git a/internal/api/security_regression_test.go b/internal/api/security_regression_test.go
index 65efb1429f..3d748515cb 100644
--- a/internal/api/security_regression_test.go
+++ b/internal/api/security_regression_test.go
@@ -30,6 +30,20 @@ type wsRawMessage struct {
Payload json.RawMessage `json:"payload,omitempty"`
}
+func TestBrowserCookiePolicyWritesSecureCookiesForTLS(t *testing.T) {
+ req := httptest.NewRequest(http.MethodGet, "https://pulse.example/api/config", nil)
+ rec := httptest.NewRecorder()
+ getBrowserCookiePolicy(req).set(rec, &http.Cookie{Name: CookieNameCSRF, Value: "token", Path: "/"})
+
+ cookies := rec.Result().Cookies()
+ if len(cookies) != 1 || !cookies[0].Secure {
+ t.Fatalf("TLS cookie policy = %+v, want one Secure cookie", cookies)
+ }
+ if cookies[0].SameSite != http.SameSiteLaxMode {
+ t.Fatalf("SameSite = %v, want Lax", cookies[0].SameSite)
+ }
+}
+
type denyAuthorizer struct{}
func (d *denyAuthorizer) Authorize(_ context.Context, _ string, _ string) (bool, error) {
diff --git a/internal/api/sso_outbound.go b/internal/api/sso_outbound.go
index 9d6c57d247..b1c3ec8825 100644
--- a/internal/api/sso_outbound.go
+++ b/internal/api/sso_outbound.go
@@ -7,7 +7,6 @@ import (
"fmt"
"net/http"
"net/url"
- "os"
"path/filepath"
"strings"
"time"
@@ -17,6 +16,8 @@ import (
var allowLoopbackSSOFetch bool
+const maxSSOFileSize = 4 << 20
+
func ssoOutboundHTTPOptions(tlsConfig *tls.Config) securityutil.RestrictedOutboundHTTPOptions {
return securityutil.RestrictedOutboundHTTPOptions{
AllowedSchemes: []string{"http", "https"},
@@ -35,23 +36,25 @@ func newSSOHTTPClient(timeout time.Duration, tlsConfig *tls.Config) *http.Client
}
func readSSORegularFile(rawPath string) ([]byte, error) {
- cleaned := filepath.Clean(strings.TrimSpace(rawPath))
- if cleaned == "" {
- return nil, errors.New("SSO file path is empty")
+ absolute, err := normalizeConfiguredSSOFilePath(rawPath)
+ if err != nil {
+ return nil, err
}
- absolute, err := filepath.Abs(cleaned)
- if err != nil {
- return nil, fmt.Errorf("resolve SSO file path: %w", err)
+ return securityutil.ReadSecureStorageFile(absolute, maxSSOFileSize)
+}
+
+// normalizeConfiguredSSOFilePath establishes the privileged operator-config
+// boundary for SSO certificate and key files. Request data must never reach it.
+func normalizeConfiguredSSOFilePath(rawPath string) (string, error) {
+ cleaned := filepath.Clean(strings.TrimSpace(rawPath))
+ if cleaned == "" || cleaned == "." {
+ return "", errors.New("SSO file path is empty")
}
- info, err := os.Stat(absolute)
+ absolute, err := filepath.Abs(cleaned)
if err != nil {
- return nil, err
- }
- if !info.Mode().IsRegular() {
- return nil, fmt.Errorf("SSO file must be a regular file")
+ return "", fmt.Errorf("resolve SSO file path: %w", err)
}
-
- return os.ReadFile(absolute)
+ return filepath.Clean(absolute), nil
}
diff --git a/internal/api/sso_outbound_test.go b/internal/api/sso_outbound_test.go
new file mode 100644
index 0000000000..f383a183fc
--- /dev/null
+++ b/internal/api/sso_outbound_test.go
@@ -0,0 +1,57 @@
+package api
+
+import (
+ "errors"
+ "os"
+ "path/filepath"
+ "testing"
+
+ "github.com/rcourtman/pulse-go-rewrite/internal/securityutil"
+)
+
+func TestReadSSORegularFile(t *testing.T) {
+ root := t.TempDir()
+ path := filepath.Join(root, "idp.pem")
+ if err := os.WriteFile(path, []byte("certificate"), 0o600); err != nil {
+ t.Fatalf("write SSO file: %v", err)
+ }
+
+ data, err := readSSORegularFile(path)
+ if err != nil {
+ t.Fatalf("readSSORegularFile() error = %v", err)
+ }
+ if string(data) != "certificate" {
+ t.Fatalf("readSSORegularFile() = %q", data)
+ }
+}
+
+func TestReadSSORegularFileRejectsSymlinkAndOversizedFile(t *testing.T) {
+ root := t.TempDir()
+ target := filepath.Join(root, "target.pem")
+ if err := os.WriteFile(target, []byte("certificate"), 0o600); err != nil {
+ t.Fatalf("write target: %v", err)
+ }
+ symlink := filepath.Join(root, "idp.pem")
+ if err := os.Symlink(target, symlink); err != nil {
+ t.Fatalf("create symlink: %v", err)
+ }
+ if _, err := readSSORegularFile(symlink); !errors.Is(err, securityutil.ErrUnsafeStorageFile) {
+ t.Fatalf("symlink error = %v, want ErrUnsafeStorageFile", err)
+ }
+
+ oversized := filepath.Join(root, "oversized.pem")
+ file, err := os.Create(oversized)
+ if err != nil {
+ t.Fatalf("create oversized file: %v", err)
+ }
+ if err := file.Truncate(maxSSOFileSize + 1); err != nil {
+ _ = file.Close()
+ t.Fatalf("truncate oversized file: %v", err)
+ }
+ if err := file.Close(); err != nil {
+ t.Fatalf("close oversized file: %v", err)
+ }
+ if _, err := readSSORegularFile(oversized); !errors.Is(err, securityutil.ErrUnsafeStorageFile) {
+ t.Fatalf("oversized error = %v, want ErrUnsafeStorageFile", err)
+ }
+}
diff --git a/internal/cloudcp/handoff/handoff.go b/internal/cloudcp/handoff/handoff.go
index da9185e6c9..8db2966d87 100644
--- a/internal/cloudcp/handoff/handoff.go
+++ b/internal/cloudcp/handoff/handoff.go
@@ -5,12 +5,12 @@ import (
"encoding/hex"
"fmt"
"io"
- "net/url"
"strings"
"time"
"github.com/golang-jwt/jwt/v5"
"github.com/rcourtman/pulse-go-rewrite/internal/cloudcp/registry"
+ "github.com/rcourtman/pulse-go-rewrite/pkg/securityutil"
)
const (
@@ -125,16 +125,9 @@ func sanitizeID(s string) string {
}
func sanitizeTargetPath(raw string) string {
- raw = strings.TrimSpace(raw)
- if raw == "" || !strings.HasPrefix(raw, "/") || strings.HasPrefix(raw, "//") {
- return ""
- }
- if strings.IndexFunc(raw, func(r rune) bool { return r < 0x20 || r == 0x7f }) >= 0 {
- return ""
- }
- parsed, err := url.Parse(raw)
- if err != nil || parsed.IsAbs() || parsed.Host != "" || parsed.Path == "" || !strings.HasPrefix(parsed.Path, "/") {
+ targetPath, err := securityutil.NormalizeLocalRedirectPath(raw)
+ if err != nil {
return ""
}
- return parsed.String()
+ return targetPath
}
diff --git a/internal/cloudcp/handoff/handoff_test.go b/internal/cloudcp/handoff/handoff_test.go
index 911e3e703e..744f28ffaf 100644
--- a/internal/cloudcp/handoff/handoff_test.go
+++ b/internal/cloudcp/handoff/handoff_test.go
@@ -108,6 +108,24 @@ func TestMintHandoffTokenDropsUnsafeTargetPath(t *testing.T) {
}
}
+func TestSanitizeTargetPathRejectsCrossOriginVariants(t *testing.T) {
+ for _, raw := range []string{
+ "//evil.example/path",
+ `/\\evil.example/path`,
+ "/%2f%2fevil.example/path",
+ "/%5cevil.example/path",
+ "https://evil.example/path",
+ "/settings\nnext",
+ } {
+ if got := sanitizeTargetPath(raw); got != "" {
+ t.Errorf("sanitizeTargetPath(%q) = %q, want empty", raw, got)
+ }
+ }
+ if got := sanitizeTargetPath("/settings/infrastructure?add=linux-host"); got != "/settings/infrastructure?add=linux-host" {
+ t.Fatalf("valid target path = %q", got)
+ }
+}
+
func TestExpiredToken(t *testing.T) {
secret := []byte("0123456789abcdef0123456789abcdef")
past := time.Now().UTC().Add(-2 * time.Minute)
diff --git a/internal/hostagent/commands_deploy.go b/internal/hostagent/commands_deploy.go
index 9f2340baca..97aa81fea0 100644
--- a/internal/hostagent/commands_deploy.go
+++ b/internal/hostagent/commands_deploy.go
@@ -12,6 +12,7 @@ import (
"time"
"github.com/gorilla/websocket"
+ "github.com/rcourtman/pulse-go-rewrite/internal/agentexec"
)
var deploySSHUserPattern = regexp.MustCompile(`^[A-Za-z0-9_][A-Za-z0-9._-]{0,63}$`)
@@ -629,6 +630,9 @@ func makeSemaphore(maxParallel int) chan struct{} {
if maxParallel <= 0 {
maxParallel = 1
}
+ if maxParallel > agentexec.MaxDeployParallel {
+ maxParallel = agentexec.MaxDeployParallel
+ }
return make(chan struct{}, maxParallel)
}
diff --git a/internal/hostagent/commands_deploy_test.go b/internal/hostagent/commands_deploy_test.go
index 472401dd70..4ed5e4240e 100644
--- a/internal/hostagent/commands_deploy_test.go
+++ b/internal/hostagent/commands_deploy_test.go
@@ -6,6 +6,7 @@ import (
"strings"
"testing"
+ "github.com/rcourtman/pulse-go-rewrite/internal/agentexec"
sshknownhosts "github.com/rcourtman/pulse-go-rewrite/internal/ssh/knownhosts"
"github.com/rs/zerolog"
)
@@ -111,6 +112,11 @@ func TestMakeSemaphore(t *testing.T) {
if cap(sem) != 3 {
t.Errorf("expected capacity 3, got %d", cap(sem))
}
+
+ sem = makeSemaphore(1 << 30)
+ if cap(sem) != agentexec.MaxDeployParallel {
+ t.Errorf("expected capacity %d for oversized value, got %d", agentexec.MaxDeployParallel, cap(sem))
+ }
}
func TestMarshalPreflightResult(t *testing.T) {
diff --git a/internal/mock/generator.go b/internal/mock/generator.go
index fa30324c05..382d00f976 100644
--- a/internal/mock/generator.go
+++ b/internal/mock/generator.go
@@ -816,6 +816,12 @@ func ptrFloat64(v float64) *float64 {
}
func generateNodes(config MockConfig) []models.Node {
+ if config.NodeCount < minMockNodeCount {
+ config.NodeCount = minMockNodeCount
+ }
+ if config.NodeCount > maxMockNodeCount {
+ config.NodeCount = maxMockNodeCount
+ }
nodes := make([]models.Node, 0, config.NodeCount)
// First 5 nodes are part of the cluster
diff --git a/internal/mock/generator_test.go b/internal/mock/generator_test.go
index 269198ee74..11f06fdc8c 100644
--- a/internal/mock/generator_test.go
+++ b/internal/mock/generator_test.go
@@ -445,6 +445,19 @@ func TestBuildFixtureStateCreatesHostEntriesForKubernetesNodes(t *testing.T) {
}
}
+func TestGenerateNodesBoundsDirectConfiguration(t *testing.T) {
+ cfg := DefaultConfig
+ cfg.NodeCount = 1 << 30
+ if got := len(generateNodes(cfg)); got != maxMockNodeCount {
+ t.Fatalf("generateNodes() count = %d, want max %d", got, maxMockNodeCount)
+ }
+
+ cfg.NodeCount = -1
+ if got := len(generateNodes(cfg)); got != minMockNodeCount {
+ t.Fatalf("generateNodes() count = %d, want min %d", got, minMockNodeCount)
+ }
+}
+
func TestBuildFixtureStateIncludesKubernetesStorageInventory(t *testing.T) {
cfg := DefaultConfig
cfg.K8sClusterCount = 1
diff --git a/internal/monitoring/availability_poller.go b/internal/monitoring/availability_poller.go
index 1e7d2391d7..29a7303123 100644
--- a/internal/monitoring/availability_poller.go
+++ b/internal/monitoring/availability_poller.go
@@ -2,7 +2,6 @@ package monitoring
import (
"context"
- "crypto/tls"
"fmt"
"net"
"net/http"
@@ -18,6 +17,7 @@ import (
"github.com/rcourtman/pulse-go-rewrite/internal/securityutil"
"github.com/rcourtman/pulse-go-rewrite/internal/storagehealth"
"github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources"
+ "github.com/rcourtman/pulse-go-rewrite/pkg/tlsutil"
)
// AvailabilityProbeStatus captures the last observed state of an agentless
@@ -464,10 +464,7 @@ func availabilityHTTPOutboundOptions() securityutil.RestrictedOutboundHTTPOption
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.
- },
+ TLSConfig: tlsutil.UnverifiedPeerCertificateCaptureTLSConfig(),
}
}
diff --git a/internal/monitoring/availability_poller_test.go b/internal/monitoring/availability_poller_test.go
index 926930b44f..e05e5a9e6b 100644
--- a/internal/monitoring/availability_poller_test.go
+++ b/internal/monitoring/availability_poller_test.go
@@ -37,6 +37,16 @@ func TestProbeAvailabilityTargetHTTPFallsBackToGETWhenHeadNotAllowed(t *testing.
}
}
+func TestAvailabilityHTTPOutboundOptionsUsesSharedPeerCertificateCapture(t *testing.T) {
+ tlsConfig := availabilityHTTPOutboundOptions().TLSConfig
+ if tlsConfig == nil || !tlsConfig.InsecureSkipVerify {
+ t.Fatal("availability TLS config must enter explicit peer-certificate capture mode")
+ }
+ if tlsConfig.VerifyPeerCertificate == nil {
+ t.Fatal("availability TLS config must reject missing or malformed peer certificates")
+ }
+}
+
func TestProbeAvailabilityTargetHTTPTreatsServerErrorsAsUnavailable(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusServiceUnavailable)
diff --git a/internal/monitoring/canonical_guardrails_test.go b/internal/monitoring/canonical_guardrails_test.go
index 14d87dd50b..1d3650f274 100644
--- a/internal/monitoring/canonical_guardrails_test.go
+++ b/internal/monitoring/canonical_guardrails_test.go
@@ -28,6 +28,20 @@ var bannedSnapshotResourceAccessPatterns = []struct {
},
}
+func TestAvailabilityTLSUsesSharedCertificateCaptureBoundary(t *testing.T) {
+ source, err := os.ReadFile("availability_poller.go")
+ if err != nil {
+ t.Fatalf("read availability_poller.go: %v", err)
+ }
+ text := string(source)
+ if !strings.Contains(text, "tlsutil.UnverifiedPeerCertificateCaptureTLSConfig()") {
+ t.Fatal("availability probes must use the shared peer-certificate capture boundary")
+ }
+ if strings.Contains(text, "InsecureSkipVerify: true") {
+ t.Fatal("availability probes must not define a local skip-verification TLS config")
+ }
+}
+
type guardrailSupplementalProvider struct {
records []unifiedresources.IngestRecord
}
diff --git a/internal/securityutil/httpurl_test.go b/internal/securityutil/httpurl_test.go
index ea9a74c056..2762d4771c 100644
--- a/internal/securityutil/httpurl_test.go
+++ b/internal/securityutil/httpurl_test.go
@@ -5,8 +5,18 @@ import (
"net"
"strings"
"testing"
+
+ pubsec "github.com/rcourtman/pulse-go-rewrite/pkg/securityutil"
)
+func TestPublicLocalRedirectBoundaryRejectsAuthorityVariants(t *testing.T) {
+ for _, raw := range []string{"//evil.example/path", `/\\evil.example/path`, "/%2f%2fevil.example/path"} {
+ if got, err := pubsec.NormalizeLocalRedirectPath(raw); err == nil {
+ t.Errorf("NormalizeLocalRedirectPath(%q) = %q, want rejection", raw, got)
+ }
+ }
+}
+
func TestNormalizeHTTPBaseURLAddsDefaultScheme(t *testing.T) {
parsed, err := NormalizeHTTPBaseURL("pbs.example.com:8007", "https")
if err != nil {
diff --git a/internal/securityutil/secure_storage_dir.go b/internal/securityutil/secure_storage_dir.go
index fa017aa3c9..8ea9a85c4c 100644
--- a/internal/securityutil/secure_storage_dir.go
+++ b/internal/securityutil/secure_storage_dir.go
@@ -92,6 +92,29 @@ func ReadSecureStorageFile(path string, maxSize int64) ([]byte, error) {
return data, nil
}
+// RenameSecureStorageFile renames a regular, non-symlink file between two
+// validated paths in the same owned storage directory.
+func RenameSecureStorageFile(sourcePath, destinationPath string) error {
+ if filepath.Dir(sourcePath) != filepath.Dir(destinationPath) {
+ return fmt.Errorf("secure storage rename must remain in one directory")
+ }
+
+ info, err := secureStorageFileLstatFn(sourcePath)
+ if err != nil {
+ return err
+ }
+ if info.Mode()&os.ModeSymlink != 0 || !info.Mode().IsRegular() {
+ return fmt.Errorf("%w: refusing non-regular source path %q", ErrUnsafeStorageFile, sourcePath)
+ }
+ if _, err := secureStorageFileLstatFn(destinationPath); err == nil {
+ return fmt.Errorf("%w: refusing to replace existing destination %q", ErrUnsafeStorageFile, destinationPath)
+ } else if !errors.Is(err, os.ErrNotExist) {
+ return err
+ }
+
+ return secureStorageFileRenameFn(sourcePath, destinationPath)
+}
+
// WriteSecureStorageFile writes a file via a temp file + rename inside an
// already validated storage directory so file creation stays owner-only and
// does not follow pre-existing symlinks at the destination path.
diff --git a/internal/securityutil/secure_storage_dir_test.go b/internal/securityutil/secure_storage_dir_test.go
index be6cdfc181..800947f637 100644
--- a/internal/securityutil/secure_storage_dir_test.go
+++ b/internal/securityutil/secure_storage_dir_test.go
@@ -157,3 +157,40 @@ func TestWriteSecureStorageFile_CreatesOwnerOnlyFile(t *testing.T) {
t.Fatalf("permissions = %o, want 600", got)
}
}
+
+func TestRenameSecureStorageFile(t *testing.T) {
+ root := t.TempDir()
+ source := filepath.Join(root, "source.json")
+ destination := filepath.Join(root, "source.json.bak")
+ if err := os.WriteFile(source, []byte("payload"), 0o600); err != nil {
+ t.Fatalf("write source: %v", err)
+ }
+
+ if err := RenameSecureStorageFile(source, destination); err != nil {
+ t.Fatalf("RenameSecureStorageFile() error = %v", err)
+ }
+ if _, err := os.Stat(source); !errors.Is(err, os.ErrNotExist) {
+ t.Fatalf("source stat error = %v, want not exist", err)
+ }
+ if data, err := os.ReadFile(destination); err != nil || string(data) != "payload" {
+ t.Fatalf("destination = %q, err = %v", data, err)
+ }
+}
+
+func TestRenameSecureStorageFileRejectsUnsafePaths(t *testing.T) {
+ root := t.TempDir()
+ source := filepath.Join(root, "source.json")
+ destination := filepath.Join(root, "source.json.bak")
+ if err := os.WriteFile(source, []byte("payload"), 0o600); err != nil {
+ t.Fatalf("write source: %v", err)
+ }
+ if err := os.WriteFile(destination, []byte("existing"), 0o600); err != nil {
+ t.Fatalf("write destination: %v", err)
+ }
+ if err := RenameSecureStorageFile(source, destination); !errors.Is(err, ErrUnsafeStorageFile) {
+ t.Fatalf("existing destination error = %v, want ErrUnsafeStorageFile", err)
+ }
+ if err := RenameSecureStorageFile(source, filepath.Join(t.TempDir(), "other.json")); err == nil {
+ t.Fatal("expected cross-directory rename rejection")
+ }
+}
diff --git a/internal/websocket/hub_multitenant_test.go b/internal/websocket/hub_multitenant_test.go
index 6733000570..9708859cf3 100644
--- a/internal/websocket/hub_multitenant_test.go
+++ b/internal/websocket/hub_multitenant_test.go
@@ -35,7 +35,7 @@ type testAuditLogger struct {
events []audit.Event
}
-func (l *testAuditLogger) Log(event audit.Event) error {
+func (l *testAuditLogger) Record(event audit.Event) error {
l.mu.Lock()
defer l.mu.Unlock()
l.events = append(l.events, event)
diff --git a/pkg/audit/async_logger.go b/pkg/audit/async_logger.go
index 391dde7b6c..b1ec8c9d25 100644
--- a/pkg/audit/async_logger.go
+++ b/pkg/audit/async_logger.go
@@ -43,13 +43,13 @@ func NewAsyncLogger(backend Logger, cfg AsyncLoggerConfig) *AsyncLogger {
return l
}
-// Log enqueues the event for async processing. If the queue is full, it falls back to sync logging.
-func (l *AsyncLogger) Log(event Event) error {
+// Record enqueues the event for async persistence. If the queue is full, it falls back to a synchronous record.
+func (l *AsyncLogger) Record(event Event) error {
if l == nil {
return nil
}
if l.closed.Load() {
- return l.backend.Log(event)
+ return l.backend.Record(event)
}
select {
@@ -57,7 +57,7 @@ func (l *AsyncLogger) Log(event Event) error {
return nil
default:
// Queue full; fall back to synchronous logging to avoid dropping events.
- return l.backend.Log(event)
+ return l.backend.Record(event)
}
}
@@ -129,7 +129,7 @@ func (l *AsyncLogger) drain() {
func (l *AsyncLogger) logEvent(event Event) {
start := time.Now()
- if err := l.backend.Log(event); err != nil {
+ if err := l.backend.Record(event); err != nil {
log.Error().Err(err).Str("event", event.EventType).Msg("Failed to log audit event")
return
}
diff --git a/pkg/audit/audit.go b/pkg/audit/audit.go
index 97c39e7f73..f1a34a9025 100644
--- a/pkg/audit/audit.go
+++ b/pkg/audit/audit.go
@@ -48,8 +48,8 @@ type QueryFilter struct {
// The OSS version uses ConsoleLogger which outputs to zerolog.
// Enterprise implementations can provide persistent storage with signing.
type Logger interface {
- // Log records an audit event
- Log(event Event) error
+ // Record persists an audit event. Realtime logging is a separate, redacted projection.
+ Record(event Event) error
// Query retrieves audit events matching the filter (optional, may return empty for console logger)
Query(filter QueryFilter) ([]Event, error)
@@ -149,7 +149,7 @@ func Log(eventType, user, ip, path string, success bool, details string) {
Details: details,
}
- if err := GetLogger().Log(event); err != nil {
+ if err := GetLogger().Record(event); err != nil {
log.Error().Err(err).Str("event", eventType).Msg("Failed to log audit event")
}
}
@@ -166,6 +166,13 @@ func appendRealtimeAuditDetailFields(ctx zerolog.Context, details string) zerolo
Str("details_sha256", hex.EncodeToString(sum[:]))
}
+func appendRealtimeAuditIdentityFields(ctx zerolog.Context, event Event) zerolog.Context {
+ return ctx.
+ Bool("user_present", event.User != "").
+ Bool("ip_present", event.IP != "").
+ Str("path", event.Path)
+}
+
// ConsoleLogger implements Logger by writing to zerolog.
// This is the default implementation used by the OSS version.
type ConsoleLogger struct{}
@@ -180,15 +187,13 @@ func (c *ConsoleLogger) IsPersistentAuditLogger() bool {
return false
}
-// Log writes an audit event to zerolog.
-func (c *ConsoleLogger) Log(event Event) error {
+// Record writes a redacted audit event projection to zerolog.
+func (c *ConsoleLogger) Record(event Event) error {
logContext := log.With().
Str("audit_id", event.ID).
Str("event", event.EventType).
- Str("user", event.User).
- Str("ip", event.IP).
- Str("path", event.Path).
Time("timestamp", event.Timestamp)
+ logContext = appendRealtimeAuditIdentityFields(logContext, event)
logEvent := appendRealtimeAuditDetailFields(logContext, event.Details).Logger()
if event.Success {
diff --git a/pkg/audit/audit_test.go b/pkg/audit/audit_test.go
index 8be88ac7f4..1cdd07b341 100644
--- a/pkg/audit/audit_test.go
+++ b/pkg/audit/audit_test.go
@@ -5,6 +5,7 @@ import (
"crypto/sha256"
"encoding/hex"
"encoding/json"
+ "strings"
"testing"
"time"
@@ -25,7 +26,7 @@ func TestConsoleLogger_Log(t *testing.T) {
Details: "Basic auth login",
}
- err := logger.Log(event)
+ err := logger.Record(event)
if err != nil {
t.Errorf("ConsoleLogger.Log() returned error: %v", err)
}
@@ -45,7 +46,7 @@ func TestConsoleLogger_Log_Failed(t *testing.T) {
Details: "Invalid credentials",
}
- err := logger.Log(event)
+ err := logger.Record(event)
if err != nil {
t.Errorf("ConsoleLogger.Log() returned error: %v", err)
}
@@ -122,6 +123,21 @@ func TestAppendRealtimeAuditDetailFields(t *testing.T) {
}
}
+func TestAppendRealtimeAuditIdentityFieldsOmitsRawIdentity(t *testing.T) {
+ var buf bytes.Buffer
+ event := Event{User: "[email protected]", IP: "192.0.2.10", Path: "/api/login"}
+ logger := appendRealtimeAuditIdentityFields(zerolog.New(&buf).With(), event).Logger()
+ logger.Info().Msg("audit")
+
+ output := buf.String()
+ if strings.Contains(output, event.User) || strings.Contains(output, event.IP) {
+ t.Fatalf("realtime audit output exposed raw identity: %s", output)
+ }
+ if !strings.Contains(output, `"user_present":true`) || !strings.Contains(output, `"ip_present":true`) {
+ t.Fatalf("realtime audit output omitted presence markers: %s", output)
+ }
+}
+
func TestSetLogger_GetLogger(t *testing.T) {
// Create a custom logger for testing
customLogger := NewConsoleLogger()
diff --git a/pkg/audit/export_test.go b/pkg/audit/export_test.go
index 0706ad1fa1..5601d8b231 100644
--- a/pkg/audit/export_test.go
+++ b/pkg/audit/export_test.go
@@ -37,7 +37,7 @@ func TestExporterExportAndSummary(t *testing.T) {
}
for _, event := range events {
- if err := logger.Log(event); err != nil {
+ if err := logger.Record(event); err != nil {
t.Fatalf("log event: %v", err)
}
}
diff --git a/pkg/audit/sqlite_factory_test.go b/pkg/audit/sqlite_factory_test.go
index dc18cb8d04..7c585e4a5b 100644
--- a/pkg/audit/sqlite_factory_test.go
+++ b/pkg/audit/sqlite_factory_test.go
@@ -40,7 +40,7 @@ func TestSQLiteLoggerFactory_CreateLogger_PersistsAndSigns(t *testing.T) {
Details: "hello",
}
- if err := logger.Log(event); err != nil {
+ if err := logger.Record(event); err != nil {
t.Fatalf("Log failed: %v", err)
}
diff --git a/pkg/audit/sqlite_logger.go b/pkg/audit/sqlite_logger.go
index 59e04329e5..0a87d5b643 100644
--- a/pkg/audit/sqlite_logger.go
+++ b/pkg/audit/sqlite_logger.go
@@ -271,7 +271,7 @@ func (l *SQLiteLogger) initSchema() error {
}
// Log records an audit event with HMAC signature.
-func (l *SQLiteLogger) Log(event Event) error {
+func (l *SQLiteLogger) Record(event Event) error {
// Sign the event
event.Signature = l.signer.Sign(event)
@@ -310,10 +310,8 @@ func (l *SQLiteLogger) Log(event Event) error {
logContext := log.With().
Str("audit_id", event.ID).
Str("event", event.EventType).
- Str("user", event.User).
- Str("ip", event.IP).
- Str("path", event.Path).
Time("timestamp", event.Timestamp)
+ logContext = appendRealtimeAuditIdentityFields(logContext, event)
logEvent := appendRealtimeAuditDetailFields(logContext, event.Details).Logger()
if event.Success {
diff --git a/pkg/audit/sqlite_logger_test.go b/pkg/audit/sqlite_logger_test.go
index fcecf20608..aa2fdabb6f 100644
--- a/pkg/audit/sqlite_logger_test.go
+++ b/pkg/audit/sqlite_logger_test.go
@@ -135,7 +135,7 @@ func TestSQLiteLoggerLog(t *testing.T) {
Details: "test details",
}
- err = logger.Log(event)
+ err = logger.Record(event)
if err != nil {
t.Fatalf("Log failed: %v", err)
}
@@ -193,7 +193,7 @@ func TestSQLiteLoggerQuery(t *testing.T) {
}
for _, e := range events {
- if err := logger.Log(e); err != nil {
+ if err := logger.Record(e); err != nil {
t.Fatalf("Log failed: %v", err)
}
}
@@ -374,7 +374,7 @@ func TestSQLiteLoggerCount(t *testing.T) {
EventType: "test",
Success: i%2 == 0,
}
- if err := logger.Log(event); err != nil {
+ if err := logger.Record(event); err != nil {
t.Fatalf("Log failed: %v", err)
}
}
@@ -420,7 +420,7 @@ func TestSQLiteLoggerVerifySignature(t *testing.T) {
Success: true,
}
- if err := logger.Log(event); err != nil {
+ if err := logger.Record(event); err != nil {
t.Fatalf("Log failed: %v", err)
}
@@ -510,7 +510,7 @@ func TestSQLiteLoggerRetention(t *testing.T) {
EventType: "old",
Success: true,
}
- if err := logger.Log(oldEvent); err != nil {
+ if err := logger.Record(oldEvent); err != nil {
t.Fatalf("Log old event failed: %v", err)
}
@@ -521,7 +521,7 @@ func TestSQLiteLoggerRetention(t *testing.T) {
EventType: "new",
Success: true,
}
- if err := logger.Log(newEvent); err != nil {
+ if err := logger.Record(newEvent); err != nil {
t.Fatalf("Log new event failed: %v", err)
}
@@ -644,7 +644,7 @@ func TestSQLiteLoggerPersistence(t *testing.T) {
User: "testuser",
Success: true,
}
- if err := logger1.Log(event); err != nil {
+ if err := logger1.Record(event); err != nil {
t.Fatalf("Log failed: %v", err)
}
@@ -702,7 +702,7 @@ func TestSQLiteLoggerConcurrentAccess(t *testing.T) {
User: "user",
Success: true,
}
- if err := logger.Log(event); err != nil {
+ if err := logger.Record(event); err != nil {
t.Errorf("Concurrent log failed: %v", err)
}
}
diff --git a/pkg/audit/tenant_logger.go b/pkg/audit/tenant_logger.go
index 925173af26..bf42face8c 100644
--- a/pkg/audit/tenant_logger.go
+++ b/pkg/audit/tenant_logger.go
@@ -121,7 +121,7 @@ func (m *TenantLoggerManager) Log(orgID, eventType, user, ip, path string, succe
Success: success,
Details: details,
}
- return logger.Log(event)
+ return logger.Record(event)
}
// Query queries audit events for a specific organization.
diff --git a/pkg/audit/tenant_logger_manager_test.go b/pkg/audit/tenant_logger_manager_test.go
index 999cda693a..0a3f4374b8 100644
--- a/pkg/audit/tenant_logger_manager_test.go
+++ b/pkg/audit/tenant_logger_manager_test.go
@@ -14,7 +14,7 @@ type stubLogger struct {
urls []string
}
-func (s *stubLogger) Log(event Event) error {
+func (s *stubLogger) Record(event Event) error {
s.events = append(s.events, event)
return nil
}
diff --git a/pkg/auth/sqlite_manager.go b/pkg/auth/sqlite_manager.go
index 58c8af78cf..b00a8f7f93 100644
--- a/pkg/auth/sqlite_manager.go
+++ b/pkg/auth/sqlite_manager.go
@@ -5,16 +5,17 @@ import (
"encoding/json"
"fmt"
"net/url"
- "os"
- "path/filepath"
"sync"
"time"
"github.com/google/uuid"
+ "github.com/rcourtman/pulse-go-rewrite/internal/securityutil"
"github.com/rs/zerolog/log"
_ "modernc.org/sqlite"
)
+const maxLegacyRBACFileSize = 16 << 20
+
// SQLiteManagerConfig configures the SQLite RBAC manager.
type SQLiteManagerConfig struct {
DataDir string // Directory for rbac.db
@@ -36,13 +37,22 @@ func NewSQLiteManager(cfg SQLiteManagerConfig) (*SQLiteManager, error) {
return nil, fmt.Errorf("data directory is required")
}
- // Ensure directory exists
- rbacDir := filepath.Join(cfg.DataDir, "rbac")
- if err := os.MkdirAll(rbacDir, 0700); err != nil {
+ dataDir, err := securityutil.NormalizeStorageDir(cfg.DataDir)
+ if err != nil {
+ return nil, fmt.Errorf("normalize data directory: %w", err)
+ }
+ rbacDir, err := securityutil.JoinStorageLeaf(dataDir, "rbac")
+ if err != nil {
+ return nil, fmt.Errorf("resolve rbac directory: %w", err)
+ }
+ if err := securityutil.EnsureSecureStorageDir(rbacDir, 0700); err != nil {
return nil, fmt.Errorf("failed to create rbac directory: %w", err)
}
- dbPath := filepath.Join(rbacDir, "rbac.db")
+ dbPath, err := securityutil.JoinStorageLeaf(rbacDir, "rbac.db")
+ if err != nil {
+ return nil, fmt.Errorf("resolve rbac database path: %w", err)
+ }
// Open database with pragmas in DSN so every pool connection is configured
dsn := dbPath + "?" + url.Values{
@@ -89,7 +99,7 @@ func NewSQLiteManager(cfg SQLiteManagerConfig) (*SQLiteManager, error) {
// Migrate from file-based storage if requested
if cfg.MigrateFromFiles {
- if err := m.migrateFromFiles(cfg.DataDir); err != nil {
+ if err := m.migrateFromFiles(dataDir); err != nil {
log.Warn().Err(err).Msg("Failed to migrate RBAC from files (may not exist)")
}
}
@@ -909,8 +919,22 @@ func (m *SQLiteManager) logChangeUnsafe(action, entityType, entityID, oldValue,
// migrateFromFiles migrates data from file-based storage.
func (m *SQLiteManager) migrateFromFiles(dataDir string) error {
- rolesFile := filepath.Join(dataDir, "rbac_roles.json")
- assignmentsFile := filepath.Join(dataDir, "rbac_assignments.json")
+ rolesFile, err := securityutil.JoinStorageLeaf(dataDir, "rbac_roles.json")
+ if err != nil {
+ return fmt.Errorf("resolve legacy roles path: %w", err)
+ }
+ rolesBackup, err := securityutil.JoinStorageLeaf(dataDir, "rbac_roles.json.bak")
+ if err != nil {
+ return fmt.Errorf("resolve legacy roles backup path: %w", err)
+ }
+ assignmentsFile, err := securityutil.JoinStorageLeaf(dataDir, "rbac_assignments.json")
+ if err != nil {
+ return fmt.Errorf("resolve legacy assignments path: %w", err)
+ }
+ assignmentsBackup, err := securityutil.JoinStorageLeaf(dataDir, "rbac_assignments.json.bak")
+ if err != nil {
+ return fmt.Errorf("resolve legacy assignments backup path: %w", err)
+ }
// Check if migration is needed
var roleCount int
@@ -922,7 +946,7 @@ func (m *SQLiteManager) migrateFromFiles(dataDir string) error {
}
// Migrate roles
- if data, err := os.ReadFile(rolesFile); err == nil {
+ if data, err := securityutil.ReadSecureStorageFile(rolesFile, maxLegacyRBACFileSize); err == nil {
var roles []Role
if err := json.Unmarshal(data, &roles); err == nil {
for _, role := range roles {
@@ -935,14 +959,14 @@ func (m *SQLiteManager) migrateFromFiles(dataDir string) error {
log.Info().Int("count", len(roles)).Msg("Migrated roles from file")
// Rename old file
- if err := os.Rename(rolesFile, rolesFile+".bak"); err != nil {
+ if err := securityutil.RenameSecureStorageFile(rolesFile, rolesBackup); err != nil {
log.Warn().Err(err).Msg("Failed to rename migrated roles file")
}
}
}
// Migrate assignments
- if data, err := os.ReadFile(assignmentsFile); err == nil {
+ if data, err := securityutil.ReadSecureStorageFile(assignmentsFile, maxLegacyRBACFileSize); err == nil {
var assignments []UserRoleAssignment
if err := json.Unmarshal(data, &assignments); err == nil {
for _, a := range assignments {
@@ -953,7 +977,7 @@ func (m *SQLiteManager) migrateFromFiles(dataDir string) error {
log.Info().Int("count", len(assignments)).Msg("Migrated assignments from file")
// Rename old file
- if err := os.Rename(assignmentsFile, assignmentsFile+".bak"); err != nil {
+ if err := securityutil.RenameSecureStorageFile(assignmentsFile, assignmentsBackup); err != nil {
log.Warn().Err(err).Msg("Failed to rename migrated assignments file")
}
}
diff --git a/pkg/discovery/discovery.go b/pkg/discovery/discovery.go
index 87c313db44..fecf9113a7 100644
--- a/pkg/discovery/discovery.go
+++ b/pkg/discovery/discovery.go
@@ -1261,7 +1261,7 @@ func (s *Scanner) performTLSProbe(ctx context.Context, address string) (*tls.Con
}
dialer := &net.Dialer{Timeout: timeout}
- tlsConn, err := tls.DialWithDialer(dialer, "tcp", address, tlsutil.PeerCertificateCaptureTLSConfig())
+ tlsConn, err := tls.DialWithDialer(dialer, "tcp", address, tlsutil.UnverifiedPeerCertificateCaptureTLSConfig())
if err == nil {
state := tlsConn.ConnectionState()
tlsConn.Close()
diff --git a/pkg/securityutil/httpurl.go b/pkg/securityutil/httpurl.go
index 67469eaa66..3042f68b5b 100644
--- a/pkg/securityutil/httpurl.go
+++ b/pkg/securityutil/httpurl.go
@@ -93,9 +93,12 @@ func NormalizeHTTPBaseURL(raw string, defaultScheme string) (*url.URL, error) {
case ".", "/":
parsed.Path = ""
default:
- if !strings.HasPrefix(cleanedPath, "/") {
+ if cleanedPath[0] != '/' {
cleanedPath = "/" + cleanedPath
}
+ if len(cleanedPath) > 1 && (cleanedPath[1] == '/' || cleanedPath[1] == '\\') {
+ return nil, fmt.Errorf("base URL path must be host-local")
+ }
parsed.Path = cleanedPath
}
parsed.RawPath = ""
@@ -103,6 +106,35 @@ func NormalizeHTTPBaseURL(raw string, defaultScheme string) (*url.URL, error) {
return parsed, nil
}
+// NormalizeLocalRedirectPath validates a browser redirect that must remain on
+// the current origin. It checks the decoded path so encoded slash or backslash
+// variants cannot become scheme-relative redirects later.
+func NormalizeLocalRedirectPath(raw string) (string, error) {
+ trimmed := strings.TrimSpace(raw)
+ if trimmed == "" {
+ return "", fmt.Errorf("redirect path is required")
+ }
+ if strings.IndexFunc(trimmed, func(r rune) bool { return r < 0x20 || r == 0x7f }) >= 0 {
+ return "", fmt.Errorf("redirect path contains control characters")
+ }
+
+ parsed, err := url.Parse(trimmed)
+ if err != nil {
+ return "", fmt.Errorf("invalid redirect path: %w", err)
+ }
+ if parsed.IsAbs() || parsed.Host != "" || parsed.Path == "" {
+ return "", fmt.Errorf("redirect must be a local absolute path")
+ }
+ if parsed.Path[0] != '/' || (len(parsed.Path) > 1 && (parsed.Path[1] == '/' || parsed.Path[1] == '\\')) {
+ return "", fmt.Errorf("redirect must remain on the current origin")
+ }
+ if strings.ContainsRune(parsed.Path, '\\') {
+ return "", fmt.Errorf("redirect path must not contain backslashes")
+ }
+
+ return trimmed, nil
+}
+
// IsLoopbackHost reports whether host resolves to localhost or a loopback IP literal.
func IsLoopbackHost(host string) bool {
normalized := strings.ToLower(strings.Trim(host, "[]"))
diff --git a/pkg/securityutil/httpurl_test.go b/pkg/securityutil/httpurl_test.go
index bb630caab9..5494c8a0bb 100644
--- a/pkg/securityutil/httpurl_test.go
+++ b/pkg/securityutil/httpurl_test.go
@@ -15,6 +15,42 @@ func localNetworkHTTPOptions(resolver func(context.Context, string) ([]net.IPAdd
}
}
+func TestNormalizeLocalRedirectPath(t *testing.T) {
+ tests := []struct {
+ name string
+ raw string
+ want string
+ wantErr bool
+ }{
+ {name: "local path", raw: "/settings/infrastructure?add=linux-host", want: "/settings/infrastructure?add=linux-host"},
+ {name: "scheme relative", raw: "//evil.example/path", wantErr: true},
+ {name: "backslash authority", raw: `/\\evil.example/path`, wantErr: true},
+ {name: "encoded slash authority", raw: "/%2f%2fevil.example/path", wantErr: true},
+ {name: "encoded backslash authority", raw: "/%5cevil.example/path", wantErr: true},
+ {name: "absolute URL", raw: "https://evil.example/path", wantErr: true},
+ {name: "control character", raw: "/settings\nnext", wantErr: true},
+ {name: "relative path", raw: "settings", wantErr: true},
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ got, err := NormalizeLocalRedirectPath(tt.raw)
+ if tt.wantErr {
+ if err == nil {
+ t.Fatalf("NormalizeLocalRedirectPath(%q) = %q, want error", tt.raw, got)
+ }
+ return
+ }
+ if err != nil {
+ t.Fatalf("NormalizeLocalRedirectPath(%q) error = %v", tt.raw, err)
+ }
+ if got != tt.want {
+ t.Fatalf("NormalizeLocalRedirectPath(%q) = %q, want %q", tt.raw, got, tt.want)
+ }
+ })
+ }
+}
+
func TestNormalizePulseHTTPBaseURLWithOptionsAllowsResolvedLocalDNS(t *testing.T) {
opts := localNetworkHTTPOptions(func(_ context.Context, host string) ([]net.IPAddr, error) {
if host != "myhost.fritz.box" {
diff --git a/pkg/server/server_helpers_test.go b/pkg/server/server_helpers_test.go
index 03380d35d1..160e44a21e 100644
--- a/pkg/server/server_helpers_test.go
+++ b/pkg/server/server_helpers_test.go
@@ -16,7 +16,7 @@ type captureAuditLogger struct {
events []audit.Event
}
-func (c *captureAuditLogger) Log(event audit.Event) error {
+func (c *captureAuditLogger) Record(event audit.Event) error {
c.events = append(c.events, event)
return nil
}
diff --git a/pkg/tlsutil/fingerprint.go b/pkg/tlsutil/fingerprint.go
index 39d9088d34..16dda5e80a 100644
--- a/pkg/tlsutil/fingerprint.go
+++ b/pkg/tlsutil/fingerprint.go
@@ -29,10 +29,10 @@ func verifyPresentedPeerCertificates(rawCerts [][]byte, _ [][]*x509.Certificate)
return nil
}
-// PeerCertificateCaptureTLSConfig accepts any parseable peer certificate so discovery
-// and TOFU fingerprint workflows can inspect TLS identity material without relying on
-// blanket InsecureSkipVerify alone.
-func PeerCertificateCaptureTLSConfig() *tls.Config {
+// UnverifiedPeerCertificateCaptureTLSConfig accepts any parseable peer
+// certificate so discovery and TOFU fingerprint workflows can inspect identity
+// material before an operator establishes trust.
+func UnverifiedPeerCertificateCaptureTLSConfig() *tls.Config {
return &tls.Config{
MinVersion: minimumTLSVersion,
InsecureSkipVerify: true,
@@ -40,6 +40,12 @@ func PeerCertificateCaptureTLSConfig() *tls.Config {
}
}
+// PeerCertificateCaptureTLSConfig is retained for source compatibility. New
+// callers should use the explicitly named unverified capture boundary.
+func PeerCertificateCaptureTLSConfig() *tls.Config {
+ return UnverifiedPeerCertificateCaptureTLSConfig()
+}
+
// FetchFingerprint connects to a host and returns the SHA256 fingerprint of its TLS certificate.
// This is used for TOFU (Trust On First Use) when discovering cluster peers.
// The host should be in the format "hostname:port" or "https://hostname:port".
@@ -65,7 +71,7 @@ func FetchFingerprint(host string) (string, error) {
defer cancel()
dialer := &net.Dialer{Timeout: 5 * time.Second}
- conn, err := tls.DialWithDialer(dialer, "tcp", targetHost, PeerCertificateCaptureTLSConfig())
+ conn, err := tls.DialWithDialer(dialer, "tcp", targetHost, UnverifiedPeerCertificateCaptureTLSConfig())
if err != nil {
return "", fmt.Errorf("failed to connect to %s: %w", targetHost, err)
}
@@ -181,7 +187,7 @@ func CreateHTTPClientWithTimeout(verifySSL bool, fingerprint string, timeout tim
if !verifySSL && fingerprint == "" {
// Explicit opt-out mode still requires the peer to present parseable certificates.
- transport.TLSClientConfig = PeerCertificateCaptureTLSConfig()
+ transport.TLSClientConfig = UnverifiedPeerCertificateCaptureTLSConfig()
} else if fingerprint != "" {
// Fingerprint verification mode
transport.TLSClientConfig = FingerprintVerifier(fingerprint)
diff --git a/pkg/tlsutil/tlsutil_test.go b/pkg/tlsutil/tlsutil_test.go
index 72511ca861..45a732ee19 100644
--- a/pkg/tlsutil/tlsutil_test.go
+++ b/pkg/tlsutil/tlsutil_test.go
@@ -44,7 +44,7 @@ func TestFingerprintVerifier_NormalizesFingerprint(t *testing.T) {
}
func TestPeerCertificateCaptureTLSConfigRequiresPeerCertificate(t *testing.T) {
- config := PeerCertificateCaptureTLSConfig()
+ config := UnverifiedPeerCertificateCaptureTLSConfig()
if !config.InsecureSkipVerify {
t.Fatal("PeerCertificateCaptureTLSConfig should enable custom verification mode")
}
diff --git a/tests/migration/v5_session_db_test.go b/tests/migration/v5_session_db_test.go
index da22d1d828..1552d0eb05 100644
--- a/tests/migration/v5_session_db_test.go
+++ b/tests/migration/v5_session_db_test.go
@@ -439,7 +439,7 @@ func TestV5DataDir_AuditDBSchemaAutoMigration(t *testing.T) {
Success: true,
Details: "test migration verification",
}
- require.NoError(t, logger.Log(event))
+ require.NoError(t, logger.Record(event))
// Query the event back
events, err := logger.Query(audit.QueryFilter{ID: "test-migration-event-1"})