~bigbes/sr-ht-spec

ref: 9cec0f542b65dc63883514cd54dc664f8c00157c sr-ht-spec/mcpsrv/gate_test.go -rw-r--r-- 2.3 KiB
9cec0f54 — Eugene Blikh deps: tidy after the third uplift 9 days ago
                                                                                
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
package mcpsrv_test

import (
	"net/http"
	"net/http/httptest"
	"testing"

	"github.com/stretchr/testify/require"

	"sourcecraft.dev/bigbes/sr-ht-spec/authn"
	"sourcecraft.dev/bigbes/sr-ht-spec/mcpsrv"
)

// The read plane is fail-closed: only the owner and its agents may reach the MCP
// tools. Before this gate the three read tools (spec_search/spec_read/spec_list)
// served approved content to anyone who cleared the Host allowlist — spec_propose
// was already fail-closed in service.Propose, but the reads checked nothing. The
// gate applies the owner+agents ACL to the whole surface, the same policy graph's
// /query and the web UI apply.
func TestGate(t *testing.T) {
	cases := []struct {
		name      string
		principal authn.Principal
		wantCode  int
		wantNext  bool
	}{
		{"anonymous is refused", authn.Anonymous(), http.StatusUnauthorized, false},
		{"owner may read", authn.Principal{Kind: authn.KindOwner}, http.StatusOK, true},
		{"agent may read", authn.Principal{Kind: authn.KindAgent}, http.StatusOK, true},
	}

	for _, tc := range cases {
		t.Run(tc.name, func(t *testing.T) {
			var reached bool
			next := http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
				reached = true
				w.WriteHeader(http.StatusOK)
			})

			req := httptest.NewRequest(http.MethodPost, "/mcp", nil)
			req = req.WithContext(authn.WithPrincipal(req.Context(), tc.principal))
			rec := httptest.NewRecorder()

			mcpsrv.Gate(next).ServeHTTP(rec, req)

			require.Equal(t, tc.wantCode, rec.Code)
			require.Equal(t, tc.wantNext, reached,
				"a refused caller must never reach the MCP server")
		})
	}
}

// A request that never went through the resolver middleware has no principal in
// its context — the zero value, which is anonymous. The gate must fail that
// closed, not open, so a wiring mistake that drops the middleware denies reads
// rather than serving the whole corpus unauthenticated.
func TestGateFailsClosedWithoutMiddleware(t *testing.T) {
	var reached bool
	next := http.HandlerFunc(func(http.ResponseWriter, *http.Request) { reached = true })

	req := httptest.NewRequest(http.MethodPost, "/mcp", nil)
	rec := httptest.NewRecorder()

	mcpsrv.Gate(next).ServeHTTP(rec, req)

	require.Equal(t, http.StatusUnauthorized, rec.Code)
	require.False(t, reached, "no principal in context must deny, not admit")
}