返回 DeepSeek-Reasonix
url_test.go
根目录 / internal / mcpinteraction / url_test.go
1 package mcpinteraction
2
3 import (
4 "context"
5 "encoding/json"
6 "testing"
7 )
8
9 func TestAllowedURLModes(t *testing.T) {
10 cases := []struct {
11 raw string
12 want bool
13 }{
14 {"https://example.com/oauth", true},
15 {"http://localhost:8931/callback", true},
16 {"https://example.com/cb?state=xyz", true},
17 {"", false},
18 {"file:///etc/passwd", false},
19 {"javascript:alert(1)", false},
20 {"ftp://example.com/x", false},
21 {"https://user:pass@example.com/", false},
22 {"https://example.com/cb?password=secret", false},
23 {"not a url", false},
24 {"https://", false},
25 }
26 for _, tc := range cases {
27 if got := allowedURL(tc.raw); got != tc.want {
28 t.Errorf("allowedURL(%q) = %v, want %v", tc.raw, got, tc.want)
29 }
30 }
31 }
32
33 func TestSanitizeURLModeIgnoresFormMode(t *testing.T) {
34 req := Request{Mode: ModeForm, Message: "fill this"}
35 if !SanitizeURLMode(req) {
36 t.Fatal("form mode must not be URL-gated")
37 }
38 req = Request{Mode: ModeURL, URL: "javascript:alert(1)"}
39 if SanitizeURLMode(req) {
40 t.Fatal("dangerous url mode must be refused")
41 }
42 }
43
44 type recordingBroker struct {
45 got Request
46 res Result
47 }
48
49 func (b *recordingBroker) Interact(_ context.Context, req Request) (Result, error) {
50 b.got = req
51 return b.res, nil
52 }
53
54 func TestBrokerContextRoundTrip(t *testing.T) {
55 broker := &recordingBroker{res: Result{Action: ActionAccept, Content: map[string]any{"q": "a"}}}
56 ctx := WithBroker(context.Background(), broker)
57 got := FromContext(ctx)
58 if got == nil {
59 t.Fatal("broker not retrievable from context")
60 }
61 schema, _ := json.Marshal(map[string]any{"type": "object"})
62 res, err := got.Interact(ctx, Request{ID: "1", Server: "srv", Mode: ModeForm, RequestedSchema: schema})
63 if err != nil {
64 t.Fatal(err)
65 }
66 if res.Action != ActionAccept || res.Content["q"] != "a" {
67 t.Fatalf("result = %+v", res)
68 }
69 if broker.got.ID != "1" || broker.got.Server != "srv" {
70 t.Fatalf("request = %+v", broker.got)
71 }
72 if FromContext(context.Background()) != nil {
73 t.Fatal("empty context must resolve to nil broker")
74 }
75 //nolint:staticcheck
76 if FromContext(nil) != nil {
77 t.Fatal("nil context must resolve to nil broker")
78 }
79 }
80
80 lines GO