-
Notifications
You must be signed in to change notification settings - Fork 38
Expand file tree
/
Copy pathplugin_test.go
More file actions
952 lines (848 loc) · 32.7 KB
/
Copy pathplugin_test.go
File metadata and controls
952 lines (848 loc) · 32.7 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
package ibac
import (
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
"strings"
"testing"
"github.com/rossoctl/cortex/authbridge/authlib/pipeline"
)
// fakeJudge records what it was asked and returns the configured
// verdict / err. Tests fail-closed pathways by setting err non-nil.
type fakeJudge struct {
verdict string
reason string
err error
gotIntent string
gotAction string
calls int
}
func (f *fakeJudge) Evaluate(_ context.Context, intent, action string) (string, string, error) {
f.calls++
f.gotIntent = intent
f.gotAction = action
return f.verdict, f.reason, f.err
}
// newConfiguredIBAC returns an IBAC plugin pre-wired with a fake judge,
// minimal config, and a sensible bypass list. Uses the default
// no_intent_policy ("allow"). Callers that want to override behavior
// can mutate p.cfg / p.judge after the fact, or use
// newConfiguredIBACDeny for the strict-deny variant.
func newConfiguredIBAC(t *testing.T, fj *fakeJudge) *IBAC {
t.Helper()
p := NewIBAC()
cfg := []byte(`{"judge_endpoint":"http://judge.invalid","judge_model":"test","timeout_ms":1000}`)
if err := p.Configure(json.RawMessage(cfg)); err != nil {
t.Fatalf("Configure: %v", err)
}
p.judge = fj
return p
}
// newConfiguredIBACDeny returns an IBAC configured with
// no_intent_policy: "deny" — used by tests that exercise the strict
// fail-closed behavior on no_session / no_intent.
func newConfiguredIBACDeny(t *testing.T, fj *fakeJudge) *IBAC {
t.Helper()
p := NewIBAC()
cfg := []byte(`{"judge_endpoint":"http://judge.invalid","judge_model":"test","timeout_ms":1000,"no_intent_policy":"deny"}`)
if err := p.Configure(json.RawMessage(cfg)); err != nil {
t.Fatalf("Configure: %v", err)
}
p.judge = fj
return p
}
// invokeOnRequest mirrors the helper used by jwtvalidation tests:
// stamps Plugin/Phase on records that the plugin emits without going
// through the full pipeline driver.
func invokeOnRequest(p pipeline.Plugin, pctx *pipeline.Context) pipeline.Action {
pctx.SetCurrentPlugin(p.Name(), pipeline.InvocationPhaseRequest)
defer pctx.ClearCurrentPlugin()
return p.OnRequest(context.Background(), pctx)
}
// makePCtx builds a minimal outbound pctx with a Session containing a
// single A2A user-intent message ("summarize my emails"). Defaults
// model a typical side-effect request — POST with a non-empty body
// AND an action-classified MCP extension — so the pctx reaches the
// judge unless the test opts out by clearing the extension or
// flipping IsAction. Tests override fields by mutating the returned
// context.
//
// The MCPExtension default reflects the parser-driven classification
// model: IBAC only judges traffic some parser classified as an
// action. Tests that want to verify pass-through (no classification)
// behavior explicitly set pctx.Extensions.MCP = nil.
//
// CONTRACT CHANGE NOTE. Before the parser-classification refactor,
// makePCtx populated no protocol extension and tests had to opt IN
// by setting pctx.Extensions.MCP/A2A/Inference when they wanted IBAC
// to judge. After the refactor, makePCtx populates an action-
// classified MCPExtension by default and tests opt OUT (set
// Extensions.MCP = nil) when they want to verify pass-through. The
// flip matches IBAC's new defense-in-depth posture: classified
// traffic is the judged path; unclassified is pass-through.
func makePCtx(t *testing.T) *pipeline.Context {
t.Helper()
view := &pipeline.SessionView{
ID: "s1",
Events: []pipeline.SessionEvent{
{
Direction: pipeline.Inbound,
Phase: pipeline.SessionRequest,
A2A: &pipeline.A2AExtension{
Role: "user",
Parts: []pipeline.A2APart{
{Kind: "text", Content: "summarize my emails"},
},
},
},
},
}
pctx := &pipeline.Context{
Direction: pipeline.Outbound,
Method: "POST",
Scheme: "http",
Host: "weather-tool.team1.svc",
Path: "/api/weather",
Headers: http.Header{},
Body: []byte(`{"city":"sf"}`),
Session: view,
}
pctx.Extensions.MCP = &pipeline.MCPExtension{
Method: "tools/call",
IsAction: true,
}
return pctx
}
// --- Configure ---
func TestConfigure_RequiresJudgeEndpoint(t *testing.T) {
p := NewIBAC()
err := p.Configure(json.RawMessage(`{"judge_model":"m"}`))
if err == nil || !strings.Contains(err.Error(), "judge_endpoint") {
t.Errorf("err = %v, want judge_endpoint required", err)
}
}
func TestConfigure_RequiresJudgeModel(t *testing.T) {
p := NewIBAC()
err := p.Configure(json.RawMessage(`{"judge_endpoint":"http://j"}`))
if err == nil || !strings.Contains(err.Error(), "judge_model") {
t.Errorf("err = %v, want judge_model required", err)
}
}
func TestConfigure_AppliesDefaults(t *testing.T) {
p := NewIBAC()
if err := p.Configure(json.RawMessage(`{"judge_endpoint":"http://j","judge_model":"m"}`)); err != nil {
t.Fatalf("Configure: %v", err)
}
if p.cfg.TimeoutMs != 5000 {
t.Errorf("default TimeoutMs = %d, want 5000", p.cfg.TimeoutMs)
}
if len(p.cfg.BypassHosts) == 0 {
t.Errorf("expected non-empty default BypassHosts")
}
if len(p.cfg.BypassPaths) == 0 {
t.Errorf("expected non-empty default BypassPaths")
}
if p.cfg.NoIntentPolicy != NoIntentPolicyAllow {
t.Errorf("default NoIntentPolicy = %q, want %q (allow)",
p.cfg.NoIntentPolicy, NoIntentPolicyAllow)
}
}
func TestConfigure_NoIntentPolicy_RejectsUnknownValue(t *testing.T) {
p := NewIBAC()
cfg := `{"judge_endpoint":"http://j","judge_model":"m","no_intent_policy":"maybe"}`
err := p.Configure(json.RawMessage(cfg))
if err == nil {
t.Fatal("expected error for unknown no_intent_policy value")
}
if !strings.Contains(err.Error(), "no_intent_policy") {
t.Errorf("error should mention no_intent_policy; got %q", err.Error())
}
}
func TestConfigure_NoIntentPolicy_AcceptsExplicitValues(t *testing.T) {
for _, v := range []string{"allow", "deny"} {
t.Run(v, func(t *testing.T) {
p := NewIBAC()
cfg := fmt.Sprintf(`{"judge_endpoint":"http://j","judge_model":"m","no_intent_policy":%q}`, v)
if err := p.Configure(json.RawMessage(cfg)); err != nil {
t.Fatalf("Configure(%q): %v", v, err)
}
if p.cfg.NoIntentPolicy != v {
t.Errorf("NoIntentPolicy = %q, want %q", p.cfg.NoIntentPolicy, v)
}
})
}
}
func TestConfigure_AgentLLMHostAddedToBypass(t *testing.T) {
p := NewIBAC()
cfg := `{"judge_endpoint":"http://j","judge_model":"m","agent_llm_host":"ollama.local"}`
if err := p.Configure(json.RawMessage(cfg)); err != nil {
t.Fatalf("Configure: %v", err)
}
found := false
for _, h := range p.cfg.BypassHosts {
if h == "ollama.local" {
found = true
break
}
}
if !found {
t.Errorf("agent_llm_host not added to BypassHosts; got %v", p.cfg.BypassHosts)
}
}
func TestConfigure_RejectsUnknownFields(t *testing.T) {
p := NewIBAC()
cfg := `{"judge_endpoint":"http://j","judge_model":"m","unknown":"x"}`
err := p.Configure(json.RawMessage(cfg))
if err == nil {
t.Errorf("expected error for unknown field")
}
}
// --- OnRequest control flow ---
// Defense-in-depth: if our own judge call ever loops back through the
// pipeline (operator misconfig sending the judge endpoint via the
// proxy), IBAC must skip itself.
func TestOnRequest_ReentrancyHeader(t *testing.T) {
fj := &fakeJudge{verdict: "deny", reason: "would block"}
p := newConfiguredIBAC(t, fj)
pctx := makePCtx(t)
pctx.Headers.Set("X-IBAC-Judge", "1")
action := invokeOnRequest(p, pctx)
if action.Type != pipeline.Continue {
t.Errorf("got %v, want Continue (reentrancy guard must short-circuit before judge)", action.Type)
}
if fj.calls != 0 {
t.Errorf("judge invoked %d times during reentrancy guard; want 0", fj.calls)
}
}
func TestOnRequest_BypassPath(t *testing.T) {
fj := &fakeJudge{}
p := newConfiguredIBAC(t, fj)
pctx := makePCtx(t)
pctx.Path = "/healthz"
action := invokeOnRequest(p, pctx)
if action.Type != pipeline.Continue {
t.Errorf("got %v, want Continue for bypass path", action.Type)
}
if fj.calls != 0 {
t.Errorf("judge invoked on bypass path; want 0 calls")
}
}
func TestOnRequest_BypassHost_Default(t *testing.T) {
fj := &fakeJudge{}
p := newConfiguredIBAC(t, fj)
pctx := makePCtx(t)
// Default bypass list ships with "keycloak.*" — the agent's
// token exchange to the Keycloak service must never be judged.
pctx.Host = "keycloak.rossoctl"
action := invokeOnRequest(p, pctx)
if action.Type != pipeline.Continue {
t.Errorf("got %v, want Continue for default-bypass host", action.Type)
}
if fj.calls != 0 {
t.Errorf("judge invoked on bypass host; want 0 calls")
}
}
func TestOnRequest_BypassHost_ConfiguredAgentLLM(t *testing.T) {
fj := &fakeJudge{}
p := NewIBAC()
cfg := `{"judge_endpoint":"http://j","judge_model":"m","agent_llm_host":"ollama.local"}`
if err := p.Configure(json.RawMessage(cfg)); err != nil {
t.Fatalf("Configure: %v", err)
}
p.judge = fj
pctx := makePCtx(t)
pctx.Host = "ollama.local:11434"
action := invokeOnRequest(p, pctx)
if action.Type != pipeline.Continue {
t.Errorf("got %v, want Continue for agent_llm_host (with port)", action.Type)
}
if fj.calls != 0 {
t.Errorf("judge invoked on agent_llm_host; want 0")
}
}
// Inference traffic is bypassed by default — judging the agent's own
// reasoning loop is high-cost low-value. Operators flip judge_inference
// to opt in.
func TestOnRequest_InferenceBypassByDefault(t *testing.T) {
fj := &fakeJudge{verdict: "deny", reason: "would block"}
p := newConfiguredIBAC(t, fj)
pctx := makePCtx(t)
// Mirror what inference-parser does in production: every populated
// InferenceExtension is marked as an action. With makePCtx's default
// MCP{IsAction:true} and Inference{IsAction:true}, classification
// returns (anyAction:true, anyBypass:false), so the gate at step 4
// falls through to the step-5 inference-policy check that this test
// is actually exercising. Without IsAction:true, the test would
// short-circuit at step 4 with skip/protocol_mechanics and pass for
// the wrong reason.
pctx.Extensions.Inference = &pipeline.InferenceExtension{
Model: "gpt-4o-mini",
IsAction: true,
}
action := invokeOnRequest(p, pctx)
if action.Type != pipeline.Continue {
t.Errorf("got %v, want Continue (inference bypassed by default)", action.Type)
}
if fj.calls != 0 {
t.Errorf("judge invoked on inference; want 0")
}
// Critical assertion: verify step 5 (inference_bypass) is the step
// that fired, not step 4 (protocol_mechanics). A regression in the
// inference-policy logic would otherwise pass silently.
inv := lastInvocation(t, pctx)
if inv.Reason != "inference_bypass" {
t.Errorf("Invocation reason = %q, want %q (step-5 inference policy must be the firing step)",
inv.Reason, "inference_bypass")
}
}
func TestOnRequest_InferenceJudgedWhenEnabled(t *testing.T) {
fj := &fakeJudge{verdict: "allow", reason: "ok"}
p := NewIBAC()
cfg := `{"judge_endpoint":"http://j","judge_model":"m","judge_inference":true}`
if err := p.Configure(json.RawMessage(cfg)); err != nil {
t.Fatalf("Configure: %v", err)
}
p.judge = fj
pctx := makePCtx(t)
// inference-parser sets IsAction=true unconditionally on populated
// extensions; mirror that here so the classification gate passes
// the request through to the inference-policy step.
pctx.Extensions.Inference = &pipeline.InferenceExtension{Model: "gpt-4", IsAction: true}
invokeOnRequest(p, pctx)
if fj.calls != 1 {
t.Errorf("judge calls = %d, want 1 when judge_inference is true", fj.calls)
}
if !strings.Contains(fj.gotAction, "INFERENCE_MODEL: gpt-4") {
t.Errorf("action did not include inference model; got %q", fj.gotAction)
}
}
// no_intent under policy=deny: when the operator configures strict
// fail-closed semantics, missing intent must reject with "no_intent".
// Validates the legacy behavior is still reachable via explicit config.
func TestOnRequest_NoIntent_PolicyDeny_FailsClosed(t *testing.T) {
fj := &fakeJudge{}
p := newConfiguredIBACDeny(t, fj)
pctx := makePCtx(t)
pctx.Session = &pipeline.SessionView{ID: "empty"} // no events
action := invokeOnRequest(p, pctx)
if action.Type != pipeline.Reject {
t.Errorf("got %v, want Reject when LastIntent is nil under policy=deny", action.Type)
}
if fj.calls != 0 {
t.Errorf("judge should not be called when there's no intent")
}
inv := lastInvocation(t, pctx)
if inv.Reason != "no_intent" {
t.Errorf("Invocation reason = %q, want 'no_intent'", inv.Reason)
}
}
// no_intent under policy=allow (default): missing intent means the
// request is either a legitimate agent self-action or a non-user-
// driven flow. IBAC should not be in the middle — Skip with reason
// "no_user_context" and Continue.
func TestOnRequest_NoIntent_PolicyAllow_Bypasses(t *testing.T) {
fj := &fakeJudge{}
p := newConfiguredIBAC(t, fj) // default policy=allow
pctx := makePCtx(t)
pctx.Session = &pipeline.SessionView{ID: "empty"} // no events
action := invokeOnRequest(p, pctx)
if action.Type != pipeline.Continue {
t.Errorf("got %v, want Continue when no intent under policy=allow", action.Type)
}
if fj.calls != 0 {
t.Errorf("judge should not be called when there's no intent")
}
inv := lastInvocation(t, pctx)
if inv.Action != pipeline.ActionSkip {
t.Errorf("Invocation action = %v, want ActionSkip", inv.Action)
}
if inv.Reason != "no_user_context" {
t.Errorf("Invocation reason = %q, want 'no_user_context'", inv.Reason)
}
if inv.Details["sub_reason"] != "no_intent" {
t.Errorf("Invocation sub_reason = %q, want 'no_intent'", inv.Details["sub_reason"])
}
}
// Nil Session under policy=deny: forward-proxy at agent startup
// (before any inbound A2A) leaves pctx.Session nil. With strict
// fail-closed configured, that must reject with "no_session".
func TestOnRequest_NilSession_PolicyDeny_FailsClosed(t *testing.T) {
fj := &fakeJudge{}
p := newConfiguredIBACDeny(t, fj)
pctx := makePCtx(t)
pctx.Session = nil // before any inbound A2A
action := invokeOnRequest(p, pctx)
if action.Type != pipeline.Reject {
t.Errorf("got %v, want Reject when Session is nil under policy=deny", action.Type)
}
if fj.calls != 0 {
t.Errorf("judge should not be called when there's no session")
}
inv := lastInvocation(t, pctx)
if inv.Reason != "no_session" {
t.Errorf("Invocation reason = %q, want 'no_session'", inv.Reason)
}
}
// Nil Session under policy=allow (default): the canonical "agent
// self-action at startup" case. The agent (e.g. exgentic-a2a-tool-
// calling) makes outbound calls during its bootstrap before any user
// turn — IBAC must Skip and Continue, not deny.
func TestOnRequest_NilSession_PolicyAllow_Bypasses(t *testing.T) {
fj := &fakeJudge{}
p := newConfiguredIBAC(t, fj) // default policy=allow
pctx := makePCtx(t)
pctx.Session = nil // before any inbound A2A
action := invokeOnRequest(p, pctx)
if action.Type != pipeline.Continue {
t.Errorf("got %v, want Continue when Session is nil under policy=allow", action.Type)
}
if fj.calls != 0 {
t.Errorf("judge should not be called when there's no session")
}
inv := lastInvocation(t, pctx)
if inv.Action != pipeline.ActionSkip {
t.Errorf("Invocation action = %v, want ActionSkip", inv.Action)
}
if inv.Reason != "no_user_context" {
t.Errorf("Invocation reason = %q, want 'no_user_context'", inv.Reason)
}
if inv.Details["sub_reason"] != "no_session" {
t.Errorf("Invocation sub_reason = %q, want 'no_session'", inv.Details["sub_reason"])
}
}
// Classification gate: when any populated extension reports IsAction=
// false (parser said "this is protocol mechanics"), IBAC skips with
// reason "protocol_mechanics" before the intent check or the judge.
// The actual MCP-method classification logic lives in mcp-parser; see
// plugins/mcpparser/plugin_test.go for the per-method coverage. This
// test exercises IBAC's reading of the verdict only.
func TestOnRequest_ClassificationBypass_ProtocolMechanics(t *testing.T) {
fj := &fakeJudge{}
p := newConfiguredIBAC(t, fj)
pctx := makePCtx(t)
pctx.Session = nil // bypass must fire before the session check
pctx.Extensions.MCP = &pipeline.MCPExtension{
Method: "tools/list", // mcp-parser would set IsAction=false (default)
}
action := invokeOnRequest(p, pctx)
if action.Type != pipeline.Continue {
t.Errorf("got %v, want Continue for protocol_mechanics", action.Type)
}
if fj.calls != 0 {
t.Errorf("judge calls = %d, want 0", fj.calls)
}
inv := lastInvocation(t, pctx)
if inv.Action != pipeline.ActionSkip {
t.Errorf("Invocation action = %v, want ActionSkip", inv.Action)
}
if inv.Reason != "protocol_mechanics" {
t.Errorf("Invocation reason = %q, want 'protocol_mechanics'", inv.Reason)
}
}
// Defense-in-depth pass-through: when no extension is populated, IBAC
// has nothing to classify and passes through silently — no Skip
// recorded, no judge invocation, just Continue. This is the difference
// between IBAC and a general gate: IBAC is a layer in defense in
// depth, only firing when a parser claims the traffic.
func TestOnRequest_NoClassification_PassesThrough(t *testing.T) {
fj := &fakeJudge{}
p := newConfiguredIBAC(t, fj)
pctx := makePCtx(t)
pctx.Extensions.MCP = nil // remove the default action classification
action := invokeOnRequest(p, pctx)
if action.Type != pipeline.Continue {
t.Errorf("got %v, want Continue (defense-in-depth pass-through)", action.Type)
}
if fj.calls != 0 {
t.Errorf("judge calls = %d, want 0 (no classification, pass through)", fj.calls)
}
// Pass-through deliberately records NO Invocation — IBAC has no
// opinion to surface, so abctl would otherwise show a phantom
// "ibac: continue" row on every unrelated request.
if pctx.Extensions.Invocations != nil &&
(len(pctx.Extensions.Invocations.Inbound)+len(pctx.Extensions.Invocations.Outbound)) > 0 {
t.Errorf("expected no invocations on pass-through; got %+v", pctx.Extensions.Invocations)
}
}
// Opt-in coverage of unclassified traffic via unclassified_policy:
// "judge". The IBAC demo's plain-HTTP exfiltration scenario relies on
// this branch — without it, raw http.Post outbound from a local
// function-calling tool would pass through silently because no parser
// claims it.
func TestOnRequest_UnclassifiedPolicy_Judge(t *testing.T) {
fj := &fakeJudge{verdict: "deny", reason: "unrelated to user intent"}
p := NewIBAC()
cfg := `{"judge_endpoint":"http://j","judge_model":"m","unclassified_policy":"judge"}`
if err := p.Configure(json.RawMessage(cfg)); err != nil {
t.Fatalf("Configure: %v", err)
}
p.judge = fj
pctx := makePCtx(t)
pctx.Extensions.MCP = nil // unclassified — no parser populated anything
pctx.Method = "POST"
pctx.Host = "evil-server.example.com"
pctx.Path = "/collect"
pctx.Body = []byte(`{"exfil":"data"}`)
action := invokeOnRequest(p, pctx)
if action.Type != pipeline.Reject {
t.Errorf("got %v, want Reject (unclassified_policy=judge must reach the judge and apply its verdict)", action.Type)
}
if fj.calls != 1 {
t.Errorf("judge calls = %d, want 1 (unclassified must reach judge under policy=judge)", fj.calls)
}
inv := lastInvocation(t, pctx)
if inv.Reason != "blocked" {
t.Errorf("Invocation reason = %q, want 'blocked'", inv.Reason)
}
}
// Configure-time validation of unclassified_policy.
func TestConfigure_UnclassifiedPolicy_DefaultsToPassthrough(t *testing.T) {
p := NewIBAC()
if err := p.Configure(json.RawMessage(`{"judge_endpoint":"http://j","judge_model":"m"}`)); err != nil {
t.Fatalf("Configure: %v", err)
}
if p.cfg.UnclassifiedPolicy != UnclassifiedPolicyPassthrough {
t.Errorf("default UnclassifiedPolicy = %q, want %q",
p.cfg.UnclassifiedPolicy, UnclassifiedPolicyPassthrough)
}
}
func TestConfigure_UnclassifiedPolicy_RejectsUnknownValue(t *testing.T) {
p := NewIBAC()
cfg := `{"judge_endpoint":"http://j","judge_model":"m","unclassified_policy":"maybe"}`
err := p.Configure(json.RawMessage(cfg))
if err == nil {
t.Fatal("expected error for unknown unclassified_policy value")
}
if !strings.Contains(err.Error(), "unclassified_policy") {
t.Errorf("error should mention unclassified_policy; got %q", err.Error())
}
}
func TestConfigure_UnclassifiedPolicy_AcceptsExplicitValues(t *testing.T) {
for _, v := range []string{"passthrough", "judge"} {
t.Run(v, func(t *testing.T) {
p := NewIBAC()
cfg := fmt.Sprintf(`{"judge_endpoint":"http://j","judge_model":"m","unclassified_policy":%q}`, v)
if err := p.Configure(json.RawMessage(cfg)); err != nil {
t.Fatalf("Configure(%q): %v", v, err)
}
if p.cfg.UnclassifiedPolicy != v {
t.Errorf("UnclassifiedPolicy = %q, want %q", p.cfg.UnclassifiedPolicy, v)
}
})
}
}
// MCP tools/call (an action method per mcp-parser's classification) is
// passed through to the judge. The test mirrors what mcp-parser would
// do: populate MCPExtension with IsAction=true.
func TestOnRequest_MCPActionReachesJudge(t *testing.T) {
fj := &fakeJudge{verdict: "allow"}
p := newConfiguredIBAC(t, fj)
pctx := makePCtx(t)
pctx.Method = "POST"
pctx.Host = "user-tool"
pctx.Path = "/mcp"
pctx.Extensions.MCP = &pipeline.MCPExtension{
Method: "tools/call",
Params: map[string]any{"name": "delete_user"},
IsAction: true,
}
_ = invokeOnRequest(p, pctx)
if fj.calls != 1 {
t.Errorf("judge calls = %d, want 1 (action-classified MCP must reach judge)", fj.calls)
}
}
// MCP Streamable HTTP session termination: mcp-parser detects the
// body-less DELETE + Mcp-Session-Id pattern and emits a synthetic
// $transport/terminate extension with IsAction=false. IBAC's
// classification gate must read that verdict and skip with reason
// "protocol_mechanics" before the intent check or the judge.
// Per-method parser coverage lives in plugins/mcpparser/plugin_test.go;
// this test exercises the IBAC integration boundary only.
func TestOnRequest_TransportStream_MCPSessionTerminate(t *testing.T) {
fj := &fakeJudge{}
p := newConfiguredIBAC(t, fj)
pctx := makePCtx(t)
pctx.Session = nil
pctx.Method = "DELETE"
pctx.Host = "exgentic-mcp-gsm8k-mcp:8000"
pctx.Path = "/mcp"
pctx.Body = nil
pctx.Headers.Set("Mcp-Session-Id", "abc-123")
pctx.Extensions.MCP = &pipeline.MCPExtension{
Method: "$transport/terminate", // mcp-parser sets IsAction=false (default)
}
action := invokeOnRequest(p, pctx)
if action.Type != pipeline.Continue {
t.Errorf("got %v, want Continue for MCP session terminate", action.Type)
}
if fj.calls != 0 {
t.Errorf("judge calls = %d, want 0 (session terminate must not reach judge)", fj.calls)
}
inv := lastInvocation(t, pctx)
if inv.Action != pipeline.ActionSkip {
t.Errorf("Invocation action = %v, want ActionSkip", inv.Action)
}
if inv.Reason != "protocol_mechanics" {
t.Errorf("Invocation reason = %q, want 'protocol_mechanics'", inv.Reason)
}
}
// Body-less DELETE WITHOUT the Mcp-Session-Id header must still be
// judged. A real "delete this resource" call (e.g. DELETE /api/
// users/42) carries no MCP session header and is exactly the kind
// of side-effect action IBAC exists to evaluate. The header is the
// load-bearing distinguisher between transport cleanup and a user-
// meaningful delete.
func TestOnRequest_TransportStream_BodylessDELETEWithoutHeaderIsJudged(t *testing.T) {
fj := &fakeJudge{verdict: "allow"}
p := newConfiguredIBAC(t, fj)
pctx := makePCtx(t)
pctx.Method = "DELETE"
pctx.Host = "api.example.com"
pctx.Path = "/api/users/42"
pctx.Body = nil
// no Mcp-Session-Id header
_ = invokeOnRequest(p, pctx)
if fj.calls != 1 {
t.Errorf("judge calls = %d, want 1 (real DELETE without MCP header must be judged)", fj.calls)
}
}
// DELETE + Mcp-Session-Id header + non-empty body must still be
// judged. The header alone isn't sufficient — the body-first guard
// in isTransportShaped is what keeps an attacker (or a misbehaving
// SDK) from smuggling action payload through what looks like
// transport cleanup. Locks in the same "header + body → not
// bypassed" invariant that body-having GETs already cover.
func TestOnRequest_TransportStream_MCPSessionTerminate_WithBodyIsJudged(t *testing.T) {
fj := &fakeJudge{verdict: "allow"}
p := newConfiguredIBAC(t, fj)
pctx := makePCtx(t)
pctx.Method = "DELETE"
pctx.Host = "exgentic-mcp-gsm8k-mcp:8000"
pctx.Path = "/mcp"
pctx.Body = []byte(`{"unexpected":"payload"}`)
pctx.Headers.Set("Mcp-Session-Id", "abc-123")
_ = invokeOnRequest(p, pctx)
if fj.calls != 1 {
t.Errorf("judge calls = %d, want 1 (DELETE+Mcp-Session-Id with body must be judged, not bypassed)", fj.calls)
}
}
// describeAction's first non-empty token must be the HTTP method, with
// no leading whitespace. This locks in the listener-side pctx.Method
// wiring contract: if any listener regresses to leaving Method empty,
// describeAction renders " http://..." (note the leading space) and
// the judge sees a malformed prompt while operators see a confusing
// session-event display. The visible-symptom test catches that here
// rather than relying on the listener-package tests alone.
func TestOnRequest_DescribeActionHasNoLeadingWhitespace(t *testing.T) {
fj := &fakeJudge{verdict: "allow"}
p := newConfiguredIBAC(t, fj)
pctx := makePCtx(t) // POST + body, will be judged
_ = invokeOnRequest(p, pctx)
if fj.calls != 1 {
t.Fatalf("expected judge to be called once; got calls=%d", fj.calls)
}
if fj.gotAction == "" {
t.Fatal("describeAction was empty; cannot assert format")
}
if first := fj.gotAction[0]; first == ' ' || first == '\t' || first == '\n' {
t.Errorf("describeAction starts with whitespace (listener Method regression?); got %q", fj.gotAction)
}
if !strings.HasPrefix(fj.gotAction, "POST ") {
t.Errorf("describeAction should start with 'POST '; got %q", fj.gotAction)
}
}
// Email-poison parity: this is the canonical case the plugin exists
// for. Raw HTTP exfiltration to an unknown server, no MCP/Inference
// extensions, judge denies → 403. This test is the contract that
// ports the original huang195/ibac demo's threat model.
func TestOnRequest_EmailPoisonParity(t *testing.T) {
fj := &fakeJudge{
verdict: "deny",
reason: "POSTing to unknown server is unrelated to summarize emails",
}
p := newConfiguredIBAC(t, fj)
pctx := makePCtx(t)
pctx.Method = "POST"
pctx.Host = "evil-server.ibac.svc.cluster.local:9999"
pctx.Path = "/collect?code=X7B-92K&budget=2.4M"
pctx.Body = []byte("x")
action := invokeOnRequest(p, pctx)
if action.Type != pipeline.Reject {
t.Fatalf("got %v, want Reject (email-poison must be blocked)", action.Type)
}
// The judge must have seen the bare HTTP request line — without
// MCP enrichment, this is all the plugin has to work with.
if !strings.Contains(fj.gotAction, "POST http://evil-server.ibac.svc.cluster.local:9999/collect?code=X7B-92K&budget=2.4M") {
t.Errorf("action description missing raw HTTP line; got %q", fj.gotAction)
}
if !strings.Contains(fj.gotIntent, "summarize my emails") {
t.Errorf("intent not extracted from session; got %q", fj.gotIntent)
}
inv := lastInvocation(t, pctx)
if inv.Reason != "blocked" {
t.Errorf("reason = %q, want 'blocked'", inv.Reason)
}
if inv.Details["llm_reason"] != fj.reason {
t.Errorf("llm_reason = %q, want %q", inv.Details["llm_reason"], fj.reason)
}
if !strings.Contains(inv.Details["intent_preview"], "summarize my emails") {
t.Errorf("intent_preview = %q, want it to contain the intent", inv.Details["intent_preview"])
}
}
// MCP enrichment: when mcp-parser ran first, the action description
// includes the parsed tool name and args.
func TestOnRequest_MCPEnrichment(t *testing.T) {
fj := &fakeJudge{verdict: "deny", reason: "delete_user is unrelated"}
p := newConfiguredIBAC(t, fj)
pctx := makePCtx(t)
pctx.Method = "POST"
pctx.Host = "user-tool"
pctx.Path = "/mcp"
pctx.Extensions.MCP = &pipeline.MCPExtension{
Method: "tools/call",
IsAction: true,
Params: map[string]any{
"name": "delete_user",
"arguments": map[string]any{"user_id": "alice"},
},
}
action := invokeOnRequest(p, pctx)
if action.Type != pipeline.Reject {
t.Fatalf("got %v, want Reject", action.Type)
}
if !strings.Contains(fj.gotAction, "MCP_TOOL: delete_user") {
t.Errorf("action did not include MCP_TOOL; got %q", fj.gotAction)
}
if !strings.Contains(fj.gotAction, "alice") {
t.Errorf("action did not include MCP args; got %q", fj.gotAction)
}
}
// Plain HTTP path with no parsers — should still be judged. The bare
// METHOD scheme://host/path line is what the judge gets.
func TestOnRequest_PlainHTTPNoParsers(t *testing.T) {
fj := &fakeJudge{verdict: "allow", reason: "weather lookup is fine"}
p := newConfiguredIBAC(t, fj)
pctx := makePCtx(t)
pctx.Method = "GET"
pctx.Host = "api.weather.com"
pctx.Path = "/v1/forecast?city=Boston"
action := invokeOnRequest(p, pctx)
if action.Type != pipeline.Continue {
t.Errorf("got %v, want Continue", action.Type)
}
if fj.calls != 1 {
t.Fatalf("judge calls = %d, want 1", fj.calls)
}
if !strings.Contains(fj.gotAction, "GET http://api.weather.com/v1/forecast?city=Boston") {
t.Errorf("action description = %q, want bare HTTP line", fj.gotAction)
}
}
// Authorization values must NEVER reach the judge LLM — bearer tokens
// in a judge prompt are a credential exposure risk via judge logs /
// upstream LLM provider retention.
func TestOnRequest_AuthorizationHeaderNotInActionDescription(t *testing.T) {
fj := &fakeJudge{verdict: "allow", reason: "ok"}
p := newConfiguredIBAC(t, fj)
pctx := makePCtx(t)
pctx.Headers.Set("Authorization", "Bearer SUPER-SECRET-TOKEN-VALUE")
pctx.Headers.Set("Cookie", "session=SECRET-COOKIE-VALUE")
invokeOnRequest(p, pctx)
if strings.Contains(fj.gotAction, "SUPER-SECRET") {
t.Errorf("judge prompt leaked Authorization value: %q", fj.gotAction)
}
if strings.Contains(fj.gotAction, "SECRET-COOKIE") {
t.Errorf("judge prompt leaked Cookie value: %q", fj.gotAction)
}
}
// Judge errors fail closed: 503 not 403, since it's an availability
// issue not a policy denial. Operators distinguish "judge is down"
// from "request was actually bad" via the status code.
func TestOnRequest_JudgeError_503(t *testing.T) {
fj := &fakeJudge{err: errors.New("connection refused")}
p := newConfiguredIBAC(t, fj)
pctx := makePCtx(t)
action := invokeOnRequest(p, pctx)
if action.Type != pipeline.Reject {
t.Fatalf("got %v, want Reject on judge error", action.Type)
}
if action.Violation.Status != 503 {
t.Errorf("RejectStatus = %d, want 503 (judge errors are availability issues, not policy denials)",
action.Violation.Status)
}
inv := lastInvocation(t, pctx)
if inv.Reason != "judge_unavailable" {
t.Errorf("reason = %q, want 'judge_unavailable'", inv.Reason)
}
}
// Judge "uncertain" errors (parse / unrecognized verdict) fail closed
// with a DIFFERENT code: 403 ibac.judge_uncertain rather than 503
// ibac.judge_unavailable. The judge IS up — it just emitted output
// we can't act on. Routing this through "unavailable" would inflate
// the "judge down" metric on every model misbehavior.
func TestOnRequest_JudgeUncertain_403(t *testing.T) {
fj := &fakeJudge{err: fmt.Errorf("%w: model emitted gibberish", ErrJudgeUncertain)}
p := newConfiguredIBAC(t, fj)
pctx := makePCtx(t)
action := invokeOnRequest(p, pctx)
if action.Type != pipeline.Reject {
t.Fatalf("got %v, want Reject on judge_uncertain", action.Type)
}
if action.Violation.Status != 403 {
t.Errorf("Violation.Status = %d, want 403 (uncertain judge output is a fail-closed deny, not infra outage)",
action.Violation.Status)
}
inv := lastInvocation(t, pctx)
if inv.Reason != "judge_uncertain" {
t.Errorf("reason = %q, want 'judge_uncertain'", inv.Reason)
}
}
func TestOnRequest_AllowVerdict(t *testing.T) {
fj := &fakeJudge{verdict: "allow", reason: "looks fine"}
p := newConfiguredIBAC(t, fj)
pctx := makePCtx(t)
action := invokeOnRequest(p, pctx)
if action.Type != pipeline.Continue {
t.Errorf("got %v, want Continue on allow", action.Type)
}
inv := lastInvocation(t, pctx)
if inv.Action != pipeline.ActionAllow {
t.Errorf("Invocation.Action = %q, want allow", inv.Action)
}
if inv.Details["llm_reason"] != "looks fine" {
t.Errorf("llm_reason = %q, want 'looks fine'", inv.Details["llm_reason"])
}
}
func TestOnRequest_DenyVerdict(t *testing.T) {
fj := &fakeJudge{verdict: "deny", reason: "off-policy"}
p := newConfiguredIBAC(t, fj)
pctx := makePCtx(t)
action := invokeOnRequest(p, pctx)
if action.Type != pipeline.Reject {
t.Fatalf("got %v, want Reject on deny verdict", action.Type)
}
if action.Violation.Status != 403 {
t.Errorf("RejectStatus = %d, want 403 on policy deny", action.Violation.Status)
}
}
// Unconfigured plugin returns 503 — Configure must run before traffic.
func TestOnRequest_Unconfigured(t *testing.T) {
p := NewIBAC()
pctx := &pipeline.Context{Headers: http.Header{}}
action := invokeOnRequest(p, pctx)
if action.Type != pipeline.Reject {
t.Errorf("got %v, want Reject for unconfigured plugin", action.Type)
}
}
// --- helpers ---
// lastInvocation returns the most recent Invocation pushed onto the
// outbound side of pctx (IBAC always runs outbound).
func lastInvocation(t *testing.T, pctx *pipeline.Context) pipeline.Invocation {
t.Helper()
if pctx.Extensions.Invocations == nil || len(pctx.Extensions.Invocations.Outbound) == 0 {
t.Fatalf("expected at least one outbound Invocation; got %+v", pctx.Extensions.Invocations)
}
out := pctx.Extensions.Invocations.Outbound
return out[len(out)-1]
}