-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathhandler_test.go
More file actions
1002 lines (808 loc) · 27 KB
/
handler_test.go
File metadata and controls
1002 lines (808 loc) · 27 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
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package main
import (
"bytes"
"encoding/json"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/go-chi/chi/v5"
)
// Test helpers
func createTestKeyStore(t *testing.T) (*APIKeyStore, string) {
t.Helper()
tempDir := t.TempDir()
keyFile := filepath.Join(tempDir, "test-keys.toml")
file, err := os.Create(keyFile)
if err != nil {
t.Fatalf("Failed to create test key file: %v", err)
}
file.Close()
store, err := NewStore(keyFile)
if err != nil {
t.Fatalf("Failed to create key store: %v", err)
}
apiKey, err := store.AddKey("test-key")
if err != nil {
t.Fatalf("Failed to add test key: %v", err)
}
return store, apiKey
}
func createTestRouter(t *testing.T, tasks map[string]Task, store *APIKeyStore) *chi.Mux {
t.Helper()
r := chi.NewRouter()
for name, task := range tasks {
taskCopy := task
taskCopy.applyDefaults() // Apply defaults like the main config does
tm, err := NewTaskManager(name, &taskCopy, store)
if err != nil {
t.Fatalf("Failed to create task manager for %s: %v", name, err)
}
tm.ConfigureRoutes(r)
}
return r
}
func getTestScriptPath(t *testing.T, scriptName string) string {
t.Helper()
wd, err := os.Getwd()
if err != nil {
t.Fatalf("Failed to get working directory: %v", err)
}
return filepath.Join(wd, "testdata", scriptName)
}
// Test: Basic synchronous task execution
func TestSyncTask_Success(t *testing.T) {
store, apiKey := createTestKeyStore(t)
tasks := map[string]Task{
"fast": {
Command: []string{getTestScriptPath(t, "fast_task.sh")},
APIKeyNames: []string{"test-key"},
Async: false,
ExecutionTimeoutSeconds: 5,
},
}
router := createTestRouter(t, tasks, store)
req := httptest.NewRequest("POST", "/tasks/fast", bytes.NewBufferString("test input"))
req.Header.Set("Authorization", "Bearer "+apiKey)
w := httptest.NewRecorder()
router.ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Errorf("Expected status 200, got %d", w.Code)
}
var result taskExecutionResult
if err := json.NewDecoder(w.Body).Decode(&result); err != nil {
t.Fatalf("Failed to decode response: %v", err)
}
if result.Status != "success" {
t.Errorf("Expected status 'success', got '%s'", result.Status)
}
if result.ExitCode != 0 {
t.Errorf("Expected exit code 0, got %d", result.ExitCode)
}
if !strings.Contains(result.StdOut, "Fast task completed") {
t.Errorf("Expected output to contain 'Fast task completed', got '%s'", result.StdOut)
}
}
// Test: Task timeout
func TestSyncTask_Timeout(t *testing.T) {
store, apiKey := createTestKeyStore(t)
tasks := map[string]Task{
"timeout": {
Command: []string{getTestScriptPath(t, "timeout_task.sh")},
APIKeyNames: []string{"test-key"},
Async: false,
ExecutionTimeoutSeconds: 2, // Task sleeps 10 seconds but timeout is 2
},
}
router := createTestRouter(t, tasks, store)
req := httptest.NewRequest("POST", "/tasks/timeout", nil)
req.Header.Set("Authorization", "Bearer "+apiKey)
w := httptest.NewRecorder()
start := time.Now()
router.ServeHTTP(w, req)
duration := time.Since(start)
if w.Code != http.StatusOK {
t.Errorf("Expected status 200, got %d", w.Code)
}
var result taskExecutionResult
if err := json.NewDecoder(w.Body).Decode(&result); err != nil {
t.Fatalf("Failed to decode response: %v", err)
}
if result.Status != "timeout" {
t.Errorf("Expected status 'timeout', got '%s'", result.Status)
}
if result.ExitCode != -1 {
t.Errorf("Expected exit code -1, got %d", result.ExitCode)
}
// Should timeout around 2 seconds, not wait full 10 seconds
// Note: On some systems, process cleanup may take longer
if duration > 12*time.Second {
t.Errorf("Task took too long: %v (expected ~2s, but allowing up to 12s for cleanup)", duration)
}
}
// Test: Task failure with exit code
func TestSyncTask_Failure(t *testing.T) {
store, apiKey := createTestKeyStore(t)
tasks := map[string]Task{
"failing": {
Command: []string{getTestScriptPath(t, "failing_task.sh")},
APIKeyNames: []string{"test-key"},
Async: false,
ExecutionTimeoutSeconds: 5,
},
}
router := createTestRouter(t, tasks, store)
req := httptest.NewRequest("POST", "/tasks/failing", nil)
req.Header.Set("Authorization", "Bearer "+apiKey)
w := httptest.NewRecorder()
router.ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Errorf("Expected status 200, got %d", w.Code)
}
var result taskExecutionResult
if err := json.NewDecoder(w.Body).Decode(&result); err != nil {
t.Fatalf("Failed to decode response: %v", err)
}
if result.Status != "failure" {
t.Errorf("Expected status 'failure', got '%s'", result.Status)
}
if result.ExitCode != 42 {
t.Errorf("Expected exit code 42, got %d", result.ExitCode)
}
if !strings.Contains(result.StdErr, "Task failed") {
t.Errorf("Expected stderr to contain 'Task failed', got '%s'", result.StdErr)
}
}
// Test: Async task execution
func TestAsyncTask_Basic(t *testing.T) {
store, apiKey := createTestKeyStore(t)
tasks := map[string]Task{
"slow": {
Command: []string{getTestScriptPath(t, "slow_task.sh")},
APIKeyNames: []string{"test-key"},
Async: true,
ExecutionTimeoutSeconds: 10,
},
}
router := createTestRouter(t, tasks, store)
// Submit task
req := httptest.NewRequest("POST", "/tasks/slow", nil)
req.Header.Set("Authorization", "Bearer "+apiKey)
w := httptest.NewRecorder()
start := time.Now()
router.ServeHTTP(w, req)
submitDuration := time.Since(start)
// Should return immediately
if submitDuration > 500*time.Millisecond {
t.Errorf("Async task submission took too long: %v", submitDuration)
}
if w.Code != http.StatusOK {
t.Errorf("Expected status 200, got %d", w.Code)
}
var submitResponse map[string]string
if err := json.NewDecoder(w.Body).Decode(&submitResponse); err != nil {
t.Fatalf("Failed to decode response: %v", err)
}
taskID, ok := submitResponse["task_id"]
if !ok || taskID == "" {
t.Fatalf("Expected task_id in response, got: %v", submitResponse)
}
// Poll for result
var result taskExecutionResult
maxAttempts := 10
for i := 0; i < maxAttempts; i++ {
req = httptest.NewRequest("GET", "/tasks/slow/"+taskID, nil)
req.Header.Set("Authorization", "Bearer "+apiKey)
w = httptest.NewRecorder()
router.ServeHTTP(w, req)
if w.Code == http.StatusNotFound {
// Task not found yet or cleaned up
time.Sleep(500 * time.Millisecond)
continue
}
if err := json.NewDecoder(w.Body).Decode(&result); err != nil {
t.Fatalf("Failed to decode result: %v", err)
}
if result.Status == "running" {
time.Sleep(500 * time.Millisecond)
continue
}
break
}
if result.Status != "success" {
t.Errorf("Expected status 'success', got '%s'", result.Status)
}
if result.ExitCode != 0 {
t.Errorf("Expected exit code 0, got %d", result.ExitCode)
}
}
// Test: Async task with timeout
func TestAsyncTask_Timeout(t *testing.T) {
store, apiKey := createTestKeyStore(t)
tasks := map[string]Task{
"timeout-async": {
Command: []string{getTestScriptPath(t, "timeout_task.sh")},
APIKeyNames: []string{"test-key"},
Async: true,
ExecutionTimeoutSeconds: 2,
},
}
router := createTestRouter(t, tasks, store)
// Submit task
req := httptest.NewRequest("POST", "/tasks/timeout-async", nil)
req.Header.Set("Authorization", "Bearer "+apiKey)
w := httptest.NewRecorder()
router.ServeHTTP(w, req)
var submitResponse map[string]string
json.NewDecoder(w.Body).Decode(&submitResponse)
taskID := submitResponse["task_id"]
// Poll for timeout completion (task sleeps 10s but timeout is 2s, so ~10s on macOS)
var result taskExecutionResult
maxAttempts := 25 // 25 * 500ms = 12.5s total wait
for i := 0; i < maxAttempts; i++ {
req = httptest.NewRequest("GET", "/tasks/timeout-async/"+taskID, nil)
req.Header.Set("Authorization", "Bearer "+apiKey)
w = httptest.NewRecorder()
router.ServeHTTP(w, req)
if w.Code == http.StatusNotFound {
time.Sleep(500 * time.Millisecond)
continue
}
json.NewDecoder(w.Body).Decode(&result)
if result.Status == "running" {
time.Sleep(500 * time.Millisecond)
continue
}
break
}
if result.Status != "timeout" {
t.Errorf("Expected status 'timeout', got '%s'", result.Status)
}
if result.ExitCode != -1 {
t.Errorf("Expected exit code -1, got %d", result.ExitCode)
}
}
// Test: Rate limiting
func TestRateLimit_Exceeded(t *testing.T) {
store, apiKey := createTestKeyStore(t)
tasks := map[string]Task{
"limited": {
Command: []string{getTestScriptPath(t, "fast_task.sh")},
APIKeyNames: []string{"test-key"},
Async: false,
RateLimit: 1.0, // 1 request per second
ExecutionTimeoutSeconds: 5,
},
}
router := createTestRouter(t, tasks, store)
// First request should succeed
req := httptest.NewRequest("POST", "/tasks/limited", nil)
req.Header.Set("Authorization", "Bearer "+apiKey)
w := httptest.NewRecorder()
router.ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Errorf("First request: expected status 200, got %d", w.Code)
}
// Second immediate request should be rate limited
req = httptest.NewRequest("POST", "/tasks/limited", nil)
req.Header.Set("Authorization", "Bearer "+apiKey)
w = httptest.NewRecorder()
router.ServeHTTP(w, req)
if w.Code != http.StatusTooManyRequests {
t.Errorf("Second request: expected status 429, got %d", w.Code)
}
// After waiting, should succeed again
time.Sleep(1100 * time.Millisecond)
req = httptest.NewRequest("POST", "/tasks/limited", nil)
req.Header.Set("Authorization", "Bearer "+apiKey)
w = httptest.NewRecorder()
router.ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Errorf("Third request after delay: expected status 200, got %d", w.Code)
}
}
// Test: Max concurrent tasks (synchronous)
func TestMaxConcurrentTasks_Sync(t *testing.T) {
store, apiKey := createTestKeyStore(t)
tasks := map[string]Task{
"concurrent": {
Command: []string{getTestScriptPath(t, "slow_task.sh")},
APIKeyNames: []string{"test-key"},
Async: false,
MaxConcurrentTasks: 2, // Allow only 2 concurrent tasks
ExecutionTimeoutSeconds: 10,
},
}
router := createTestRouter(t, tasks, store)
var wg sync.WaitGroup
results := make([]int, 5)
// Launch 5 concurrent requests
for i := 0; i < 5; i++ {
wg.Add(1)
go func(index int) {
defer wg.Done()
req := httptest.NewRequest("POST", "/tasks/concurrent", nil)
req.Header.Set("Authorization", "Bearer "+apiKey)
w := httptest.NewRecorder()
router.ServeHTTP(w, req)
results[index] = w.Code
}(i)
time.Sleep(100 * time.Millisecond) // Stagger requests slightly
}
wg.Wait()
successCount := 0
rejectedCount := 0
for _, code := range results {
if code == http.StatusOK {
successCount++
} else if code == http.StatusTooManyRequests {
rejectedCount++
}
}
// We expect some to succeed and some to be rejected
if rejectedCount < 1 {
t.Errorf("Expected at least 1 rejection, got %d (success: %d, rejected: %d)",
rejectedCount, successCount, rejectedCount)
}
t.Logf("Results: %d succeeded, %d rejected", successCount, rejectedCount)
}
// Test: Max concurrent tasks (async)
func TestMaxConcurrentTasks_Async(t *testing.T) {
store, apiKey := createTestKeyStore(t)
tasks := map[string]Task{
"concurrent-async": {
Command: []string{getTestScriptPath(t, "slow_task.sh")},
APIKeyNames: []string{"test-key"},
Async: true,
MaxConcurrentTasks: 2,
ExecutionTimeoutSeconds: 10,
},
}
router := createTestRouter(t, tasks, store)
var wg sync.WaitGroup
var acceptedCount atomic.Int32
var rejectedCount atomic.Int32
// Launch 10 concurrent requests quickly
for i := 0; i < 10; i++ {
wg.Add(1)
go func() {
defer wg.Done()
req := httptest.NewRequest("POST", "/tasks/concurrent-async", nil)
req.Header.Set("Authorization", "Bearer "+apiKey)
w := httptest.NewRecorder()
router.ServeHTTP(w, req)
if w.Code == http.StatusOK {
acceptedCount.Add(1)
} else if w.Code == http.StatusTooManyRequests {
rejectedCount.Add(1)
}
}()
time.Sleep(50 * time.Millisecond)
}
wg.Wait()
accepted := acceptedCount.Load()
rejected := rejectedCount.Load()
t.Logf("Async results: %d accepted, %d rejected", accepted, rejected)
// With async and semaphore, we should accept some and reject others
if rejected != 8 {
t.Errorf("Expected 8 rejections with MaxConcurrentTasks=2, got %d", rejected)
}
if accepted != 2 {
t.Errorf("Expected 8 accepts with MaxConcurrentTasks=2, got %d", rejected)
}
}
// Test: Environment variables
func TestTaskWithEnvironment(t *testing.T) {
store, apiKey := createTestKeyStore(t)
tasks := map[string]Task{
"env": {
Command: []string{getTestScriptPath(t, "env_reader.sh")},
APIKeyNames: []string{"test-key"},
Async: false,
ExecutionTimeoutSeconds: 5,
Environment: map[string]string{
"TEST_VAR": "hello_world",
},
},
}
router := createTestRouter(t, tasks, store)
req := httptest.NewRequest("POST", "/tasks/env", nil)
req.Header.Set("Authorization", "Bearer "+apiKey)
w := httptest.NewRecorder()
router.ServeHTTP(w, req)
var result taskExecutionResult
json.NewDecoder(w.Body).Decode(&result)
if !strings.Contains(result.StdOut, "TEST_VAR=hello_world") {
t.Errorf("Expected output to contain 'TEST_VAR=hello_world', got '%s'", result.StdOut)
}
}
// Test: Pass request headers
func TestPassRequestHeaders(t *testing.T) {
store, apiKey := createTestKeyStore(t)
tasks := map[string]Task{
"headers": {
Command: []string{getTestScriptPath(t, "env_reader.sh")},
APIKeyNames: []string{"test-key"},
Async: false,
ExecutionTimeoutSeconds: 5,
PassRequestHeaders: []string{"X-Custom"},
},
}
router := createTestRouter(t, tasks, store)
req := httptest.NewRequest("POST", "/tasks/headers", nil)
req.Header.Set("Authorization", "Bearer "+apiKey)
req.Header.Set("X-Custom", "test_value")
w := httptest.NewRecorder()
router.ServeHTTP(w, req)
var result taskExecutionResult
json.NewDecoder(w.Body).Decode(&result)
if !strings.Contains(result.StdOut, "REQUEST_HEADER_X_CUSTOM=test_value") {
t.Errorf("Expected output to contain 'REQUEST_HEADER_X_CUSTOM=test_value', got '%s'", result.StdOut)
}
}
// Test: Input/output
func TestTaskWithInput(t *testing.T) {
store, apiKey := createTestKeyStore(t)
tasks := map[string]Task{
"echo": {
Command: []string{getTestScriptPath(t, "echo_stdin.sh")},
APIKeyNames: []string{"test-key"},
Async: false,
ExecutionTimeoutSeconds: 5,
},
}
router := createTestRouter(t, tasks, store)
testInput := "Hello from test!"
req := httptest.NewRequest("POST", "/tasks/echo", bytes.NewBufferString(testInput))
req.Header.Set("Authorization", "Bearer "+apiKey)
w := httptest.NewRecorder()
router.ServeHTTP(w, req)
var result taskExecutionResult
json.NewDecoder(w.Body).Decode(&result)
if !strings.Contains(result.StdOut, testInput) {
t.Errorf("Expected output to contain '%s', got '%s'", testInput, result.StdOut)
}
}
// Test: Combined scenario - async + timeout + concurrent
func TestCombinedScenario_AsyncTimeoutConcurrent(t *testing.T) {
store, apiKey := createTestKeyStore(t)
tasks := map[string]Task{
"combined": {
Command: []string{getTestScriptPath(t, "slow_task.sh")},
APIKeyNames: []string{"test-key"},
Async: true,
MaxConcurrentTasks: 3,
ExecutionTimeoutSeconds: 5,
RateLimit: 10.0,
},
}
router := createTestRouter(t, tasks, store)
var wg sync.WaitGroup
taskIDs := make([]string, 5)
var taskIDsMutex sync.Mutex
// Submit multiple async tasks
for i := 0; i < 5; i++ {
wg.Add(1)
go func(index int) {
defer wg.Done()
req := httptest.NewRequest("POST", "/tasks/combined", nil)
req.Header.Set("Authorization", "Bearer "+apiKey)
w := httptest.NewRecorder()
router.ServeHTTP(w, req)
if w.Code == http.StatusOK {
var resp map[string]string
json.NewDecoder(w.Body).Decode(&resp)
taskIDsMutex.Lock()
taskIDs[index] = resp["task_id"]
taskIDsMutex.Unlock()
}
}(i)
time.Sleep(100 * time.Millisecond)
}
wg.Wait()
// Wait for tasks to complete
time.Sleep(5 * time.Second)
// Check results
successCount := 0
for _, taskID := range taskIDs {
if taskID == "" {
continue
}
req := httptest.NewRequest("GET", "/tasks/combined/"+taskID, nil)
req.Header.Set("Authorization", "Bearer "+apiKey)
w := httptest.NewRecorder()
router.ServeHTTP(w, req)
if w.Code == http.StatusOK {
var result taskExecutionResult
json.NewDecoder(w.Body).Decode(&result)
if result.Status == "success" {
successCount++
}
t.Logf("Task %s: status=%s, exitCode=%d", taskID, result.Status, result.ExitCode)
}
}
t.Logf("Successfully completed tasks: %d", successCount)
if successCount < 1 {
t.Error("Expected at least 1 task to complete successfully")
}
}
// Test: Invalid API key
func TestInvalidAPIKey(t *testing.T) {
store, _ := createTestKeyStore(t)
tasks := map[string]Task{
"test-invalid": {
Command: []string{getTestScriptPath(t, "fast_task.sh")},
APIKeyNames: []string{"test-key"},
Async: false,
ExecutionTimeoutSeconds: 5,
},
}
router := createTestRouter(t, tasks, store)
req := httptest.NewRequest("POST", "/tasks/test-invalid", nil)
req.Header.Set("Authorization", "Bearer invalid-key")
w := httptest.NewRecorder()
router.ServeHTTP(w, req)
if w.Code != http.StatusUnauthorized {
t.Errorf("Expected status 401, got %d", w.Code)
}
}
// Test: Missing API key
func TestMissingAPIKey(t *testing.T) {
store, _ := createTestKeyStore(t)
tasks := map[string]Task{
"test-missing": {
Command: []string{getTestScriptPath(t, "fast_task.sh")},
APIKeyNames: []string{"test-key"},
Async: false,
ExecutionTimeoutSeconds: 5,
},
}
router := createTestRouter(t, tasks, store)
req := httptest.NewRequest("POST", "/tasks/test-missing", nil)
w := httptest.NewRecorder()
router.ServeHTTP(w, req)
if w.Code != http.StatusUnauthorized {
t.Errorf("Expected status 401, got %d", w.Code)
}
}
// Test: Async task result cleanup
func TestAsyncTask_Cleanup(t *testing.T) {
store, apiKey := createTestKeyStore(t)
tasks := map[string]Task{
"cleanup-test": {
Command: []string{getTestScriptPath(t, "fast_task.sh")},
APIKeyNames: []string{"test-key"},
Async: true,
ExecutionTimeoutSeconds: 5,
AsyncResultRetentionSeconds: 2, // 2 seconds retention for faster testing
},
}
router := createTestRouter(t, tasks, store)
// Submit async task
req := httptest.NewRequest("POST", "/tasks/cleanup-test", nil)
req.Header.Set("Authorization", "Bearer "+apiKey)
w := httptest.NewRecorder()
router.ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Fatalf("Expected status 200, got %d", w.Code)
}
var submitResponse map[string]string
json.NewDecoder(w.Body).Decode(&submitResponse)
taskID := submitResponse["task_id"]
if taskID == "" {
t.Fatal("Expected task_id in response")
}
// Wait for task to complete
time.Sleep(500 * time.Millisecond)
// Task result should be available immediately after completion
req = httptest.NewRequest("GET", "/tasks/cleanup-test/"+taskID, nil)
req.Header.Set("Authorization", "Bearer "+apiKey)
w = httptest.NewRecorder()
router.ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Errorf("Expected result to be available, got status %d", w.Code)
}
var result taskExecutionResult
json.NewDecoder(w.Body).Decode(&result)
if result.Status != "success" {
t.Errorf("Expected status 'success', got '%s'", result.Status)
}
// Wait for cleanup (2 seconds retention + 500ms buffer)
time.Sleep(2500 * time.Millisecond)
// Task result should be cleaned up
req = httptest.NewRequest("GET", "/tasks/cleanup-test/"+taskID, nil)
req.Header.Set("Authorization", "Bearer "+apiKey)
w = httptest.NewRecorder()
router.ServeHTTP(w, req)
if w.Code != http.StatusNotFound {
t.Errorf("Expected status 404 after cleanup, got %d", w.Code)
}
var errorResponse map[string]string
json.NewDecoder(w.Body).Decode(&errorResponse)
if errorResponse["error"] != "task not found" {
t.Errorf("Expected 'task not found' error, got '%s'", errorResponse["error"])
}
}
// Test: MergeStderr configuration
func TestTask_MergeStderr(t *testing.T) {
store, apiKey := createTestKeyStore(t)
tasks := map[string]Task{
"merge-stderr-false": {
Command: []string{getTestScriptPath(t, "stderr_test.sh")},
APIKeyNames: []string{"test-key"},
Async: false,
MergeStderr: false, // Keep separate
ExecutionTimeoutSeconds: 5,
},
"merge-stderr-true": {
Command: []string{getTestScriptPath(t, "stderr_test.sh")},
APIKeyNames: []string{"test-key"},
Async: false,
MergeStderr: true, // Merge into stdout
ExecutionTimeoutSeconds: 5,
},
}
router := createTestRouter(t, tasks, store)
// Test with MergeStderr = false (separate streams)
req := httptest.NewRequest("POST", "/tasks/merge-stderr-false", nil)
req.Header.Set("Authorization", "Bearer "+apiKey)
w := httptest.NewRecorder()
router.ServeHTTP(w, req)
var result1 taskExecutionResult
json.NewDecoder(w.Body).Decode(&result1)
if !strings.Contains(result1.StdOut, "This is stdout") {
t.Errorf("Expected stdout to contain 'This is stdout', got '%s'", result1.StdOut)
}
if !strings.Contains(result1.StdErr, "This is stderr") {
t.Errorf("Expected stderr to contain 'This is stderr', got '%s'", result1.StdErr)
}
if strings.Contains(result1.StdOut, "This is stderr") {
t.Errorf("stderr should not be in stdout when MergeStderr=false")
}
// Test with MergeStderr = true (merged into stdout)
req = httptest.NewRequest("POST", "/tasks/merge-stderr-true", nil)
req.Header.Set("Authorization", "Bearer "+apiKey)
w = httptest.NewRecorder()
router.ServeHTTP(w, req)
var result2 taskExecutionResult
json.NewDecoder(w.Body).Decode(&result2)
if !strings.Contains(result2.StdOut, "This is stdout") {
t.Errorf("Expected stdout to contain 'This is stdout', got '%s'", result2.StdOut)
}
if !strings.Contains(result2.StdOut, "This is stderr") {
t.Errorf("Expected stderr to be merged into stdout, got '%s'", result2.StdOut)
}
if result2.StdErr != "" {
t.Errorf("Expected stderr to be empty when MergeStderr=true, got '%s'", result2.StdErr)
}
}
// Test: MaxInputBytes limit
func TestTask_MaxInputBytes(t *testing.T) {
store, apiKey := createTestKeyStore(t)
tasks := map[string]Task{
"limited-input": {
Command: []string{getTestScriptPath(t, "echo_stdin.sh")},
APIKeyNames: []string{"test-key"},
Async: false,
MaxInputBytes: 10, // Only 10 bytes allowed
ExecutionTimeoutSeconds: 5,
},
}
router := createTestRouter(t, tasks, store)
// Test with input within limit
smallInput := "small"
req := httptest.NewRequest("POST", "/tasks/limited-input", strings.NewReader(smallInput))
req.Header.Set("Authorization", "Bearer "+apiKey)
w := httptest.NewRecorder()
router.ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Errorf("Expected status 200 for small input, got %d", w.Code)
}
// Test with input exceeding limit
largeInput := strings.Repeat("x", 100)
req = httptest.NewRequest("POST", "/tasks/limited-input", strings.NewReader(largeInput))
req.Header.Set("Authorization", "Bearer "+apiKey)
w = httptest.NewRecorder()
router.ServeHTTP(w, req)
if w.Code != http.StatusBadRequest {
t.Errorf("Expected status 400 for large input, got %d", w.Code)
}
}
// Test: MaxOutputBytes limit
func TestTask_MaxOutputBytes(t *testing.T) {
store, apiKey := createTestKeyStore(t)
tasks := map[string]Task{
"limited-output": {
Command: []string{getTestScriptPath(t, "large_output.sh")},
APIKeyNames: []string{"test-key"},
Async: false,
MaxOutputBytes: 50, // Only 50 bytes
ExecutionTimeoutSeconds: 5,
},
}
router := createTestRouter(t, tasks, store)
req := httptest.NewRequest("POST", "/tasks/limited-output", nil)
req.Header.Set("Authorization", "Bearer "+apiKey)
w := httptest.NewRecorder()
router.ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Errorf("Expected status 200, got %d", w.Code)
}
var result taskExecutionResult
json.NewDecoder(w.Body).Decode(&result)
// Output should be truncated to MaxOutputBytes
if len(result.StdOut) > 50 {
t.Errorf("Expected stdout to be truncated to 50 bytes, got %d bytes", len(result.StdOut))
}
}
// Test: WebhookSecrets
func TestTask_WebhookSecrets(t *testing.T) {
store, _ := createTestKeyStore(t)
webhookHash := "test-webhook-hash-123"
tasks := map[string]Task{
"webhook-task": {
Command: []string{getTestScriptPath(t, "fast_task.sh")},
Async: false,
WebhookSecrets: map[string]string{"webhook1": webhookHash},
ExecutionTimeoutSeconds: 5,
},
}
router := createTestRouter(t, tasks, store)
// Test webhook without API key (should work)
req := httptest.NewRequest("POST", "/wh/"+webhookHash, nil)
w := httptest.NewRecorder()
router.ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Errorf("Expected status 200 for webhook, got %d", w.Code)
}
var result taskExecutionResult
json.NewDecoder(w.Body).Decode(&result)
if result.Status != "success" {
t.Errorf("Expected status 'success', got '%s'", result.Status)
}
// Test with wrong webhook hash (should 404)
req = httptest.NewRequest("POST", "/wh/wrong-hash", nil)
w = httptest.NewRecorder()
router.ServeHTTP(w, req)
if w.Code != http.StatusNotFound {
t.Errorf("Expected status 404 for wrong webhook hash, got %d", w.Code)
}
}
// Test: WebhookSecretFiles
func TestTask_WebhookSecretFiles(t *testing.T) {
store, _ := createTestKeyStore(t)
// Create a temporary file with webhook hash
tempDir := t.TempDir()
webhookFile := tempDir + "/webhook-secret"
webhookHash := "file-webhook-hash-456"
err := os.WriteFile(webhookFile, []byte(webhookHash+"\n"), 0600)
if err != nil {
t.Fatalf("Failed to create webhook file: %v", err)
}
tasks := map[string]Task{
"webhook-file-task": {
Command: []string{getTestScriptPath(t, "fast_task.sh")},
Async: false,
WebhookSecretFiles: map[string]string{"webhook2": webhookFile},
ExecutionTimeoutSeconds: 5,
},
}
router := createTestRouter(t, tasks, store)
// Test webhook from file (should work)
req := httptest.NewRequest("POST", "/wh/"+webhookHash, nil)
w := httptest.NewRecorder()
router.ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Errorf("Expected status 200 for webhook from file, got %d", w.Code)
}
var result taskExecutionResult
json.NewDecoder(w.Body).Decode(&result)
if result.Status != "success" {
t.Errorf("Expected status 'success', got '%s'", result.Status)