-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcheckpointer_test.go
More file actions
408 lines (364 loc) · 9.56 KB
/
Copy pathcheckpointer_test.go
File metadata and controls
408 lines (364 loc) · 9.56 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
package sql_test
import (
"context"
"database/sql"
"testing"
"time"
"github.com/hupe1980/agentmesh/pkg/checkpoint"
sqlcp "github.com/hupe1980/agentmesh/pkg/checkpoint/sql"
_ "github.com/mattn/go-sqlite3" // SQLite driver
)
func TestSQLiteCheckpointer(t *testing.T) {
// Create in-memory SQLite database
db, err := sql.Open("sqlite3", ":memory:")
if err != nil {
t.Fatalf("Failed to open SQLite: %v", err)
}
defer db.Close()
ctx := context.Background()
// Create checkpointer
checkpointer, err := sqlcp.NewSQLiteCheckpointer(ctx, db)
if err != nil {
t.Fatalf("Failed to create checkpointer: %v", err)
}
defer checkpointer.Close()
// Test Save
cp := &checkpoint.Checkpoint{
RunID: "test-run-1",
Superstep: 1,
Timestamp: time.Now(),
State: map[string]any{
"counter": 42,
"status": "processing",
},
CompletedNodes: []string{"node1", "node2"},
PausedNodes: []string{},
Metadata: map[string]any{
"version": "1.0",
},
}
if err := checkpointer.Save(ctx, cp); err != nil {
t.Fatalf("Failed to save checkpoint: %v", err)
}
// Test Load
loaded, err := checkpointer.Load(ctx, "test-run-1")
if err != nil {
t.Fatalf("Failed to load checkpoint: %v", err)
}
if loaded == nil {
t.Fatal("Loaded checkpoint is nil")
}
if loaded.RunID != cp.RunID {
t.Errorf("RunID mismatch: got %s, want %s", loaded.RunID, cp.RunID)
}
if loaded.Superstep != cp.Superstep {
t.Errorf("Superstep mismatch: got %d, want %d", loaded.Superstep, cp.Superstep)
}
// Test List
checkpoints, err := checkpointer.List(ctx, "test-run-1")
if err != nil {
t.Fatalf("Failed to list checkpoints: %v", err)
}
if len(checkpoints) != 1 {
t.Errorf("Expected 1 checkpoint, got %d", len(checkpoints))
}
// Test LoadAtSuperstep
atSuperstep, err := checkpointer.LoadAtSuperstep(ctx, "test-run-1", 1)
if err != nil {
t.Fatalf("Failed to load at superstep: %v", err)
}
if atSuperstep == nil {
t.Fatal("Checkpoint at superstep is nil")
}
// Test Delete
if err := checkpointer.Delete(ctx, "test-run-1"); err != nil {
t.Fatalf("Failed to delete checkpoints: %v", err)
}
// Verify deletion
deleted, err := checkpointer.Load(ctx, "test-run-1")
if err != nil {
t.Fatalf("Error loading after delete: %v", err)
}
if deleted != nil {
t.Error("Expected nil after deletion")
}
}
func TestSQLiteCheckpointer_MultipleSupersteps(t *testing.T) {
db, err := sql.Open("sqlite3", ":memory:")
if err != nil {
t.Fatalf("Failed to open SQLite: %v", err)
}
defer db.Close()
ctx := context.Background()
checkpointer, err := sqlcp.NewSQLiteCheckpointer(ctx, db)
if err != nil {
t.Fatalf("Failed to create checkpointer: %v", err)
}
defer checkpointer.Close()
// Save multiple checkpoints
for i := int64(1); i <= 5; i++ {
cp := &checkpoint.Checkpoint{
RunID: "multi-run",
Superstep: i,
Timestamp: time.Now(),
State: map[string]any{
"superstep": i,
},
CompletedNodes: []string{},
PausedNodes: []string{},
Metadata: map[string]any{},
}
if err := checkpointer.Save(ctx, cp); err != nil {
t.Fatalf("Failed to save checkpoint %d: %v", i, err)
}
}
// Load should return most recent
loaded, err := checkpointer.Load(ctx, "multi-run")
if err != nil {
t.Fatalf("Failed to load: %v", err)
}
if loaded.Superstep != 5 {
t.Errorf("Expected superstep 5, got %d", loaded.Superstep)
}
// List should return all in descending order
all, err := checkpointer.List(ctx, "multi-run")
if err != nil {
t.Fatalf("Failed to list: %v", err)
}
if len(all) != 5 {
t.Errorf("Expected 5 checkpoints, got %d", len(all))
}
// Verify descending order
for i, cp := range all {
expectedSuperstep := int64(5 - i)
if cp.Superstep != expectedSuperstep {
t.Errorf("Checkpoint %d: expected superstep %d, got %d", i, expectedSuperstep, cp.Superstep)
}
}
// Load specific superstep
cp3, err := checkpointer.LoadAtSuperstep(ctx, "multi-run", 3)
if err != nil {
t.Fatalf("Failed to load superstep 3: %v", err)
}
if cp3.Superstep != 3 {
t.Errorf("Expected superstep 3, got %d", cp3.Superstep)
}
}
func TestTableNameValidation(t *testing.T) {
db, err := sql.Open("sqlite3", ":memory:")
if err != nil {
t.Fatalf("Failed to open SQLite: %v", err)
}
defer db.Close()
ctx := context.Background()
tests := []struct {
name string
tableName string
wantError bool
errorMsg string
}{
// Valid table names
{
name: "valid_default",
tableName: "checkpoints",
wantError: false,
},
{
name: "valid_underscores",
tableName: "my_checkpoints_table",
wantError: false,
},
{
name: "valid_alphanumeric",
tableName: "checkpoints123",
wantError: false,
},
{
name: "valid_starts_with_underscore",
tableName: "_checkpoints",
wantError: false,
},
{
name: "valid_mixed_case",
tableName: "MyCheckpoints",
wantError: false,
},
// Invalid table names - SQL injection attempts
{
name: "injection_drop_table",
tableName: "checkpoints; DROP TABLE users--",
wantError: true,
errorMsg: "invalid table name",
},
{
name: "injection_union_select",
tableName: "checkpoints UNION SELECT * FROM users",
wantError: true,
errorMsg: "invalid table name",
},
{
name: "injection_comment",
tableName: "checkpoints--",
wantError: true,
errorMsg: "SQL comment",
},
{
name: "injection_single_quote",
tableName: "checkpoint'; DROP TABLE users--",
wantError: true,
errorMsg: "invalid table name",
},
{
name: "injection_double_quote",
tableName: `checkpoint"; DROP TABLE users--`,
wantError: true,
errorMsg: "invalid table name",
},
// Invalid table names - special characters
{
name: "invalid_hyphens",
tableName: "my-checkpoints",
wantError: true,
errorMsg: "invalid table name",
},
{
name: "invalid_spaces",
tableName: "my checkpoints",
wantError: true,
errorMsg: "invalid table name",
},
{
name: "invalid_special_chars",
tableName: "check@points",
wantError: true,
errorMsg: "invalid table name",
},
{
name: "invalid_dot",
tableName: "my.checkpoints",
wantError: true,
errorMsg: "invalid table name",
},
{
name: "invalid_backslash",
tableName: "check\\points",
wantError: true,
errorMsg: "invalid table name",
},
// Invalid table names - SQL keywords
{
name: "keyword_select",
tableName: "SELECT",
wantError: true,
errorMsg: "SQL keyword",
},
{
name: "keyword_drop",
tableName: "DROP",
wantError: true,
errorMsg: "SQL keyword",
},
{
name: "keyword_insert",
tableName: "INSERT",
wantError: true,
errorMsg: "SQL keyword",
},
{
name: "keyword_delete",
tableName: "DELETE",
wantError: true,
errorMsg: "SQL keyword",
},
{
name: "keyword_table",
tableName: "TABLE",
wantError: true,
errorMsg: "SQL keyword",
},
// Invalid table names - length/format
{
name: "empty_string",
tableName: "",
wantError: true,
errorMsg: "cannot be empty",
},
{
name: "starts_with_number",
tableName: "123checkpoints",
wantError: true,
errorMsg: "invalid table name",
},
{
name: "too_long",
tableName: "this_is_a_very_long_table_name_that_exceeds_the_maximum_length_limit_of_64_characters",
wantError: true,
errorMsg: "too long",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
_, err := sqlcp.NewCheckpointer(ctx, db, sqlcp.WithTableName(tt.tableName))
if tt.wantError {
if err == nil {
t.Errorf("Expected error for table name %q, got nil", tt.tableName)
} else if tt.errorMsg != "" && !containsString(err.Error(), tt.errorMsg) {
t.Errorf("Expected error containing %q, got %q", tt.errorMsg, err.Error())
}
} else {
if err != nil {
t.Errorf("Expected no error for table name %q, got %v", tt.tableName, err)
}
}
})
}
}
func TestSQLInjectionPrevention(t *testing.T) {
db, err := sql.Open("sqlite3", ":memory:")
if err != nil {
t.Fatalf("Failed to open SQLite: %v", err)
}
defer db.Close()
ctx := context.Background()
// Create a test table to verify injection doesn't work
_, err = db.ExecContext(ctx, "CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT)")
if err != nil {
t.Fatalf("Failed to create test table: %v", err)
}
// Try to create checkpointer with malicious table name
maliciousNames := []string{
"checkpoints; DROP TABLE users--",
"checkpoints' OR '1'='1",
"checkpoints UNION SELECT * FROM users",
"checkpoints\"; DROP TABLE users--",
}
for _, name := range maliciousNames {
t.Run("injection_"+name, func(t *testing.T) {
_, err := sqlcp.NewCheckpointer(ctx, db, sqlcp.WithTableName(name))
if err == nil {
t.Errorf("Expected error for malicious table name %q, got nil", name)
}
})
}
// Verify the users table still exists and wasn't dropped
var count int
err = db.QueryRowContext(ctx, "SELECT COUNT(*) FROM sqlite_master WHERE type='table' AND name='users'").Scan(&count)
if err != nil {
t.Fatalf("Failed to query sqlite_master: %v", err)
}
if count != 1 {
t.Error("users table was affected by injection attempt")
}
}
// Helper function to check if a string contains a substring
func containsString(s, substr string) bool {
return len(substr) > 0 && len(s) >= len(substr) && (s == substr || len(s) > len(substr) && (s[:len(substr)] == substr || s[len(s)-len(substr):] == substr || findSubstring(s, substr)))
}
func findSubstring(s, substr string) bool {
for i := 0; i <= len(s)-len(substr); i++ {
if s[i:i+len(substr)] == substr {
return true
}
}
return false
}