-
Notifications
You must be signed in to change notification settings - Fork 21
Expand file tree
/
Copy pathguard_test.go
More file actions
847 lines (697 loc) · 23.9 KB
/
guard_test.go
File metadata and controls
847 lines (697 loc) · 23.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
package guard
import (
"context"
"sync"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/github/gh-aw-mcpg/internal/auth"
"github.com/github/gh-aw-mcpg/internal/difc"
)
// mockGuard is a simple guard implementation for testing that can be distinguished by ID
type mockGuard struct {
id string
}
func (m *mockGuard) Name() string { return "mock-" + m.id }
func (m *mockGuard) LabelAgent(ctx context.Context, policy interface{}, backend BackendCaller, caps *difc.Capabilities) (*LabelAgentResult, error) {
return &LabelAgentResult{DIFCMode: difc.ModeStrict}, nil
}
func (m *mockGuard) LabelResource(ctx context.Context, toolName string, args interface{}, backend BackendCaller, caps *difc.Capabilities) (*difc.LabeledResource, difc.OperationType, error) {
return &difc.LabeledResource{}, difc.OperationRead, nil
}
func (m *mockGuard) LabelResponse(ctx context.Context, toolName string, result interface{}, backend BackendCaller, caps *difc.Capabilities) (difc.LabeledData, error) {
return nil, nil
}
func TestNoopGuard(t *testing.T) {
guard := NewNoopGuard()
t.Run("Name returns noop", func(t *testing.T) {
assert.Equal(t, "noop", guard.Name())
})
t.Run("LabelResource returns empty labels", func(t *testing.T) {
ctx := context.Background()
caps := difc.NewCapabilities()
resource, operation, err := guard.LabelResource(ctx, "test_tool", map[string]interface{}{}, nil, caps)
require.NoError(t, err)
require.NotNil(t, resource)
assert.True(t, resource.Secrecy.Label.IsEmpty(), "Expected empty secrecy labels")
assert.True(t, resource.Integrity.Label.IsEmpty(), "Expected empty integrity labels")
assert.Equal(t, difc.OperationReadWrite, operation)
})
t.Run("LabelAgent returns defaults", func(t *testing.T) {
ctx := context.Background()
caps := difc.NewCapabilities()
result, err := guard.LabelAgent(ctx, map[string]interface{}{"AllowOnly": map[string]interface{}{}}, nil, caps)
require.NoError(t, err)
require.NotNil(t, result)
assert.Equal(t, difc.ModeStrict, result.DIFCMode)
assert.Empty(t, result.Agent.Secrecy)
assert.Empty(t, result.Agent.Integrity)
})
t.Run("LabelResponse returns nil", func(t *testing.T) {
ctx := context.Background()
caps := difc.NewCapabilities()
labeledData, err := guard.LabelResponse(ctx, "test_tool", map[string]interface{}{}, nil, caps)
require.NoError(t, err)
assert.Nil(t, labeledData)
})
t.Run("LabelResource with nil capabilities", func(t *testing.T) {
ctx := context.Background()
resource, operation, err := guard.LabelResource(ctx, "test_tool", map[string]interface{}{}, nil, nil)
require.NoError(t, err)
require.NotNil(t, resource)
assert.True(t, resource.Secrecy.Label.IsEmpty())
assert.True(t, resource.Integrity.Label.IsEmpty())
assert.Equal(t, difc.OperationReadWrite, operation)
})
t.Run("LabelResponse with nil capabilities", func(t *testing.T) {
ctx := context.Background()
labeledData, err := guard.LabelResponse(ctx, "test_tool", map[string]interface{}{}, nil, nil)
require.NoError(t, err)
assert.Nil(t, labeledData)
})
t.Run("LabelResource with empty tool name", func(t *testing.T) {
ctx := context.Background()
caps := difc.NewCapabilities()
resource, operation, err := guard.LabelResource(ctx, "", map[string]interface{}{}, nil, caps)
require.NoError(t, err)
require.NotNil(t, resource)
assert.Equal(t, difc.OperationReadWrite, operation)
})
t.Run("LabelResource with nil args", func(t *testing.T) {
ctx := context.Background()
caps := difc.NewCapabilities()
resource, operation, err := guard.LabelResource(ctx, "test_tool", nil, nil, caps)
require.NoError(t, err)
require.NotNil(t, resource)
assert.Equal(t, difc.OperationReadWrite, operation)
})
t.Run("LabelResponse with various result types", func(t *testing.T) {
ctx := context.Background()
caps := difc.NewCapabilities()
tests := []struct {
name string
result interface{}
}{
{"nil result", nil},
{"string result", "test-result"},
{"map result", map[string]interface{}{"key": "value"}},
{"slice result", []interface{}{1, 2, 3}},
{"int result", 42},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
labeledData, err := guard.LabelResponse(ctx, "test_tool", tt.result, nil, caps)
require.NoError(t, err)
assert.Nil(t, labeledData)
})
}
})
}
func TestGuardRegistry(t *testing.T) {
t.Run("Register and Get guard", func(t *testing.T) {
registry := NewRegistry()
guard := NewNoopGuard()
registry.Register("test-server", guard)
retrieved := registry.Get("test-server")
assert.Equal(t, guard, retrieved)
})
t.Run("Get non-existent guard returns noop", func(t *testing.T) {
registry := NewRegistry()
guard := registry.Get("non-existent")
assert.Equal(t, "noop", guard.Name())
})
t.Run("Has checks guard existence", func(t *testing.T) {
registry := NewRegistry()
guard := NewNoopGuard()
assert.False(t, registry.Has("test-server"))
registry.Register("test-server", guard)
assert.True(t, registry.Has("test-server"))
})
t.Run("List returns all server IDs", func(t *testing.T) {
registry := NewRegistry()
registry.Register("server1", NewNoopGuard())
registry.Register("server2", NewNoopGuard())
list := registry.List()
assert.Len(t, list, 2)
assert.Contains(t, list, "server1")
assert.Contains(t, list, "server2")
})
t.Run("GetGuardInfo returns guard names", func(t *testing.T) {
registry := NewRegistry()
registry.Register("server1", NewNoopGuard())
info := registry.GetGuardInfo()
assert.Equal(t, "noop", info["server1"])
})
t.Run("Remove removes guard registration", func(t *testing.T) {
registry := NewRegistry()
guard := NewNoopGuard()
registry.Register("test-server", guard)
assert.True(t, registry.Has("test-server"))
registry.Remove("test-server")
assert.False(t, registry.Has("test-server"))
// Getting removed guard returns noop
retrieved := registry.Get("test-server")
assert.Equal(t, "noop", retrieved.Name())
})
t.Run("Remove non-existent guard is no-op", func(t *testing.T) {
registry := NewRegistry()
// Should not panic
registry.Remove("non-existent")
assert.False(t, registry.Has("non-existent"))
})
t.Run("Register overwrites existing guard", func(t *testing.T) {
registry := NewRegistry()
guard1 := &mockGuard{id: "first"}
guard2 := &mockGuard{id: "second"}
registry.Register("test-server", guard1)
retrieved1 := registry.Get("test-server")
assert.Same(t, guard1, retrieved1)
// Overwrite with guard2
registry.Register("test-server", guard2)
retrieved2 := registry.Get("test-server")
assert.Same(t, guard2, retrieved2)
assert.NotSame(t, guard1, retrieved2)
assert.Equal(t, "mock-second", retrieved2.Name())
})
t.Run("Empty registry returns empty list", func(t *testing.T) {
registry := NewRegistry()
list := registry.List()
assert.Empty(t, list)
info := registry.GetGuardInfo()
assert.Empty(t, info)
})
t.Run("Registry operations with empty server ID", func(t *testing.T) {
registry := NewRegistry()
guard := NewNoopGuard()
// Empty string as server ID should work
registry.Register("", guard)
assert.True(t, registry.Has(""))
retrieved := registry.Get("")
assert.Equal(t, guard, retrieved)
registry.Remove("")
assert.False(t, registry.Has(""))
})
t.Run("Registry operations with special characters in server ID", func(t *testing.T) {
registry := NewRegistry()
guard := NewNoopGuard()
serverIDs := []string{
"server-with-dashes",
"server_with_underscores",
"server.with.dots",
"server/with/slashes",
"server:with:colons",
}
for _, serverID := range serverIDs {
registry.Register(serverID, guard)
assert.True(t, registry.Has(serverID), "Failed for serverID: %s", serverID)
retrieved := registry.Get(serverID)
assert.NotNil(t, retrieved, "Failed to retrieve guard for serverID: %s", serverID)
}
list := registry.List()
assert.Len(t, list, len(serverIDs))
})
t.Run("GetGuardInfo with multiple guards", func(t *testing.T) {
registry := NewRegistry()
registry.Register("server1", NewNoopGuard())
registry.Register("server2", NewNoopGuard())
registry.Register("server3", NewNoopGuard())
info := registry.GetGuardInfo()
assert.Len(t, info, 3)
assert.Equal(t, "noop", info["server1"])
assert.Equal(t, "noop", info["server2"])
assert.Equal(t, "noop", info["server3"])
})
t.Run("List returns independent slice", func(t *testing.T) {
registry := NewRegistry()
registry.Register("server1", NewNoopGuard())
list1 := registry.List()
require.Len(t, list1, 1)
// Modify returned slice
list1[0] = "modified"
// Get new list - should not be affected
list2 := registry.List()
assert.Equal(t, "server1", list2[0], "Registry internal state should not be affected by slice modification")
})
}
func TestGuardRegistryConcurrency(t *testing.T) {
t.Run("Concurrent Register and Get", func(t *testing.T) {
registry := NewRegistry()
var wg sync.WaitGroup
// Concurrent registrations
for i := 0; i < 10; i++ {
wg.Add(1)
go func(id int) {
defer wg.Done()
guard := NewNoopGuard()
serverID := "server-" + string(rune('A'+id))
registry.Register(serverID, guard)
}(i)
}
// Concurrent reads
for i := 0; i < 10; i++ {
wg.Add(1)
go func(id int) {
defer wg.Done()
serverID := "server-" + string(rune('A'+id))
guard := registry.Get(serverID)
assert.NotNil(t, guard)
}(i)
}
wg.Wait()
// Verify all registered
list := registry.List()
assert.Len(t, list, 10)
})
t.Run("Concurrent Has checks", func(t *testing.T) {
registry := NewRegistry()
registry.Register("test-server", NewNoopGuard())
var wg sync.WaitGroup
for i := 0; i < 100; i++ {
wg.Add(1)
go func() {
defer wg.Done()
has := registry.Has("test-server")
assert.True(t, has)
}()
}
wg.Wait()
})
t.Run("Concurrent List and GetGuardInfo", func(t *testing.T) {
registry := NewRegistry()
registry.Register("server1", NewNoopGuard())
registry.Register("server2", NewNoopGuard())
var wg sync.WaitGroup
for i := 0; i < 50; i++ {
wg.Add(2)
go func() {
defer wg.Done()
list := registry.List()
assert.Len(t, list, 2)
}()
go func() {
defer wg.Done()
info := registry.GetGuardInfo()
assert.Len(t, info, 2)
}()
}
wg.Wait()
})
t.Run("Concurrent Register and Remove", func(t *testing.T) {
registry := NewRegistry()
var wg sync.WaitGroup
// Concurrent register and remove operations
for i := 0; i < 20; i++ {
wg.Add(2)
go func(id int) {
defer wg.Done()
serverID := "server-" + string(rune('A'+id))
registry.Register(serverID, NewNoopGuard())
}(i)
go func(id int) {
defer wg.Done()
serverID := "server-" + string(rune('A'+id))
registry.Remove(serverID)
}(i)
}
wg.Wait()
// Registry should be in a valid state (no panics)
list := registry.List()
assert.NotNil(t, list)
})
}
func TestGuardRegistry_HasNonNoopGuard(t *testing.T) {
t.Run("empty registry returns false", func(t *testing.T) {
registry := NewRegistry()
assert.False(t, registry.HasNonNoopGuard())
})
t.Run("only noop guards returns false", func(t *testing.T) {
registry := NewRegistry()
registry.Register("server1", NewNoopGuard())
registry.Register("server2", NewNoopGuard())
assert.False(t, registry.HasNonNoopGuard())
})
t.Run("one non-noop guard returns true", func(t *testing.T) {
registry := NewRegistry()
registry.Register("server1", &mockGuard{id: "wasm"})
assert.True(t, registry.HasNonNoopGuard())
})
t.Run("mix of noop and non-noop returns true", func(t *testing.T) {
registry := NewRegistry()
registry.Register("server1", NewNoopGuard())
registry.Register("server2", &mockGuard{id: "github"})
assert.True(t, registry.HasNonNoopGuard())
})
t.Run("removing non-noop guard makes it return false", func(t *testing.T) {
registry := NewRegistry()
registry.Register("server1", &mockGuard{id: "wasm"})
assert.True(t, registry.HasNonNoopGuard())
registry.Remove("server1")
assert.False(t, registry.HasNonNoopGuard())
})
t.Run("replacing non-noop with noop returns false", func(t *testing.T) {
registry := NewRegistry()
registry.Register("server1", &mockGuard{id: "wasm"})
assert.True(t, registry.HasNonNoopGuard())
registry.Register("server1", NewNoopGuard())
assert.False(t, registry.HasNonNoopGuard())
})
}
func TestCreateGuard(t *testing.T) {
tests := []struct {
name string
guardType string
wantErr bool
wantName string
description string
}{
{
name: "noop guard",
guardType: "noop",
wantErr: false,
wantName: "noop",
description: "Create built-in noop guard",
},
{
name: "empty string returns noop",
guardType: "",
wantErr: false,
wantName: "noop",
description: "Empty string defaults to noop",
},
{
name: "unknown guard type",
guardType: "unknown-guard-type",
wantErr: true,
wantName: "",
description: "Unknown guard type returns error",
},
{
name: "case sensitive guard type",
guardType: "NOOP",
wantErr: true,
wantName: "",
description: "Guard type is case sensitive",
},
{
name: "guard type with whitespace",
guardType: " noop ",
wantErr: true,
wantName: "",
description: "Whitespace not trimmed",
},
{
name: "guard type with special chars",
guardType: "no!op",
wantErr: true,
wantName: "",
description: "Special characters cause error",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
guard, err := CreateGuard(tt.guardType)
if tt.wantErr {
assert.Error(t, err, tt.description)
assert.Nil(t, guard)
assert.Contains(t, err.Error(), "unknown guard type")
} else {
require.NoError(t, err, tt.description)
require.NotNil(t, guard)
assert.Equal(t, tt.wantName, guard.Name())
}
})
}
}
func TestRegisterGuardType(t *testing.T) {
t.Run("Register custom guard type", func(t *testing.T) {
// Clean slate - note: this modifies global state
// In real tests, you'd want to save/restore registeredGuards
called := false
factory := func() (Guard, error) {
called = true
return NewNoopGuard(), nil
}
RegisterGuardType("custom-test", factory)
guard, err := CreateGuard("custom-test")
require.NoError(t, err)
require.NotNil(t, guard)
assert.True(t, called, "Factory should have been called")
assert.Equal(t, "noop", guard.Name())
})
t.Run("GetRegisteredGuardTypes includes noop", func(t *testing.T) {
types := GetRegisteredGuardTypes()
assert.Contains(t, types, "noop")
})
t.Run("GetRegisteredGuardTypes includes custom types", func(t *testing.T) {
RegisterGuardType("custom-type-1", func() (Guard, error) {
return NewNoopGuard(), nil
})
RegisterGuardType("custom-type-2", func() (Guard, error) {
return NewNoopGuard(), nil
})
types := GetRegisteredGuardTypes()
assert.Contains(t, types, "noop")
assert.Contains(t, types, "custom-type-1")
assert.Contains(t, types, "custom-type-2")
})
}
func TestContextHelpers(t *testing.T) {
t.Run("GetAgentIDFromContext returns default", func(t *testing.T) {
ctx := context.Background()
agentID := GetAgentIDFromContext(ctx)
assert.Equal(t, "default", agentID)
})
t.Run("SetAgentIDInContext and retrieve", func(t *testing.T) {
ctx := context.Background()
ctx = SetAgentIDInContext(ctx, "test-agent")
agentID := GetAgentIDFromContext(ctx)
assert.Equal(t, "test-agent", agentID)
})
t.Run("SetAgentIDInContext with empty string", func(t *testing.T) {
ctx := context.Background()
ctx = SetAgentIDInContext(ctx, "")
// Empty string is stored as-is
agentID := GetAgentIDFromContext(ctx)
assert.Equal(t, "default", agentID, "Empty agent ID should return default")
})
t.Run("SetAgentIDInContext multiple times", func(t *testing.T) {
ctx := context.Background()
ctx = SetAgentIDInContext(ctx, "first-agent")
ctx = SetAgentIDInContext(ctx, "second-agent")
ctx = SetAgentIDInContext(ctx, "third-agent")
agentID := GetAgentIDFromContext(ctx)
assert.Equal(t, "third-agent", agentID, "Should get most recent agent ID")
})
t.Run("GetAgentIDFromContext with wrong value type in context", func(t *testing.T) {
ctx := context.Background()
ctx = context.WithValue(ctx, AgentIDContextKey, 12345) // Wrong type
agentID := GetAgentIDFromContext(ctx)
assert.Equal(t, "default", agentID, "Should return default for wrong type")
})
t.Run("auth.ExtractAgentID Bearer", func(t *testing.T) {
agentID := auth.ExtractAgentID("Bearer test-token-123")
assert.Equal(t, "test-token-123", agentID)
})
t.Run("auth.ExtractAgentID Agent", func(t *testing.T) {
agentID := auth.ExtractAgentID("Agent my-agent-id")
assert.Equal(t, "my-agent-id", agentID)
})
t.Run("auth.ExtractAgentID empty", func(t *testing.T) {
agentID := auth.ExtractAgentID("")
assert.Equal(t, "default", agentID)
})
t.Run("auth.ExtractAgentID with whitespace", func(t *testing.T) {
agentID := auth.ExtractAgentID("Bearer token-with-spaces ")
// This tests actual behavior of ExtractAgentID
assert.NotEmpty(t, agentID)
})
}
func TestRequestStateContext(t *testing.T) {
t.Run("GetRequestStateFromContext returns nil for empty context", func(t *testing.T) {
ctx := context.Background()
state := GetRequestStateFromContext(ctx)
assert.Nil(t, state)
})
t.Run("SetRequestStateInContext and retrieve", func(t *testing.T) {
ctx := context.Background()
testState := "test-state-data"
ctx = SetRequestStateInContext(ctx, testState)
state := GetRequestStateFromContext(ctx)
require.NotNil(t, state)
assert.Equal(t, testState, state)
})
t.Run("SetRequestStateInContext with nil state", func(t *testing.T) {
ctx := context.Background()
ctx = SetRequestStateInContext(ctx, nil)
state := GetRequestStateFromContext(ctx)
assert.Nil(t, state)
})
t.Run("SetRequestStateInContext with various types", func(t *testing.T) {
tests := []struct {
name string
state RequestState
}{
{"string state", "test-string"},
{"int state", 42},
{"map state", map[string]interface{}{"key": "value"}},
{"struct state", struct{ Field string }{"value"}},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
ctx := context.Background()
ctx = SetRequestStateInContext(ctx, tt.state)
state := GetRequestStateFromContext(ctx)
require.NotNil(t, state)
assert.Equal(t, tt.state, state)
})
}
})
t.Run("SetRequestStateInContext multiple times", func(t *testing.T) {
ctx := context.Background()
ctx = SetRequestStateInContext(ctx, "first")
ctx = SetRequestStateInContext(ctx, "second")
ctx = SetRequestStateInContext(ctx, "third")
state := GetRequestStateFromContext(ctx)
assert.Equal(t, "third", state, "Should get most recent state")
})
}
func TestNormalizePolicyPayload(t *testing.T) {
t.Run("accepts object policy", func(t *testing.T) {
input := map[string]interface{}{
"allow-only": map[string]interface{}{
"repos": "public",
"integrity": "none",
},
}
result, err := normalizePolicyPayload(input)
require.NoError(t, err)
require.NotNil(t, result)
})
t.Run("parses stringified json policy to object", func(t *testing.T) {
input := `{"allow-only":{"repos":"public","integrity":"none"}}`
result, err := normalizePolicyPayload(input)
require.NoError(t, err)
resultMap, ok := result.(map[string]interface{})
require.True(t, ok)
require.NotNil(t, resultMap["allow-only"])
})
t.Run("rejects invalid policy string", func(t *testing.T) {
_, err := normalizePolicyPayload("not-json")
require.Error(t, err)
})
}
func TestBuildStrictLabelAgentPayload(t *testing.T) {
t.Run("accepts top-level allow-only payload", func(t *testing.T) {
input := map[string]interface{}{
"allow-only": map[string]interface{}{
"repos": "public",
"integrity": "none",
},
}
payload, err := buildStrictLabelAgentPayload(input)
require.NoError(t, err)
require.NotNil(t, payload)
assert.Contains(t, payload, "allow-only")
assert.NotContains(t, payload, "policy")
})
t.Run("rejects legacy policy envelope", func(t *testing.T) {
input := map[string]interface{}{
"policy": map[string]interface{}{
"allow-only": map[string]interface{}{
"repos": "public",
"integrity": "none",
},
},
}
_, err := buildStrictLabelAgentPayload(input)
require.Error(t, err)
assert.Equal(t, "gateway policy adapter is outdated: remove legacy envelope key policy before calling label_agent", err.Error())
})
t.Run("rejects missing top-level allow-only", func(t *testing.T) {
input := map[string]interface{}{
"something_else": map[string]interface{}{},
}
_, err := buildStrictLabelAgentPayload(input)
require.Error(t, err)
assert.Equal(t, "label_agent policy must use top-level allow-only object (received policy.allow-only)", err.Error())
})
t.Run("rejects invalid repos value", func(t *testing.T) {
input := map[string]interface{}{
"allow-only": map[string]interface{}{
"repos": []interface{}{},
"integrity": "none",
},
}
_, err := buildStrictLabelAgentPayload(input)
require.Error(t, err)
assert.Equal(t, "invalid repos value: expected all, public, or non-empty array of scoped strings", err.Error())
})
t.Run("rejects invalid integrity value", func(t *testing.T) {
input := map[string]interface{}{
"allow-only": map[string]interface{}{
"repos": "all",
"integrity": "reader-contrib",
},
}
_, err := buildStrictLabelAgentPayload(input)
require.Error(t, err)
assert.Equal(t, "invalid integrity value: expected one of none|unapproved|approved|merged", err.Error())
})
}
func TestParseLabelAgentResponse(t *testing.T) {
t.Run("success payload parses", func(t *testing.T) {
payload := []byte(`{"agent":{"secrecy":[],"integrity":[]},"difc_mode":"strict","normalized_policy":{"scope_kind":"public","integrity":"none"}}`)
result, err := parseLabelAgentResponse(payload)
require.NoError(t, err)
require.NotNil(t, result)
assert.Equal(t, "strict", result.DIFCMode)
})
t.Run("non success fails closed", func(t *testing.T) {
payload := []byte(`{"success":false,"error":"missing field allow-only"}`)
result, err := parseLabelAgentResponse(payload)
require.Error(t, err)
assert.Nil(t, result)
assert.Contains(t, err.Error(), "missing field allow-only")
})
}
func TestIsValidAllowOnlyRepos(t *testing.T) {
tests := []struct {
name string
input interface{}
want bool
}{
// String "all" variants
{name: "string all lowercase", input: "all", want: true},
{name: "string all uppercase", input: "ALL", want: true},
{name: "string all with spaces", input: " all ", want: true},
// String "public" variants
{name: "string public lowercase", input: "public", want: true},
{name: "string public uppercase", input: "PUBLIC", want: true},
{name: "string public mixed case", input: "Public", want: true},
// Invalid strings
{name: "string private", input: "private", want: false},
{name: "string empty", input: "", want: false},
{name: "string whitespace only", input: " ", want: false},
{name: "string random", input: "owner/repo", want: false},
// Valid arrays
{name: "array with one string", input: []interface{}{"owner/repo"}, want: true},
{name: "array with multiple strings", input: []interface{}{"owner/repo1", "owner/repo2"}, want: true},
// Invalid arrays
{name: "empty array", input: []interface{}{}, want: false},
{name: "array with non-string element", input: []interface{}{42}, want: false},
{name: "array with mixed string and non-string", input: []interface{}{"owner/repo", 42}, want: false},
{name: "array with nil element", input: []interface{}{nil}, want: false},
// Other types
{name: "integer", input: 42, want: false},
{name: "nil", input: nil, want: false},
{name: "bool true", input: true, want: false},
{name: "map", input: map[string]interface{}{"key": "value"}, want: false},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := isValidAllowOnlyRepos(tt.input)
assert.Equal(t, tt.want, got)
})
}
}
// TestParseResourceResponse and TestParseCollectionLabeledData are in wasm_response_parse_test.go