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")
}