From 2b5ac946354101773dae74ac01092a0d9b158c65 Mon Sep 17 00:00:00 2001 From: Algis Dumbris Date: Tue, 1 Sep 2026 16:05:01 +0300 Subject: [PATCH] fix(security): close the per-user door's remaining shared-server leaks (#1161) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Issue #1161 was fixed for the three handlers it named (listServers, getServer, enableServer, commit ad22f08e2). This closes the rest of the same class on the same trust boundary. The server edition's whole per-user surface leans on ONE entitlement predicate — `sc.Shared` — because setup.go hands every handler `deps.Config.Servers`, the admin's WHOLE server list, under the name `sharedServers`. Two sibling handlers on that door never applied it: - getDiagnostics iterated the list unfiltered and labelled every entry `ownership:"shared"`, so any authenticated user learned the name, transport and enablement of admin upstreams the admin did not share. - The credential surfaces selected on `AuthBroker != nil` alone. A non-shared brokered upstream was therefore enumerable AND its per-user OAuth connect flow drivable: following the connect path ran the gateway's flow against the admin's registered client and persisted a per-user credential for a server the caller was never granted. They now select through one shared `brokerEntitled` predicate. Shared servers now mask under AuditRedaction rather than LiveRedaction. `•••• ( chars)` is an affordance for someone editing their OWN credential; the reader of a shared server is a different tenant who cannot edit it at all (updateServer and deleteServer answer 403, enableServer stores only a per-user preference), so it bought them nothing while publishing the admin credential's exact length and trailing bytes to every user of the deployment. RedactServerConfigSecrets takes the policy as a parameter. getServer's shared branch rendered the caller's own preference as unset, so the detail read disagreed with listServers and with the .../enable response. It now threads the stored preference. Tests: the fail-closed route walk now covers the WHOLE `/user/` prefix and is driven by RegisterRoutesWithPrefix — the form production actually wires — rather than `/user/servers` on a router only assembled from UserHandlers, which is why neither leaking sibling was reachable by it. It asserts both halves: no shared credential is echoed, and an unentitled upstream answers exactly as an absent one (no existence oracle). A parity test pins the two hand-maintained route tables against each other. CI: `./internal/oauth/...` now runs under `-tags server`. The mask decisions for the `auth_broker` block live behind that tag, so the canary enforcing "every text-carrying leaf has a decision" — the guarantee this whole fix rests on — never compiled in CI. The fourth leak this branch originally carried — GET /api/v1/config serving the raw config to any agent-token caller — landed independently in #1164 (round 9), with a stronger fix: masked for everyone by default with a matching write-path unmask twin (oauth.UnmaskLiveConfigTree), rather than gated on caller identity. That work supersedes this branch's version, which is dropped here along with its now-redundant test. --- .github/workflows/release-qa-gate.yml | 2 +- .github/workflows/unit-tests.yml | 10 +- internal/oauth/serverconfigfields.go | 16 +- internal/oauth/serverconfigfields_test.go | 12 +- .../serveredition/api/credential_handlers.go | 21 +- .../api/shared_entitlement_test.go | 352 ++++++++++++++++++ internal/serveredition/api/user_activity.go | 9 + internal/serveredition/api/user_handlers.go | 37 +- 8 files changed, 440 insertions(+), 19 deletions(-) create mode 100644 internal/serveredition/api/shared_entitlement_test.go diff --git a/.github/workflows/release-qa-gate.yml b/.github/workflows/release-qa-gate.yml index d654cf757..fb0427ea2 100644 --- a/.github/workflows/release-qa-gate.yml +++ b/.github/workflows/release-qa-gate.yml @@ -234,7 +234,7 @@ jobs: run: | ./dist-bin/release-gate run-suite \ --name suite/server-race --report-dir "${GATE_REPORT_DIR}" \ - -- go test -tags server -race ./internal/serveredition/... + -- go test -tags server -race ./internal/serveredition/... ./internal/oauth/... - name: Upload report fragment if: always() diff --git a/.github/workflows/unit-tests.yml b/.github/workflows/unit-tests.yml index 0b3c9b394..30057bf22 100644 --- a/.github/workflows/unit-tests.yml +++ b/.github/workflows/unit-tests.yml @@ -243,8 +243,16 @@ jobs: - name: Build server edition run: go build -tags server ./cmd/mcpproxy + # internal/oauth is where the redaction rules live, and half of them are + # build-tagged: serverfields_serveredition.go holds the mask decisions for + # the `auth_broker` block, whose fields do not exist in the personal + # edition. Its canaries — the walk over config.ServerConfig that fails + # when a text-carrying leaf has no decision — therefore only compile under + # `-tags server`. Without this package in the list they never ran, and the + # guarantee the #1161 fix rests on (a field added to the tagged block is + # masked because the walk reaches it) was unenforced in CI. - name: Test server edition packages - run: go test -race -tags server ./internal/serveredition/... ./internal/config/... + run: go test -race -tags server ./internal/serveredition/... ./internal/config/... ./internal/oauth/... build: name: Build diff --git a/internal/oauth/serverconfigfields.go b/internal/oauth/serverconfigfields.go index 66551f009..94a6b254f 100644 --- a/internal/oauth/serverconfigfields.go +++ b/internal/oauth/serverconfigfields.go @@ -79,10 +79,20 @@ func RedactedServerConfigViews(servers []*config.ServerConfig, r Redaction) []ma return out } -// RedactServerConfigSecrets returns a masked COPY of sc under the LIVE policy, +// RedactServerConfigSecrets returns a masked COPY of sc under the given policy, // for a door that must hand back a *config.ServerConfig rather than a map (the // server edition's ServerResponse embeds one). // +// The policy is a PARAMETER because the choice is the caller's and it is not +// obvious. Pass LiveRedaction on a surface whose reader owns the credential and +// may edit it — MaskValue's `•••• ( chars)` says which token is +// configured and the write-path unmaskers recognise it. Pass AuditRedaction +// wherever the reader is NOT the owner: for a server edition shared server the +// affordance buys that reader nothing (shared servers are read-only to users) +// while publishing the admin credential's exact length and trailing bytes to +// every tenant of the deployment — a durable fingerprint and a correlation +// handle, which is the case AuditMaskValue was written for. +// // The input is never mutated and the result shares no map, slice or pointer // with it: the masked view is decoded into a FRESH struct. That matters because // the caller's config is typically the LIVE one — `h.sharedServers` is the @@ -96,11 +106,11 @@ func RedactedServerConfigViews(servers []*config.ServerConfig, r Redaction) []ma // unredacted credential is this issue. // // Returns nil for a nil config. -func RedactServerConfigSecrets(sc *config.ServerConfig) *config.ServerConfig { +func RedactServerConfigSecrets(sc *config.ServerConfig, r Redaction) *config.ServerConfig { if sc == nil { return nil } - view := RedactedServerConfigView(sc, LiveRedaction) + view := RedactedServerConfigView(sc, r) encoded, err := json.Marshal(view) if err != nil { return &config.ServerConfig{Name: sc.Name} diff --git a/internal/oauth/serverconfigfields_test.go b/internal/oauth/serverconfigfields_test.go index 1dec03d61..206559ec6 100644 --- a/internal/oauth/serverconfigfields_test.go +++ b/internal/oauth/serverconfigfields_test.go @@ -26,7 +26,7 @@ func TestRedactServerConfigSecrets_MasksEverySecretBearingLeaf(t *testing.T) { sc := &config.ServerConfig{} fillTextLeaves(reflect.ValueOf(sc).Elem(), ghpToken) - masked := RedactServerConfigSecrets(sc) + masked := RedactServerConfigSecrets(sc, LiveRedaction) require.NotNil(t, masked) for _, path := range findTokenPaths(t, masked, ghpToken) { @@ -42,7 +42,7 @@ func TestRedactServerConfigSecrets_MasksEverySecretBearingLeaf(t *testing.T) { func TestRedactServerConfigSecrets_MasksTheNamedShapes(t *testing.T) { sc := secretBearingServerConfig() - masked := RedactServerConfigSecrets(sc) + masked := RedactServerConfigSecrets(sc, LiveRedaction) require.NotNil(t, masked) assert.NotContains(t, masked.Headers["Authorization"], "hdrsecretvalue") @@ -73,7 +73,7 @@ func TestRedactServerConfigSecrets_LeavesTheInputUntouched(t *testing.T) { sc := secretBearingServerConfig() pristine := secretBearingServerConfig() - masked := RedactServerConfigSecrets(sc) + masked := RedactServerConfigSecrets(sc, LiveRedaction) require.NotNil(t, masked) assert.Equal(t, pristine, sc, "redacting a read payload mutated the config it was built from") @@ -120,7 +120,7 @@ func TestRedactServerConfigSecrets_PreservesNonSecretFields(t *testing.T) { SourceRegistryProvenance: "official", } - masked := RedactServerConfigSecrets(sc) + masked := RedactServerConfigSecrets(sc, LiveRedaction) require.NotNil(t, masked) assert.Equal(t, sc.Name, masked.Name) @@ -151,7 +151,7 @@ func TestRedactServerConfigSecrets_PreservesNonSecretFields(t *testing.T) { } func TestRedactServerConfigSecrets_NilIsNil(t *testing.T) { - assert.Nil(t, RedactServerConfigSecrets(nil)) + assert.Nil(t, RedactServerConfigSecrets(nil, LiveRedaction)) assert.Nil(t, RedactedServerConfigView(nil, LiveRedaction)) } @@ -162,7 +162,7 @@ func TestRedactServerConfigSecrets_AgreesWithTheMapView(t *testing.T) { sc := secretBearingServerConfig() view := RedactedServerConfigView(sc, LiveRedaction) - typed := RedactServerConfigSecrets(sc) + typed := RedactServerConfigSecrets(sc, LiveRedaction) require.NotNil(t, typed) assert.Equal(t, view, NormalizeForRedaction(typed), diff --git a/internal/serveredition/api/credential_handlers.go b/internal/serveredition/api/credential_handlers.go index 6605e986f..5d8f43a0c 100644 --- a/internal/serveredition/api/credential_handlers.go +++ b/internal/serveredition/api/credential_handlers.go @@ -323,11 +323,28 @@ func (h *CredentialHandlers) lookupServer(w http.ResponseWriter, r *http.Request return srv, true } +// brokerEntitled reports whether a per-user credential surface may act on this +// upstream at all. +// +// `Shared` is the ENTITLEMENT check (issue #1161 follow-up), not a formality: +// setup.go hands these handlers `deps.Config.Servers` — the admin's WHOLE +// server list — under the name `sharedServers`. Selecting on `AuthBroker != nil` +// alone therefore reached admin upstreams the admin deliberately did not share, +// disclosing their existence and broker mode through the list, and letting any +// authenticated user drive the connect flow against the admin's registered +// OAuth client for a server they were never granted. +// +// Every credential surface selects through this one predicate so a new one +// cannot reintroduce the gap by copying the old two-thirds of the condition. +func brokerEntitled(s *config.ServerConfig) bool { + return s != nil && s.Shared && s.AuthBroker != nil +} + // brokerServerList returns the shared servers that carry an auth_broker block. func (h *CredentialHandlers) brokerServerList() []*config.ServerConfig { out := make([]*config.ServerConfig, 0, len(h.brokerServers)) for _, s := range h.brokerServers { - if s != nil && s.AuthBroker != nil { + if brokerEntitled(s) { out = append(out, s) } } @@ -337,7 +354,7 @@ func (h *CredentialHandlers) brokerServerList() []*config.ServerConfig { // brokerServerByName finds a brokered upstream by case-insensitive name. func (h *CredentialHandlers) brokerServerByName(name string) *config.ServerConfig { for _, s := range h.brokerServers { - if s != nil && s.AuthBroker != nil && strings.EqualFold(s.Name, name) { + if brokerEntitled(s) && strings.EqualFold(s.Name, name) { return s } } diff --git a/internal/serveredition/api/shared_entitlement_test.go b/internal/serveredition/api/shared_entitlement_test.go new file mode 100644 index 000000000..df9ed25dc --- /dev/null +++ b/internal/serveredition/api/shared_entitlement_test.go @@ -0,0 +1,352 @@ +//go:build server + +package api + +import ( + "bytes" + "encoding/json" + "net/http" + "net/http/httptest" + "sort" + "strings" + "testing" + + "github.com/go-chi/chi/v5" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/smart-mcp-proxy/mcpproxy-go/internal/auth" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/config" +) + +// Issue #1161, follow-up sweep. +// +// The fix for #1161 masked the SHARED servers on the per-user door. It relied +// throughout on one entitlement predicate — `sc.Shared` — because +// internal/serveredition/setup.go hands EVERY handler `deps.Config.Servers`, +// the admin's whole server list, under the name `sharedServers`. A handler that +// forgets the predicate does not merely leak a masked shared server: it +// discloses admin upstreams the admin deliberately did NOT share. +// +// user_handlers.go applies the predicate at all six of its loops. Two sibling +// handlers on the SAME per-user door did not: +// +// - UserActivityHandlers.getDiagnostics iterated the list unfiltered and +// labelled every entry `ownership:"shared"`; +// - CredentialHandlers selected purely on `AuthBroker != nil`, so a +// non-shared brokered upstream was enumerable AND its per-user OAuth +// connect flow was drivable by any authenticated user. +// +// These tests pin the predicate at every per-user door, not just the three the +// original issue named. + +// unsharedAdminServer is an admin-configured upstream that is explicitly NOT +// shared. No per-user surface may name it. +func unsharedAdminServer() *config.ServerConfig { + return &config.ServerConfig{ + Name: "prod-payments-admin", + URL: "https://payments.internal/mcp", + Protocol: "http", + Enabled: true, + Shared: false, + } +} + +// unsharedBrokeredAdminServer is a non-shared admin upstream that carries an +// auth_broker block in the connect-flow mode — the shape the credential +// surfaces select on. +func unsharedBrokeredAdminServer() *config.ServerConfig { + srv := brokerHTTPServer("internal-hr", config.AuthBrokerModeOAuthConnect) + srv.Shared = false + return srv +} + +func TestGetDiagnostics_OmitsUnsharedAdminServers(t *testing.T) { + admin := []*config.ServerConfig{ + defaultSharedServers()[0], // shared: must be listed + unsharedAdminServer(), // not shared: must not be + } + handlers, _ := activityTestSetup(t, nil, admin) + router := activityTestRouter(handlers, defaultAuthContext()) + + req := httptest.NewRequest(http.MethodGet, "/api/v1/user/diagnostics", nil) + w := httptest.NewRecorder() + router.ServeHTTP(w, req) + + require.Equal(t, http.StatusOK, w.Code) + assert.NotContains(t, w.Body.String(), "prod-payments-admin", + "diagnostics disclosed an admin upstream that was never shared") + + var resp DiagnosticsResponse + require.NoError(t, json.Unmarshal(w.Body.Bytes(), &resp)) + require.Len(t, resp.Servers, 1, "only the shared server belongs on a per-user surface") + assert.Equal(t, "shared-github", resp.Servers[0].Name) +} + +func TestCredentialsList_OmitsUnsharedAdminServers(t *testing.T) { + shared := brokerHTTPServer("shared-gh", config.AuthBrokerModeOAuthConnect) + handlers := NewCredentialHandlers( + credTestStore(t), + []*config.ServerConfig{shared, unsharedBrokeredAdminServer()}, + nil, nil, + ) + router := credRouter(handlers, defaultAuthContext()) + + req := httptest.NewRequest(http.MethodGet, "/api/v1/user/credentials", nil) + w := httptest.NewRecorder() + router.ServeHTTP(w, req) + + require.Equal(t, http.StatusOK, w.Code) + assert.NotContains(t, w.Body.String(), "internal-hr", + "the credential list disclosed a brokered upstream that was never shared") + + var resp CredentialListResponse + require.NoError(t, json.Unmarshal(w.Body.Bytes(), &resp)) + require.Len(t, resp.Credentials, 1) + assert.Equal(t, "shared-gh", resp.Credentials[0].Server) +} + +// The connect flow is the ACTIONABLE half of the same omission: reaching it for +// an unentitled upstream drives the gateway's OAuth flow against the admin's +// registered client and persists a per-user credential for a server the caller +// was never granted. Disconnect and callback select through the same lookup. +func TestCredentialRoutes_RejectUnsharedAdminServer(t *testing.T) { + handlers := NewCredentialHandlers( + credTestStore(t), + []*config.ServerConfig{unsharedBrokeredAdminServer()}, + nil, nil, + ) + router := credRouter(handlers, defaultAuthContext()) + + for _, tc := range []struct { + method string + target string + }{ + {http.MethodGet, "/api/v1/user/credentials/internal-hr/connect"}, + {http.MethodGet, "/api/v1/user/credentials/internal-hr/callback"}, + {http.MethodDelete, "/api/v1/user/credentials/internal-hr"}, + } { + req := httptest.NewRequest(tc.method, tc.target, nil) + w := httptest.NewRecorder() + router.ServeHTTP(w, req) + + assert.Equal(t, http.StatusNotFound, w.Code, + "%s %s reached an admin upstream that was never shared", tc.method, tc.target) + } +} + +// getServer is one of the two handlers issue #1161 names. Its shared branch +// rendered the caller's preference as unset, so the detail read disagreed with +// the list read and with the enable response — a user who had disabled a shared +// server saw the admin's `enabled` and no `user_enabled` at all. +func TestGetServer_ReportsCallersSharedServerPreference(t *testing.T) { + shared := defaultSharedServers()[:1] + handlers, store := testSetup(t, shared) + require.NoError(t, store.SetSharedServerPref(testUserID, shared[0].Name, false)) + + router := testRouter(handlers, defaultAuthContext()) + req := httptest.NewRequest(http.MethodGet, "/api/v1/user/servers/"+shared[0].Name, nil) + w := httptest.NewRecorder() + router.ServeHTTP(w, req) + + require.Equal(t, http.StatusOK, w.Code) + + var resp ServerResponse + require.NoError(t, json.Unmarshal(w.Body.Bytes(), &resp)) + assert.Equal(t, "shared", resp.Ownership) + require.NotNil(t, resp.UserEnabled, "the detail read dropped the caller's own preference") + assert.False(t, *resp.UserEnabled) +} + +// unsharedBrokerSecret is planted on the NON-shared admin upstream below, so +// the whole-door net fails distinctly on an entitlement gap (a server that must +// not be named at all) versus a redaction gap (a shared server's secret). +const unsharedBrokerSecret = "unsharedsecret_MDk4NzY1NDMyMWFi" + +// perUserDoorRouter builds the router PRODUCTION builds: all three per-user +// handler sets, registered through RegisterRoutesWithPrefix — the form +// internal/serveredition/setup.go actually calls — over one admin server list. +func perUserDoorRouter(t *testing.T, admin []*config.ServerConfig) *chi.Mux { + t.Helper() + + userHandlers, _ := testSetup(t, admin) + activityHandlers, _ := activityTestSetup(t, nil, admin) + credHandlers := NewCredentialHandlers(credTestStore(t), admin, nil, nil) + + r := chi.NewRouter() + r.Use(func(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { + ctx := auth.WithAuthContext(req.Context(), defaultAuthContext()) + next.ServeHTTP(w, req.WithContext(ctx)) + }) + }) + userHandlers.RegisterRoutesWithPrefix(r, "/api/v1") + activityHandlers.RegisterRoutesWithPrefix(r, "/api/v1") + credHandlers.RegisterRoutesWithPrefix(r, "/api/v1") + return r +} + +// The fail-closed net for the WHOLE per-user door. +// +// The #1161 fix shipped a net like this scoped to `/user/servers` and driven by +// a router assembled only from UserHandlers. Both limits mattered: the two +// routes that still leaked — /user/diagnostics and /user/credentials — are +// siblings on the same door, mounted by the same Group in setup.go, and neither +// was reachable by that walk. A hand-drawn boundary around the handlers that +// were known to leak is the shape this defect keeps taking, so this walk takes +// the whole `/user/` prefix off the PRODUCTION registration and asserts two +// things at once: no shared server's credential is echoed, and no upstream the +// admin did not share is so much as named. +func TestPerUserDoor_LeaksNoSecretAndNamesNoUnsharedServer(t *testing.T) { + unshared := unsharedBrokeredAdminServer() + unshared.Headers = map[string]string{"Authorization": "Bearer " + unsharedBrokerSecret} + admin := []*config.ServerConfig{secretBearingSharedServer(), unshared} + + router := perUserDoorRouter(t, admin) + + // A body that decodes cleanly as every request type this door accepts, so a + // route is exercised for real rather than bouncing off a 400. + body := []byte(`{"enabled":false}`) + + // A route that echoes the name the CALLER just put in the path discloses + // nothing — the caller already knew it. What must not differ is the ANSWER: + // an unshared upstream has to look exactly like one that does not exist, or + // the status code is an existence oracle over the admin's whole config. + const absentName = "no-such-server-Zq7" + + call := func(method, route, name string) *httptest.ResponseRecorder { + target := strings.ReplaceAll(route, "{name}", name) + target = strings.ReplaceAll(target, "{server}", name) + // chi renders a trailing-slash subroute as "/*"; the bare path is the + // one clients call. + target = strings.TrimSuffix(target, "/*") + + req := httptest.NewRequest(method, target, bytes.NewReader(body)) + req.Header.Set("Content-Type", "application/json") + w := httptest.NewRecorder() + router.ServeHTTP(w, req) + return w + } + + walked := 0 + err := chi.Walk(router, func(method, route string, _ http.Handler, _ ...func(http.Handler) http.Handler) error { + if !strings.Contains(route, "/user/") { + return nil + } + // Aim every parameterised route at BOTH fixtures: the shared server + // tests redaction, the unshared one tests entitlement. + for _, name := range []string{"shared-secrets", unshared.Name} { + walked++ + w := call(method, route, name) + + // A redirect carries its payload in Location, not the body. + haystack := w.Body.String() + "\n" + w.Header().Get("Location") + + for _, secret := range append(sharedSecrets(), unsharedBrokerSecret) { + assert.NotContains(t, haystack, secret, + "%s %s echoed an admin credential (status %d)", method, route, w.Code) + } + + if name != unshared.Name { + continue + } + if !strings.Contains(route, "{name}") && !strings.Contains(route, "{server}") { + // A COLLECTION route takes no name; substituting one is a + // no-op, so its 200 is expected. What it must not do is + // enumerate the unentitled upstream. + assert.NotContains(t, haystack, unshared.Name, + "%s %s enumerated an admin upstream that was never shared", method, route) + continue + } + // On a route that ADDRESSES a server by name, no successful answer + // may exist for an unentitled upstream, and the failure must be the + // one a nonexistent name gets. + assert.GreaterOrEqual(t, w.Code, 400, + "%s %s answered for an admin upstream that was never shared", method, route) + assert.Equal(t, call(method, route, absentName).Code, w.Code, + "%s %s answers differently for an unshared upstream than for an absent one — an existence oracle over the admin's config", + method, route) + } + return nil + }) + require.NoError(t, err) + assert.GreaterOrEqual(t, walked, 26, "the walk must reach every /user/ route on the door") +} + +// The two registration tables on each handler set are hand-maintained +// duplicates, and only RegisterRoutesWithPrefix is wired in production +// (setup.go). A route added to one and not the other either ships unreachable +// or — worse for a security net — ships live while every test that walks the +// other table stays green. Assert the two tables describe the same door. +func TestRouteTables_AgreeBetweenPrefixedAndNestedForms(t *testing.T) { + admin := defaultSharedServers() + userHandlers, _ := testSetup(t, admin) + activityHandlers, _ := activityTestSetup(t, nil, admin) + credHandlers := NewCredentialHandlers(credTestStore(t), admin, nil, nil) + + collect := func(register func(chi.Router)) []string { + r := chi.NewRouter() + register(r) + var routes []string + require.NoError(t, chi.Walk(r, func(method, route string, _ http.Handler, _ ...func(http.Handler) http.Handler) error { + // The nested form renders a collection root as "/user/servers/"; + // the prefixed form as "/user/servers". Normalise so the comparison + // is about the DOOR, not chi's rendering of it. + route = strings.TrimSuffix(route, "/*") + if len(route) > 1 { + route = strings.TrimSuffix(route, "/") + } + routes = append(routes, method+" "+route) + return nil + })) + sort.Strings(routes) + return routes + } + + nested := collect(func(r chi.Router) { + r.Route("/api/v1", func(r chi.Router) { + userHandlers.RegisterRoutes(r) + activityHandlers.RegisterRoutes(r) + credHandlers.RegisterRoutes(r) + }) + }) + prefixed := collect(func(r chi.Router) { + userHandlers.RegisterRoutesWithPrefix(r, "/api/v1") + activityHandlers.RegisterRoutesWithPrefix(r, "/api/v1") + credHandlers.RegisterRoutesWithPrefix(r, "/api/v1") + }) + + assert.Equal(t, nested, prefixed, + "the nested and prefixed route tables disagree; production wires only the prefixed one") +} + +// A shared server is masked for a DIFFERENT tenant than the one who configured +// it, so it must be masked under the AUDIT policy, not the LIVE one. +// +// MaskValue's `•••• ( chars)` rendering is an affordance for an +// operator editing their own credential: it says which token is configured and +// is re-read within seconds. A shared server is read-only to the user seeing it +// (updateServer and deleteServer answer 403, enableServer stores only a +// per-user preference), so the affordance buys that reader nothing — while +// handing every tenant of the deployment a durable fingerprint of the admin's +// credential: its exact length and last two bytes, a correlation handle across +// users and a materially smaller search space for a low-entropy secret. That is +// precisely the reasoning AuditMaskValue was written for. +func TestSharedServer_MaskDisclosesNeitherLengthNorTail(t *testing.T) { + shared := []*config.ServerConfig{secretBearingSharedServer()} + handlers, _ := testSetup(t, shared) + router := testRouter(handlers, defaultAuthContext()) + + req := httptest.NewRequest(http.MethodGet, "/api/v1/user/servers", nil) + w := httptest.NewRecorder() + router.ServeHTTP(w, req) + require.Equal(t, http.StatusOK, w.Code) + + body := w.Body.String() + assert.NotRegexp(t, `\(\d+ chars\)`, body, + "the response published the exact length of an admin credential") + for _, secret := range sharedSecrets() { + assert.NotContains(t, body, secret[len(secret)-2:]+" (", + "the response published the trailing bytes of an admin credential") + } +} diff --git a/internal/serveredition/api/user_activity.go b/internal/serveredition/api/user_activity.go index 2089b4487..cc2911d39 100644 --- a/internal/serveredition/api/user_activity.go +++ b/internal/serveredition/api/user_activity.go @@ -131,7 +131,16 @@ func (h *UserActivityHandlers) getDiagnostics(w http.ResponseWriter, r *http.Req var diagnostics []*ServerDiagnostic // Add shared servers. + // + // The `Shared` gate is the ENTITLEMENT check, not a formality (issue #1161 + // follow-up): setup.go hands every handler `deps.Config.Servers` — the + // admin's whole server list — under the name `sharedServers`, so a loop + // without this guard reports admin upstreams the admin deliberately did not + // share, labelled `ownership:"shared"`, to every authenticated user. for _, sc := range h.sharedServers { + if sc == nil || !sc.Shared { + continue + } diagnostics = append(diagnostics, &ServerDiagnostic{ Name: sc.Name, Ownership: "shared", diff --git a/internal/serveredition/api/user_handlers.go b/internal/serveredition/api/user_handlers.go index 141fd56d0..434270641 100644 --- a/internal/serveredition/api/user_handlers.go +++ b/internal/serveredition/api/user_handlers.go @@ -214,10 +214,19 @@ type ServerListResponse struct { // listServers, getServer and enableServer alike. This is the same defect class // the MCP, REST and SSE doors closed; this door that sweep did not reach. // -// The rules are oauth.LiveRedaction — the SAME ones every other door applies — -// reached through oauth.RedactServerConfigSecrets, which walks the struct -// rather than enumerating it, so a field added to config.ServerConfig (or to -// the build-tagged auth_broker block) is masked because the walk reaches it. +// The rules are the SAME ones every other door applies, reached through +// oauth.RedactServerConfigSecrets, which walks the struct rather than +// enumerating it, so a field added to config.ServerConfig (or to the +// build-tagged auth_broker block) is masked because the walk reaches it. +// +// The POLICY is oauth.AuditRedaction, not the LiveRedaction an owner-facing +// surface uses. MaskValue's `•••• ( chars)` rendering is an +// affordance for someone editing their OWN credential; here the reader is a +// different tenant who cannot edit this server at all, so the affordance buys +// them nothing while publishing the admin credential's exact length and +// trailing bytes to every user of the deployment — a durable fingerprint, a +// correlation handle across tenants, and a materially smaller search space for +// a low-entropy secret. // // It returns a masked COPY: `h.sharedServers` is the LIVE admin configuration, // and writing a mask through it would be the #1142/#1146 read-modify-write @@ -236,7 +245,7 @@ type ServerListResponse struct { // masks over the user's real secrets. func sharedServerResponse(sc *config.ServerConfig, userEnabled *bool) *ServerResponse { return &ServerResponse{ - ServerConfig: oauth.RedactServerConfigSecrets(sc), + ServerConfig: oauth.RedactServerConfigSecrets(sc, oauth.AuditRedaction), Ownership: "shared", UserEnabled: userEnabled, } @@ -391,7 +400,23 @@ func (h *UserHandlers) getServer(w http.ResponseWriter, r *http.Request) { // Check shared servers. for _, shared := range h.sharedServers { if shared.Shared && strings.EqualFold(shared.Name, name) { - writeJSON(w, http.StatusOK, sharedServerResponse(shared, nil)) + // The caller's own preference belongs on the DETAIL read too. + // Rendering it as unset made this route disagree with listServers + // (which threads it from GetSharedServerPrefs) and with the 200 body + // of .../enable: a user who had disabled a shared server saw only + // the admin's `enabled` and no `user_enabled` at all. + // + // Keyed on shared.Name — the canonical name the preference is + // stored under — rather than on the case-insensitively matched URL + // param, matching how listServers and enableServer key it. + var userEnabled *bool + if pref, perr := h.userStore.GetSharedServerPref(userID, shared.Name); perr != nil { + // Non-fatal: the server itself is still worth returning. + h.logger.Errorw("failed to load shared server pref", "user_id", userID, "name", shared.Name, "error", perr) + } else if pref != nil { + userEnabled = &pref.Enabled + } + writeJSON(w, http.StatusOK, sharedServerResponse(shared, userEnabled)) return } }