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 AI storage leaf path handling

rcourtman82b24f5d902d
diff --git a/docs/release-control/v6/internal/subsystems/ai-runtime.md b/docs/release-control/v6/internal/subsystems/ai-runtime.md
index b6377def4e..0e26047eb7 100644
--- a/docs/release-control/v6/internal/subsystems/ai-runtime.md
+++ b/docs/release-control/v6/internal/subsystems/ai-runtime.md
@@ -527,6 +527,10 @@ That coverage explanation must also stay faithful to the actual recent run
shape. When the most recent verification evidence includes a full Patrol run
that ended with errors, the health summary must say that a recent full patrol
errored rather than claiming recent activity was limited to scoped runs.
+The Patrol status payload must keep that same scope distinction explicit in its
+own recency fields. `last_patrol_at` is reserved for the most recent completed
+full Patrol run, while scoped runs and fix-verification checks advance
+`last_activity_at` without pretending a full verification sweep just happened.
The Patrol startup scheduler must preserve that coverage guarantee as well:
`internal/ai/patrol_run.go` may skip the startup full patrol only when recent
run history already includes a successful full Patrol run, not merely because
diff --git a/internal/ai/chat/session.go b/internal/ai/chat/session.go
index 6ab6552da2..b586ab3d74 100644
--- a/internal/ai/chat/session.go
+++ b/internal/ai/chat/session.go
@@ -72,7 +72,7 @@ func (s *SessionStore) sessionPath(id string) (string, error) {
if err := validateSessionID(id); err != nil {
return "", err
}
- return filepath.Join(s.dataDir, securityutil.HashedStorageName(id)+".json"), nil
+ return securityutil.JoinStorageLeaf(s.dataDir, securityutil.HashedStorageName(id)+".json")
}
func (s *SessionStore) findLegacySessionPath(id string) (string, error) {
@@ -94,7 +94,11 @@ func (s *SessionStore) findLegacySessionPath(id string) (string, error) {
if entry.Name() == canonicalName {
continue
}
- path := filepath.Join(s.dataDir, entry.Name())
+ path, err := securityutil.JoinStorageLeaf(s.dataDir, entry.Name())
+ if err != nil {
+ log.Warn().Err(err).Str("file", entry.Name()).Msg("failed to resolve legacy session candidate path")
+ continue
+ }
data, err := os.ReadFile(path)
if err != nil {
log.Warn().Err(err).Str("file", entry.Name()).Msg("failed to read legacy session candidate")
@@ -128,7 +132,13 @@ func (s *SessionStore) List() ([]Session, error) {
continue
}
- file, err := os.ReadFile(filepath.Join(s.dataDir, entry.Name()))
+ path, err := securityutil.JoinStorageLeaf(s.dataDir, entry.Name())
+ if err != nil {
+ log.Warn().Err(err).Str("file", entry.Name()).Msg("failed to resolve session file path")
+ continue
+ }
+
+ file, err := os.ReadFile(path)
if err != nil {
log.Warn().Err(err).Str("file", entry.Name()).Msg("failed to read session file")
continue
diff --git a/internal/ai/chat/session_test.go b/internal/ai/chat/session_test.go
index 429ce672e0..59507203f2 100644
--- a/internal/ai/chat/session_test.go
+++ b/internal/ai/chat/session_test.go
@@ -4,6 +4,7 @@ import (
"encoding/json"
"os"
"path/filepath"
+ "strings"
"testing"
"time"
@@ -152,6 +153,20 @@ func TestSessionStoreMigratesLegacySessionFileOnWrite(t *testing.T) {
assert.ErrorIs(t, err, os.ErrNotExist)
}
+func TestSessionStoreSessionPathUsesOpaqueHashedLeaf(t *testing.T) {
+ store, err := NewSessionStore(t.TempDir())
+ require.NoError(t, err)
+
+ sessionID := "guest-alpha_123"
+ path, err := store.sessionPath(sessionID)
+ require.NoError(t, err)
+
+ base := filepath.Base(path)
+ assert.True(t, strings.HasSuffix(base, ".json"))
+ assert.NotContains(t, base, "guest")
+ assert.NotContains(t, base, "alpha")
+}
+
func TestMessage_UsesCanonicalEmptyCollections(t *testing.T) {
payload, err := json.Marshal(EmptyMessage())
require.NoError(t, err)
diff --git a/internal/ai/knowledge/store.go b/internal/ai/knowledge/store.go
index fe2abdf9c9..770fd68fdb 100644
--- a/internal/ai/knowledge/store.go
+++ b/internal/ai/knowledge/store.go
@@ -118,10 +118,15 @@ func NewStore(dataDir string) (*Store, error) {
func (s *Store) guestFilePath(guestID string) string {
// Use .enc extension for encrypted files
fileBase := securityutil.HashedStorageName(guestID)
+ leaf := fileBase + ".json"
if s.crypto != nil {
- return filepath.Join(s.dataDir, fileBase+".enc")
+ leaf = fileBase + ".enc"
}
- return filepath.Join(s.dataDir, fileBase+".json")
+ path, err := securityutil.JoinStorageLeaf(s.dataDir, leaf)
+ if err != nil {
+ panic(fmt.Sprintf("resolve guest knowledge storage path: %v", err))
+ }
+ return path
}
func (s *Store) loadKnowledgeFromPath(path string) (*GuestKnowledge, bool, error) {
@@ -178,7 +183,14 @@ func (s *Store) findLegacyKnowledgePath(guestID string) (string, error) {
continue
}
- path := filepath.Join(s.dataDir, entry.Name())
+ path, err := securityutil.JoinStorageLeaf(s.dataDir, entry.Name())
+ if err != nil {
+ if entry.Name() == legacyEnc || entry.Name() == legacyJSON {
+ return "", fmt.Errorf("invalid legacy knowledge file path %q: %w", entry.Name(), err)
+ }
+ log.Warn().Err(err).Str("file", entry.Name()).Msg("failed to resolve legacy knowledge candidate path")
+ continue
+ }
knowledge, _, err := s.loadKnowledgeFromPath(path)
if err != nil {
if entry.Name() == legacyEnc || entry.Name() == legacyJSON {
diff --git a/internal/ai/knowledge/store_coverage_test.go b/internal/ai/knowledge/store_coverage_test.go
index a73f65cf2d..5193045fae 100644
--- a/internal/ai/knowledge/store_coverage_test.go
+++ b/internal/ai/knowledge/store_coverage_test.go
@@ -66,12 +66,18 @@ func TestGuestFilePath_Extensions(t *testing.T) {
if !strings.HasSuffix(encPath, ".enc") {
t.Errorf("expected encrypted path, got %q", encPath)
}
+ if strings.Contains(filepath.Base(encPath), "guest-1") {
+ t.Fatalf("expected encrypted guest path to use opaque hashed leaf, got %q", encPath)
+ }
store.crypto = nil
jsonPath := store.guestFilePath("guest-1")
if !strings.HasSuffix(jsonPath, ".json") {
t.Errorf("expected json path, got %q", jsonPath)
}
+ if strings.Contains(filepath.Base(jsonPath), "guest-1") {
+ t.Fatalf("expected json guest path to use opaque hashed leaf, got %q", jsonPath)
+ }
}
func TestGetKnowledge_LegacyFallback(t *testing.T) {
diff --git a/internal/securityutil/storagepath.go b/internal/securityutil/storagepath.go
index 2a7bc7824a..ee637d4b57 100644
--- a/internal/securityutil/storagepath.go
+++ b/internal/securityutil/storagepath.go
@@ -3,6 +3,9 @@ package securityutil
import (
"crypto/sha256"
"encoding/hex"
+ "fmt"
+ "path/filepath"
+ "strings"
)
// HashedStorageName derives an opaque, fixed-width storage filename stem from an external identifier.
@@ -10,3 +13,27 @@ func HashedStorageName(id string) string {
sum := sha256.Sum256([]byte(id))
return hex.EncodeToString(sum[:])
}
+
+// JoinStorageLeaf joins an already-owned storage directory with a validated leaf filename.
+func JoinStorageLeaf(dir, leaf string) (string, error) {
+ trimmedDir := strings.TrimSpace(dir)
+ if trimmedDir == "" {
+ return "", fmt.Errorf("storage directory is required")
+ }
+
+ name := strings.TrimSpace(leaf)
+ if name == "" {
+ return "", fmt.Errorf("storage leaf is required")
+ }
+ if name == "." || name == ".." {
+ return "", fmt.Errorf("storage leaf must not be '.' or '..'")
+ }
+ if filepath.Base(name) != name {
+ return "", fmt.Errorf("storage leaf must not contain path separators")
+ }
+ if strings.ContainsAny(name, `/\`) {
+ return "", fmt.Errorf("storage leaf must not contain path separators")
+ }
+
+ return filepath.Join(trimmedDir, name), nil
+}
diff --git a/internal/securityutil/storagepath_test.go b/internal/securityutil/storagepath_test.go
new file mode 100644
index 0000000000..9530ffb999
--- /dev/null
+++ b/internal/securityutil/storagepath_test.go
@@ -0,0 +1,30 @@
+package securityutil
+
+import "testing"
+
+func TestJoinStorageLeaf(t *testing.T) {
+ path, err := JoinStorageLeaf("/tmp/pulse", "session.json")
+ if err != nil {
+ t.Fatalf("JoinStorageLeaf() error = %v", err)
+ }
+ if path != "/tmp/pulse/session.json" {
+ t.Fatalf("JoinStorageLeaf() = %q", path)
+ }
+}
+
+func TestJoinStorageLeafRejectsPathSeparators(t *testing.T) {
+ tests := []string{
+ "../session.json",
+ "nested/session.json",
+ `nested\session.json`,
+ ".",
+ "..",
+ "",
+ }
+
+ for _, leaf := range tests {
+ if _, err := JoinStorageLeaf("/tmp/pulse", leaf); err == nil {
+ t.Fatalf("expected %q to be rejected", leaf)
+ }
+ }
+}