Repository navigation
Expand file tree
/
Copy pathcoverage_test.go
More file actions
1677 lines (1591 loc) · 58.9 KB
/
Copy pathcoverage_test.go
File metadata and controls
1677 lines (1591 loc) · 58.9 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 guardagent
// Coverage tests, unit tier: deterministic branches that need no Redis.
// Redis-backed durability branches live in coverage_integration_test.go.
import (
"bytes"
"compress/gzip"
"context"
"crypto/aes"
"crypto/cipher"
crand "crypto/rand"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"io"
"log"
"net/http"
"os"
"path/filepath"
"strings"
"sync"
"testing"
"time"
)
// Seams are restored to these production values.
var (
randRead = crand.Read
gzipNewWriter = gzip.NewWriter
)
func base64Pad(b []byte) string { return base64.URLEncoding.EncodeToString(b) }
func errWriter() io.Writer {
return failingWriter{}
}
type failingWriter struct{}
func (failingWriter) Write(p []byte) (int, error) { return 0, errors.New("write exploded") }
// lockedBuffer lets a test read log output while agent goroutines write it.
type lockedBuffer struct {
mu sync.Mutex
buf bytes.Buffer
}
func (b *lockedBuffer) Write(p []byte) (int, error) {
b.mu.Lock()
defer b.mu.Unlock()
return b.buf.Write(p)
}
func (b *lockedBuffer) String() string {
b.mu.Lock()
defer b.mu.Unlock()
return b.buf.String()
}
// sealRawPlaintext seals arbitrary bytes with the project key exactly like
// PayloadEncryptor does, so tests can present well-formed ciphertexts with
// arbitrary plaintexts.
func sealRawPlaintext(projectKey, plaintext string) (string, error) {
key, err := decodeUrlsafeBase64(projectKey)
if err != nil {
return "", err
}
block, err := aes.NewCipher(key)
if err != nil {
return "", err
}
aead, err := cipher.NewGCM(block)
if err != nil {
return "", err
}
nonce := make([]byte, encryptionNonceSize)
if _, err := randRead(nonce); err != nil {
return "", err
}
return encodeUrlsafeBase64(aead.Seal(nonce, nonce, []byte(plaintext), nil)), nil
}
func testEncryptionKey() string {
key := make([]byte, 32)
for i := range key {
key[i] = byte(i)
}
return base64Pad(key)
}
// ------------------------------------------------------------ errors.go --
func TestTypedErrorMessages(t *testing.T) {
bufferFull := &BufferFullError{Kind: "event", MaxLen: 5}
if !strings.Contains(bufferFull.Error(), "event buffer full at maxlen=5") {
t.Fatalf("BufferFullError message mismatch: %q", bufferFull.Error())
}
permanent := &PermanentError{StatusCode: 400, Detail: "bad"}
if !strings.Contains(permanent.Error(), "permanent rejection with status 400: bad") {
t.Fatalf("PermanentError message mismatch: %q", permanent.Error())
}
rateLimited := &RateLimitedError{RetryAfter: 7 * time.Second}
if rateLimited.Error() != "guardagent: rate limited, retry after 7s" {
t.Fatalf("RateLimitedError message mismatch: %q", rateLimited.Error())
}
if !errors.Is(bufferFull, ErrBufferFull) {
t.Fatal("BufferFullError must match ErrBufferFull")
}
}
// --------------------------------------------------------- encryption.go --
func TestEncryptionErrorMessages(t *testing.T) {
enc := &EncryptionError{"boom"}
if enc.Error() != "boom" {
t.Fatalf("EncryptionError message mismatch: %q", enc.Error())
}
cfgErr := &EncryptionConfigError{msg: "no fallback"}
if cfgErr.Error() != "no fallback" {
t.Fatalf("EncryptionConfigError message mismatch: %q", cfgErr.Error())
}
}
func TestNewPayloadEncryptorRejectsBadKeys(t *testing.T) {
if _, err := NewPayloadEncryptor(""); err == nil || !strings.Contains(err.Error(), "cannot be empty") {
t.Fatalf("empty key must be rejected, got %v", err)
}
if _, err := NewPayloadEncryptor("!!!! not base64 !!!"); err == nil || !strings.Contains(err.Error(), "Invalid project key format") {
t.Fatalf("invalid base64 must be rejected, got %v", err)
}
short := base64Pad(make([]byte, 16))
if _, err := NewPayloadEncryptor(short); err == nil || !strings.Contains(err.Error(), "Invalid key size: 16") {
t.Fatalf("short key must be rejected, got %v", err)
}
}
func TestEncryptDecryptRoundTripWithAssociatedData(t *testing.T) {
p, err := NewPayloadEncryptor(testEncryptionKey())
if err != nil {
t.Fatalf("encryptor: %v", err)
}
payload := map[string]any{"b": 2, "a": "x"}
sealed, err := p.Encrypt(payload, "project-42")
if err != nil {
t.Fatalf("Encrypt: %v", err)
}
opened, err := p.Decrypt(sealed, "project-42")
if err != nil {
t.Fatalf("Decrypt: %v", err)
}
if opened["a"] != "x" {
t.Fatalf("round trip mismatch: %v", opened)
}
// AAD mismatch must fail the GCM open.
if _, err := p.Decrypt(sealed, "other-project"); err == nil {
t.Fatal("decrypt with the wrong associated data must fail")
}
}
func TestDecryptRejectsMalformedPayloads(t *testing.T) {
p, err := NewPayloadEncryptor(testEncryptionKey())
if err != nil {
t.Fatalf("encryptor: %v", err)
}
if _, err := p.Decrypt("!!!", ""); err == nil {
t.Fatal("invalid base64 must fail")
}
short := base64Pad(make([]byte, 8))
if _, err := p.Decrypt(short, ""); err == nil {
t.Fatal("truncated payload must fail")
}
sealed, err := p.Encrypt(map[string]any{"a": 1}, "")
if err != nil {
t.Fatalf("Encrypt: %v", err)
}
// Corrupt one ciphertext byte in the middle.
raw, err := decodeUrlsafeBase64(sealed)
if err != nil {
t.Fatalf("decode: %v", err)
}
raw[len(raw)/2] ^= 0xFF
if _, err := p.Decrypt(encodeUrlsafeBase64(raw), ""); err == nil {
t.Fatal("tampered payload must fail")
}
// A valid GCM payload whose plaintext is not a JSON object (null) and
// one whose plaintext is not JSON at all, both sealed with the same key.
for name, plaintext := range map[string]string{"null": "null", "junk": "not json"} {
sealedPlaintext, err := sealRawPlaintext(testEncryptionKey(), plaintext)
if err != nil {
t.Fatalf("seal %s: %v", name, err)
}
if _, err := p.Decrypt(sealedPlaintext, ""); err == nil {
t.Fatalf("a %s plaintext must fail to decode as an object", name)
}
}
}
func TestEncryptFailsWithoutEntropy(t *testing.T) {
cryptoRandRead = func(b []byte) (int, error) { return 0, errors.New("no entropy") }
defer func() { cryptoRandRead = randRead }()
p, err := NewPayloadEncryptor(testEncryptionKey())
if err != nil {
t.Fatalf("encryptor: %v", err)
}
if _, err := p.Encrypt(map[string]any{"a": 1}, ""); err == nil {
t.Fatal("Encrypt must surface the entropy failure")
}
// The startup round-trip verification must report the failure too.
if p.VerifyKey() {
t.Fatal("VerifyKey must fail when encryption fails")
}
// Identifier generators must fall back instead of failing.
if id := newUUID4(); len(id) != 36 {
t.Fatalf("uuid fallback must still produce a shaped id, got %q", id)
}
if h := randomHex(4); len(h) != 8 {
t.Fatalf("randomHex fallback must still produce hex, got %q", h)
}
}
func TestCanonicalJSONPythonShape(t *testing.T) {
payload := map[string]any{
"int8": int8(-8),
"int16": int16(-16),
"int32": int32(-32),
"int64": int64(-64),
"uint": uint(1),
"uint8": uint8(8),
"uint16": uint16(16),
"uint32": uint32(32),
"uint64": uint64(64),
"float32": float32(0.5),
"float64": 2.0,
"neg": -3.0,
"big": 1e20,
"raw": json.RawMessage(`{"raw":true}`),
"number": json.Number("42"),
"slice": []any{nil, true, "x"},
"nested": map[string]any{"z": 1, "a": map[string]any{"deep": 3.25}},
"time": time.Unix(0, 0).UTC(),
"chan": make(chan int),
}
got := canonicalJSON(payload)
for _, want := range []string{
`"int8":-8`, `"uint64":64`, `"float32":0.5`, `"float64":2.0`,
`"neg":-3.0`, `"big":1e+20`, `"raw":{"raw":true}`, `"number":42`,
`"slice":[null,true,"x"]`, `"nested":{"a":{"deep":3.25},"z":1}`,
`"time":"1970-01-01T00:00:00Z"`, `"chan":null`,
} {
if !strings.Contains(got, want) {
t.Fatalf("canonical JSON missing %s in %s", want, got)
}
}
// Keys must be sorted recursively: "nested" comes after "number" and
// before "raw".
if strings.Index(got, `"nested"`) > strings.Index(got, `"raw"`) {
t.Fatalf("keys must be sorted: %s", got)
}
}
func TestCanonicalStringEscaping(t *testing.T) {
cases := map[string]string{
"quote\":back\\": `"quote\":back\\"`,
"\b\f\n\r\t": `"\b\f\n\r\t"`,
"ascii ok": `"ascii ok"`,
"café": `"caf\u00e9"`,
"emoji \U0001F600": `"emoji \ud83d\ude00"`,
"caf\u00e9 latin": `"caf\u00e9 latin"`,
string([]byte{0x01}): `"\u0001"`,
string([]rune{0x10FFFF}): `"\udbff\udfff"`,
}
for input, want := range cases {
var b strings.Builder
writeCanonicalString(input, &b)
if b.String() != want {
t.Fatalf("escape %q: got %s want %s", input, b.String(), want)
}
}
}
func TestCreateEncryptorNilWithoutKey(t *testing.T) {
p, err := CreateEncryptor("")
if p != nil || err != nil {
t.Fatalf("empty key must yield a nil encryptor, got %v %v", p, err)
}
}
// ---------------------------------------------------------- install_id.go --
func TestResolveInstallIDPaths(t *testing.T) {
logger := log.New(io.Discard, "", 0)
if id := resolveInstallID("explicit", "", logger); id != "explicit" {
t.Fatalf("override must win, got %q", id)
}
dir := t.TempDir()
statePath := filepath.Join(dir, "sub", "install-id")
first := resolveInstallID("", statePath, logger)
second := resolveInstallID("", statePath, logger)
if first == "" || first != second {
t.Fatalf("install id must persist across resolves, got %q then %q", first, second)
}
// A whitespace-only file falls through to a fresh id.
emptyPath := filepath.Join(dir, "empty-id")
if err := os.WriteFile(emptyPath, []byte(" \n"), 0o600); err != nil {
t.Fatalf("write: %v", err)
}
if id := resolveInstallID("", emptyPath, logger); id == "" {
t.Fatal("whitespace file must produce a fresh id")
}
// A directory at the state path: read fails (logged, not ErrNotExist),
// the write also fails, and the id still resolves in memory.
if id := resolveInstallID("", dir, logger); id == "" {
t.Fatal("unreadable state file must fall back to an in-memory id")
}
// A path under a regular file: MkdirAll fails and is logged.
blocker := filepath.Join(dir, "blocker")
if err := os.WriteFile(blocker, []byte("x"), 0o600); err != nil {
t.Fatalf("write: %v", err)
}
if id := resolveInstallID("", filepath.Join(blocker, "sub", "id"), logger); id == "" {
t.Fatal("uncreatable state directory must fall back to an in-memory id")
}
// A file with a genuine read error (permission denied).
denied := filepath.Join(dir, "denied")
if err := os.WriteFile(denied, []byte("secret"), 0o000); err != nil {
t.Fatalf("write: %v", err)
}
if err := os.Chmod(denied, 0o000); err != nil {
t.Fatalf("chmod: %v", err)
}
resolveInstallID("", denied, logger) // must log, not crash
_ = os.Chmod(denied, 0o644)
}
func TestDefaultInstallIDPathWithoutHome(t *testing.T) {
t.Setenv("HOME", "")
if path := defaultInstallIDPath(); path != "" {
t.Fatalf("no home must yield an empty default path, got %q", path)
}
}
// ---------------------------------------------------------- redact.go --
func TestSanitizeHeadersDeepStructures(t *testing.T) {
sensitive := []string{"Authorization"}
deep := map[string]any{}
cursor := deep
for i := 0; i < 15; i++ {
next := map[string]any{}
cursor["deep"] = next
cursor = next
}
got := SanitizeHeaders(map[string]any{
"list": []any{"a", 2, map[string]any{"authorization": "s"}},
"strings": []string{"x", "y"},
"jsonScan": `{"authorization":"s","keep":1}`,
"jsonDeep": "[1,2,3]",
"badJSON": "{not json",
"whole": strings.Repeat("{", maxJSONScanLen+1),
"plain": "hello",
"empty": " ",
"scalar": 3.14,
"bytes": []byte("bytes"),
"duration": time.Second,
"jsonNum": json.Number("9"),
"deepLimit": deep,
"func": func() {},
}, sensitive)
m, ok := got.(map[string]any)
if !ok {
t.Fatalf("sanitize must return a map, got %T", got)
}
if m["func"] != redactedMarker {
t.Fatalf("unrepresentable values must redact, got %v", m["func"])
}
if strings.Contains(fmt.Sprint(m["jsonScan"]), "s") {
t.Fatalf("sensitive key inside a JSON string must redact: %v", m["jsonScan"])
}
if m["plain"] != "hello" || m["badJSON"] != "{not json" || m["empty"] != " " {
t.Fatalf("non-JSON and unparseable strings must pass through: %v", m)
}
if m["whole"] != redactedMarker {
t.Fatalf("oversized JSON candidates must redact wholesale, got %v", m["whole"])
}
if strings.Contains(fmt.Sprint(m["deepLimit"]), `"secret"`) {
t.Fatalf("over-depth subtree must redact wholesale: %v", m["deepLimit"])
}
list, ok := m["list"].([]any)
if !ok {
t.Fatalf("lists must survive: %T", m["list"])
}
listMap, ok := list[2].(map[string]any)
if !ok || listMap["authorization"] != redactedMarker {
t.Fatalf("sensitive keys inside list entries must redact: %v", list[2])
}
// map[string]string values sanitize through the same walker.
strMap := SanitizeHeaders(map[string]string{
"authorization": "secret",
"json": `{"authorization":"s"}`,
"plain": "ok",
}, nil).(map[string]string)
if strMap["authorization"] != redactedMarker {
t.Fatalf("sensitive map values must redact: %v", strMap)
}
if strMap["json"] != `{"authorization":"[REDACTED]"}` {
t.Fatalf("JSON-looking values must reserialize sanitized: %q", strMap["json"])
}
if strMap["plain"] != "ok" {
t.Fatalf("plain values must pass: %q", strMap["plain"])
}
// Nil sensitive headers fall back to the defaults.
fallback := SanitizeHeaders(map[string]any{"Cookie": "c"}, nil).(map[string]any)
if fallback["Cookie"] != redactedMarker {
t.Fatalf("default sensitive set must apply, got %v", fallback)
}
}
func TestRedactEventAndMetricCopies(t *testing.T) {
ev := SecurityEvent{EventType: "e", Metadata: map[string]any{"authorization": "s", "n": 1}}
redacted := redactEventMetadata(ev, nil)
if redacted.Metadata["authorization"] != redactedMarker {
t.Fatalf("sensitive metadata must redact: %v", redacted.Metadata)
}
if ev.Metadata["authorization"] != "s" {
t.Fatal("the input map must never be mutated")
}
if kept := redactEventMetadata(SecurityEvent{EventType: "e"}, nil); kept.Metadata != nil {
t.Fatalf("nil metadata must pass through untouched: %v", kept.Metadata)
}
metric := SecurityMetric{MetricType: MetricRequestCount, Tags: map[string]string{"x-api-key": "s"}}
tagged := redactMetricTags(metric, nil)
if tagged.Tags["x-api-key"] != redactedMarker {
t.Fatalf("sensitive tags must redact: %v", tagged.Tags)
}
if kept := redactMetricTags(SecurityMetric{MetricType: MetricRequestCount}, nil); kept.Tags != nil {
t.Fatalf("nil tags must pass through untouched: %v", kept.Tags)
}
batch := &eventBatch{Events: []SecurityEvent{ev}, Metrics: []SecurityMetric{metric}}
redactBatch(batch, nil)
if batch.Events[0].Metadata["authorization"] != redactedMarker ||
batch.Metrics[0].Tags["x-api-key"] != redactedMarker {
t.Fatalf("batch redaction must cover both kinds: %+v", batch)
}
}
// ------------------------------------------------------ rate_limiter.go --
func TestRateLimiterRetryAfter(t *testing.T) {
l := newRateLimiter(2, 40*time.Millisecond)
if l.RetryAfter() != 0 {
t.Fatal("a fresh limiter must admit immediately")
}
if !l.Acquire() {
t.Fatal("under the cap, the first acquire must succeed")
}
if !l.Acquire() {
t.Fatal("under the cap, the second acquire must succeed")
}
if l.Acquire() {
t.Fatal("a saturated limiter must deny")
}
if wait := l.RetryAfter(); wait <= 0 || wait > 40*time.Millisecond {
t.Fatalf("retry window must bound the wait, got %s", wait)
}
// A fully aged window admits again and RetryAfter reports zero.
l.mu.Lock()
l.calls = []time.Time{time.Now().Add(-2 * l.window)}
l.mu.Unlock()
if wait := l.RetryAfter(); wait != 0 {
t.Fatalf("an expired window must report zero wait, got %s", wait)
}
if !l.Acquire() {
t.Fatal("aged calls must prune on acquire")
}
}
// --------------------------------------------------------- transport.go --
func TestParseRetryAfterBounds(t *testing.T) {
cases := []struct {
header string
want time.Duration
}{
{"5", 5 * time.Second},
{" 7 ", 7 * time.Second},
{"0.25", 250 * time.Millisecond},
{"bogus", 60 * time.Second},
{"-3", 0},
{"9999", 300 * time.Second},
{"", 60 * time.Second},
}
for _, tc := range cases {
if got := parseRetryAfter(tc.header); got != tc.want {
t.Fatalf("parseRetryAfter(%q) = %s, want %s", tc.header, got, tc.want)
}
}
}
func TestRetryAndPartialBackoffBounds(t *testing.T) {
if got := retryBackoff(31, 1.0); got != maxRetryBackoff {
t.Fatalf("attempt beyond 30 must cap, got %s", got)
}
if got := retryBackoff(1, 0); got != time.Second {
t.Fatalf("non-positive delay must floor at 1s, got %s", got)
}
if got := retryBackoff(10, 1000.0); got != maxRetryBackoff {
t.Fatalf("huge delays must cap, got %s", got)
}
if got := retryBackoff(1, 1.0); got != 2*time.Second {
t.Fatalf("exponential base must double, got %s", got)
}
if got := partialFailureBackoff(0, time.Second); got != time.Second {
t.Fatalf("streaks below one must clamp to the interval, got %s", got)
}
if got := partialFailureBackoff(1, 0); got != maxPartialBackoff {
t.Fatalf("a zero interval must floor at the cap, got %s", got)
}
if got := partialFailureBackoff(1, time.Second); got != time.Second {
t.Fatalf("first streak uses the flush interval, got %s", got)
}
if got := partialFailureBackoff(20, time.Hour); got != maxPartialBackoff {
t.Fatalf("huge backoffs must cap, got %s", got)
}
}
func TestSleepCtx(t *testing.T) {
if !sleepCtx(context.Background(), 0) {
t.Fatal("zero sleep on a live context must succeed")
}
ctx, cancel := context.WithCancel(context.Background())
cancel()
if sleepCtx(ctx, 0) {
t.Fatal("zero sleep on a canceled context must report the cancel")
}
if sleepCtx(ctx, time.Hour) {
t.Fatal("a canceled context must interrupt the sleep")
}
if !sleepCtx(context.Background(), time.Millisecond) {
t.Fatal("a short sleep on a live context must complete")
}
}
func TestTruncate(t *testing.T) {
if got := truncate("short", 10); got != "short" {
t.Fatalf("short strings pass through, got %q", got)
}
if got := truncate("0123456789abcdef", 4); got != "0123" {
t.Fatalf("long strings cut, got %q", got)
}
}
func TestEvaluateBatchResponse(t *testing.T) {
tr := newTransport(DefaultConfig(), "install", nil, log.New(io.Discard, "", 0))
if outcome, err := tr.evaluateBatchResponse([]byte(`{"success":true}`)); outcome != outcomeAccepted || err != nil {
t.Fatalf("clean 200 must accept, got %v %v", outcome, err)
}
if outcome, err := tr.evaluateBatchResponse([]byte(`{"success":false}`)); outcome != outcomePartial || err != nil {
t.Fatalf("success:false must be partial, got %v %v", outcome, err)
}
if outcome, err := tr.evaluateBatchResponse([]byte(`{garbage`)); outcome != outcomePartial || err == nil {
t.Fatalf("malformed bodies must be partial, got %v %v", outcome, err)
}
}
func TestMarshalBatchCompressionFlag(t *testing.T) {
cfg := DefaultConfig()
cfg.CompressionThreshold = 32
tr := newTransport(cfg, "install", nil, log.New(io.Discard, "", 0))
batch := &eventBatch{ProjectID: "p", Events: []SecurityEvent{testEvent(1, strings.Repeat("x", 64))}}
raw, err := tr.marshalBatch(batch)
if err != nil {
t.Fatalf("marshalBatch: %v", err)
}
if !batch.Compressed {
t.Fatal("bodies over the threshold must set the compressed flag")
}
var decoded eventBatch
if err := json.Unmarshal(raw, &decoded); err != nil {
t.Fatalf("re-marshaled batch must stay valid JSON: %v", err)
}
plainCfg := cfg
plainCfg.CompressionThreshold = 4096
smallTr := newTransport(plainCfg, "install", nil, log.New(io.Discard, "", 0))
small := &eventBatch{ProjectID: "p", Events: []SecurityEvent{testEvent(1, "")}}
if _, err := smallTr.marshalBatch(small); err != nil {
t.Fatalf("marshalBatch: %v", err)
}
if small.Compressed {
t.Fatal("bodies under the threshold must not claim compression")
}
}
func TestEncodeBodyCompression(t *testing.T) {
cfg := DefaultConfig()
cfg.CompressionThreshold = 16
tr := newTransport(cfg, "install", nil, log.New(io.Discard, "", 0))
raw := []byte(strings.Repeat("a", 2048))
wire, encoding := tr.encodeBody(raw)
if encoding != "gzip" || len(wire) >= len(raw) {
t.Fatalf("compressible bodies must gzip, got encoding=%q len=%d", encoding, len(wire))
}
plain, encoding := tr.encodeBody([]byte("tiny"))
if encoding != "" || string(plain) != "tiny" {
t.Fatalf("small bodies must stay plain, got encoding=%q", encoding)
}
newGzipWriter = func(w io.Writer) *gzip.Writer { return gzip.NewWriter(errWriter()) }
failed, failedEncoding := tr.encodeBody(raw)
newGzipWriter = gzipNewWriter
if failedEncoding != "" || !bytes.Equal(failed, raw) {
t.Fatalf("a failing gzip writer must fall back to plain bytes, got %q %d", failedEncoding, len(failed))
}
}
func TestProjectIDOrDefault(t *testing.T) {
tr := newTransport(DefaultConfig(), "install", nil, log.New(io.Discard, "", 0))
if got := tr.projectIDOrDefault(); got != "default" {
t.Fatalf("missing project id must default, got %q", got)
}
tr.cfg.ProjectID = "acme"
if got := tr.projectIDOrDefault(); got != "acme" {
t.Fatalf("configured project id must win, got %q", got)
}
}
func TestLimiterGateWaitsAndBurnsAttempts(t *testing.T) {
cfg := DefaultConfig()
cfg.RetryAttempts = 1
tr := newTransport(cfg, "install", nil, log.New(io.Discard, "", 0))
tr.limiter = newRateLimiter(1, 20*time.Millisecond)
saturate := func() {
tr.limiter.mu.Lock()
tr.limiter.calls = []time.Time{time.Now()}
tr.limiter.mu.Unlock()
}
if allowed, err := tr.limiterGate(context.Background(), 0, "batch send"); !allowed || err != nil {
t.Fatalf("a fresh limiter must admit, got %v %v", allowed, err)
}
// Saturated: the gate waits out the window and reports retry-eligible.
saturate()
if allowed, err := tr.limiterGate(context.Background(), 0, "batch send"); allowed || err != nil {
t.Fatalf("a saturated gate must defer, got %v %v", allowed, err)
}
// At the attempt budget the gate errors instead of retrying.
saturate()
if allowed, err := tr.limiterGate(context.Background(), 1, "batch send"); allowed || err == nil {
t.Fatalf("an exhausted attempt budget must error, got %v %v", allowed, err)
}
saturate()
ctx, cancel := context.WithCancel(context.Background())
cancel()
if allowed, err := tr.limiterGate(ctx, 0, "batch send"); allowed || !errors.Is(err, context.Canceled) {
t.Fatalf("a canceled context must surface immediately, got %v %v", allowed, err)
}
}
func TestSendBatchStatusHandling(t *testing.T) {
m := newMockIngest(t)
cfg := DefaultConfig()
cfg.APIKey = "test-api-key-123"
cfg.Endpoint = m.URL
cfg.RetryAttempts = 1
cfg.BackoffFactor = 0.001
tr := newTransport(cfg, "install", nil, log.New(io.Discard, "", 0))
// 200 + evaluate clean body.
if outcome, err := tr.sendBatch(context.Background(), eventsPath, []byte(`{"x":1}`)); outcome != outcomeAccepted || err != nil {
t.Fatalf("clean 200 must accept, got %v %v", outcome, err)
}
// 201 skips evaluation.
if outcome, err := func() (sendOutcome, error) {
m.mu.Lock()
m.statusCodeOverride = http.StatusCreated
m.mu.Unlock()
defer func() { m.statusCodeOverride = 0 }()
return tr.sendBatch(context.Background(), eventsPath, []byte(`{}`))
}(); outcome != outcomeAccepted || err != nil {
t.Fatalf("201 must accept without evaluation, got %v %v", outcome, err)
}
// Permanent rejections.
for _, code := range []int{http.StatusBadRequest, http.StatusNotFound, http.StatusUnprocessableEntity} {
m.mu.Lock()
m.statusCodeOverride = code
m.mu.Unlock()
outcome, err := tr.sendBatch(context.Background(), eventsPath, []byte(`{}`))
m.mu.Lock()
m.statusCodeOverride = 0
m.mu.Unlock()
var permanent *PermanentError
if outcome != outcomePermanent || !errors.As(err, &permanent) || permanent.StatusCode != code {
t.Fatalf("status %d must be permanent, got %v %v", code, outcome, err)
}
}
// An unexpected 4xx is partial (and exempt from the breaker).
m.mu.Lock()
m.statusCodeOverride = http.StatusConflict
m.mu.Unlock()
outcome, err := tr.sendBatch(context.Background(), eventsPath, []byte(`{}`))
m.mu.Lock()
m.statusCodeOverride = 0
m.mu.Unlock()
if outcome != outcomePartial || err == nil {
t.Fatalf("unexpected 4xx must be partial, got %v %v", outcome, err)
}
// 403 retries with backoff and then fails.
m.mu.Lock()
m.statusCodeOverride = http.StatusForbidden
m.mu.Unlock()
outcome, err = tr.sendBatch(context.Background(), eventsPath, []byte(`{}`))
m.mu.Lock()
m.statusCodeOverride = 0
m.mu.Unlock()
if outcome != outcomeFailed || err == nil || !strings.Contains(err.Error(), "authentication failed") {
t.Fatalf("403 must retry then fail, got %v %v", outcome, err)
}
// A canceled context during the send surfaces the context error.
ctx, cancel := context.WithCancel(context.Background())
cancel()
if outcome, err := tr.sendBatch(ctx, eventsPath, []byte(`{}`)); outcome != outcomeFailed || !errors.Is(err, context.Canceled) {
t.Fatalf("canceled sends must report the context, got %v %v", outcome, err)
}
// Network errors retry with backoff and exhaust into outcomeFailed.
down := newTransport(cfg, "install", nil, log.New(io.Discard, "", 0))
down.cfg.Endpoint = "http://127.0.0.1:1"
if outcome, err := down.sendBatch(context.Background(), eventsPath, []byte(`{}`)); outcome != outcomeFailed || err == nil {
t.Fatalf("unreachable endpoints must fail after retries, got %v %v", outcome, err)
}
}
func TestSendEventsTransportPaths(t *testing.T) {
m := newMockIngest(t)
cfg := DefaultConfig()
cfg.APIKey = "test-api-key-123"
cfg.Endpoint = m.URL
cfg.RetryAttempts = 1
cfg.BackoffFactor = 0.001
cfg.OnError = func(stage string, err error, ctx map[string]any) {}
tr := newTransport(cfg, "install", nil, log.New(io.Discard, "", 0))
// Empty batches short-circuit to accepted.
if outcome, err := tr.sendEvents(context.Background(), nil); outcome != outcomeAccepted || err != nil {
t.Fatalf("empty batches must accept, got %v %v", outcome, err)
}
if outcome, err := tr.sendMetrics(context.Background(), nil); outcome != outcomeAccepted || err != nil {
t.Fatalf("empty batches must accept, got %v %v", outcome, err)
}
// Serialization failure retains the batch as partial and fires the hook.
jsonMarshal = func(v any) ([]byte, error) { return nil, errors.New("marshal exploded") }
var hookStage string
tr.cfg.OnError = func(stage string, err error, ctx map[string]any) { hookStage = stage }
if outcome, err := tr.sendEvents(context.Background(), []SecurityEvent{testEvent(1, "")}); outcome != outcomePartial || err == nil {
t.Fatalf("marshal failure must be partial, got %v %v", outcome, err)
}
if hookStage != StageTransportSend {
t.Fatalf("marshal failure must fire the transport hook, got %q", hookStage)
}
if outcome, err := tr.sendMetrics(context.Background(), []SecurityMetric{testMetric(1)}); outcome != outcomePartial || err == nil {
t.Fatalf("marshal failure must be partial, got %v %v", outcome, err)
}
jsonMarshal = json.Marshal
// A 413 on a multi-item batch splits recursively and confirms both halves.
m.setMaxBody(10)
big := make([]SecurityEvent, 4)
for i := range big {
big[i] = testEvent(i, "")
}
if outcome, err := tr.sendEvents(context.Background(), big); outcome != outcomeAccepted || err != nil {
t.Fatalf("413 split must confirm when every part confirms, got %v %v", outcome, err)
}
bigMetrics := make([]SecurityMetric, 4)
for i := range bigMetrics {
bigMetrics[i] = testMetric(i)
}
if outcome, err := tr.sendMetrics(context.Background(), bigMetrics); outcome != outcomeAccepted || err != nil {
t.Fatalf("413 metric split must confirm when every part confirms, got %v %v", outcome, err)
}
// A 413 on a singleton drops it durably.
m.setMaxBody(10)
if outcome, err := tr.sendEvents(context.Background(), []SecurityEvent{testEvent(9, strings.Repeat("y", 64))}); outcome != outcomePermanent || err != nil {
t.Fatalf("singleton 413 must drop durably, got %v %v", outcome, err)
}
if outcome, err := tr.sendMetrics(context.Background(), []SecurityMetric{{MetricType: MetricRequestCount, Value: 1, Tags: map[string]string{"pad": strings.Repeat("y", 64)}}}); outcome != outcomePermanent || err != nil {
t.Fatalf("singleton metric 413 must drop durably, got %v %v", outcome, err)
}
// A failed half makes the whole split report failure.
m.setMaxBody(262144)
m.failNext(2)
if outcome, _ := tr.sendEvents(context.Background(), big); outcome != outcomeFailed {
t.Fatalf("a failed batch must report failure, got %v", outcome)
}
m.clearKnobs()
}
func TestSendStatusPaths(t *testing.T) {
m := newMockIngest(t)
cfg := DefaultConfig()
cfg.APIKey = "test-api-key-123"
cfg.Endpoint = m.URL
cfg.RetryAttempts = 1
cfg.BackoffFactor = 0.001
tr := newTransport(cfg, "install", nil, log.New(io.Discard, "", 0))
payload := agentStatusPayload{Timestamp: time.Now().UTC(), Status: StatusHealthy}
if outcome, err := tr.sendStatus(context.Background(), payload); outcome != outcomeAccepted || err != nil {
t.Fatalf("clean status must accept, got %v %v", outcome, err)
}
// Serialization failure is partial.
jsonMarshal = func(v any) ([]byte, error) { return nil, errors.New("marshal exploded") }
if outcome, err := tr.sendStatus(context.Background(), payload); outcome != outcomePartial || err == nil {
t.Fatalf("status marshal failure must be partial, got %v %v", outcome, err)
}
jsonMarshal = json.Marshal
// A 413 on status is a failed push (fire and forget), never requeued.
m.setMaxBody(1)
if outcome, err := tr.sendStatus(context.Background(), payload); outcome != outcomeFailed || err == nil {
t.Fatalf("oversized status must fail the push, got %v %v", outcome, err)
}
m.setMaxBody(262144)
}
func TestCanonicalItemsJSON(t *testing.T) {
payload, err := canonicalItemsJSON([]SecurityEvent{testEvent(1, "")}, []SecurityMetric{testMetric(2)})
if err != nil {
t.Fatalf("canonicalItemsJSON: %v", err)
}
events, ok := payload["events"].([]any)
if !ok || len(events) != 1 {
t.Fatalf("events must round trip: %v", payload["events"])
}
metrics, ok := payload["metrics"].([]any)
if !ok || len(metrics) != 1 {
t.Fatalf("metrics must round trip: %v", payload["metrics"])
}
metadata, ok := events[0].(map[string]any)["metadata"].(map[string]any)
if !ok {
t.Fatalf("event metadata must round trip: %v", events[0])
}
if _, ok := metadata["seq"].(json.Number); !ok {
t.Fatalf("integers must stay numbers on the canonical plaintext, got %T", metadata["seq"])
}
empty, err := canonicalItemsJSON(nil, nil)
if err != nil {
t.Fatalf("canonicalItemsJSON: %v", err)
}
if e, ok := empty["events"].([]any); !ok || len(e) != 0 {
t.Fatal("empty events must serialize as an empty list")
}
// Serialization failure surfaces.
jsonMarshal = func(v any) ([]byte, error) { return nil, errors.New("marshal exploded") }
if _, err := canonicalItemsJSON([]SecurityEvent{testEvent(1, "")}, nil); err == nil {
t.Fatal("event marshal failure must surface")
}
if _, err := canonicalItemsJSON(nil, []SecurityMetric{testMetric(1)}); err == nil {
t.Fatal("metric marshal failure must surface")
}
jsonMarshal = json.Marshal
}
func TestSendEncryptedBatchPaths(t *testing.T) {
m := newMockIngest(t)
cfg := DefaultConfig()
cfg.APIKey = "test-api-key-123"
cfg.Endpoint = m.URL
cfg.RetryAttempts = 1
cfg.BackoffFactor = 0.001
cfg.ProjectEncryptionKey = testEncryptionKey()
cfg.OnError = func(string, error, map[string]any) {}
tr := newTransport(cfg, "install", nil, log.New(io.Discard, "", 0))
encryptor, err := NewPayloadEncryptor(testEncryptionKey())
if err != nil {
t.Fatalf("encryptor: %v", err)
}
tr.encryptor = encryptor
if outcome, err := tr.sendEncryptedBatch(context.Background(), []SecurityEvent{testEvent(1, "")}, nil); outcome != outcomeAccepted || err != nil {
t.Fatalf("encrypted batch must confirm, got %v %v", outcome, err)
}
calls := m.callsTo(encryptedPath)
if len(calls) != 1 {
t.Fatalf("encrypted batches must hit %s, got %v", encryptedPath, calls)
}
// 413 on an encrypted batch drops it durably: it cannot be split.
m.setMaxBody(1)
if outcome, err := tr.sendEncryptedBatch(context.Background(), nil, []SecurityMetric{testMetric(1)}); outcome != outcomePermanent || err != nil {
t.Fatalf("oversized encrypted batches must drop durably, got %v %v", outcome, err)
}
m.setMaxBody(262144)
// Encryption failure retains the batch.
cryptoRandRead = func(b []byte) (int, error) { return 0, errors.New("no entropy") }
if outcome, err := tr.sendEncryptedBatch(context.Background(), []SecurityEvent{testEvent(2, "")}, nil); outcome != outcomePartial || err == nil {
t.Fatalf("encryption failure must be partial, got %v %v", outcome, err)
}
cryptoRandRead = randRead
// Serialization failure retains the batch.
jsonMarshal = func(v any) ([]byte, error) { return nil, errors.New("marshal exploded") }
if outcome, err := tr.sendEncryptedBatch(context.Background(), []SecurityEvent{testEvent(3, "")}, nil); outcome != outcomePartial || err == nil {
t.Fatalf("serialization failure must be partial, got %v %v", outcome, err)
}
jsonMarshal = json.Marshal
}
// ------------------------------------------------------ dynamic_rules.go --
func sampleRulesJSON() string {
limit := 10
return fmt.Sprintf(`{"rule_id":"saas-rule","version":7,"ttl":120,"ip_ban_duration":60,
"ip_blacklist":["10.0.0.1"],"ip_whitelist":["10.0.0.2"],
"blocked_countries":["CN"],"whitelist_countries":["US"],
"global_rate_limit":%d,"global_rate_window":60,
"endpoint_rate_limits":{"/api":[5,60]},
"blocked_cloud_providers":["AWS"],"blocked_user_agents":["bot"],
"suspicious_patterns":["union select"],
"enable_penetration_detection":true,"enable_ip_banning":false,
"enable_rate_limiting":true,"auto_ban_threshold":3,"auto_ban_duration":600,
"enable_rate_limit_auto_ban":true,"emergency_mode":true,
"emergency_whitelist":["192.0.2.1"],"emergency_whitelist_only":true,
"message":"locked","expires_at":"2030-01-01T00:00:00Z"}`, limit)
}
func TestDynamicRulesUnmarshalAppliesDefaultsAndOverrides(t *testing.T) {
var sparse DynamicRules
if err := json.Unmarshal([]byte(`{}`), &sparse); err != nil {
t.Fatalf("sparse decode: %v", err)
}
def := DefaultDynamicRules()
if sparse.RuleID != def.RuleID || sparse.TTL != def.TTL || sparse.IPBanDuration != def.IPBanDuration {
t.Fatalf("sparse rules must carry the python defaults, got %+v", sparse)
}
if sparse.IPBlacklist == nil || sparse.EndpointRateLimits == nil || sparse.EmergencyWhitelist == nil {
t.Fatal("absent lists must default to empty, never nil")
}
var full DynamicRules
if err := json.Unmarshal([]byte(sampleRulesJSON()), &full); err != nil {
t.Fatalf("full decode: %v", err)
}
if full.RuleID != "saas-rule" || full.Version != 7 || full.TTL != 120 || full.IPBanDuration != 60 {
t.Fatalf("overrides must apply, got %+v", full)
}
if full.GlobalRateLimit == nil || *full.GlobalRateLimit != 10 || full.EndpointRateLimits["/api"][0] != 5 {
t.Fatalf("pointer fields must decode, got %+v", full)
}
if full.EnableIPBanning == nil || *full.EnableIPBanning || !*full.EnableRateLimitAutoBan {
t.Fatalf("bool pointers must decode, got %+v", full)
}
if full.Message == nil || *full.Message != "locked" || full.ExpiresAt == nil {
t.Fatalf("optional fields must decode, got %+v", full)
}
if !full.EmergencyMode || !full.EmergencyWhitelistOnly || len(full.EmergencyWhitelist) != 1 {
t.Fatalf("emergency fields must decode, got %+v", full)
}
if len(full.SuspiciousPatterns) != 1 || full.SuspiciousPatterns[0] != "union select" {
t.Fatalf("pattern lists must decode, got %+v", full)
}
// Malformed payloads surface the decoder error.
if err := json.Unmarshal([]byte(`{"version":"not-a-number"}`), &full); err == nil {
t.Fatal("type mismatches must surface")
}
}
func TestGetDynamicRulesCacheAndFallback(t *testing.T) {
m := newMockIngest(t)
m.serveRules(http.StatusOK, sampleRulesJSON())
agent := newTestAgent(t, m, nil)
ctx := context.Background()
first := agent.GetDynamicRules(ctx)
if first == nil || first.RuleID != "saas-rule" {
t.Fatalf("first fetch must return the document, got %+v", first)
}
if agent.Stats().RulesFetched != 1 {
t.Fatalf("successful fetches must count, got %+v", agent.Stats())
}
// Inside the TTL the cache answers without an HTTP call.
if cached := agent.GetDynamicRules(ctx); cached != first {
t.Fatal("cache must serve inside the TTL")
}
if len(m.callsTo(rulesPath)) != 1 {
t.Fatalf("cached reads must not hit the API, got %d calls", len(m.callsTo(rulesPath)))
}
// Expired TTL refetches.
agent.mu.Lock()
agent.rulesLastUpdate = time.Now().Add(-10 * time.Minute)
agent.mu.Unlock()
if again := agent.GetDynamicRules(ctx); again == nil || again.RuleID != "saas-rule" {
t.Fatalf("expired cache must refetch, got %+v", again)
}
// A failed refetch serves the last known rules.
m.serveRules(http.StatusInternalServerError, "")
agent.mu.Lock()
agent.rulesLastUpdate = time.Now().Add(-10 * time.Minute)
agent.mu.Unlock()
if served := agent.GetDynamicRules(ctx); served == nil || served.RuleID != "saas-rule" {
t.Fatalf("outage must serve the cached rules, got %+v", served)
}
// No cache plus an outage yields nil without erroring out.
agent.mu.Lock()
agent.cachedRules = nil
agent.mu.Unlock()
if served := agent.GetDynamicRules(ctx); served != nil {
t.Fatalf("an outage without cache must return nil, got %+v", served)