| 1 | package session |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "database/sql" |
| 6 | "database/sql/driver" |
| 7 | "encoding/json" |
| 8 | "path/filepath" |
| 9 | "strings" |
| 10 | "sync" |
| 11 | "sync/atomic" |
| 12 | "testing" |
| 13 | |
| 14 | "modernc.org/sqlite" |
| 15 | "reasonix/internal/provider" |
| 16 | ) |
| 17 | |
| 18 | var sessionAuditProbes sync.Map |
| 19 | |
| 20 | func init() { |
| 21 | // SQLite evaluates CHECK expressions during integrity_check. This observes |
| 22 | // real full audits through public query APIs without timing assertions. |
| 23 | sqlite.MustRegisterDeterministicScalarFunction("reasonix_test_session_audit", 1, |
| 24 | func(_ *sqlite.FunctionContext, args []driver.Value) (driver.Value, error) { |
| 25 | if counter, ok := sessionAuditProbes.Load(args[0]); ok { |
| 26 | counter.(*atomic.Int64).Add(1) |
| 27 | } |
| 28 | return int64(1), nil |
| 29 | }) |
| 30 | } |
| 31 | |
| 32 | func TestSessionReadPathsReuseIntegrityAndRecheckChanges(t *testing.T) { |
| 33 | root := filepath.Join(t.TempDir(), "sessions") |
| 34 | service, err := NewService("local", NewFilesystemPersistence(root)) |
| 35 | if err != nil { |
| 36 | t.Fatal(err) |
| 37 | } |
| 38 | t.Cleanup(func() { _ = service.CloseAll(context.Background()) }) |
| 39 | runtime, err := service.Create(t.Context(), CreateOptions{SessionID: "audit-reads"}) |
| 40 | if err != nil { |
| 41 | t.Fatal(err) |
| 42 | } |
| 43 | payload, err := json.Marshal(map[string]any{"message": provider.Message{ID: "needle", Role: provider.RoleUser, Content: strings.Repeat("needle ", 20000)}}) |
| 44 | if err != nil { |
| 45 | t.Fatal(err) |
| 46 | } |
| 47 | if _, err := runtime.Session().AppendBatch(t.Context(), "message", []Event{{Kind: "message/complete", Payload: payload}}); err != nil { |
| 48 | t.Fatal(err) |
| 49 | } |
| 50 | if _, err := runtime.Session().Flush(t.Context()); err != nil { |
| 51 | t.Fatal(err) |
| 52 | } |
| 53 | query, ref := service.Query(), runtime.Ref() |
| 54 | windowReady(t, query, ref, HistoryWindowRequest{Limit: 1}) |
| 55 | searchHistoryReady(t, query, ref, "needle", "", 1) |
| 56 | for _, scenario := range []struct { |
| 57 | name, path string |
| 58 | read func() error |
| 59 | }{ |
| 60 | {"window", historyIndexPath(root, ref.SessionID), func() error { |
| 61 | _, err := query.ReadHistoryWindow(t.Context(), ref, HistoryWindowRequest{Limit: 1}) |
| 62 | return err |
| 63 | }}, |
| 64 | {"field", historyIndexPath(root, ref.SessionID), func() error { |
| 65 | page, err := query.ReadMessageField(t.Context(), ref, "needle", 0, "content", 0, 64) |
| 66 | if err == nil && page.Status != "ready" { |
| 67 | t.Fatalf("field status %s", page.Status) |
| 68 | } |
| 69 | return err |
| 70 | }}, |
| 71 | {"attachment-authorization", historyIndexPath(root, ref.SessionID), func() error { |
| 72 | _, _, err := query.lookupHistoryAttachment(t.Context(), query.persistence.(*FilesystemPersistence), ref, "absent") |
| 73 | return err |
| 74 | }}, |
| 75 | {"export", historyIndexPath(root, ref.SessionID), func() error { |
| 76 | snapshot, err := query.CaptureExportSnapshot(t.Context(), ref) |
| 77 | if err != nil { |
| 78 | return err |
| 79 | } |
| 80 | return query.VisitExportMessages(t.Context(), snapshot, func(PersistentMessage) error { return nil }) |
| 81 | }}, |
| 82 | {"search", searchIndexPath(root, ref.SessionID), func() error { _, err := query.SearchHistory(t.Context(), ref, "needle", "", 1); return err }}, |
| 83 | } { |
| 84 | t.Run(scenario.name, func(t *testing.T) { |
| 85 | var calls atomic.Int64 |
| 86 | token := t.Name() |
| 87 | sessionAuditProbes.Store(token, &calls) |
| 88 | defer sessionAuditProbes.Delete(token) |
| 89 | write := func(statement string, args ...any) { |
| 90 | t.Helper() |
| 91 | db, err := sql.Open("sqlite", scenario.path) |
| 92 | if err != nil { |
| 93 | t.Fatal(err) |
| 94 | } |
| 95 | _, execErr := db.ExecContext(t.Context(), statement, args...) |
| 96 | closeErr := db.Close() |
| 97 | if execErr != nil { |
| 98 | t.Fatal(execErr) |
| 99 | } |
| 100 | if closeErr != nil { |
| 101 | t.Fatal(closeErr) |
| 102 | } |
| 103 | } |
| 104 | write("CREATE TABLE IF NOT EXISTS audit_probe (token TEXT CHECK(reasonix_test_session_audit(token)=1), revision INTEGER)") |
| 105 | write("DELETE FROM audit_probe") |
| 106 | write("INSERT INTO audit_probe VALUES (?,0)", token) |
| 107 | calls.Store(0) |
| 108 | if err := scenario.read(); err != nil { |
| 109 | t.Fatal(err) |
| 110 | } |
| 111 | if calls.Load() == 0 { |
| 112 | t.Fatal("changed projection was not audited") |
| 113 | } |
| 114 | calls.Store(0) |
| 115 | for range 3 { |
| 116 | if err := scenario.read(); err != nil { |
| 117 | t.Fatal(err) |
| 118 | } |
| 119 | } |
| 120 | if count := calls.Load(); count != 0 { |
| 121 | t.Fatalf("unchanged projection re-audited %d times", count) |
| 122 | } |
| 123 | write("UPDATE audit_probe SET revision=revision+1") |
| 124 | calls.Store(0) |
| 125 | if err := scenario.read(); err != nil { |
| 126 | t.Fatal(err) |
| 127 | } |
| 128 | if calls.Load() == 0 { |
| 129 | t.Fatal("external write did not revoke integrity proof") |
| 130 | } |
| 131 | }) |
| 132 | } |
| 133 | } |
| 134 |