Files
Pulse/internal/api/session_store_test.go
pulse-triage[bot] c14186ba2d Check the distinct incomplete-session startup diagnostic
Keep exact once-per-startup and once-per-preservation checks for both old malformed-input fixtures and the new missing-key/null-row cases. Expect the new semantic-admission diagnostic only for those new inputs; retain byte, inode, privacy, persistence and restart assertions unchanged.

Contract-Neutral: Test-only diagnostic expectation repair; no runtime behavior, subsystem guarantee, source format, API or rendered payload change.
Change-source: pulse-maintainer
2026-11-16 23:04:21 +00:00

1437 lines
43 KiB
Go

package api
import (
"bytes"
"encoding/json"
"fmt"
"os"
"path/filepath"
"strings"
"testing"
"time"
)
func sessionPreservedFiles(t *testing.T, dir string) []string {
t.Helper()
dirs, err := filepath.Glob(filepath.Join(dir, ".sessions-unread-*"))
if err != nil {
t.Fatal(err)
}
var paths []string
for _, preservedDir := range dirs {
info, err := os.Stat(preservedDir)
if err != nil {
t.Fatal(err)
}
if !info.IsDir() || info.Mode().Perm()&0077 != 0 {
t.Fatalf("preserved session directory is not owner-private: %v", info.Mode())
}
entries, err := os.ReadDir(preservedDir)
if err != nil || len(entries) != 1 || entries[0].Name() != "sessions.json" {
t.Fatalf("preserved directory contents = %v, error = %v", entries, err)
}
paths = append(paths, filepath.Join(preservedDir, "sessions.json"))
}
return paths
}
func TestSessionStore_UnreadStartupPreservesBeforeEverySave(t *testing.T) {
validPrefix := fmt.Sprintf(`{"key":%q,"username":"saved-fixture","expires_at":"2099-01-01T00:00:00Z"}`, sessionHash("old-synthetic-session"))
inputs := map[string]string{
"garbage": "not a session inventory",
"truncated-array": "[" + validPrefix + ",",
"partial-element": "[" + validPrefix + `,{"key":42}]`,
"truncated-legacy": `{"old-synthetic-session":{"expires_at":"2099-01-01T00:00:00Z"},`,
"missing-key": "[" + validPrefix + `,{"expires_at":"2099-01-01T00:00:00Z"}]`,
"null-row": "[" + validPrefix + `,null]`,
"legacy-empty-key": `{"old-synthetic-session":{"expires_at":"2099-01-01T00:00:00Z"},"":{"expires_at":"2099-01-01T00:00:00Z"}}`,
"scalar": `"synthetic-session-content"`,
"zero-bytes": "",
"whitespace": " \n\t",
}
for name, original := range inputs {
for _, firstSave := range []string{"periodic", "create", "delete", "delete-user", "shutdown"} {
t.Run(name+"/"+firstSave, func(t *testing.T) {
dir := t.TempDir()
path := filepath.Join(dir, "sessions.json")
if err := os.WriteFile(path, []byte(original), 0644); err != nil {
t.Fatal(err)
}
before, err := os.Stat(path)
if err != nil {
t.Fatal(err)
}
logs := captureTestLogs(t)
store := NewSessionStore(dir)
t.Cleanup(store.Shutdown)
if store.ValidateSession("old-synthetic-session") || len(store.sessions) != 0 {
t.Fatal("failed decode admitted partial saved authority")
}
switch firstSave {
case "periodic":
store.save()
case "create":
store.CreateSession("new-synthetic-session", time.Hour, "fixture", "127.0.0.1", "new-fixture")
case "delete":
store.DeleteSession("old-synthetic-session")
case "delete-user":
if keys := store.DeleteSessionsForUser("saved-fixture"); len(keys) != 0 {
t.Fatal("unread inventory supplied live session keys")
}
case "shutdown":
store.Shutdown()
}
preserved := sessionPreservedFiles(t, dir)
if len(preserved) != 1 {
t.Fatalf("preserved files = %d, want one before the first snapshot", len(preserved))
}
after, err := os.Stat(preserved[0])
if err != nil || !os.SameFile(before, after) {
t.Fatalf("original session inode was not retained: %v", err)
}
data, err := os.ReadFile(preserved[0])
if err != nil || string(data) != original {
t.Fatalf("original session bytes changed: %v", err)
}
if firstSave != "shutdown" {
store.CreateSession("control-session", time.Hour, "fixture", "127.0.0.1", "control-user")
store.CreateSession("withdrawn-session", time.Hour, "fixture", "127.0.0.1", "withdrawn-user")
if !store.ValidateAndExtendSession("control-session") {
t.Fatal("new authenticated session cannot operate after preservation")
}
store.DeleteSession("new-synthetic-session")
store.DeleteSessionsForUser("withdrawn-user")
}
store.Shutdown()
if len(sessionPreservedFiles(t, dir)) != 1 {
t.Fatal("subsequent saves created another preserved copy")
}
if _, err := os.Lstat(path + ".tmp"); !os.IsNotExist(err) {
t.Fatalf("session temporary file remained: %v", err)
}
startupDiagnostic := "Failed to decode sessions file;"
if name == "missing-key" || name == "null-row" {
startupDiagnostic = "Incomplete session credential record;"
}
if strings.Count(logs.String(), startupDiagnostic) != 1 || strings.Count(logs.String(), "Unread session file preserved outside active storage;") != 1 {
t.Fatal("startup and preservation diagnostics were not emitted once")
}
if strings.Contains(logs.String(), "old-synthetic-session") || strings.Contains(logs.String(), "synthetic-session-content") {
t.Fatal("startup diagnostics disclosed session contents")
}
restarted := NewSessionStore(dir)
defer restarted.Shutdown()
if restarted.ValidateSession("old-synthetic-session") || restarted.ValidateSession("withdrawn-session") || restarted.ValidateSession("new-synthetic-session") {
t.Fatal("restart resurrected unverified or revoked session authority")
}
if firstSave != "shutdown" && !restarted.ValidateSession("control-session") {
t.Fatal("new independent session did not persist")
}
})
}
}
}
func TestSessionStore_UnreadStartupPermissionFailure(t *testing.T) {
if os.Geteuid() == 0 {
t.Skip("ordinary-user permission witness; nonregular-path control also runs as root")
}
for _, firstSave := range []string{"create", "delete", "delete-user", "shutdown"} {
t.Run(firstSave, func(t *testing.T) {
dir := t.TempDir()
path := filepath.Join(dir, "sessions.json")
original := fmt.Sprintf(`[{"key":%q,"username":"saved-user","expires_at":"2099-01-01T00:00:00Z"}]`, sessionHash("saved-session"))
if err := os.WriteFile(path, []byte(original), 0000); err != nil {
t.Fatal(err)
}
if _, err := os.ReadFile(path); err == nil {
t.Fatal("permission fixture remained readable")
}
store := NewSessionStore(dir)
t.Cleanup(store.Shutdown)
if store.ValidateSession("saved-session") {
t.Fatal("unreadable session was admitted")
}
switch firstSave {
case "create":
store.CreateSession("new-session", time.Hour, "fixture", "127.0.0.1", "new-user")
case "delete":
store.DeleteSession("saved-session")
case "delete-user":
store.DeleteSessionsForUser("saved-user")
case "shutdown":
store.Shutdown()
}
preserved := sessionPreservedFiles(t, dir)
if len(preserved) != 1 {
t.Fatalf("preserved unread files = %d, want one", len(preserved))
}
info, err := os.Stat(preserved[0])
if err != nil || info.Mode().Perm() != 0600 {
t.Fatalf("retained mode000 input is not owner-readable for backups: %v", err)
}
data, err := os.ReadFile(preserved[0])
if err != nil || string(data) != original {
t.Fatalf("unread original was not retained byte-for-byte: %v", err)
}
store.Shutdown()
restarted := NewSessionStore(dir)
defer restarted.Shutdown()
if restarted.ValidateSession("saved-session") || (firstSave == "create" && !restarted.ValidateSession("new-session")) {
t.Fatal("restart restored unknown authority or lost the new authenticated session")
}
})
}
}
func TestSessionStore_UnreadStartupPreservationFailureAndRecovery(t *testing.T) {
if os.Geteuid() == 0 {
t.Skip("requires ordinary-user directory permissions")
}
dir := t.TempDir()
path := filepath.Join(dir, "sessions.json")
original := []byte("{unverified synthetic session bytes")
if err := os.WriteFile(path, original, 0600); err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = os.Chmod(dir, 0700) })
logs := captureTestLogs(t)
store := NewSessionStore(dir)
t.Cleanup(store.Shutdown)
// Crypto initialization hardens its directory to writable owner access.
// Impose the storage failure only after construction has finished, then
// prove this process cannot prepare a preservation directory there.
if err := os.Chmod(dir, 0500); err != nil {
t.Fatal(err)
}
if probe, err := os.MkdirTemp(dir, ".blocked-preservation-probe-*"); !os.IsPermission(err) {
if err == nil {
_ = os.Remove(probe)
}
t.Fatalf("fixture did not block preservation-directory creation: %v", err)
}
store.CreateSession("live-session", time.Hour, "fixture", "127.0.0.1", "live-user")
store.CreateSession("withdrawn-session", time.Hour, "fixture", "127.0.0.1", "withdrawn-user")
store.DeleteSessionsForUser("withdrawn-user")
store.save()
data, err := os.ReadFile(path)
if err != nil || !bytes.Equal(data, original) {
t.Fatalf("failed preservation overwrote original: %v", err)
}
if len(sessionPreservedFiles(t, dir)) != 0 || !store.ValidateAndExtendSession("live-session") || store.ValidateSession("withdrawn-session") {
t.Fatal("failed preservation changed files or blocked live authentication/withdrawal")
}
if strings.Count(logs.String(), "Cannot preserve unread session file;") != 1 || !strings.Contains(logs.String(), "New sign-ins are memory-only") {
t.Fatal("persistence hold must be explicit without repeating errors on every save")
}
if err := os.Chmod(dir, 0700); err != nil {
t.Fatal(err)
}
// A normal later save must preserve the old input before publishing the
// fresh live inventory. No restart or blanket revocation is required.
store.save()
preserved := sessionPreservedFiles(t, dir)
if len(preserved) != 1 {
t.Fatalf("recovered preservation count = %d, want one", len(preserved))
}
data, err = os.ReadFile(preserved[0])
if err != nil || !bytes.Equal(data, original) {
t.Fatalf("recovered storage did not retain original bytes: %v", err)
}
store.Shutdown()
restarted := NewSessionStore(dir)
defer restarted.Shutdown()
if !restarted.ValidateSession("live-session") || restarted.ValidateSession("withdrawn-session") {
t.Fatal("storage recovery lost a valid session or revived withdrawn authority")
}
}
func TestSessionStore_UnreadStartupNonregularPathStaysUntouched(t *testing.T) {
dir := t.TempDir()
path := filepath.Join(dir, "sessions.json")
if err := os.Symlink("sessions.json", path); err != nil {
t.Fatal(err)
}
store := NewSessionStore(dir)
t.Cleanup(store.Shutdown)
store.CreateSession("live-session", time.Hour, "fixture", "127.0.0.1", "live-user")
store.DeleteSessionsForUser("unknown-user")
store.Shutdown()
target, err := os.Readlink(path)
if err != nil || target != "sessions.json" {
t.Fatalf("unread nonregular path was replaced: %v", err)
}
if len(sessionPreservedFiles(t, dir)) != 0 {
t.Fatal("nonregular path was moved or left a preservation placeholder")
}
if _, err := os.Lstat(path + ".tmp"); !os.IsNotExist(err) {
t.Fatalf("a snapshot was staged before preservation: %v", err)
}
}
func TestSessionStore_UnreadStartupCopiesStayDistinct(t *testing.T) {
dir := t.TempDir()
path := filepath.Join(dir, "sessions.json")
var expected = map[string]bool{"first-unread-fixture": false, "second-unread-fixture": false}
for _, original := range []string{"first-unread-fixture", "second-unread-fixture"} {
if err := os.WriteFile(path, []byte(original), 0600); err != nil {
t.Fatal(err)
}
store := NewSessionStore(dir)
store.Shutdown()
}
for _, path := range sessionPreservedFiles(t, dir) {
data, err := os.ReadFile(path)
if err != nil {
t.Fatal(err)
}
if _, ok := expected[string(data)]; !ok || expected[string(data)] {
t.Fatal("a preserved copy was overwritten or duplicated")
}
expected[string(data)] = true
}
for _, seen := range expected {
if !seen {
t.Fatal("an earlier preservation was overwritten")
}
}
}
func TestSessionStore_UnreadStartupRenameFailureRemovesPlaceholder(t *testing.T) {
dir := t.TempDir()
path := filepath.Join(dir, "sessions.json")
original := []byte("unverified fixture")
if err := os.WriteFile(path, original, 0600); err != nil {
t.Fatal(err)
}
// A fixed injected rename failure exercises the same boundary as a
// file-level bind mount, without requiring host mounts or process races.
for attempt := 0; attempt < 3; attempt++ {
retained, err := preserveUnreadSessionFile(dir, func(from, to string) error {
if from != path || filepath.Dir(filepath.Dir(to)) != dir {
t.Fatal("preservation escaped its source directory")
}
return fmt.Errorf("synthetic rename failure")
})
if err == nil || retained != "" {
t.Fatal("rename failure reported successful preservation")
}
if len(sessionPreservedFiles(t, dir)) != 0 {
t.Fatal("failed rename leaked a preservation directory")
}
data, err := os.ReadFile(path)
if err != nil || !bytes.Equal(data, original) {
t.Fatalf("rename failure changed original bytes: %v", err)
}
}
}
func TestSessionStore_UnreadStartupOperatorMovedOriginal(t *testing.T) {
dir := t.TempDir()
path := filepath.Join(dir, "sessions.json")
original := []byte("unverified fixture")
if err := os.WriteFile(path, original, 0600); err != nil {
t.Fatal(err)
}
store := NewSessionStore(dir)
t.Cleanup(store.Shutdown)
retained := filepath.Join(dir, "manually-retained-session-fixture")
if err := os.Rename(path, retained); err != nil {
t.Fatal(err)
}
store.CreateSession("new-session", time.Hour, "fixture", "127.0.0.1", "new-user")
store.Shutdown()
data, err := os.ReadFile(retained)
if err != nil || !bytes.Equal(data, original) {
t.Fatalf("operator-retained bytes changed: %v", err)
}
restarted := NewSessionStore(dir)
defer restarted.Shutdown()
if !restarted.ValidateSession("new-session") || len(sessionPreservedFiles(t, dir)) != 0 {
t.Fatal("operator removal of unknown authority did not release normal saves")
}
}
func TestSessionStore_UnreadStartupSnapshotFailureDoesNotRequarantine(t *testing.T) {
dir := t.TempDir()
path := filepath.Join(dir, "sessions.json")
original := []byte("unverified fixture")
if err := os.WriteFile(path, original, 0600); err != nil {
t.Fatal(err)
}
store := NewSessionStore(dir)
t.Cleanup(store.Shutdown)
// Preservation can succeed even when preparing the fresh snapshot fails.
// Its successful retirement must be recorded before persistSnapshot runs.
store.persistMu.Lock()
store.snapshotWrite = func(file *os.File, data []byte) (int, error) {
n, _ := file.Write(data[:1])
return n, os.ErrPermission
}
store.persistMu.Unlock()
store.CreateSession("new-session", time.Hour, "fixture", "127.0.0.1", "new-user")
store.persistMu.Lock()
needsPreservation := store.preserveBeforeSave
store.persistMu.Unlock()
if needsPreservation || len(sessionPreservedFiles(t, dir)) != 1 {
t.Fatal("successful preservation was forgotten after a snapshot failure")
}
if _, err := os.Stat(path); !os.IsNotExist(err) {
t.Fatalf("failed snapshot unexpectedly published: %v", err)
}
checkNoOwnedAuthTemps(t, dir, "sessions.json")
store.persistMu.Lock()
store.snapshotWrite = nil
store.persistMu.Unlock()
store.save()
store.Shutdown()
if len(sessionPreservedFiles(t, dir)) != 1 {
t.Fatal("retry quarantined a fresh snapshot")
}
restarted := NewSessionStore(dir)
defer restarted.Shutdown()
if !restarted.ValidateSession("new-session") {
t.Fatal("snapshot recovery did not persist the authenticated session")
}
}
func TestSessionStore_ValidStartupKeepsPersistence(t *testing.T) {
for _, initial := range []string{"missing", "[]", "null", "{}", "hashed", "legacy"} {
t.Run(initial, func(t *testing.T) {
dir := t.TempDir()
path := filepath.Join(dir, "sessions.json")
content := initial
switch initial {
case "hashed":
content = fmt.Sprintf(`[{"key":%q,"username":"saved-user","expires_at":"2099-01-01T00:00:00Z"}]`, sessionHash("saved-session"))
case "legacy":
content = `{"saved-session":{"username":"saved-user","expires_at":"2099-01-01T00:00:00Z"}}`
}
if initial != "missing" {
if err := os.WriteFile(path, []byte(content), 0600); err != nil {
t.Fatal(err)
}
}
store := NewSessionStore(dir)
t.Cleanup(store.Shutdown)
if store.ValidateSession("saved-session") != (initial == "hashed" || initial == "legacy") {
t.Fatal("valid saved session loading changed")
}
store.CreateSession("new-session", time.Hour, "fixture", "127.0.0.1", "new-user")
store.Shutdown()
if len(sessionPreservedFiles(t, dir)) != 0 {
t.Fatal("valid or missing inventory was quarantined")
}
restarted := NewSessionStore(dir)
defer restarted.Shutdown()
if !restarted.ValidateSession("new-session") {
t.Fatal("valid startup no longer persists new sessions")
}
if restarted.ValidateSession("saved-session") != (initial == "hashed" || initial == "legacy") {
t.Fatal("valid original session did not survive restart")
}
})
}
}
func TestSessionHash(t *testing.T) {
tests := []struct {
name string
token1 string
token2 string
same bool
}{
{
name: "same token produces same hash",
token1: "test-token-123",
token2: "test-token-123",
same: true,
},
{
name: "different tokens produce different hashes",
token1: "token-a",
token2: "token-b",
same: false,
},
{
name: "empty token produces consistent hash",
token1: "",
token2: "",
same: true,
},
{
name: "empty vs non-empty token",
token1: "",
token2: "something",
same: false,
},
{
name: "case sensitive",
token1: "Token",
token2: "token",
same: false,
},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
hash1 := sessionHash(tc.token1)
hash2 := sessionHash(tc.token2)
if tc.same && hash1 != hash2 {
t.Errorf("sessionHash(%q) = %q, sessionHash(%q) = %q; want same", tc.token1, hash1, tc.token2, hash2)
}
if !tc.same && hash1 == hash2 {
t.Errorf("sessionHash(%q) and sessionHash(%q) produced same hash %q; want different", tc.token1, tc.token2, hash1)
}
})
}
}
func TestSessionStoreDeleteSessionsForUser(t *testing.T) {
store := NewSessionStore(t.TempDir())
t.Cleanup(store.Shutdown)
store.CreateSession("alice-one", time.Hour, "agent", "127.0.0.1", "alice")
store.CreateSession("alice-two", time.Hour, "agent", "127.0.0.1", "alice")
store.CreateSession("bob-one", time.Hour, "agent", "127.0.0.1", "bob")
deletedKeys := store.DeleteSessionsForUser("alice")
if len(deletedKeys) != 2 {
t.Fatalf("deleted session keys = %d, want 2", len(deletedKeys))
}
if store.GetSession("alice-one") != nil || store.GetSession("alice-two") != nil {
t.Fatal("target user's sessions survived deletion")
}
if store.GetSession("bob-one") == nil {
t.Fatal("another user's session was deleted")
}
}
func TestSessionHash_Format(t *testing.T) {
hash := sessionHash("test-token")
// SHA256 produces 64 hex characters
if len(hash) != 64 {
t.Errorf("sessionHash length = %d, want 64", len(hash))
}
// Should only contain hex characters
for _, c := range hash {
if !((c >= '0' && c <= '9') || (c >= 'a' && c <= 'f')) {
t.Errorf("sessionHash contains non-hex character: %c", c)
}
}
}
func TestSessionHash_Deterministic(t *testing.T) {
token := "reproducible-token-value"
// Call multiple times
results := make([]string, 100)
for i := range results {
results[i] = sessionHash(token)
}
// All results should be identical
for i := 1; i < len(results); i++ {
if results[i] != results[0] {
t.Errorf("sessionHash call %d returned %q, want %q", i, results[i], results[0])
}
}
}
func TestSessionData_Fields(t *testing.T) {
now := time.Now()
duration := 24 * time.Hour
data := SessionData{
ExpiresAt: now.Add(duration),
CreatedAt: now,
UserAgent: "Mozilla/5.0",
IP: "192.168.1.100",
OriginalDuration: duration,
}
if data.ExpiresAt.Before(data.CreatedAt) {
t.Error("ExpiresAt should be after CreatedAt")
}
if data.UserAgent != "Mozilla/5.0" {
t.Errorf("UserAgent = %q, want Mozilla/5.0", data.UserAgent)
}
if data.IP != "192.168.1.100" {
t.Errorf("IP = %q, want 192.168.1.100", data.IP)
}
if data.OriginalDuration != duration {
t.Errorf("OriginalDuration = %v, want %v", data.OriginalDuration, duration)
}
}
func TestSessionStore_CreateAndValidate(t *testing.T) {
tmpDir := t.TempDir()
store := &SessionStore{
sessions: make(map[string]*SessionData),
dataPath: tmpDir,
stopChan: make(chan bool),
}
token := "test-session-token"
duration := time.Hour
// Create session
store.CreateSession(token, duration, "TestAgent", "127.0.0.1", "testuser")
// Validate session
if !store.ValidateSession(token) {
t.Error("ValidateSession returned false for valid session")
}
// Verify internal state
store.mu.RLock()
key := sessionHash(token)
session, exists := store.sessions[key]
store.mu.RUnlock()
if !exists {
t.Fatal("Session not found in store")
}
if session.UserAgent != "TestAgent" {
t.Errorf("UserAgent = %q, want TestAgent", session.UserAgent)
}
if session.IP != "127.0.0.1" {
t.Errorf("IP = %q, want 127.0.0.1", session.IP)
}
if session.OriginalDuration != duration {
t.Errorf("OriginalDuration = %v, want %v", session.OriginalDuration, duration)
}
}
func TestSessionStore_CreateRecoverySession_PersistsRecoveryBypass(t *testing.T) {
tmpDir := t.TempDir()
store := NewSessionStore(tmpDir)
token := "recovery-session-token"
store.CreateRecoverySession(token, time.Hour, "TestAgent", "loopback", "recovery")
store.Shutdown()
data, err := os.ReadFile(filepath.Join(tmpDir, "sessions.json"))
if err != nil {
t.Fatalf("ReadFile sessions.json: %v", err)
}
var persisted []sessionPersisted
if err := json.Unmarshal(data, &persisted); err != nil {
t.Fatalf("Unmarshal persisted sessions: %v", err)
}
if len(persisted) != 1 {
t.Fatalf("expected 1 persisted session, got %d", len(persisted))
}
if !persisted[0].RecoveryBypass {
t.Fatal("expected persisted recovery session to retain RecoveryBypass")
}
reloaded := NewSessionStore(tmpDir)
defer reloaded.Shutdown()
session := reloaded.GetSession(token)
if session == nil {
t.Fatal("expected reloaded recovery session to exist")
}
if !session.RecoveryBypass {
t.Fatal("expected reloaded recovery session to retain RecoveryBypass")
}
if session.Username != "recovery" {
t.Fatalf("reloaded recovery session username = %q, want %q", session.Username, "recovery")
}
if session.IP != "loopback" {
t.Fatalf("reloaded recovery session IP = %q, want %q", session.IP, "loopback")
}
}
func TestSessionStore_CreateOIDCSession_PersistsAccessTokenIssuedAt(t *testing.T) {
tmpDir := t.TempDir()
issuedAt := time.Unix(1_700_000_000, 0).UTC()
expiresAt := issuedAt.Add(5 * time.Minute)
token := "oidc-issued-at-token"
store := NewSessionStore(tmpDir)
store.CreateOIDCSession(token, time.Hour, "TestAgent", "127.0.0.1", "testuser", &OIDCTokenInfo{
RefreshToken: "refresh-token",
AccessTokenExp: expiresAt,
IssuedAt: issuedAt,
Issuer: "https://issuer.example",
ClientID: "client-id",
})
store.Shutdown()
reloaded := NewSessionStore(tmpDir)
defer reloaded.Shutdown()
session := reloaded.GetSession(token)
if session == nil {
t.Fatal("expected reloaded OIDC session to exist")
}
if !session.OIDCAccessTokenIssuedAt.Equal(issuedAt) {
t.Fatalf("OIDCAccessTokenIssuedAt = %s, want %s", session.OIDCAccessTokenIssuedAt, issuedAt)
}
if !session.OIDCAccessTokenExp.Equal(expiresAt) {
t.Fatalf("OIDCAccessTokenExp = %s, want %s", session.OIDCAccessTokenExp, expiresAt)
}
}
func TestSessionStore_CreateSAMLSession_PersistsDisplayUsernameSeparatelyFromPrincipal(t *testing.T) {
tmpDir := t.TempDir()
token := "saml-display-token"
principal := "sso:saml:test-saml:stable-principal"
displayUsername := "Alice Example"
store := NewSessionStore(tmpDir)
store.CreateSAMLSessionWithDisplayName(token, time.Hour, "TestAgent", "127.0.0.1", principal, displayUsername, &SAMLTokenInfo{
ProviderID: "test-saml",
NameID: "name-id-123",
SessionIndex: "session-index-123",
})
store.Shutdown()
reloaded := NewSessionStore(tmpDir)
defer reloaded.Shutdown()
session := reloaded.GetSession(token)
if session == nil {
t.Fatal("expected reloaded SAML session to exist")
}
if session.Username != principal {
t.Fatalf("session principal = %q, want %q", session.Username, principal)
}
if session.DisplayUsername != displayUsername {
t.Fatalf("session display username = %q, want %q", session.DisplayUsername, displayUsername)
}
}
func TestSessionStore_ValidateSession_NonExistent(t *testing.T) {
store := &SessionStore{
sessions: make(map[string]*SessionData),
dataPath: t.TempDir(),
stopChan: make(chan bool),
}
if store.ValidateSession("nonexistent-token") {
t.Error("ValidateSession returned true for nonexistent session")
}
}
func TestSessionStore_ValidateSession_Expired(t *testing.T) {
store := &SessionStore{
sessions: make(map[string]*SessionData),
dataPath: t.TempDir(),
stopChan: make(chan bool),
}
token := "expired-token"
key := sessionHash(token)
// Add an already-expired session
store.mu.Lock()
store.sessions[key] = &SessionData{
ExpiresAt: time.Now().Add(-time.Hour), // Expired an hour ago
CreatedAt: time.Now().Add(-2 * time.Hour),
}
store.mu.Unlock()
if store.ValidateSession(token) {
t.Error("ValidateSession returned true for expired session")
}
}
func TestSessionStore_DeleteSession(t *testing.T) {
tmpDir := t.TempDir()
store := &SessionStore{
sessions: make(map[string]*SessionData),
dataPath: tmpDir,
stopChan: make(chan bool),
}
token := "delete-me-token"
// Create session
store.CreateSession(token, time.Hour, "", "", "testuser")
// Verify exists
if !store.ValidateSession(token) {
t.Fatal("Session should exist before deletion")
}
// Delete session
store.DeleteSession(token)
// Verify deleted
if store.ValidateSession(token) {
t.Error("Session should not exist after deletion")
}
}
func TestSessionStore_ValidateAndExtendSession(t *testing.T) {
store := &SessionStore{
sessions: make(map[string]*SessionData),
dataPath: t.TempDir(),
stopChan: make(chan bool),
}
token := "extend-me-token"
duration := time.Hour
// Create session
store.CreateSession(token, duration, "", "", "testuser")
// Get original expiry
store.mu.RLock()
key := sessionHash(token)
originalExpiry := store.sessions[key].ExpiresAt
store.mu.RUnlock()
// Wait a moment
time.Sleep(10 * time.Millisecond)
// Validate and extend
if !store.ValidateAndExtendSession(token) {
t.Error("ValidateAndExtendSession returned false for valid session")
}
// Verify expiry was extended
store.mu.RLock()
newExpiry := store.sessions[key].ExpiresAt
store.mu.RUnlock()
if !newExpiry.After(originalExpiry) {
t.Error("Session expiry was not extended")
}
}
func TestSessionStore_ValidateAndExtendSession_NonExistent(t *testing.T) {
store := &SessionStore{
sessions: make(map[string]*SessionData),
dataPath: t.TempDir(),
stopChan: make(chan bool),
}
if store.ValidateAndExtendSession("nonexistent-token") {
t.Error("ValidateAndExtendSession returned true for nonexistent session")
}
}
func TestSessionStore_ValidateAndExtendSession_Expired(t *testing.T) {
store := &SessionStore{
sessions: make(map[string]*SessionData),
dataPath: t.TempDir(),
stopChan: make(chan bool),
}
token := "expired-extend-token"
key := sessionHash(token)
// Add an already-expired session
store.mu.Lock()
store.sessions[key] = &SessionData{
ExpiresAt: time.Now().Add(-time.Hour),
CreatedAt: time.Now().Add(-2 * time.Hour),
OriginalDuration: time.Hour,
}
store.mu.Unlock()
if store.ValidateAndExtendSession(token) {
t.Error("ValidateAndExtendSession returned true for expired session")
}
}
func TestSessionStore_ValidateAndExtendSession_ZeroDuration(t *testing.T) {
store := &SessionStore{
sessions: make(map[string]*SessionData),
dataPath: t.TempDir(),
stopChan: make(chan bool),
}
token := "zero-duration-token"
key := sessionHash(token)
// Add session with zero original duration
store.mu.Lock()
store.sessions[key] = &SessionData{
ExpiresAt: time.Now().Add(time.Hour),
CreatedAt: time.Now(),
OriginalDuration: 0, // Zero duration - should not extend
}
store.mu.Unlock()
originalExpiry := store.sessions[key].ExpiresAt
// Validate and extend
if !store.ValidateAndExtendSession(token) {
t.Error("ValidateAndExtendSession returned false for valid session")
}
// Expiry should not change (zero duration means no sliding)
store.mu.RLock()
newExpiry := store.sessions[key].ExpiresAt
store.mu.RUnlock()
if !newExpiry.Equal(originalExpiry) {
t.Error("Session with zero OriginalDuration should not have expiry extended")
}
}
func TestSessionStore_MultipleSessions(t *testing.T) {
store := &SessionStore{
sessions: make(map[string]*SessionData),
dataPath: t.TempDir(),
stopChan: make(chan bool),
}
tokens := []string{"token-1", "token-2", "token-3"}
// Create multiple sessions
for _, token := range tokens {
store.CreateSession(token, time.Hour, "Agent-"+token, "", "testuser")
}
// All should be valid
for _, token := range tokens {
if !store.ValidateSession(token) {
t.Errorf("ValidateSession(%q) = false, want true", token)
}
}
// Delete middle one
store.DeleteSession("token-2")
// First and last should still be valid
if !store.ValidateSession("token-1") {
t.Error("token-1 should still be valid")
}
if store.ValidateSession("token-2") {
t.Error("token-2 should be deleted")
}
if !store.ValidateSession("token-3") {
t.Error("token-3 should still be valid")
}
}
func TestSessionStore_Persistence(t *testing.T) {
tmpDir := t.TempDir()
// Create store and add session
store1 := &SessionStore{
sessions: make(map[string]*SessionData),
dataPath: tmpDir,
stopChan: make(chan bool),
}
token := "persistent-token"
store1.CreateSession(token, time.Hour, "PersistAgent", "10.0.0.1", "persistuser")
// Verify file was created
sessionsFile := filepath.Join(tmpDir, "sessions.json")
if _, err := os.Stat(sessionsFile); os.IsNotExist(err) {
t.Fatal("sessions.json was not created")
}
// Create new store that should load from disk
store2 := &SessionStore{
sessions: make(map[string]*SessionData),
dataPath: tmpDir,
stopChan: make(chan bool),
}
store2.load()
// Session should be loaded
if !store2.ValidateSession(token) {
t.Error("Session was not persisted and loaded correctly")
}
// Verify metadata was preserved
store2.mu.RLock()
key := sessionHash(token)
session := store2.sessions[key]
store2.mu.RUnlock()
if session == nil {
t.Fatal("Session not found after load")
}
if session.UserAgent != "PersistAgent" {
t.Errorf("UserAgent = %q, want PersistAgent", session.UserAgent)
}
if session.IP != "10.0.0.1" {
t.Errorf("IP = %q, want 10.0.0.1", session.IP)
}
}
func TestSessionStore_LoadExpiredSessions(t *testing.T) {
tmpDir := t.TempDir()
// Manually create a sessions file with an expired session
store := &SessionStore{
sessions: make(map[string]*SessionData),
dataPath: tmpDir,
stopChan: make(chan bool),
}
token := "already-expired"
key := sessionHash(token)
// Add expired session
store.mu.Lock()
store.sessions[key] = &SessionData{
ExpiresAt: time.Now().Add(-time.Hour),
CreatedAt: time.Now().Add(-2 * time.Hour),
}
store.mu.Unlock()
store.save()
// Create new store and load
store2 := &SessionStore{
sessions: make(map[string]*SessionData),
dataPath: tmpDir,
stopChan: make(chan bool),
}
store2.load()
// Expired session should not be loaded
store2.mu.RLock()
_, exists := store2.sessions[key]
store2.mu.RUnlock()
if exists {
t.Error("Expired session should not be loaded from disk")
}
}
func TestSessionStore_Cleanup(t *testing.T) {
store := &SessionStore{
sessions: make(map[string]*SessionData),
dataPath: t.TempDir(),
stopChan: make(chan bool),
}
// Add a valid and an expired session
validKey := sessionHash("valid-session")
expiredKey := sessionHash("expired-session")
store.mu.Lock()
store.sessions[validKey] = &SessionData{
ExpiresAt: time.Now().Add(time.Hour),
CreatedAt: time.Now(),
}
store.sessions[expiredKey] = &SessionData{
ExpiresAt: time.Now().Add(-time.Hour),
CreatedAt: time.Now().Add(-2 * time.Hour),
}
store.mu.Unlock()
// Run cleanup
store.cleanup()
// Valid session should remain
store.mu.RLock()
_, validExists := store.sessions[validKey]
_, expiredExists := store.sessions[expiredKey]
store.mu.RUnlock()
if !validExists {
t.Error("Valid session was incorrectly removed during cleanup")
}
if expiredExists {
t.Error("Expired session was not removed during cleanup")
}
}
func TestSessionPersistedStruct_Fields(t *testing.T) {
now := time.Now()
duration := 2 * time.Hour
persisted := sessionPersisted{
Key: "abc123",
ExpiresAt: now.Add(duration),
CreatedAt: now,
UserAgent: "TestUA",
IP: "1.2.3.4",
OriginalDuration: duration,
}
if persisted.Key != "abc123" {
t.Errorf("Key = %q, want abc123", persisted.Key)
}
if persisted.UserAgent != "TestUA" {
t.Errorf("UserAgent = %q, want TestUA", persisted.UserAgent)
}
if persisted.IP != "1.2.3.4" {
t.Errorf("IP = %q, want 1.2.3.4", persisted.IP)
}
if persisted.OriginalDuration != duration {
t.Errorf("OriginalDuration = %v, want %v", persisted.OriginalDuration, duration)
}
}
func TestSessionStore_Save_MkdirAllError(t *testing.T) {
// Create a file where the directory should be - MkdirAll will fail
tmpDir := t.TempDir()
blockedPath := filepath.Join(tmpDir, "blocked")
// Create a file at the path where dataPath should be
if err := os.WriteFile(blockedPath, []byte("blocking file"), 0644); err != nil {
t.Fatalf("failed to create blocking file: %v", err)
}
store := &SessionStore{
sessions: make(map[string]*SessionData),
dataPath: blockedPath, // This is a file, not a directory
stopChan: make(chan bool),
}
// Add a session to save
key := sessionHash("test-token")
store.sessions[key] = &SessionData{
ExpiresAt: time.Now().Add(time.Hour),
CreatedAt: time.Now(),
}
// save should handle error gracefully (logs but doesn't panic)
store.save()
// Verify the blocking file still exists (wasn't overwritten)
data, err := os.ReadFile(blockedPath)
if err != nil {
t.Fatalf("blocking file was removed: %v", err)
}
if string(data) != "blocking file" {
t.Error("blocking file was modified")
}
}
func TestSessionStore_Save_WriteFileError(t *testing.T) {
if os.Geteuid() == 0 {
t.Skip("Skipping permission test running as root")
}
// Create a read-only directory to prevent file creation
tmpDir := t.TempDir()
readOnlyDir := filepath.Join(tmpDir, "readonly")
if err := os.Mkdir(readOnlyDir, 0755); err != nil {
t.Fatalf("failed to create readonly dir: %v", err)
}
store := &SessionStore{
sessions: make(map[string]*SessionData),
dataPath: readOnlyDir,
stopChan: make(chan bool),
}
// Add a session
key := sessionHash("test-token")
store.sessions[key] = &SessionData{
ExpiresAt: time.Now().Add(time.Hour),
CreatedAt: time.Now(),
}
// Make directory read-only after it exists (MkdirAll succeeds, WriteFile fails)
if err := os.Chmod(readOnlyDir, 0555); err != nil {
t.Fatalf("failed to make dir readonly: %v", err)
}
t.Cleanup(func() {
_ = os.Chmod(readOnlyDir, 0755) // Restore for cleanup
})
// save should handle error gracefully (logs but doesn't panic)
store.save()
// Verify no file was created
sessionsFile := filepath.Join(readOnlyDir, "sessions.json")
if _, err := os.Stat(sessionsFile); err == nil {
t.Error("sessions file should not exist after write failure")
}
}
func TestSessionStore_Save_RenameError(t *testing.T) {
// Create a directory at the target path to cause rename error
tmpDir := t.TempDir()
// Create a directory at the exact path where sessions.json should go
sessionsFilePath := filepath.Join(tmpDir, "sessions.json")
if err := os.Mkdir(sessionsFilePath, 0755); err != nil {
t.Fatalf("failed to create blocking directory: %v", err)
}
store := &SessionStore{
sessions: make(map[string]*SessionData),
dataPath: tmpDir,
stopChan: make(chan bool),
}
// Add a session
key := sessionHash("test-token")
store.sessions[key] = &SessionData{
ExpiresAt: time.Now().Add(time.Hour),
CreatedAt: time.Now(),
}
// save should handle rename error gracefully
store.save()
// The blocking directory should still exist (rename failed)
info, err := os.Stat(sessionsFilePath)
if err != nil {
t.Fatalf("blocking directory was removed: %v", err)
}
if !info.IsDir() {
t.Error("blocking directory was replaced with a file")
}
}
func TestSessionStore_Load_ReadError(t *testing.T) {
tmpDir := t.TempDir()
// Create a directory where the sessions file should be - reading it will fail
sessionsPath := filepath.Join(tmpDir, "sessions.json")
if err := os.Mkdir(sessionsPath, 0755); err != nil {
t.Fatalf("failed to create directory: %v", err)
}
store := &SessionStore{
sessions: make(map[string]*SessionData),
dataPath: tmpDir,
stopChan: make(chan bool),
}
// Should not panic and should log error
store.load()
if len(store.sessions) != 0 {
t.Errorf("store should be empty after read error, got %d sessions", len(store.sessions))
}
}
func TestSessionStore_Load_InvalidJSON(t *testing.T) {
tmpDir := t.TempDir()
// Write invalid JSON that won't match either format
sessionsFile := filepath.Join(tmpDir, "sessions.json")
if err := os.WriteFile(sessionsFile, []byte("not valid json at all"), 0600); err != nil {
t.Fatalf("failed to write invalid JSON: %v", err)
}
store := &SessionStore{
sessions: make(map[string]*SessionData),
dataPath: tmpDir,
stopChan: make(chan bool),
}
// Should not panic
store.load()
if len(store.sessions) != 0 {
t.Errorf("store should be empty after loading invalid JSON, got %d sessions", len(store.sessions))
}
}
func TestSessionStore_Load_MigratesLegacyFormat(t *testing.T) {
tmpDir := t.TempDir()
// Create legacy format JSON (map[token]sessionData) with snake_case fields
// The legacy format uses raw tokens as keys
legacyJSON := `{
"raw-token-1": {"expires_at": "2099-12-31T23:59:59Z", "created_at": "2024-01-01T00:00:00Z", "user_agent": "Agent1", "ip": "1.1.1.1"},
"raw-token-2": {"expires_at": "2099-12-31T23:59:59Z", "created_at": "2024-01-01T00:00:00Z", "user_agent": "Agent2", "ip": "2.2.2.2"},
"raw-token-expired": {"expires_at": "2020-01-01T00:00:00Z", "created_at": "2019-01-01T00:00:00Z", "user_agent": "ExpiredAgent", "ip": "3.3.3.3"}
}`
sessionsFile := filepath.Join(tmpDir, "sessions.json")
if err := os.WriteFile(sessionsFile, []byte(legacyJSON), 0600); err != nil {
t.Fatalf("failed to write legacy format JSON: %v", err)
}
store := &SessionStore{
sessions: make(map[string]*SessionData),
dataPath: tmpDir,
stopChan: make(chan bool),
}
store.load()
if len(store.sessions) != 2 {
t.Fatalf("store should load 2 active legacy sessions, got %d", len(store.sessions))
}
if !store.ValidateSession("raw-token-1") {
t.Fatal("raw-token-1 should validate after legacy load")
}
if !store.ValidateSession("raw-token-2") {
t.Fatal("raw-token-2 should validate after legacy load")
}
if store.ValidateSession("raw-token-expired") {
t.Fatal("expired raw-token-expired session should be filtered during legacy load")
}
if _, ok := store.sessions[sessionHash("raw-token-1")]; !ok {
t.Fatal("raw-token-1 should be stored under its hashed key")
}
if _, ok := store.sessions[sessionHash("raw-token-2")]; !ok {
t.Fatal("raw-token-2 should be stored under its hashed key")
}
savedData, err := os.ReadFile(sessionsFile)
if err != nil {
t.Fatalf("failed to read migrated sessions file: %v", err)
}
var persisted []sessionPersisted
if err := json.Unmarshal(savedData, &persisted); err != nil {
t.Fatalf("migrated sessions file should be hashed array format: %v", err)
}
if len(persisted) != 2 {
t.Fatalf("migrated sessions file should contain 2 active sessions, got %d", len(persisted))
}
}
func TestSessionStore_InitReconfiguresDataPath(t *testing.T) {
resetSessionStoreForTests()
t.Cleanup(resetSessionStoreForTests)
dirOne := t.TempDir()
dirTwo := t.TempDir()
InitSessionStore(dirOne)
GetSessionStore().CreateSession("session-one", time.Hour, "agent", "127.0.0.1", "alice")
InitSessionStore(dirTwo)
if GetSessionStore().GetSession("session-one") != nil {
t.Fatal("reconfigured session store should not retain sessions from the previous data path")
}
GetSessionStore().CreateSession("session-two", time.Hour, "agent", "127.0.0.1", "bob")
if _, err := os.Stat(filepath.Join(dirOne, "sessions.json")); err != nil {
t.Fatalf("expected original sessions file to remain readable: %v", err)
}
if _, err := os.Stat(filepath.Join(dirTwo, "sessions.json")); err != nil {
t.Fatalf("expected reconfigured sessions file to exist: %v", err)
}
}
func TestEnsureSessionStoreReturnsOwnedStoreForPath(t *testing.T) {
resetSessionStoreForTests()
t.Cleanup(resetSessionStoreForTests)
dirOne := t.TempDir()
dirTwo := t.TempDir()
storeOne := ensureSessionStore(dirOne)
if storeOne == nil {
t.Fatal("ensureSessionStore should initialize a store for a valid data path")
}
if storeOne != GetSessionStore() {
t.Fatal("ensureSessionStore should return the active store for the configured data path")
}
storeTwo := ensureSessionStore(dirTwo)
if storeTwo == nil {
t.Fatal("ensureSessionStore should initialize a reconfigured store")
}
if storeTwo != GetSessionStore() {
t.Fatal("ensureSessionStore should return the reconfigured active store")
}
if storeOne == storeTwo {
t.Fatal("ensureSessionStore should return a distinct store after data-path reconfiguration")
}
select {
case <-storeOne.workerDone:
default:
t.Fatal("reconfigured session store should shut down the previous worker")
}
}
func TestSessionStore_Save_DropsRefreshTokenWithoutCrypto(t *testing.T) {
tmpDir := t.TempDir()
store := &SessionStore{
sessions: make(map[string]*SessionData),
dataPath: tmpDir,
stopChan: make(chan bool),
crypto: nil,
}
store.sessions[sessionHash("oidc-token")] = &SessionData{
Username: "alice",
ExpiresAt: time.Now().Add(time.Hour),
CreatedAt: time.Now(),
OIDCRefreshToken: "plain-refresh-token",
}
store.save()
data, err := os.ReadFile(filepath.Join(tmpDir, "sessions.json"))
if err != nil {
t.Fatalf("ReadFile sessions.json: %v", err)
}
if bytes.Contains(data, []byte("plain-refresh-token")) {
t.Fatalf("sessions.json leaked plaintext refresh token: %s", string(data))
}
var persisted []sessionPersisted
if err := json.Unmarshal(data, &persisted); err != nil {
t.Fatalf("Unmarshal persisted sessions: %v", err)
}
if len(persisted) != 1 {
t.Fatalf("expected 1 persisted session, got %d", len(persisted))
}
if persisted[0].OIDCRefreshToken != "" {
t.Fatalf("expected refresh token to be dropped without crypto, got %q", persisted[0].OIDCRefreshToken)
}
}
func TestSessionStore_LoadHashedSessions_DropsRefreshTokenWithoutCrypto(t *testing.T) {
store := &SessionStore{
sessions: make(map[string]*SessionData),
crypto: nil,
}
loaded := store.loadHashedSessions([]sessionPersisted{
{
Key: sessionHash("oidc-token"),
Username: "alice",
ExpiresAt: time.Now().Add(time.Hour),
CreatedAt: time.Now(),
OIDCRefreshToken: "plaintext-refresh-token",
},
}, time.Now())
if loaded != 1 {
t.Fatalf("expected 1 session loaded, got %d", loaded)
}
session := store.sessions[sessionHash("oidc-token")]
if session == nil {
t.Fatal("expected loaded session")
}
if session.OIDCRefreshToken != "" {
t.Fatalf("expected refresh token to be dropped without crypto, got %q", session.OIDCRefreshToken)
}
}
func TestSessionStore_ShutdownReturnsWithoutWaitingForWorkerReceive(t *testing.T) {
dir := t.TempDir()
store := NewSessionStore(dir)
done := make(chan struct{})
go func() {
store.Shutdown()
close(done)
}()
select {
case <-done:
case <-time.After(500 * time.Millisecond):
t.Fatal("Shutdown should not block waiting for the background worker to receive a stop signal")
}
}
func TestSessionStore_StartupRegularInventoryLink(t *testing.T) {
testAuthInventoryRegularLink(t, "sessions")
}