Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
feat(mcp): SQL statement clamp for read-only MCP sessions, and the READ_ONLY cutover (P1b 1b-3) (#21210)
Vincent Huang58e21067dbd6
diff --git a/backend/api/auth/auth.go b/backend/api/auth/auth.goindex ab291f5790..75080e4c92 100644--- a/backend/api/auth/auth.go+++ b/backend/api/auth/auth.go@@ -528,6 +528,30 @@ func MCPClassIsRefused(class v1pb.MCPMethodClass) bool {}}+// MCPCeilingServesAnything reports whether a workspace capability ceiling+// serves any method class at all, which is what the /mcp connection gate needs+// to decide whether a session may open.+//+// It lives here for the same reason MCPClassIsRefused does: the serving table+// is in backend/api/v1 with the code that evaluates it, the connection gate is+// in backend/api/mcp, and the two must not disagree about which ceilings this+// build serves. TestLintCeilingAdmissionMatchesTheServingTable holds this+// function against that table over the whole enum, so a mode that starts or+// stops serving a class cannot leave the connection gate stale.+//+// Everything this build cannot interpret is refused: UNSPECIFIED is a zero+// value nobody resolved, and a stored number no release ever wrote — the+// reserved 2, or anything from a newer build — is a ceiling nobody decided+// about. Both fall to the default.+func MCPCeilingServesAnything(capability storepb.WorkspaceProfileSetting_MCPCapability) bool {+ switch capability {+ case storepb.WorkspaceProfileSetting_READ_WRITE, storepb.WorkspaceProfileSetting_READ_ONLY:+ return true+ default:+ return false+ }+}+// MCPMethodClassOfProcedure resolves the MCP classification for a connect// procedure path such as "/bytebase.v1.AuthService/Login". Callers that only// decide what to ADVERTISE may treat an error as "not classified"; thediff --git a/backend/api/mcp/server.go b/backend/api/mcp/server.goindex a3dba6e19b..28a15f8ab0 100644--- a/backend/api/mcp/server.go+++ b/backend/api/mcp/server.go@@ -206,13 +206,11 @@ func (s *Server) authMiddleware(next echo.HandlerFunc) echo.HandlerFunc {}// Enforce the workspace MCP capability ceiling before dispatching to any- // tool. DISABLED rejects the connection outright, and so does READ_ONLY:- // the per-method gate on the internal chain now serves a read-only- // ceiling correctly, but the query tool still reaches SQLService/Query,- // which authorizes writes per statement. Admitting a read-only session- // before that clamp exists would be a read-only session that can write.- // Read live so an admin change takes effect on the next request without- // re-issuing tokens.+ // tool. DISABLED rejects the connection outright; READ_ONLY admits it,+ // and what a read-only session may then do is decided per method by the+ // gate on the internal chain and per statement by the SQL clamp in+ // SQLService/Query. Read live so an admin change takes effect on the+ // next request without re-issuing tokens.capability, err := s.mcpCapability(c.Request().Context(), workspaceID)if err != nil {// Infra failure reading the policy, not a verdict on the@@ -589,27 +587,18 @@ func (s *Server) unauthorized(c *echo.Context, errDescription string) error {return echo.NewHTTPError(http.StatusUnauthorized, errDescription)}-// mcpConnectionAllowed reports whether an MCP connection may proceed under the-// resolved workspace capability ceiling. DISABLED is rejected, and so is-// READ_ONLY: per-method enforcement exists from P1b 1b-2, but the SQL statement-// clamp does not, so a read-only session admitted here could still write-// through the query tool. 1b-3 lands the clamp and flips this to-// allow-with-clamp; nothing before it may. Unknown stored values (e.g. the-// reserved number) hit the default arm and fail closed too.+// mcpConnectionAllowed reports whether an MCP connection may proceed: a ceiling+// that serves some method class opens a session, one that serves none does not.//-// UNSPECIFIED is refused rather than treated as "never configured", even though-// that is what an unset ceiling means in the stored proto. The resolution-// happens before this point — store.GetMCPCapabilityUncached returns READ_WRITE-// for a workspace that never set one — so UNSPECIFIED reaching here is a zero-// value nobody resolved, and a gate that admits on a zero value is one-// mistake away from admitting on a failure.+// The rule lives in auth.MCPCeilingServesAnything so this gate and the+// per-method serving table cannot state the same policy twice; a lint holds the+// two against each other over the whole enum.+//+// UNSPECIFIED is refused rather than read as "never configured":+// store.GetMCPCapabilityUncached already resolves an unset ceiling to+// READ_WRITE, so a zero value arriving here was resolved by nobody.func mcpConnectionAllowed(capability storepb.WorkspaceProfileSetting_MCPCapability) bool {- switch capability {- case storepb.WorkspaceProfileSetting_READ_WRITE:- return true- default:- return false- }+ return auth.MCPCeilingServesAnything(capability)}// mcpCapability resolves the workspace's effective MCP capability ceiling fordiff --git a/backend/api/mcp/server_killswitch_test.go b/backend/api/mcp/server_killswitch_test.goindex 70437f976f..d22e2fd4c1 100644--- a/backend/api/mcp/server_killswitch_test.go+++ b/backend/api/mcp/server_killswitch_test.go@@ -24,11 +24,14 @@ import (_ "github.com/bytebase/bytebase/backend/plugin/db/pg")-// TestMCPConnectionAllowed pins the connection-level gate: only READ_WRITE-// admits a connection in this phase. DISABLED, the not-yet-enforceable-// READ_ONLY ceiling, unknown stored values (such as the reserved number 2), and-// the zero value all fail closed, so a ceiling the server cannot apply per-tool-// never silently grants read-write.+// TestMCPConnectionAllowed pins the connection-level gate: READ_WRITE and+// READ_ONLY admit a connection, and everything else fails closed — DISABLED,+// unknown stored values such as the reserved number 2, and the zero value.+//+// READ_ONLY is admitted from the cutover, once the SQL clamp made a read-only+// session one that cannot write. What it may then do is decided per method by+// the ceiling gate and per statement by the clamp; this function only decides+// whether the session opens at all.//// UNSPECIFIED is refused here even though an unset stored ceiling means// READ_WRITE: the store resolves that before this point, so a zero value@@ -41,8 +44,9 @@ func TestMCPConnectionAllowed(t *testing.T) {{storepb.WorkspaceProfileSetting_MCP_CAPABILITY_UNSPECIFIED, false},{storepb.WorkspaceProfileSetting_READ_WRITE, true},{storepb.WorkspaceProfileSetting_DISABLED, false},- {storepb.WorkspaceProfileSetting_MCPCapability(2), false}, // reserved (was METADATA_ONLY)- {storepb.WorkspaceProfileSetting_READ_ONLY, false},+ {storepb.WorkspaceProfileSetting_MCPCapability(2), false}, // reserved (was METADATA_ONLY)+ {storepb.WorkspaceProfileSetting_MCPCapability(99), false}, // no such value in any build+ {storepb.WorkspaceProfileSetting_READ_ONLY, true},}for _, tt := range tests {t.Run(tt.capability.String(), func(t *testing.T) {@@ -208,10 +212,12 @@ func tokenForWorkspace(t *testing.T, secret, workspaceID string) string {// nothing. An unknown enum NUMBER never had that problem, because protojson// keeps it and no mode serves it.//-// The read-only row is the cutover pin. READ_ONLY is enforceable per method-// from this PR, but a read-only session can still write SQL through the query-// tool until 1b-3 clamps statements, so the connection stays refused. If this-// row ever returns 200 without the clamp shipping, the cutover moved early.+// The read-only row is the cutover pin, now on its other side: READ_ONLY opens+// a session, because a read-only session can no longer write — the ceiling gate+// refuses the methods the mode does not cover and the SQL clamp refuses a+// statement that writes. The rows around it are what must NOT have moved with+// it: a ceiling this build cannot read still refuses, and so does a value no+// Bytebase write produces.func TestMCPCeilingStoredValueFailsClosed(t *testing.T) {ctx := context.Background()container := testcontainer.GetTestPgContainer(ctx, t)@@ -232,8 +238,8 @@ func TestMCPCeilingStoredValueFailsClosed(t *testing.T) {"the reserved number was METADATA_ONLY; no mode serves it"},{"ws-explicit-unset", `{"mcpCapability":"MCP_CAPABILITY_UNSPECIFIED"}`, http.StatusForbidden,"no Bytebase write produces this key with this value, so a row that has it was hand-edited"},- {"ws-readonly", `{"mcpCapability":"READ_ONLY"}`, http.StatusForbidden,- "READ_ONLY does not admit a connection until the SQL clamp lands (1b-3)"},+ {"ws-readonly", `{"mcpCapability":"READ_ONLY"}`, http.StatusOK,+ "READ_ONLY admits a session now that the SQL clamp holds it to reads"},{"ws-other-unknown-field", `{"someFieldFromANewerRelease":"x"}`, http.StatusOK,"one unknown field must not disable MCP: only the ceiling key is read strictly"},{"ws-open", `{}`, http.StatusOK,@@ -273,8 +279,9 @@ func TestMCPCeilingStoredValueFailsClosed(t *testing.T) {// ceiling to every other tenant — a kill switch answering for the wrong// workspace. Six workspaces with six different stored values sit in this// one database, so each must still resolve to its own; the ws-readonly row- // is additionally the value 1b-3's cutover will flip against, and it must- // resolve as itself rather than as a fail-closed error.+ // must resolve as itself rather than as a fail-closed error, which is what+ // separates "the ceiling says read-only" from "the ceiling could not be+ // read" now that both no longer answer the same way at the connection.for workspace, want := range map[string]storepb.WorkspaceProfileSetting_MCPCapability{"ws-readonly": storepb.WorkspaceProfileSetting_READ_ONLY,"ws-open": storepb.WorkspaceProfileSetting_READ_WRITE,diff --git a/backend/api/mcp/tool_query.go b/backend/api/mcp/tool_query.goindex c0d2f36933..b4bd64f572 100644--- a/backend/api/mcp/tool_query.go+++ b/backend/api/mcp/tool_query.go@@ -198,7 +198,18 @@ func (s *Server) executeQuery(ctx context.Context, resolved *resolvedDatabase, s}suggestion := "check your SQL syntax and try again"if resp.Status == http.StatusForbidden || resp.Status == http.StatusUnauthorized {- suggestion = "you may not have permission to query this database — request the SQL Editor role on the project"+ // A refusal that already names its own way out gets none added.+ // The workspace MCP ceiling is one of these, and telling an agent+ // to request a project role for it sends the person it acts for+ // after a grant that cannot lift a workspace setting.+ //+ // The phrase crosses a process boundary as an error body, so the+ // producer pins it too: see the assertion on this exact substring+ // in TestMCPClampRefusesWhatItCannotShowIsARead (backend/api/v1).+ suggestion = ""+ if !strings.Contains(errMsg, "MCP capability ceiling") {+ suggestion = "you may not have permission to query this database — request the SQL Editor role on the project"+ }}return nil, &toolError{Code: "QUERY_ERROR",diff --git a/backend/api/v1/mcp_gate.go b/backend/api/v1/mcp_gate.goindex 08a0e2a0b8..34f512cf10 100644--- a/backend/api/v1/mcp_gate.go+++ b/backend/api/v1/mcp_gate.go@@ -262,9 +262,9 @@ var mcpServingClasses = map[storepb.WorkspaceProfileSetting_MCPCapability][]v1pb// mcpCeilingReader is the whole of what the gate needs from the store: one live// read of the workspace's ceiling. *store.Store satisfies it; a test supplies-// its own, which is what lets a READ_ONLY ceiling be exercised at all before-// 1b-3 lets one connect. Named for what it does rather than for what satisfies-// it, per the convention for a single-method interface.+// its own, which is what lets each ceiling be exercised without a database.+// Named for what it does rather than for what satisfies it, per the convention+// for a single-method interface.type mcpCeilingReader interface {GetMCPCapabilityUncached(ctx context.Context, workspace string) (storepb.WorkspaceProfileSetting_MCPCapability, error)}@@ -348,7 +348,7 @@ func NewInternalMCPGateInterceptor(stores mcpCeilingReader) connect.Interceptorfunc (in *internalMCPGateInterceptor) WrapUnary(next connect.UnaryFunc) connect.UnaryFunc {return func(ctx context.Context, req connect.AnyRequest) (connect.AnyResponse, error) {- policyDenial, err := in.refuse(ctx, req)+ ctx, policyDenial, err := in.refuse(ctx, req)if err == nil {return next(ctx, req)}@@ -389,51 +389,57 @@ func (*internalMCPGateInterceptor) WrapStreamingHandler(connect.StreamingHandler// refuse returns the error the gate refuses this request with, or nil to let it// through to ACL. The bool reports whether the refusal is a verdict about the// caller, which is an audited outcome; an infrastructure failure is not.-func (in *internalMCPGateInterceptor) refuse(ctx context.Context, req connect.AnyRequest) (bool, error) {+//+// The context it returns carries the ceiling this request was held against,+// for the one handler that enforces on the request's argument rather than on+// its method (see mcpCeilingFromContext).+func (in *internalMCPGateInterceptor) refuse(ctx context.Context, req connect.AnyRequest) (context.Context, bool, error) {procedure := req.Spec().ProcedureauthCtx, ok := common.GetAuthContextFromContext(ctx)if !ok {// The auth interceptor runs first and always sets this. Its absence// means the chain was reordered, and guessing which class a method is// in is exactly the wrong response.- return false, connect.NewError(connect.CodeInternal,+ return ctx, false, connect.NewError(connect.CodeInternal,errors.New("MCP method classification unavailable: no auth context"))}switch authCtx.MCPMethodClass {case v1pb.MCPMethodClass_FORBIDDEN:- return true, connect.NewError(connect.CodePermissionDenied, errors.Errorf(+ return ctx, true, connect.NewError(connect.CodePermissionDenied, errors.Errorf("%s is not available to MCP sessions because %s. Perform this action signed in to the Bytebase console instead",procedure, denialReason(authCtx.MCPMethodClass, authCtx.MCPDenialReason, reasonForbiddenClass)))case v1pb.MCPMethodClass_EXCLUDED:- return true, connect.NewError(connect.CodePermissionDenied, errors.Errorf(+ return ctx, true, connect.NewError(connect.CodePermissionDenied, errors.Errorf("%s is served by no MCP capability ceiling because %s. Perform this action signed in to the Bytebase console instead",procedure, denialReason(authCtx.MCPMethodClass, authCtx.MCPDenialReason, reasonExcludedClass)))case v1pb.MCPMethodClass_READ, v1pb.MCPMethodClass_WRITE:default:- return true, connect.NewError(connect.CodePermissionDenied, errors.Errorf(+ return ctx, true, connect.NewError(connect.CodePermissionDenied, errors.Errorf("%s carries no MCP classification, so no MCP session may call it", procedure))}- if policyDenial, err := in.refuseByCeiling(ctx, procedure, authCtx.MCPMethodClass); err != nil {- return policyDenial, err+ ceiling, policyDenial, err := in.refuseByCeiling(ctx, procedure, authCtx.MCPMethodClass)+ if err != nil {+ return ctx, policyDenial, err}if err := refuseByRequestShape(procedure, req.Any()); err != nil {- return true, err+ return ctx, true, err}- return false, nil+ return withMCPCeiling(ctx, ceiling), false, nil}// refuseByCeiling holds the method's class against the workspace's live-// ceiling.-func (in *internalMCPGateInterceptor) refuseByCeiling(ctx context.Context, procedure string, class v1pb.MCPMethodClass) (bool, error) {+// ceiling, and returns the ceiling it resolved so the request can be held+// against the same one further in.+func (in *internalMCPGateInterceptor) refuseByCeiling(ctx context.Context, procedure string, class v1pb.MCPMethodClass) (storepb.WorkspaceProfileSetting_MCPCapability, bool, error) {// The internal auth interceptor puts the delegated credential's workspace// on every request it admits, so an empty one means the chain was// reordered — a bug in this process, not an outage, and not a verdict// about the caller.workspaceID := common.GetWorkspaceIDFromContext(ctx)if workspaceID == "" {- return false, connect.NewError(connect.CodeInternal, errors.Errorf(+ return storepb.WorkspaceProfileSetting_MCP_CAPABILITY_UNSPECIFIED, false, connect.NewError(connect.CodeInternal, errors.Errorf("%s cannot be checked against the MCP capability ceiling: no workspace on the request", procedure))}// The store applies the backward-compatible default for a workspace that@@ -452,27 +458,27 @@ func (in *internalMCPGateInterceptor) refuseByCeiling(ctx context.Context, proceslog.Warn("failed to resolve the MCP capability ceiling; refusing the request",slog.String("method", procedure), slog.String("workspace", workspaceID), log.BBError(err))if errors.Is(err, store.ErrMCPCapabilityUnreadable) {- return true, connect.NewError(connect.CodePermissionDenied, errors.Errorf(+ return ceiling, true, connect.NewError(connect.CodePermissionDenied, errors.Errorf("%s is refused: this workspace's stored MCP capability ceiling is not one this build understands, "+"so the request fails closed. Ask a workspace admin to set the MCP ceiling again in the workspace settings",procedure))}- return false, connect.NewError(connect.CodeUnavailable, errors.Errorf(+ return ceiling, false, connect.NewError(connect.CodeUnavailable, errors.Errorf("%s is refused: this workspace's MCP capability ceiling could not be read, so the request fails closed. "+"Retry shortly; if it persists, a workspace admin must check the workspace MCP settings",procedure))}served, known := mcpServingClasses[ceiling]if !known {- return true, connect.NewError(connect.CodePermissionDenied, errors.Errorf(+ return ceiling, true, connect.NewError(connect.CodePermissionDenied, errors.Errorf("%s is refused: this workspace's stored MCP capability ceiling %v is not one this build serves. "+"Ask a workspace admin to set the MCP ceiling to a supported value in the workspace settings",procedure, ceiling))}if slices.Contains(served, class) {- return false, nil+ return ceiling, false, nil}- return true, connect.NewError(connect.CodePermissionDenied, errors.Errorf(+ return ceiling, true, connect.NewError(connect.CodePermissionDenied, errors.Errorf("%s is a %v method and this workspace's MCP capability ceiling is %v, which serves %s. "+"Ask a workspace admin to raise the MCP ceiling in the workspace settings, "+"or perform this action signed in to the Bytebase console instead",diff --git a/backend/api/v1/mcp_gate_test.go b/backend/api/v1/mcp_gate_test.goindex 5773dfb1b5..3a4601bb46 100644--- a/backend/api/v1/mcp_gate_test.go+++ b/backend/api/v1/mcp_gate_test.go@@ -380,6 +380,27 @@ func TestLintRefusedClassesMatchTheServingTable(t *testing.T) {}}+// TestLintCeilingAdmissionMatchesTheServingTable is the connection gate's half+// of the same arrangement. The /mcp boundary decides whether a session opens at+// all, and it asks auth.MCPCeilingServesAnything, which cannot see this table.+// This holds the two against each other over every ceiling value, so a mode+// that serves no class cannot start admitting sessions — or the reverse, which+// would refuse a connection whose methods the gate is ready to serve.+func TestLintCeilingAdmissionMatchesTheServingTable(t *testing.T) {+ values := storepb.WorkspaceProfileSetting_MCPCapability(0).Descriptor().Values()+ for i := range values.Len() {+ capability := storepb.WorkspaceProfileSetting_MCPCapability(values.Get(i).Number())+ require.Equal(t, len(mcpServingClasses[capability]) > 0, auth.MCPCeilingServesAnything(capability),+ "%v: the serving table and auth.MCPCeilingServesAnything disagree about whether this ceiling serves anything", capability)+ }+ // A stored number no release ever wrote is refused too, and it cannot come+ // from the descriptor because it is in no build's enum.+ for _, unknown := range []storepb.WorkspaceProfileSetting_MCPCapability{2, 99} {+ require.False(t, auth.MCPCeilingServesAnything(unknown),+ "%v: a ceiling this build cannot interpret must not open a session", unknown)+ }+}+// TestMCPCapabilityEnumsAgree is what lets the lint above read one enum and the// gate read the other. The settings API writes the v1 ceiling, the setting row// stores the store ceiling, and the conversion between them is by number@@ -753,10 +774,9 @@ func TestMCPClassificationInventory(t *testing.T) {// --- the gate ----// mcpGateStore stands in for the workspace's stored ceiling. A READ_ONLY-// ceiling cannot be reached end to end yet — mcpConnectionAllowed still refuses-// the connection until 1b-3 lands the SQL clamp — so the only way to exercise-// the read-only half of the rule today is here.+// mcpGateStore stands in for the workspace's stored ceiling, so the rule can be+// exercised without a database. The end-to-end path exists too, in+// backend/tests, now that a READ_ONLY ceiling admits a connection.type mcpGateStore struct {ceiling storepb.WorkspaceProfileSetting_MCPCapabilityerr error@@ -778,6 +798,9 @@ type mcpGateResult struct {dispatched boolauditMarked boolerr error+ // dispatchedCtx is the context the handler was called with, so a test can+ // assert what the gate stamped on the way in.+ dispatchedCtx context.Context}// invokeMCPGate runs one request through the gate alone. auditMarked is what@@ -788,8 +811,9 @@ type mcpGateResult struct {func invokeMCPGate(t *testing.T, stores mcpCeilingReader, authCtx *common.AuthContext, procedure string, req connect.AnyRequest) mcpGateResult {t.Helper()out := mcpGateResult{}- next := func(_ context.Context, _ connect.AnyRequest) (connect.AnyResponse, error) {+ next := func(ctx context.Context, _ connect.AnyRequest) (connect.AnyResponse, error) {out.dispatched = true+ out.dispatchedCtx = ctxreturn connect.NewResponse(&v1pb.User{}), nil}ctx := context.Background()@@ -850,12 +874,11 @@ func TestMCPGateServesTheAdmittedClasses(t *testing.T) {}}-// TestMCPGateUnderAReadOnlyCeiling is the rule this PR exists for: the same-// session that reaches a WRITE method under read-write is refused it under-// read-only, while its reads keep working. It is unit-level because READ_ONLY-// cannot connect until 1b-3: TestMCPConnectionAllowed and the ws-readonly row-// of TestMCPCeilingStoredValueFailsClosed (backend/api/mcp) are the pins that-// the cutover has not moved.+// TestMCPGateUnderAReadOnlyCeiling is the ceiling half of the read-only rule:+// the same session that reaches a WRITE method under read-write is refused it+// under read-only, while its reads keep working. Unit-level so every class is+// covered cheaply; TestMCPReadOnlyCeilingRefusesAWrite (backend/tests) drives+// the same rule over a live session and a real database.func TestMCPGateUnderAReadOnlyCeiling(t *testing.T) {t.Run("a READ method is served", func(t *testing.T) {got := invokeMCPGate(t, readOnlyCeiling(), classContext(v1pb.MCPMethodClass_READ),diff --git a/backend/api/v1/mcp_sql_clamp.go b/backend/api/v1/mcp_sql_clamp.gonew file mode 100644index 0000000000..9d92977ea9--- /dev/null+++ b/backend/api/v1/mcp_sql_clamp.go@@ -0,0 +1,144 @@+package v1++import (+ "context"+ "fmt"++ "connectrpc.com/connect"+ "github.com/pkg/errors"++ "github.com/bytebase/bytebase/backend/common"+ storepb "github.com/bytebase/bytebase/backend/generated-go/store"+ parserbase "github.com/bytebase/bytebase/backend/plugin/parser/base"+)++// SQLService/Query is classified READ, but on the EngineSupportQueryNewACL+// engines it authorizes DML and DDL per statement against the caller's own+// RBAC — so its class depends on its argument, and a read-only session held by+// someone who may write would write. The clamp is the point that reads the+// argument.+//+// Ceiling: classifier-enforced, not proven. A structurally-reading statement+// can still have an effect, and a classifier can be wrong about a grammar it+// does not fully model; closing that is the conformance lane's work.++// mcpCeilingContextKey carries the ceiling the gate already resolved, so the+// clamp holds the request against that same read rather than a second one the+// gate could disagree with.+type mcpCeilingContextKey struct{}++func withMCPCeiling(ctx context.Context, ceiling storepb.WorkspaceProfileSetting_MCPCapability) context.Context {+ return context.WithValue(ctx, mcpCeilingContextKey{}, ceiling)+}++func mcpCeilingFromContext(ctx context.Context) (storepb.WorkspaceProfileSetting_MCPCapability, bool) {+ ceiling, ok := ctx.Value(mcpCeilingContextKey{}).(storepb.WorkspaceProfileSetting_MCPCapability)+ return ceiling, ok+}++// mcpReadOnlyClampApplies reports whether this request must be held to+// read-only statements.+//+// Keyed on the grant's presence, never a field value: a legacy or+// scope-omitting session leaves every field empty, so no value marks MCP+// origin. An MCP request with no stamped ceiling means the gate never ran, and+// an unresolved ceiling is not a read-write one.+func mcpReadOnlyClampApplies(ctx context.Context) (bool, error) {+ authCtx, ok := common.GetAuthContextFromContext(ctx)+ if !ok || authCtx.DelegatedGrant == nil {+ return false, nil+ }+ ceiling, ok := mcpCeilingFromContext(ctx)+ if !ok {+ return false, connect.NewError(connect.CodeInternal, errors.New(+ "this MCP request cannot be checked against the workspace MCP capability ceiling, so it fails closed"))+ }+ return ceiling == storepb.WorkspaceProfileSetting_READ_ONLY, nil+}++// refuseNonReadOnlyStatement classifies a request fail-closed. Nothing here+// calls base.ValidateSQLForEditor bare: it answers "read-only" for an engine+// with no registered validator, which suits a caller that only routes on the+// verdict and admits every write for one that must refuse a write.+//+// A statement that returns no data is refused as well as one that is not a+// read. Every unit of a request runs on one connection, and Postgres applies a+// changed default_transaction_read_only to the next transaction, so+// "SET default_transaction_read_only = off" followed by a classifier-admitted+// read disarms the depth layer and writes (verified, PG 17). The same bool+// carries the other rebinding statements — Trino USE and SET ROLE, Redis+// SELECT — which repoint the connection so a later read resolves somewhere the+// caller never named.+//+// Not closed: a structurally-reading statement can still call a function that+// rewrites the same setting (set_config, BOT-88).+func refuseNonReadOnlyStatement(engine storepb.Engine, statement string) error {+ if !parserbase.HasQueryValidator(engine) {+ return refuseClampedStatement(fmt.Sprintf(+ "Bytebase has no read-only classifier for %v, so no statement on this engine can be shown to be a read", engine))+ }+ units := mcpClampUnits(engine, statement)+ for i, unit := range units {+ readOnly, allQuery, err := parserbase.ValidateSQLForEditor(engine, unit)+ if err != nil {+ return refuseClampedStatement(fmt.Sprintf(+ "%s could not be parsed, so it cannot be shown to be a read: %v", describeClampUnit(i, len(units)), err))+ }+ if !readOnly {+ return refuseClampedStatement(fmt.Sprintf("%s is not a read", describeClampUnit(i, len(units))))+ }+ if !allQuery {+ return refuseClampedStatement(fmt.Sprintf(+ "%s returns no data, so it either rewrites the session it runs on, which can switch off the read-only session the rest of the request depends on, or runs the query to measure it. A read-only ceiling serves statements that only read",+ describeClampUnit(i, len(units))))+ }+ }+ return nil+}++// mcpClampUnits splits a request the way queryRetryStopOnError does, including+// its whole-request fallback for an engine with no splitter (Redis) or a failed+// split, so the clamp classifies the text that would execute.+//+// A splitter can also succeed and still return the request whole: ClickHouse+// and Hive break on newlines rather than terminators (BOT-86). Their validator+// refuses a unit carrying a terminator it did not end with, which is what keeps+// that from being read on its leading statement.+//+// MSSQL differs in the safe direction: split for analysis, sent to the driver+// whole to keep variable scope, so the clamp is stricter than the executor.+func mcpClampUnits(engine storepb.Engine, statement string) []string {+ statements, err := parserbase.SplitMultiSQL(engine, statement)+ if err != nil {+ return []string{statement}+ }+ var units []string+ for _, s := range statements {+ if s.Empty {+ continue+ }+ units = append(units, s.Text)+ }+ if len(units) == 0 {+ return []string{statement}+ }+ return units+}++// describeClampUnit names the offending statement the way a denial should read+// for a request holding one statement and for a batch alike.+func describeClampUnit(index, total int) string {+ if total <= 1 {+ return "the statement"+ }+ return fmt.Sprintf("statement %d of %d", index+1, total)+}++// refuseClampedStatement wraps a reason in the denial the gate set the shape+// for: what refused, why, and the two ways out.+func refuseClampedStatement(reason string) error {+ return connect.NewError(connect.CodePermissionDenied, errors.Errorf(+ "this workspace's MCP capability ceiling is READ_ONLY, so an MCP session may only run statements Bytebase can show are reads: %s. "++ "Ask a workspace admin to raise the MCP ceiling in the workspace settings, "++ "or run this statement signed in to the Bytebase console instead", reason))+}diff --git a/backend/api/v1/mcp_sql_clamp_test.go b/backend/api/v1/mcp_sql_clamp_test.gonew file mode 100644index 0000000000..45e0dacae2--- /dev/null+++ b/backend/api/v1/mcp_sql_clamp_test.go@@ -0,0 +1,563 @@+package v1++import (+ "context"+ "testing"++ "connectrpc.com/connect"+ "github.com/stretchr/testify/require"++ "github.com/bytebase/bytebase/backend/common"+ storepb "github.com/bytebase/bytebase/backend/generated-go/store"+ v1pb "github.com/bytebase/bytebase/backend/generated-go/v1"+ parserbase "github.com/bytebase/bytebase/backend/plugin/parser/base"++ // The clamp asks the parser registry what it can classify and how it+ // splits, so this test binary has to register what the server registers.+ // The set is the parser half of backend/server/ultimate.go, verbatim:+ // naming a subset would make a row's verdict depend on which packages this+ // file happens to import rather than on the engine it says it is about,+ // and a missing splitter reads as "no splitter" without saying so.+ _ "github.com/bytebase/bytebase/backend/plugin/parser/bigquery"+ _ "github.com/bytebase/bytebase/backend/plugin/parser/cassandra"+ _ "github.com/bytebase/bytebase/backend/plugin/parser/cosmosdb"+ _ "github.com/bytebase/bytebase/backend/plugin/parser/doris"+ _ "github.com/bytebase/bytebase/backend/plugin/parser/elasticsearch"+ _ "github.com/bytebase/bytebase/backend/plugin/parser/mariadb"+ _ "github.com/bytebase/bytebase/backend/plugin/parser/mongodb"+ _ "github.com/bytebase/bytebase/backend/plugin/parser/mysql"+ _ "github.com/bytebase/bytebase/backend/plugin/parser/partiql"+ _ "github.com/bytebase/bytebase/backend/plugin/parser/pg"+ _ "github.com/bytebase/bytebase/backend/plugin/parser/plsql"+ _ "github.com/bytebase/bytebase/backend/plugin/parser/redis"+ _ "github.com/bytebase/bytebase/backend/plugin/parser/redshift"+ _ "github.com/bytebase/bytebase/backend/plugin/parser/snowflake"+ _ "github.com/bytebase/bytebase/backend/plugin/parser/spanner"+ _ "github.com/bytebase/bytebase/backend/plugin/parser/standard"+ _ "github.com/bytebase/bytebase/backend/plugin/parser/starrocks"+ _ "github.com/bytebase/bytebase/backend/plugin/parser/tidb"+ _ "github.com/bytebase/bytebase/backend/plugin/parser/trino"+ _ "github.com/bytebase/bytebase/backend/plugin/parser/tsql"+)++// unclassifiedEngineWrites are the engines with no registered read-only+// classifier, each with a statement that writes on it. Every one fails closed+// under the clamp rather than gaining a validator in this change.+//+// One map rather than a list beside a lookup table: two copies of this set+// could disagree about which engines the test is even about.+var unclassifiedEngineWrites = map[storepb.Engine]string{+ storepb.Engine_MONGODB: `db.employee.insertOne({name: "Bytebase"})`,+ storepb.Engine_ELASTICSEARCH: "POST /employee/_doc\n{\"name\":\"Bytebase\"}",+ storepb.Engine_DATABRICKS: "INSERT INTO employee VALUES ('Bytebase')",+}++// TestMCPClampRefusesWhatItCannotShowIsARead is the clamp's whole rule: a+// request is served only when every statement the driver would run classifies+// as a read.+func TestMCPClampRefusesWhatItCannotShowIsARead(t *testing.T) {+ rows := []struct {+ name string+ engine storepb.Engine+ statement string+ refused bool+ reason string+ }{+ {+ name: "a plain read is served",+ engine: storepb.Engine_POSTGRES,+ statement: "SELECT * FROM employee",+ },+ {+ name: "an all-read batch is served whole",+ engine: storepb.Engine_POSTGRES,+ statement: "SELECT 1; SELECT 2; SELECT 3;",+ },+ {+ name: "a write is refused",+ engine: storepb.Engine_POSTGRES,+ statement: "INSERT INTO employee (name) VALUES ('a')",+ refused: true,+ reason: "the statement is not a read",+ },+ {+ name: "one write refuses the whole batch",+ engine: storepb.Engine_POSTGRES,+ statement: "SELECT 1; UPDATE employee SET name = 'a'; SELECT 2;",+ refused: true,+ reason: "statement 2 of 3 is not a read",+ },+ {+ name: "a write last in the batch refuses it too",+ engine: storepb.Engine_MYSQL,+ statement: "SELECT 1; SELECT 2; DELETE FROM employee;",+ refused: true,+ reason: "statement 3 of 3 is not a read",+ },+ {+ name: "a statement that will not parse is refused",+ engine: storepb.Engine_POSTGRES,+ statement: "SELECT FROM WHERE (((",+ refused: true,+ reason: "could not be parsed",+ },+ {+ name: "DDL is refused",+ engine: storepb.Engine_MYSQL,+ statement: "CREATE TABLE t (id INT)",+ refused: true,+ reason: "the statement is not a read",+ },+ {+ name: "a data-modifying CTE is refused",+ engine: storepb.Engine_POSTGRES,+ statement: "WITH moved AS (DELETE FROM employee RETURNING *) SELECT * FROM moved",+ refused: true,+ reason: "the statement is not a read",+ },+ {+ // Nothing to refuse: an empty request carries no statement, so it+ // reaches the driver as one and writes nothing. The clamp has no+ // opinion on it, and query_database rejects it before this point.+ name: "an empty request has no statement to refuse",+ engine: storepb.Engine_POSTGRES,+ statement: "",+ },+ {+ // The engines whose validator classifies by leading keyword over+ // whatever string it is handed. Passing the request whole would+ // read this as a SELECT; classifying the statements the driver+ // will run is what catches the tail.+ name: "a leading-keyword engine still has its batch tail classified",+ engine: storepb.Engine_CASSANDRA,+ statement: "SELECT * FROM employee; DROP TABLE employee",+ refused: true,+ reason: "statement 2 of 2 is not a read",+ },+ {+ name: "the same on Spanner",+ engine: storepb.Engine_SPANNER,+ statement: "SELECT 1; DELETE FROM employee WHERE true",+ refused: true,+ reason: "statement 2 of 2 is not a read",+ },+ {+ name: "a statement that rewrites the session is refused",+ engine: storepb.Engine_POSTGRES,+ statement: "SET default_transaction_read_only = off",+ refused: true,+ reason: "rewrites the session it runs on",+ },+ {+ // The disarm this rule exists for. Both statements classify as+ // reads, every unit of a request runs on one connection, and+ // Postgres applies the changed default to the next transaction —+ // so admitting the first would let the second write.+ name: "a session rewrite ahead of a read is refused before either runs",+ engine: storepb.Engine_POSTGRES,+ statement: "SET default_transaction_read_only = off; SELECT nextval('s')",+ refused: true,+ reason: "statement 1 of 2 returns no data",+ },+ {+ name: "the same on MySQL",+ engine: storepb.Engine_MYSQL,+ statement: "SET SESSION TRANSACTION READ WRITE; SELECT 1",+ refused: true,+ reason: "rewrites the session it runs on",+ },+ {+ // A single well-formed statement the server executes as a+ // server-side file write. The MySQL family has no read-only+ // driver session, so the classifier is the whole guarantee here.+ name: "SELECT INTO OUTFILE is a write, not a read",+ engine: storepb.Engine_MYSQL,+ statement: "SELECT * FROM employee INTO OUTFILE '/tmp/employee.txt'",+ refused: true,+ reason: "the statement is not a read",+ },+ {+ name: "so is INTO DUMPFILE",+ engine: storepb.Engine_MYSQL,+ statement: "SELECT * FROM employee INTO DUMPFILE '/tmp/employee.bin'",+ refused: true,+ reason: "the statement is not a read",+ },+ {+ name: "and on MariaDB, which shares the validator",+ engine: storepb.Engine_MARIADB,+ statement: "SELECT * FROM employee INTO OUTFILE '/tmp/employee.txt'",+ refused: true,+ reason: "the statement is not a read",+ },+ {+ // TiDB carries its own validator and its own AST. It rejects+ // DUMPFILE at parse time, so OUTFILE is the form to pin.+ name: "and on TiDB, which carries its own",+ engine: storepb.Engine_TIDB,+ statement: "SELECT * FROM employee INTO OUTFILE '/tmp/employee.txt'",+ refused: true,+ reason: "the statement is not a read",+ },+ {+ // The forms that put INTO below the root. The parser attaches it+ // to an arm of a set operation or to a parenthesized query, so a+ // check on the statement it hands back misses all three — pg+ // walks its arms for the same reason.+ name: "INTO OUTFILE on a set operation is still a write",+ engine: storepb.Engine_MYSQL,+ statement: "SELECT 1 UNION SELECT 2 INTO OUTFILE '/tmp/u.txt'",+ refused: true,+ reason: "the statement is not a read",+ },+ {+ name: "and on the leading arm of one",+ engine: storepb.Engine_MYSQL,+ statement: "SELECT * FROM employee INTO OUTFILE '/tmp/x.txt' UNION SELECT 1",+ refused: true,+ reason: "the statement is not a read",+ },+ {+ name: "and inside a parenthesized query",+ engine: storepb.Engine_MYSQL,+ statement: "(SELECT * FROM employee INTO OUTFILE '/tmp/p.txt')",+ refused: true,+ reason: "the statement is not a read",+ },+ {+ // INTO a variable assigns session state and returns no rows. It+ // is refused, but as the "returns no data" case rather than as a+ // write, because that is what it is.+ name: "INTO a variable is session state, not a file write",+ engine: storepb.Engine_MYSQL, // TiDB rejects this form at parse time.+ statement: "SELECT id FROM employee INTO @found",+ refused: true,+ reason: "returns no data",+ },+ {+ // The clause form decides, not the path it names: these fields+ // hold the decoded filename, so an empty one is still a write.+ name: "an empty OUTFILE target is still a file write",+ engine: storepb.Engine_MYSQL,+ statement: "SELECT 1 INTO OUTFILE ''",+ refused: true,+ reason: "the statement is not a read",+ },+ {+ // StarRocks and Doris export straight out of the database, to S3+ // or HDFS, which leaves before Bytebase can mask a returned row.+ name: "StarRocks INTO OUTFILE exports out of the database",+ engine: storepb.Engine_STARROCKS,+ statement: `SELECT * FROM employee INTO OUTFILE "s3://bucket/export/" FORMAT AS PARQUET PROPERTIES("a" = "b")`,+ refused: true,+ reason: "the statement is not a read",+ },+ {+ name: "and so does Doris",+ engine: storepb.Engine_DORIS,+ statement: `SELECT * FROM employee INTO OUTFILE "s3://bucket/export/" FORMAT AS PARQUET PROPERTIES("a" = "b")`,+ refused: true,+ reason: "the statement is not a read",+ },+ {+ // Doris nests block comments; the shared stripper stops at the+ // first "*/", so stripping first would leave text between INTO+ // and OUTFILE and lose a keyword-pair match. The guard reads the+ // raw statement for that reason.+ name: "a nested comment cannot hide a Doris export",+ engine: storepb.Engine_DORIS,+ statement: "SELECT * FROM employee\nINTO /* outer /* inner */ tail */ OUTFILE \"s3://bucket/export/\"\nFORMAT AS PARQUET",+ refused: true,+ reason: "the statement is not a read",+ },+ {+ name: "nor can a line comment",+ engine: storepb.Engine_DORIS,+ statement: "SELECT * FROM employee INTO\n-- c\nOUTFILE \"s3://b/\"",+ refused: true,+ reason: "the statement is not a read",+ },+ {+ name: "an unlexable Doris statement fails closed",+ engine: storepb.Engine_DORIS,+ statement: "SELECT * FROM t WHERE a = 'unterminated",+ refused: true,+ reason: "the statement is not a read",+ },+ {+ // USE rebinds the connection's catalog and schema, so an+ // unqualified read after it resolves somewhere the caller never+ // named and the span ACL never authorized.+ name: "Trino USE rebinds the connection",+ engine: storepb.Engine_TRINO,+ statement: "USE other_catalog.secret_schema; SELECT * FROM t",+ refused: true,+ reason: "returns no data",+ },+ {+ name: "so does SET SESSION AUTHORIZATION",+ engine: storepb.Engine_TRINO,+ statement: "SET SESSION AUTHORIZATION alice",+ refused: true,+ reason: "returns no data",+ },+ {+ // Redis SELECT switches the connection's logical database, so the+ // GET after it reads a database the caller did not ask for.+ name: "Redis SELECT switches the logical database",+ engine: storepb.Engine_REDIS,+ statement: "SELECT 1\nGET secret",+ refused: true,+ reason: "returns no data",+ },+ {+ name: "an unseparated batch is refused rather than read on its first statement",+ engine: storepb.Engine_CLICKHOUSE,+ statement: "SELECT 1; DROP TABLE employee",+ refused: true,+ reason: "the statement is not a read",+ },+ {+ // The lexer, not the text, decides. Reading an audit log for+ // attempted exports is a plausible read-only task, so the keyword+ // inside a literal, a quoted identifier or a comment must serve.+ name: "Doris serves the export keyword inside a string literal",+ engine: storepb.Engine_DORIS,+ statement: "SELECT * FROM audit_log WHERE statement LIKE '%INTO OUTFILE%'",+ },+ {+ name: "and inside a quoted identifier",+ engine: storepb.Engine_DORIS,+ statement: "SELECT `outfile` FROM t",+ },+ {+ name: "and inside a comment",+ engine: storepb.Engine_DORIS,+ statement: "SELECT 1 /* INTO OUTFILE 's3://b/' */",+ },+ {+ // Not "inside a comment" for a NESTED one: omni's Doris lexer ends+ // a comment at the first "*/", so the tail leaks back into the+ // token stream and the keyword is seen. Doris itself nests, so+ // this query is a plain SELECT 1 there and Bytebase refuses it+ // anyway (BOT-93). Pinned as the cost of failing closed on a+ // disagreement rather than guessing which lexer is right.+ name: "a nested comment holding the keyword refuses, though Doris would not",+ engine: storepb.Engine_DORIS,+ statement: "SELECT 1 /* outer /* inner */ OUTFILE */",+ refused: true,+ reason: "the statement is not a read",+ },+ {+ name: "a read on an engine with no splitter is still classified",+ engine: storepb.Engine_REDIS,+ statement: "GET k",+ },+ {+ name: "a write on an engine with no splitter is refused",+ engine: storepb.Engine_REDIS,+ statement: "GET k\nSET k v",+ refused: true,+ reason: "the statement is not a read",+ },+ }++ for _, row := range rows {+ t.Run(row.name, func(t *testing.T) {+ err := refuseNonReadOnlyStatement(row.engine, row.statement)+ if !row.refused {+ require.NoError(t, err)+ return+ }+ require.Error(t, err)+ require.Equal(t, connect.CodePermissionDenied, connect.CodeOf(err),+ "a clamp refusal is a policy denial, the same kind the ceiling gate returns")+ require.Contains(t, err.Error(), row.reason)+ require.Contains(t, err.Error(), "READ_ONLY",+ "the denial must name the ceiling that refused")+ // query_database suppresses its own "request the SQL Editor role"+ // suggestion when it sees this phrase in the body, because no+ // project role lifts a workspace ceiling. The two live in+ // different processes and meet only over HTTP, so the producer+ // pins the phrase here and executeQuery (backend/api/mcp) keys on+ // the same one.+ require.Contains(t, err.Error(), "MCP capability ceiling",+ "query_database keys its suggestion suppression on this phrase")+ require.Contains(t, err.Error(), "raise the MCP ceiling",+ "the denial must name the way out")+ require.Contains(t, err.Error(), "Bytebase console",+ "the denial must name where the human can do it instead")+ })+ }+}++// TestMCPClampBatchTailIsClassifiedOnEveryEngine walks one adversarial batch —+// a leading read with a write behind it — across every engine that has a+// classifier, and pins which ones the clamp catches it on.+//+// It exists because the rule is only as good as the split, and two engines+// cannot make it: the ClickHouse and Hive splitters break on newlines rather+// than statement terminators, so a one-line batch reaches the leading-keyword+// validator whole (BOT-86). That validator now refuses a statement still+// carrying a terminator it did not end with, which is what keeps the exception+// set below empty.+//+// The set is kept rather than deleted: an engine that starts serving such a+// batch fails this test instead of passing quietly.+func TestMCPClampBatchTailIsClassifiedOnEveryEngine(t *testing.T) {+ const batch = "SELECT 1; DROP TABLE employee"++ // Empty, and it must stay that way. The ClickHouse and Hive splitters+ // still break on newlines rather than terminators (BOT-86), but their+ // validator now refuses a statement that carries a terminator which is not+ // its own, so an unseparated batch fails closed instead of being read on+ // its leading SELECT.+ servesTheWholeBatch := map[storepb.Engine]bool{}++ values := storepb.Engine(0).Descriptor().Values()+ for i := range values.Len() {+ engine := storepb.Engine(values.Get(i).Number())+ if engine == storepb.Engine_ENGINE_UNSPECIFIED || !parserbase.HasQueryValidator(engine) {+ continue+ }+ // Redis takes commands, not SQL, and separates them by newline, so+ // this probe is not a batch there at all — it is one malformed SELECT+ // command. Its batch rule is covered by the newline rows in+ // TestMCPClampRefusesWhatItCannotShowIsARead instead.+ if engine == storepb.Engine_REDIS {+ continue+ }+ t.Run(engine.String(), func(t *testing.T) {+ err := refuseNonReadOnlyStatement(engine, batch)+ if servesTheWholeBatch[engine] {+ require.NoError(t, err,+ "%v is a recorded BOT-86 exception; if it now refuses the batch, delete its row here", engine)+ return+ }+ require.Error(t, err, "%v must not serve a batch whose second statement writes", engine)+ })+ }+}++// TestMCPClampRefusesEngineItCannotClassify is the reason the clamp owns a+// wrapper instead of calling base.ValidateSQLForEditor the way the rest of the+// file does.+//+// The first half is the fail-open itself, pinned: for an engine with no+// registered validator the bare call answers "read-only" for a statement that+// writes. Substitute that call for the wrapper in the clamp and this engine's+// writes run under a read-only ceiling. The second half is the wrapper+// refusing the same statements.+func TestMCPClampRefusesEngineItCannotClassify(t *testing.T) {+ for engine, statement := range unclassifiedEngineWrites {+ t.Run(engine.String(), func(t *testing.T) {+ require.False(t, parserbase.HasQueryValidator(engine),+ "this test is about the engines with no classifier; %v has gained one", engine)++ readOnly, _, err := parserbase.ValidateSQLForEditor(engine, statement)+ require.NoError(t, err)+ require.True(t, readOnly,+ "the bare call answers read-only here, which is the fail-open the wrapper exists to close")++ err = refuseNonReadOnlyStatement(engine, statement)+ require.Error(t, err, "the wrapper must refuse an engine it cannot classify")+ require.Equal(t, connect.CodePermissionDenied, connect.CodeOf(err))+ require.Contains(t, err.Error(), "has no read-only classifier")++ require.Error(t, refuseNonReadOnlyStatement(engine, "SELECT 1"),+ "a statement that looks like a read is refused too: the engine, not the statement, is what cannot be shown")+ })+ }+}++// TestMCPClampAppliesOnlyToReadOnlyMCPSessions pins what turns the clamp on.+// The marker is the presence of the delegated grant, never a field of it, and+// the ceiling is the one the gate already resolved for this request.+func TestMCPClampAppliesOnlyToReadOnlyMCPSessions(t *testing.T) {+ withGrant := &common.AuthContext{DelegatedGrant: &common.DelegatedGrant{}}++ rows := []struct {+ name string+ ctx context.Context+ applies bool+ failure bool+ }{+ {+ name: "a human request carries no auth context here",+ ctx: context.Background(),+ },+ {+ name: "a public-chain request carries no delegated grant",+ ctx: contextWithAuth(&common.AuthContext{}),+ },+ {+ name: "an MCP session under a read-write ceiling is not clamped",+ ctx: withMCPCeiling(contextWithAuth(withGrant),+ storepb.WorkspaceProfileSetting_READ_WRITE),+ },+ {+ name: "an MCP session under a read-only ceiling is clamped",+ ctx: withMCPCeiling(contextWithAuth(withGrant),+ storepb.WorkspaceProfileSetting_READ_ONLY),+ applies: true,+ },+ {+ name: "an MCP session whose ceiling never resolved fails closed",+ ctx: contextWithAuth(withGrant),++ failure: true,+ },+ }++ for _, row := range rows {+ t.Run(row.name, func(t *testing.T) {+ applies, err := mcpReadOnlyClampApplies(row.ctx)+ if row.failure {+ require.Error(t, err, "an MCP request the gate never held must not run unclamped")+ require.Equal(t, connect.CodeInternal, connect.CodeOf(err))+ return+ }+ require.NoError(t, err)+ require.Equal(t, row.applies, applies)+ })+ }+}++// TestMCPClampReadsTheCeilingTheGateResolved is the agreement the three+// enforcement points rest on. The gate resolves the workspace ceiling once,+// per request, and stamps it; the clamp holds the same request against that+// same value rather than reading the setting again. One resolution per request+// is what makes it impossible for the gate to admit a call the clamp then+// judges under a different ceiling.+func TestMCPClampReadsTheCeilingTheGateResolved(t *testing.T) {+ for _, row := range []struct {+ name string+ stores mcpGateStore+ clamped bool+ }{+ {name: "read-only", stores: readOnlyCeiling(), clamped: true},+ {name: "read-write", stores: readWriteCeiling(), clamped: false},+ } {+ t.Run(row.name, func(t *testing.T) {+ got := invokeMCPGate(t, row.stores, &common.AuthContext{+ MCPMethodClass: v1pb.MCPMethodClass_READ,+ DelegatedGrant: &common.DelegatedGrant{},+ }, "/bytebase.v1.SQLService/Query", connect.NewRequest(&v1pb.QueryRequest{}))++ require.NoError(t, got.err)+ require.True(t, got.dispatched)++ ceiling, ok := mcpCeilingFromContext(got.dispatchedCtx)+ require.True(t, ok, "the gate must hand the handler the ceiling it resolved")+ require.Equal(t, row.stores.ceiling, ceiling)++ clamped, err := mcpReadOnlyClampApplies(got.dispatchedCtx)+ require.NoError(t, err)+ require.Equal(t, row.clamped, clamped)+ })+ }+}++func contextWithAuth(authCtx *common.AuthContext) context.Context {+ return context.WithValue(context.Background(), common.AuthContextKey, authCtx)+}diff --git a/backend/api/v1/sql_service.go b/backend/api/v1/sql_service.goindex 7a121765b4..50a3a9c5ca 100644--- a/backend/api/v1/sql_service.go+++ b/backend/api/v1/sql_service.go@@ -347,6 +347,27 @@ func (s *SQLService) Query(ctx context.Context, req *connect.Request[v1pb.QueryR}}+ // The MCP read-only clamp. Unconditional on Explain, unlike the gate+ // above: an explain request carries the bare statement and the driver+ // prepends EXPLAIN, so skipping it would hand a read-only session an+ // unclassified write to send.+ clamped, err := mcpReadOnlyClampApplies(ctx)+ if err != nil {+ return nil, err+ }+ if clamped {+ if err := refuseNonReadOnlyStatement(instance.Metadata.GetEngine(), statement); err != nil {+ // The same kind of refusal the ceiling gate records, taken at the+ // one point that can see the request's argument. It adds no row+ // today — Query is annotated audit = true, so the denial is+ // recorded either way — and it is here so that stays true if that+ // annotation ever changes, which is the only thing the mark+ // controls.+ common.SetMCPPolicyDenied(ctx)+ return nil, err+ }+ }+queryRestriction := getEffectiveQueryDataPolicy(ctx,s.store,@@ -366,7 +387,12 @@ func (s *SQLService) Query(ctx context.Context, req *connect.Request[v1pb.QueryRdriver, err := s.dbFactory.GetDataSourceDriver(ctx, instance, dataSource, db.ConnectionContext{DatabaseName: database.DatabaseName,DataShare: database.Metadata.GetDatashare(),- ReadOnly: dataSource.GetType() == storepb.DataSourceType_READ_ONLY,+ // A clamped request asks for the read-only session whatever data+ // source it landed on, so the depth does not depend on the customer+ // having configured a read-only data source. The driver is opened and+ // closed inside this handler, so the session cannot outlive the+ // request or be reused by another one.+ ReadOnly: clamped || dataSource.GetType() == storepb.DataSourceType_READ_ONLY,})if err != nil {return nil, connect.NewError(connect.CodeInternal, errors.Errorf("failed to get database driver: %v", err))diff --git a/backend/generated-go/v1/setting_service.pb.go b/backend/generated-go/v1/setting_service.pb.goindex ccb4aa247c..d461429bcd 100644--- a/backend/generated-go/v1/setting_service.pb.go+++ b/backend/generated-go/v1/setting_service.pb.go@@ -155,9 +155,11 @@ const (WorkspaceProfileSetting_MCP_CAPABILITY_UNSPECIFIED WorkspaceProfileSetting_MCPCapability = 0// MCP connections are rejected.WorkspaceProfileSetting_DISABLED WorkspaceProfileSetting_MCPCapability = 1- // MCP may inspect metadata and run read-only queries. Not enforceable yet:- // until per-tool enforcement ships, this fails closed and refuses all MCP- // connections, the same as DISABLED.+ // MCP may inspect metadata and run read-only queries. A session opens, and+ // what it may do is decided per method by the capability gate and per+ // statement by the SQL clamp: a request holding a statement that is not a+ // read is refused whole, and where the engine's driver has one the+ // database session is opened read-only as well.WorkspaceProfileSetting_READ_ONLY WorkspaceProfileSetting_MCPCapability = 3// MCP may perform mutations, still bounded by the user's RBAC.WorkspaceProfileSetting_READ_WRITE WorkspaceProfileSetting_MCPCapability = 4diff --git a/backend/plugin/db/driver.go b/backend/plugin/db/driver.goindex 5de62f5179..083ef2e313 100644--- a/backend/plugin/db/driver.go+++ b/backend/plugin/db/driver.go@@ -99,7 +99,10 @@ type ConnectionContext struct {DatabaseName string// It's only set for Redshift datashare database.DataShare bool- // ReadOnly is only supported for Postgres at the moment.+ // ReadOnly asks the driver to open a read-only database session. Three+ // honor it, all by setting default_transaction_read_only on the connection+ // they open: postgres, cockroachdb, and redshift outside a datashare+ // database. Every other driver ignores it.ReadOnly bool// MessageBuffer is used for logging messages from the database server.MessageBuffer []*v1pb.QueryResult_Messagediff --git a/backend/plugin/parser/base/interface.go b/backend/plugin/parser/base/interface.goindex 8d1519c5f4..d52d4cf3eb 100644--- a/backend/plugin/parser/base/interface.go+++ b/backend/plugin/parser/base/interface.go@@ -93,6 +93,12 @@ func RegisterQueryValidator(engine storepb.Engine, f ValidateSQLForEditorFunc) {// 2. SELECT statement// We also support CTE with SELECT statements, but not with DML statements.// The first bool indicates whether the query can run in read-only mode, and the second bool determines whether all queries return data.+//+// An engine with no registered validator answers "read-only, all queries+// return data". That default suits the callers who only route or format with+// it; a caller that must REFUSE a write has to ask HasQueryValidator first,+// because here the answer for such an engine is a default rather than a+// verdict.func ValidateSQLForEditor(engine storepb.Engine, statement string) (bool, bool, error) {f, ok := queryValidators[engine]if !ok {@@ -101,6 +107,18 @@ func ValidateSQLForEditor(engine storepb.Engine, statement string) (bool, bool,return f(statement)}+// HasQueryValidator reports whether a read-only query validator is registered+// for engine, so a caller can tell ValidateSQLForEditor's verdict apart from+// its no-validator default. The map stays unexported: this is the whole of+// what a caller outside the package may learn about it.+//+// Lock-free like every other lookup here, and for the same reason: validators+// are registered from package init functions, before any request runs.+func HasQueryValidator(engine storepb.Engine) bool {+ _, ok := queryValidators[engine]+ return ok+}+func RegisterExtractChangedResourcesFunc(engine storepb.Engine, f ExtractChangedResourcesFunc) {mux.Lock()defer mux.Unlock()diff --git a/backend/plugin/parser/doris/query.go b/backend/plugin/parser/doris/query.goindex dd44c38fa7..b0c5a0c5a6 100644--- a/backend/plugin/parser/doris/query.go+++ b/backend/plugin/parser/doris/query.go@@ -2,6 +2,7 @@ package dorisimport ("github.com/bytebase/omni/doris/ast"+ "github.com/bytebase/omni/doris/parser"storepb "github.com/bytebase/bytebase/backend/generated-go/store""github.com/bytebase/bytebase/backend/plugin/parser/base"@@ -25,6 +26,14 @@ func init() {// The (bool, bool, error) return shape matches the bytebase QueryValidator// contract: (isReadOnly, isExplicitReadOnly, syntaxError).func validateQuery(statement string) (bool, bool, error) {+ // INTO OUTFILE exports to S3 or HDFS, past masking and the export gate.+ // Matched on text because omni's Doris grammar has no INTO node: it parses+ // to a bare SelectStmt identical to one without the clause (BOT-92).+ // Replace with an AST check, as starrocks/query.go does, once it has one.+ //+ if mentionsFileExport(statement) {+ return false, false, nil+ }parsed, err := parseDorisSQL(statement)if err != nil {return false, false, err@@ -90,3 +99,37 @@ func isExplainableInner(node ast.Node) bool {}return false}++// mentionsFileExport reports whether the statement carries an OUTFILE keyword+// token. Doris only; see validateQuery for why the AST cannot answer this.+//+// The lexer decides, not the text, so OUTFILE inside a string literal, a+// backtick-quoted identifier or a plain comment yields no keyword and the+// statement serves. Reading an audit log for attempted exports stays a+// servable query.+//+// Nested block comments are the exception, and they fail closed rather than+// being understood: this lexer ends a comment at the first "*/", so+// "/* a /* b */ OUTFILE */" leaks its tail back into the token stream and the+// keyword is seen. Doris itself nests, so the two disagree about what such a+// statement even is (BOT-93). The disagreement is one-directional here: what+// leaks is extra tokens, so a write Doris would run cannot go unseen.+//+// A statement that will not lex fails closed as well: an unterminated string+// or comment is exactly where a keyword could be hiding.+func mentionsFileExport(statement string) bool {+ tokens, lexErrors := parser.Tokenize(statement)+ if len(lexErrors) > 0 {+ return true+ }+ for _, token := range tokens {+ if token.Kind == outfileTokenKind {+ return true+ }+ }+ return false+}++// outfileTokenKind is resolved from the keyword table rather than hardcoded.+// DUMPFILE is deliberately absent: it is MySQL syntax, not a Doris keyword.+var outfileTokenKind, _ = parser.KeywordToken("outfile")diff --git a/backend/plugin/parser/mysql/query.go b/backend/plugin/parser/mysql/query.goindex b4e4a3c0c5..ad825301a9 100644--- a/backend/plugin/parser/mysql/query.go+++ b/backend/plugin/parser/mysql/query.go@@ -27,7 +27,16 @@ func validateQuery(statement string) (bool, bool, error) {for _, node := range stmts.Items {switch stmt := node.(type) {case *ast.SelectStmt:- // SELECT is always allowed.+ // INTO OUTFILE and INTO DUMPFILE write a file on the server, so+ // they are writes (pg refuses its own SELECT ... INTO likewise).+ // INTO <variable> returns no rows: the SET case, not a write.+ writesFile, assignsVariables := selectIntoTargets(stmt)+ if writesFile {+ return false, false, nil+ }+ if assignsVariables {+ hasExecute = true+ }case *ast.ExplainStmt:if stmt.Analyze {readOnly = false@@ -42,3 +51,30 @@ func validateQuery(statement string) (bool, bool, error) {}return readOnly, !hasExecute, nil}++// selectIntoTargets reports what a SELECT's INTO clause targets. It searches+// the whole statement rather than its root because the parser attaches INTO to+// an arm of a set operation or to a parenthesized query, not necessarily to the+// node the caller holds — the same reason pg's omniIntoClause walks its arms.+//+// A subquery cannot carry INTO in MySQL, so reaching into the tree cannot+// over-match a legal statement; if the grammar ever allowed it, the answer here+// would be conservative rather than permissive.+func selectIntoTargets(n *ast.SelectStmt) (writesFile, assignsVariables bool) {+ ast.Inspect(n, func(node ast.Node) bool {+ sel, ok := node.(*ast.SelectStmt)+ if !ok || sel.Into == nil {+ return true+ }+ // The clause form decides, not the filename it carries: those fields+ // hold the decoded path, so "INTO OUTFILE ''" leaves both empty while+ // still being a file write.+ if len(sel.Into.Vars) > 0 {+ assignsVariables = true+ } else {+ writesFile = true+ }+ return true+ })+ return writesFile, assignsVariables+}diff --git a/backend/plugin/parser/redis/query.go b/backend/plugin/parser/redis/query.goindex 0448f67835..2d5274c55e 100644--- a/backend/plugin/parser/redis/query.go+++ b/backend/plugin/parser/redis/query.go@@ -115,6 +115,7 @@ func init() {}func validateQuery(statement string) (bool, bool, error) {+ returnsData := truelines := strings.Split(statement, "\n")for _, line := range lines {fields, err := shlex.Split(line)@@ -127,8 +128,13 @@ func validateQuery(statement string) (bool, bool, error) {if !isReadCommand(fields) {return false, false, nil}+ // SELECT switches the connection's logical database, so a later command+ // runs somewhere the caller did not name.+ if strings.EqualFold(fields[0], "select") {+ returnsData = false+ }}- return true, true, nil+ return true, returnsData, nil}func isReadCommand(fields []string) bool {diff --git a/backend/plugin/parser/standard/query.go b/backend/plugin/parser/standard/query.goindex 27e3350361..4323769055 100644--- a/backend/plugin/parser/standard/query.go+++ b/backend/plugin/parser/standard/query.go@@ -37,6 +37,13 @@ func ValidateSQLForEditor(statement string) (bool, bool, error) {func CheckStatementWithoutQuotedTextAndComment(statement string) bool {formattedStr := strings.ToUpper(strings.TrimSpace(statement))+ // Leading-keyword classification speaks for one statement only, and the+ // ClickHouse and Hive splitters break on newlines rather than terminators,+ // so a one-line batch arrives whole: "SELECT 1; DROP TABLE t" would pass+ // on its SELECT.+ if strings.Contains(strings.TrimSuffix(formattedStr, ";"), ";") {+ return false+ }if isSelect, _ := regexp.MatchString(`^SELECT\s+?`, formattedStr); isSelect {return true}diff --git a/backend/plugin/parser/starrocks/query.go b/backend/plugin/parser/starrocks/query.goindex 3326b1f2c5..5aa06e01c8 100644--- a/backend/plugin/parser/starrocks/query.go+++ b/backend/plugin/parser/starrocks/query.go@@ -52,8 +52,11 @@ func validateQuery(statement string) (bool, bool, error) {// SQL after parseStarRocksSQL succeeds.func isReadOnlyAST(node ast.Node) bool {switch n := node.(type) {- case *ast.SelectStmt, *ast.SetOpStmt:- return true+ case *ast.SelectStmt:+ // INTO OUTFILE exports to S3 or HDFS, past masking and the export gate.+ return n.Into == nil+ case *ast.SetOpStmt:+ return !setOpWritesOutfile(n)case *ast.ShowStmt:// Reject bare `SHOW` (Type is empty when the parser took the stub path// without seeing a recognised variant keyword).@@ -90,3 +93,16 @@ func isExplainableInner(node ast.Node) bool {}return false}++// setOpWritesOutfile walks the arms: the parser attaches INTO to an arm rather+// than to the set operation, and arms nest.+func setOpWritesOutfile(node ast.Node) bool {+ switch n := node.(type) {+ case *ast.SelectStmt:+ return n.Into != nil+ case *ast.SetOpStmt:+ return setOpWritesOutfile(n.Left) || setOpWritesOutfile(n.Right)+ default:+ return false+ }+}diff --git a/backend/plugin/parser/tidb/query.go b/backend/plugin/parser/tidb/query.goindex bf63d7bd60..881f6290bb 100644--- a/backend/plugin/parser/tidb/query.go+++ b/backend/plugin/parser/tidb/query.go@@ -26,6 +26,18 @@ func validateQuery(statement string) (bool, bool, error) {for _, stmt := range stmtList {switch stmt := stmt.(type) {case *ast.SelectStmt:+ // INTO OUTFILE writes a file on the database server, so the+ // statement is not a read whatever the SELECT itself does — pg+ // refuses its own SELECT ... INTO on the same grounds.+ //+ // Every INTO form is refused here, not just OUTFILE, and TiDB's+ // parser is why there is nothing more to distinguish: it rejects+ // DUMPFILE, INTO <variable>, and INTO on a set operation outright,+ // so OUTFILE is the only form that reaches this line today and any+ // form a later parser accepts lands on the same refusal.+ if stmt.SelectIntoOpt != nil {+ return false, false, nil+ }case *ast.SetOprStmt:case *ast.SetStmt:hasExecute = truediff --git a/backend/plugin/parser/trino/query.go b/backend/plugin/parser/trino/query.goindex af341521c2..65b96a7eff 100644--- a/backend/plugin/parser/trino/query.go+++ b/backend/plugin/parser/trino/query.go@@ -1,6 +1,9 @@package trinoimport (+ "github.com/bytebase/omni/trino/ast"+ "github.com/bytebase/omni/trino/parser"+storepb "github.com/bytebase/bytebase/backend/generated-go/store""github.com/bytebase/bytebase/backend/plugin/parser/base")@@ -20,6 +23,20 @@ func init() {// EXPLAIN ANALYZE is special-cased exactly as the legacy plugin did: because it// executes the inner query, it is only accepted when getQueryType reports it as// read-only (base.Select); it then counts as read-only and data-returning.+// changesSession reports whether a statement rebinds the connection rather+// than reading from it.+func changesSession(node ast.Node) bool {+ switch node.(type) {+ case *parser.SetSessionStmt, *parser.ResetSessionStmt,+ *parser.SetSessionAuthorizationStmt, *parser.ResetSessionAuthorizationStmt,+ *parser.SetPathStmt, *parser.SetRoleStmt, *parser.SetTimeZoneStmt,+ *parser.UseStmt:+ return true+ default:+ return false+ }+}+func validateQuery(statement string) (bool, bool, error) {parsed, err := parseTrinoSQL(statement)if err != nil {@@ -44,7 +61,10 @@ func validateQuery(statement string) (bool, bool, error) {readOnly := queryType == base.Select ||queryType == base.Explain ||queryType == base.SelectInfoSchema- returnsData := readOnly+ // USE and the SET family rebind the connection's catalog, schema, role+ // or identity, so a later statement resolves somewhere the caller did+ // not name. Reported through the same bool as every other engine's SET.+ returnsData := readOnly && !changesSession(p.Node())if !readOnly {allReadOnly = falsediff --git a/backend/tests/mcp_migration_matrix_test.go b/backend/tests/mcp_migration_matrix_test.goindex 94e0a2904b..0465fcb7a1 100644--- a/backend/tests/mcp_migration_matrix_test.go+++ b/backend/tests/mcp_migration_matrix_test.go@@ -360,10 +360,12 @@ func TestMCPMigrationCeilingLookupFailureFailsClosed(t *testing.T) {// of an already-open session — no re-auth, no token re-issue, nothing revoked.//// The ceiling is read live on every /mcp request, which is what makes this-// admission control rather than a property of session setup. READ_ONLY is the-// tightening used here because this phase cannot yet clamp per tool, so a-// ceiling the server cannot apply must refuse the connection instead of-// silently granting read-write.+// admission control rather than a property of session setup. DISABLED is the+// tightening used here because it is the ceiling that refuses the connection+// itself. Tightening to READ_ONLY bites the same way and at the same moment,+// but a step further in: the session still opens, and what it may then do+// narrows per method and per statement — TestMCPReadOnlyTighteningBitesAnOpenSession+// drives that half, on a session that is already open when the ceiling moves.func TestMCPMigrationTightenedCeilingBitesLiveSession(t *testing.T) {t.Parallel()a := require.New(t)@@ -380,7 +382,7 @@ func TestMCPMigrationTightenedCeilingBitesLiveSession(t *testing.T) {"the session is live under the default ceiling")// An admin tightens the ceiling while the session stays open.- a.NoError(ctl.setMCPCapability(ctx, v1pb.WorkspaceProfileSetting_READ_ONLY))+ a.NoError(ctl.setMCPCapability(ctx, v1pb.WorkspaceProfileSetting_DISABLED))status, body := postMCP(t, ctl, mcpToken)a.Equal(http.StatusForbidden, status,diff --git a/backend/tests/mcp_sql_clamp_test.go b/backend/tests/mcp_sql_clamp_test.gonew file mode 100644index 0000000000..38c63d63e3--- /dev/null+++ b/backend/tests/mcp_sql_clamp_test.go@@ -0,0 +1,596 @@+package tests++import (+ "context"+ "database/sql"+ "encoding/base64"+ "encoding/json"+ "fmt"+ "net/http"+ "strings"+ "testing"++ "connectrpc.com/connect"+ "github.com/modelcontextprotocol/go-sdk/mcp"+ "github.com/stretchr/testify/require"++ v1pb "github.com/bytebase/bytebase/backend/generated-go/v1"+)++// queryToolResult is what an agent gets back from query_database: the text a+// model reads, the structured output a client can act on, and whether the tool+// reported a failure.+type queryToolResult struct {+ text string+ output QueryToolOutput+ isError bool+ rawWhole string+}++// QueryToolOutput mirrors the tool's structured output. Only the fields these+// tests assert on are named.+type QueryToolOutput struct {+ Rows [][]any `json:"rows"`+ RowCount int `json:"rowCount"`+}++// queryDatabaseOnSession runs the query_database tool the way a client would.+func queryDatabaseOnSession(ctx context.Context, t *testing.T, session *mcp.ClientSession, database, statement string) queryToolResult {+ t.Helper()+ result, err := session.CallTool(ctx, &mcp.CallToolParams{+ Name: "query_database",+ Arguments: map[string]any{+ "database": database,+ "statement": statement,+ },+ })+ require.NoError(t, err)++ out := queryToolResult{isError: result.IsError}+ var sb strings.Builder+ for _, content := range result.Content {+ if text, ok := content.(*mcp.TextContent); ok {+ sb.WriteString(text.Text)+ }+ }+ out.text = sb.String()+ if result.StructuredContent != nil {+ raw, err := json.Marshal(result.StructuredContent)+ require.NoError(t, err)+ out.rawWhole = string(raw)+ require.NoError(t, json.Unmarshal(raw, &out.output))+ }+ return out+}++// mcpClampFixture is one live server with one Postgres database holding one+// row, reachable through one open MCP session belonging to the workspace admin.+//+// The principal is deliberately the admin: RBAC would let this session write,+// so anything that refuses a write below is the ceiling and nothing else.+type mcpClampFixture struct {+ ctl *controller+ ctx context.Context+ // database is the full resource name, for the API; name is the short one+ // query_database resolves on.+ database string+ name string+ session *mcp.ClientSession+ token string+}++func setupMCPClampFixture(ctx context.Context, t *testing.T) *mcpClampFixture {+ t.Helper()+ a := require.New(t)+ ctl := &controller{}+ ctx, err := ctl.StartServerWithExternalPg(ctx)+ a.NoError(err)+ t.Cleanup(func() { ctl.Close(ctx) })++ container, err := provisionPgInstance(ctx, t)+ a.NoError(err)+ instanceResp, err := ctl.instanceServiceClient.CreateInstance(ctx, connect.NewRequest(&v1pb.CreateInstanceRequest{+ InstanceId: generateRandomString("mcp-clamp"),+ Instance: &v1pb.Instance{+ Title: "MCP clamp",+ Engine: v1pb.Engine_POSTGRES,+ Environment: new("environments/prod"),+ Activation: true,+ DataSources: []*v1pb.DataSource{container.adminDataSource()},+ },+ }))+ a.NoError(err)++ databaseName := generateRandomString("clampdb")+ a.NoError(ctl.createDatabase(ctx, ctl.project, instanceResp.Msg, nil, databaseName, ""))+ databaseResp, err := ctl.databaseServiceClient.GetDatabase(ctx, connect.NewRequest(&v1pb.GetDatabaseRequest{+ Name: fmt.Sprintf("%s/databases/%s", instanceResp.Msg.Name, databaseName),+ }))+ a.NoError(err)++ setup, err := ctl.sheetServiceClient.CreateSheet(ctx, connect.NewRequest(&v1pb.CreateSheetRequest{+ Parent: ctl.project.Name,+ Sheet: &v1pb.Sheet{Content: []byte(+ `CREATE TABLE employee(id INT PRIMARY KEY, name TEXT); INSERT INTO employee VALUES (1, 'Bytebase'); CREATE SEQUENCE employee_seq;`)},+ }))+ a.NoError(err)+ a.NoError(ctl.changeDatabase(ctx, ctl.project, databaseResp.Msg, setup.Msg, false))++ a.NoError(ctl.setMCPCapability(ctx, v1pb.WorkspaceProfileSetting_READ_ONLY))+ token, _ := mintMCPOAuthToken(t, ctl, ctl.authInterceptor.token)+ session := openMCPSession(ctx, t, ctl, token)+ t.Cleanup(func() { session.Close() })++ return &mcpClampFixture{+ ctl: ctl,+ ctx: ctx,+ database: databaseResp.Msg.Name,+ name: databaseName,+ session: session,+ token: token,+ }+}++// employeeCount reads the row count back on the human path, which is a+// different session from the agent's and is not clamped — so a write that+// slipped through is caught by the database's state rather than by the API+// that was supposed to refuse it.+func (f *mcpClampFixture) employeeCount(t *testing.T) int {+ t.Helper()+ resp, err := f.ctl.sqlServiceClient.Query(f.ctx, connect.NewRequest(&v1pb.QueryRequest{+ Name: f.database,+ Statement: "SELECT count(*) FROM employee",+ }))+ require.NoError(t, err)+ require.Len(t, resp.Msg.Results, 1)+ require.Empty(t, resp.Msg.Results[0].Error)+ return int(resp.Msg.Results[0].Rows[0].Values[0].GetInt64Value())+}++// TestMCPReadOnlyCeilingRefusesAWrite is the exit criterion of the whole+// series, as an agent meets it: a live MCP session under a read-only workspace+// ceiling, held by a principal RBAC would let write, running an INSERT through+// query_database.+//+// The control at the end is what makes it about the ceiling: the same session+// and the same principal run the same INSERT under READ_WRITE and it lands.+func TestMCPReadOnlyCeilingRefusesAWrite(t *testing.T) {+ t.Parallel()+ a := require.New(t)+ f := setupMCPClampFixture(context.Background(), t)++ // A read is served, and the response says what held it to reads. Postgres+ // gets the driver session too, so the strongest depth is what it reports.+ read := queryDatabaseOnSession(f.ctx, t, f.session, f.name, "SELECT id, name FROM employee")+ a.False(read.isError, "a read must be served under a read-only ceiling: %s", read.text)+ a.Equal(1, read.output.RowCount)++ // The write is refused, with the message the gate set the shape for.+ write := queryDatabaseOnSession(f.ctx, t, f.session, f.name,+ "INSERT INTO employee VALUES (2, 'agent')")+ a.True(write.isError, "an INSERT must be refused under a read-only ceiling: %s", write.text)+ a.Contains(write.text, "READ_ONLY", "the denial must name the ceiling that refused")+ a.Contains(write.text, "the statement is not a read", "the denial must say what was wrong with the request")+ a.Contains(write.text, "raise the MCP ceiling", "the denial must name the way out")+ a.Contains(write.text, "Bytebase console", "the denial must name where the human can do it instead")++ // Refused before execution, not after: the database is untouched.+ a.Equal(1, f.employeeCount(t), "the refused INSERT must not have reached the database")++ // The depth layer, asserted where only a real read-only session can+ // satisfy it. nextval writes, but it writes from inside a structural+ // SELECT, so the classifier calls it a read and the clamp admits it — the+ // database is what refuses, and only because the connection was opened+ // read-only. Drop the clamp term from ConnectionContext.ReadOnly and this+ // is the assertion that goes red.+ sequence := queryDatabaseOnSession(f.ctx, t, f.session, f.name, "SELECT nextval('employee_seq')")+ a.True(sequence.isError, "the read-only session must refuse a write the classifier admitted: %s", sequence.text)+ a.Contains(sequence.text, "read-only transaction",+ "the refusal must come from the database, not from the classifier")++ // The same statement on the human path proves the refusal was this+ // session's depth and not something about the statement. Query reports a+ // statement failure inside the result rather than as an RPC error, so the+ // advancing sequence is what actually distinguishes the two.+ before := f.sequenceValue(t)+ human, err := f.ctl.sqlServiceClient.Query(f.ctx, connect.NewRequest(&v1pb.QueryRequest{+ Name: f.database,+ Statement: "SELECT nextval('employee_seq')",+ }))+ a.NoError(err)+ a.Len(human.Msg.Results, 1)+ a.Empty(human.Msg.Results[0].Error,+ "a person in the console runs the same statement without a read-only session")+ a.Greater(f.sequenceValue(t), before, "the human's nextval must actually have advanced the sequence")++ // The refusal is recorded, and attributable to the agent rather than to the+ // same human working in the console.+ // Query is a database-scoped method, so its rows are parented to the+ // project rather than to the workspace.+ rows := deniedMCPRows(f.ctx, t, f.ctl, f.ctl.project.Name, "/bytebase.v1.SQLService/Query")+ a.NotEmpty(rows, "a clamp denial must be visible to an operator with MCP provenance")+ var denied *v1pb.AuditLog+ for _, row := range rows {+ if row.Status != nil && row.Status.Code != 0 {+ denied = row+ break+ }+ }+ a.NotNil(denied, "the denied query must have produced a row of its own")+ a.Contains(denied.Status.Message, "READ_ONLY")++ // The control. Same principal, same credential, same statement; only the+ // ceiling changed, and the INSERT now lands. It runs on a session opened+ // after the widening, because a ceiling is read per request and this test+ // is about the ceiling rather than about session lifetime —+ // TestMCPReadOnlyTighteningBitesAnOpenSession covers the live-session half.+ a.NoError(f.ctl.setMCPCapability(f.ctx, v1pb.WorkspaceProfileSetting_READ_WRITE))+ widened := openMCPSession(f.ctx, t, f.ctl, f.token)+ defer widened.Close()+ allowed := queryDatabaseOnSession(f.ctx, t, widened, f.name,+ "INSERT INTO employee VALUES (2, 'agent')")+ a.False(allowed.isError, "under READ_WRITE the same principal must write: %s", allowed.text)+ a.Equal(2, f.employeeCount(t))+}++// sequenceValue reads the sequence back on the human path, for the same reason+// employeeCount does.+func (f *mcpClampFixture) sequenceValue(t *testing.T) int64 {+ t.Helper()+ resp, err := f.ctl.sqlServiceClient.Query(f.ctx, connect.NewRequest(&v1pb.QueryRequest{+ Name: f.database,+ // last_value alone is 1 both before and after the first nextval; the+ // is_called flag is what separates them, so this counts calls: 0+ // before any, N after N.+ Statement: "SELECT CASE WHEN is_called THEN last_value ELSE 0 END FROM employee_seq",+ }))+ require.NoError(t, err)+ require.Len(t, resp.Msg.Results, 1)+ require.Empty(t, resp.Msg.Results[0].Error)+ return resp.Msg.Results[0].Rows[0].Values[0].GetInt64Value()+}++// TestMCPReadOnlyCeilingRefusesASessionRewrite is the escape the two layers+// would otherwise leave open between them.+//+// Both statements classify as reads: SET is not a write, and nextval writes+// from inside a structural SELECT, which no classifier catches. Every statement+// of a request runs on one connection, and Postgres applies a changed+// default_transaction_read_only to the next transaction — so admitting the SET+// would hand the second statement a session with the depth switched off, and+// the sequence would advance under a ceiling that had just reported the+// connection was opened read-only.+//+// Refusing a statement that rewrites its session is what closes it, and the+// sequence value is what proves nothing ran.+func TestMCPReadOnlyCeilingRefusesASessionRewrite(t *testing.T) {+ t.Parallel()+ a := require.New(t)+ f := setupMCPClampFixture(context.Background(), t)+ before := f.sequenceValue(t)++ disarm := queryDatabaseOnSession(f.ctx, t, f.session, f.name,+ "SET default_transaction_read_only = off; SELECT nextval('employee_seq')")+ a.True(disarm.isError, "a request that rewrites its own session must be refused: %s", disarm.text)+ a.Contains(disarm.text, "rewrites the session it runs on")+ a.Contains(disarm.text, "READ_ONLY")++ a.Equal(before, f.sequenceValue(t),+ "neither statement may run: the sequence must not have advanced")++ // The rewrite alone is refused too, so the rule is about the statement and+ // not about what follows it.+ alone := queryDatabaseOnSession(f.ctx, t, f.session, f.name,+ "SET default_transaction_read_only = off")+ a.True(alone.isError, "a bare session rewrite is refused as well: %s", alone.text)+}++// TestMCPReadOnlyCeilingJudgesTheWholeBatch pins the batch rule: a request is+// served only if every statement in it reads, and one write refuses all of it+// rather than running the reads that came before.+func TestMCPReadOnlyCeilingJudgesTheWholeBatch(t *testing.T) {+ t.Parallel()+ a := require.New(t)+ f := setupMCPClampFixture(context.Background(), t)++ reads := queryDatabaseOnSession(f.ctx, t, f.session, f.name,+ "SELECT id FROM employee; SELECT name FROM employee;")+ a.False(reads.isError, "an all-read batch must be served whole: %s", reads.text)++ mixed := queryDatabaseOnSession(f.ctx, t, f.session, f.name,+ "SELECT id FROM employee; DELETE FROM employee; SELECT name FROM employee;")+ a.True(mixed.isError, "a batch holding a write must be refused: %s", mixed.text)+ a.Contains(mixed.text, "statement 2 of 3 is not a read",+ "the denial must name which statement refused the batch")++ a.Equal(1, f.employeeCount(t), "no part of a refused batch may run")+}++// TestMCPReadOnlyCeilingLeavesTheHumanPathAlone is the other half of the claim.+// The clamp keys on the delegated grant, so a person signed in to the console+// is untouched by it — and the read-only database session the agent's request+// opened cannot reach that person's request either, because the driver is+// opened and closed inside the handler that asked for it.+func TestMCPReadOnlyCeilingLeavesTheHumanPathAlone(t *testing.T) {+ t.Parallel()+ a := require.New(t)+ f := setupMCPClampFixture(context.Background(), t)++ // The agent's read runs first and is SERVED, which is what actually opens+ // a read-only Postgres session; a refused statement never reaches a+ // connection at all, so it could not leak one.+ served := queryDatabaseOnSession(f.ctx, t, f.session, f.name, "SELECT id FROM employee")+ a.False(served.isError, "the agent's read must be served, or nothing opened a session: %s", served.text)++ refused := queryDatabaseOnSession(f.ctx, t, f.session, f.name,+ "INSERT INTO employee VALUES (3, 'agent')")+ a.True(refused.isError)++ before := f.sequenceValue(t)+ human, err := f.ctl.sqlServiceClient.Query(f.ctx, connect.NewRequest(&v1pb.QueryRequest{+ Name: f.database,+ Statement: "INSERT INTO employee VALUES (4, 'human'); SELECT nextval('employee_seq');",+ }))+ a.NoError(err, "a workspace ceiling of READ_ONLY must not bind a person in the console")+ for _, result := range human.Msg.Results {+ a.Empty(result.Error, "no statement of the human's request may fail")+ }+ a.Equal(2, f.employeeCount(t))+ a.Greater(f.sequenceValue(t), before,+ "the nextval half must have run too: a leaked read-only session would stop it while the INSERT still counted")++ humanRead, err := f.ctl.sqlServiceClient.Query(f.ctx, connect.NewRequest(&v1pb.QueryRequest{+ Name: f.database,+ Statement: "SELECT id FROM employee",+ }))+ a.NoError(err)+ a.Len(humanRead.Msg.Results, 1)+ a.Empty(humanRead.Msg.Results[0].Error, "a person's read is untouched by the ceiling")+}++// TestMCPReadOnlyTighteningBitesAnOpenSession is the half of matrix row 7 the+// cutover moved. Tightening to READ_ONLY used to refuse the connection, so the+// migration matrix could assert it at the door; now the session stays open and+// the tightening bites one layer further in, per method and per statement, on+// the next request. Nothing is re-consented and no token is re-issued.+func TestMCPReadOnlyTighteningBitesAnOpenSession(t *testing.T) {+ t.Parallel()+ a := require.New(t)+ f := setupMCPClampFixture(context.Background(), t)++ // Start read-write, on a session opened under that ceiling.+ a.NoError(f.ctl.setMCPCapability(f.ctx, v1pb.WorkspaceProfileSetting_READ_WRITE))+ session := openMCPSession(f.ctx, t, f.ctl, f.token)+ defer session.Close()+ wrote := queryDatabaseOnSession(f.ctx, t, session, f.name,+ "INSERT INTO employee VALUES (5, 'agent')")+ a.False(wrote.isError, "the session starts able to write: %s", wrote.text)+ a.Equal(2, f.employeeCount(t))++ // An admin tightens the ceiling while the session stays open.+ a.NoError(f.ctl.setMCPCapability(f.ctx, v1pb.WorkspaceProfileSetting_READ_ONLY))++ refused := queryDatabaseOnSession(f.ctx, t, session, f.name,+ "INSERT INTO employee VALUES (6, 'agent')")+ a.True(refused.isError, "the tightening must bite the very next request of the open session: %s", refused.text)+ a.Contains(refused.text, "READ_ONLY")+ a.Equal(2, f.employeeCount(t))++ // Reads keep working on that same session, so what tightened is the+ // ceiling and not the session.+ read := queryDatabaseOnSession(f.ctx, t, session, f.name, "SELECT id FROM employee")+ a.False(read.isError, "a read must still be served on the tightened session: %s", read.text)++ // Widening bites the same way, on the same session.+ a.NoError(f.ctl.setMCPCapability(f.ctx, v1pb.WorkspaceProfileSetting_READ_WRITE))+ again := queryDatabaseOnSession(f.ctx, t, session, f.name,+ "INSERT INTO employee VALUES (7, 'agent')")+ a.False(again.isError, "widening restores the write on the unchanged session: %s", again.text)+ a.Equal(3, f.employeeCount(t))+}++// TestMCPReadOnlyClampCoversAnExplainRequest pins the clamp's placement outside+// the Explain guard above it. query_database sends no explain flag, but+// call_api reaches the same handler with the whole request shape, and an+// explain request carries the bare statement for the driver to prefix — so a+// clamp that skipped it would hand a read-only session an unclassified write to+// send.+func TestMCPReadOnlyClampCoversAnExplainRequest(t *testing.T) {+ t.Parallel()+ a := require.New(t)+ f := setupMCPClampFixture(context.Background(), t)++ explained := callAPIOnSession(f.ctx, t, f.session, "SQLService/Query", map[string]any{+ "name": f.database,+ "statement": "SELECT id FROM employee",+ "explain": true,+ })+ a.Equal(http.StatusOK, explained.Status, "explaining a read is still a read: %s", explained.Error)++ refused := callAPIOnSession(f.ctx, t, f.session, "SQLService/Query", map[string]any{+ "name": f.database,+ "statement": "INSERT INTO employee VALUES (8, 'agent')",+ "explain": true,+ })+ a.Equal(http.StatusForbidden, refused.Status,+ "an explain request must be clamped like any other: %s", refused.Error)+ a.Contains(refused.Error, "READ_ONLY")+ a.Equal(1, f.employeeCount(t))+}++// TestMCPCutoverAdmitsReadOnlyAndNothingElse is the cutover itself. READ_ONLY+// opens a session and serves its class; every ceiling this build cannot serve+// still refuses the connection, including the values no Bytebase write+// produces.+func TestMCPCutoverAdmitsReadOnlyAndNothingElse(t *testing.T) {+ t.Parallel()+ a := require.New(t)+ ctx := context.Background()+ ctl := &controller{}+ ctx, err := ctl.StartServerWithExternalPg(ctx)+ a.NoError(err)+ defer ctl.Close(ctx)++ workspace, err := ctl.workspaceServiceClient.GetWorkspace(ctx, connect.NewRequest(&v1pb.GetWorkspaceRequest{+ Name: "workspaces/-",+ }))+ a.NoError(err)+ workspaceID := strings.TrimPrefix(workspace.Msg.Name, "workspaces/")++ project, err := ctl.projectServiceClient.CreateProject(ctx, connect.NewRequest(&v1pb.CreateProjectRequest{+ ProjectId: "mcp-cutover",+ Project: &v1pb.Project{Title: "MCP cutover"},+ }))+ a.NoError(err)++ token, _ := mintMCPOAuthToken(t, ctl, ctl.authInterceptor.token)++ a.NoError(ctl.setMCPCapability(ctx, v1pb.WorkspaceProfileSetting_READ_ONLY))+ status, body := postMCP(t, ctl, token)+ a.Equal(http.StatusOK, status, "READ_ONLY must admit a connection now that the clamp holds it to reads; %s", body)++ session := openMCPSession(ctx, t, ctl, token)+ defer session.Close()++ a.Equal(http.StatusOK, callAPIStatus(ctx, t, session, "WorkspaceService/ListWorkspaces", nil),+ "a READ method is what a read-only ceiling serves")++ sheet := callAPIOnSession(ctx, t, session, "SheetService/CreateSheet", map[string]any{+ "parent": project.Msg.Name,+ "sheet": map[string]any{"content": base64.StdEncoding.EncodeToString([]byte("SELECT 1;"))},+ })+ a.Equal(http.StatusForbidden, sheet.Status, "a WRITE method must stay refused under READ_ONLY")+ a.Contains(sheet.Error, "READ_ONLY")+ a.Contains(sheet.Error, "raise the MCP ceiling")++ // DISABLED is still the ceiling that closes the door.+ a.NoError(ctl.setMCPCapability(ctx, v1pb.WorkspaceProfileSetting_DISABLED))+ status, body = postMCP(t, ctl, token)+ a.Equal(http.StatusForbidden, status, "DISABLED must still refuse the connection; %s", body)++ // And so is every value this build cannot serve. The settings API refuses+ // to write these, so they are written the only way a workspace could+ // actually hold one: by hand.+ db, err := sql.Open("pgx", ctl.profile.PgURL)+ a.NoError(err)+ defer db.Close()+ for _, row := range []struct {+ value string+ why string+ }{+ {`2`, "the reserved number was METADATA_ONLY; no mode serves it"},+ {`99`, "a number no build ever wrote"},+ {`"READ_WRTIE"`, "a mistyped ceiling is not a ceiling that permits"},+ {`"MCP_CAPABILITY_UNSPECIFIED"`, "the zero value was resolved by nobody"},+ } {+ result, err := db.ExecContext(ctx, `+ UPDATE setting SET value = jsonb_set(value, '{mcpCapability}', $2::jsonb)+ WHERE workspace = $1 AND name = 'WORKSPACE_PROFILE';+ `, workspaceID, row.value)+ a.NoError(err)+ affected, err := result.RowsAffected()+ a.NoError(err)+ a.Equal(int64(1), affected, "the workspace profile row must exist for %s to mean anything", row.value)++ status, body = postMCP(t, ctl, token)+ a.Equal(http.StatusForbidden, status, "%s: %s; %s", row.value, row.why, body)+ }+}++// TestMCPReadOnlyRoleDowngradeBitesTheNextRequest extends the live-state pin+// TestInternalChainMembershipRevocationTakesEffectNextRequest holds at the+// credential — the delegated credential carries identity and grant state only,+// so authorization is re-resolved on every request — to the clamped path a+// read-only session actually runs on.+//+// A role change is the live-state case that pin cannot reach: it revokes+// membership, which the auth interceptor answers, while a downgrade that leaves+// membership intact is the ACL's to answer, one interceptor further in and+// behind the ceiling gate. The session, the grant and the token are untouched+// throughout, and no re-consent happens.+func TestMCPReadOnlyRoleDowngradeBitesTheNextRequest(t *testing.T) {+ t.Parallel()+ a := require.New(t)+ f := setupMCPClampFixture(context.Background(), t)++ const readerEmail = "[email protected]"+ const readerPassword = "1024bytebase"+ reader, err := f.ctl.userServiceClient.CreateUser(f.ctx, connect.NewRequest(&v1pb.CreateUserRequest{+ User: &v1pb.User{Title: "clamp reader", Email: readerEmail, Password: readerPassword},+ }))+ a.NoError(err)+ _, err = f.ctl.addMemberToWorkspaceIAM(f.ctx, reader.Msg.Workspace, "user:"+readerEmail, "roles/workspaceMember")+ a.NoError(err)++ setProjectRole := func(roles ...string) {+ policy, err := f.ctl.projectServiceClient.GetIamPolicy(f.ctx, connect.NewRequest(&v1pb.GetIamPolicyRequest{+ Resource: f.ctl.project.Name,+ }))+ a.NoError(err)+ var kept []*v1pb.Binding+ for _, binding := range policy.Msg.Bindings {+ var members []string+ for _, member := range binding.Members {+ if !strings.Contains(member, readerEmail) {+ members = append(members, member)+ }+ }+ if len(members) > 0 {+ binding.Members = members+ kept = append(kept, binding)+ }+ }+ for _, role := range roles {+ kept = append(kept, &v1pb.Binding{Role: role, Members: []string{"user:" + readerEmail}})+ }+ policy.Msg.Bindings = kept+ _, err = f.ctl.projectServiceClient.SetIamPolicy(f.ctx, connect.NewRequest(&v1pb.SetIamPolicyRequest{+ Resource: f.ctl.project.Name,+ Policy: policy.Msg,+ }))+ a.NoError(err)+ }++ setProjectRole("roles/sqlEditorUser")+ login, err := f.ctl.authServiceClient.Login(f.ctx, connect.NewRequest(&v1pb.LoginRequest{+ Email: readerEmail, Password: readerPassword,+ }))+ a.NoError(err)+ readerToken, _ := mintMCPOAuthToken(t, f.ctl, login.Msg.Token)+ session := openMCPSession(f.ctx, t, f.ctl, readerToken)+ defer session.Close()++ // call_api rather than query_database, so the only thing under test is the+ // permission on the query itself: query_database resolves the database by+ // listing workspace-wide first, and a listing denial would refuse this for+ // a reason that is not the one this test is about.+ query := map[string]any{"name": f.database, "statement": "SELECT id FROM employee"}+ served := callAPIOnSession(f.ctx, t, session, "SQLService/Query", query)+ a.Equal(http.StatusOK, served.Status, "the reader starts able to read: %s", served.Error)++ // The admin takes the role away. Nothing else changes: same session, same+ // token, same consented grant.+ setProjectRole()++ refused := callAPIOnSession(f.ctx, t, session, "SQLService/Query", query)+ a.Equal(http.StatusForbidden, refused.Status,+ "a role taken away must bite on the very next request: %s", refused.Error)+ a.NotContains(refused.Error, "READ_ONLY",+ "this refusal is the caller's own RBAC, not the ceiling — effective access is the intersection")++ // Live in both directions, so the refusal was the role and not damage to+ // the session.+ setProjectRole("roles/sqlEditorUser")+ restored := callAPIOnSession(f.ctx, t, session, "SQLService/Query", query)+ a.Equal(http.StatusOK, restored.Status,+ "restoring the role restores service on the unchanged session: %s", restored.Error)++ // The clamp still owns the other half for this principal: sqlEditorUser+ // carries bb.sql.dml, so RBAC would let this write and the ceiling is what+ // does not.+ written := callAPIOnSession(f.ctx, t, session, "SQLService/Query", map[string]any{+ "name": f.database, "statement": "INSERT INTO employee VALUES (9, 'reader')",+ })+ a.Equal(http.StatusForbidden, written.Status)+ a.Contains(written.Error, "READ_ONLY")+}diff --git a/frontend/src/locales/en-US.json b/frontend/src/locales/en-US.jsonindex b19bef61d8..5a67b17e3c 100644--- a/frontend/src/locales/en-US.json+++ b/frontend/src/locales/en-US.json@@ -2474,7 +2474,7 @@"self": "Disabled"},"read-only": {- "description": "Reserved for fine-grained read-only enforcement, which has not shipped yet. Until it does, choosing this refuses MCP connections entirely, the same as Disabled.",+ "description": "MCP sessions can inspect metadata and run read-only queries, still bounded by each user's own permissions. A request is refused whole if Bytebase classifies any statement in it as a write, or cannot determine that it only reads.","self": "Read-only"},"read-write": {diff --git a/frontend/src/locales/es-ES.json b/frontend/src/locales/es-ES.jsonindex 3c3900ca34..55013b1f7a 100644--- a/frontend/src/locales/es-ES.json+++ b/frontend/src/locales/es-ES.json@@ -2474,7 +2474,7 @@"self": "Deshabilitado"},"read-only": {- "description": "Reservado para el control de solo lectura detallado, que aún no está disponible. Hasta entonces, elegir esta opción rechaza por completo las conexiones MCP, igual que Deshabilitado.",+ "description": "Las sesiones MCP pueden inspeccionar metadatos y ejecutar consultas de solo lectura, siempre limitadas por los permisos de cada usuario. Se rechaza la solicitud completa si Bytebase clasifica alguna de sus instrucciones como escritura o no puede determinar que solo lee.","self": "Solo lectura"},"read-write": {diff --git a/frontend/src/locales/ja-JP.json b/frontend/src/locales/ja-JP.jsonindex 15241dc0e5..65bb72ec97 100644--- a/frontend/src/locales/ja-JP.json+++ b/frontend/src/locales/ja-JP.json@@ -2474,7 +2474,7 @@"self": "無効"},"read-only": {- "description": "きめ細かな読み取り専用制御のために予約されています(未提供)。提供されるまでは、これを選択すると MCP 接続は完全に拒否され、「無効」と同じ動作になります。",+ "description": "MCP セッションはメタデータを参照し、読み取り専用クエリを実行できますが、各ユーザー自身の権限の範囲内に制限されます。リクエスト内のいずれかのステートメントが書き込みと判定された場合、または読み取りのみであると確認できない場合、リクエスト全体が拒否されます。","self": "読み取り専用"},"read-write": {diff --git a/frontend/src/locales/vi-VN.json b/frontend/src/locales/vi-VN.jsonindex 680916ca67..c458d79c5b 100644--- a/frontend/src/locales/vi-VN.json+++ b/frontend/src/locales/vi-VN.json@@ -2474,7 +2474,7 @@"self": "Tắt"},"read-only": {- "description": "Dành cho cơ chế kiểm soát chỉ đọc chi tiết, hiện chưa được phát hành. Cho đến khi đó, chọn tùy chọn này sẽ từ chối hoàn toàn các kết nối MCP, giống như Tắt.",+ "description": "Các phiên MCP có thể xem siêu dữ liệu và chạy truy vấn chỉ đọc, vẫn bị giới hạn bởi quyền của từng người dùng. Toàn bộ yêu cầu sẽ bị từ chối nếu Bytebase xác định bất kỳ câu lệnh nào trong đó là ghi, hoặc không thể xác nhận rằng nó chỉ đọc.","self": "Chỉ đọc"},"read-write": {diff --git a/frontend/src/locales/zh-CN.json b/frontend/src/locales/zh-CN.jsonindex 96f2368b7e..851b319908 100644--- a/frontend/src/locales/zh-CN.json+++ b/frontend/src/locales/zh-CN.json@@ -2474,7 +2474,7 @@"self": "禁用"},"read-only": {- "description": "为细粒度只读控制预留,该能力尚未上线。在此之前,选择此项将完全拒绝 MCP 连接,效果与“禁用”相同。",+ "description": "MCP 会话可以查看元数据并执行只读查询,仍受每个用户自身权限的约束。如果 Bytebase 将其中任一语句判定为写入,或无法确认其仅执行读取,整个请求都会被拒绝。","self": "只读"},"read-write": {diff --git a/frontend/src/types/proto-es/v1/setting_service_pb.d.ts b/frontend/src/types/proto-es/v1/setting_service_pb.d.tsindex ff04836cc0..0b17dd1f57 100644--- a/frontend/src/types/proto-es/v1/setting_service_pb.d.ts+++ b/frontend/src/types/proto-es/v1/setting_service_pb.d.ts@@ -767,9 +767,11 @@ export enum WorkspaceProfileSetting_MCPCapability {DISABLED = 1,/**- * MCP may inspect metadata and run read-only queries. Not enforceable yet:- * until per-tool enforcement ships, this fails closed and refuses all MCP- * connections, the same as DISABLED.+ * MCP may inspect metadata and run read-only queries. A session opens, and+ * what it may do is decided per method by the capability gate and per+ * statement by the SQL clamp: a request holding a statement that is not a+ * read is refused whole, and where the engine's driver has one the+ * database session is opened read-only as well.** @generated from enum value: READ_ONLY = 3;*/diff --git a/proto/gen/grpc-doc/v1/README.md b/proto/gen/grpc-doc/v1/README.mdindex 2db88972be..84a3b9ce72 100644--- a/proto/gen/grpc-doc/v1/README.md+++ b/proto/gen/grpc-doc/v1/README.md@@ -5287,7 +5287,7 @@ workspaces are unaffected.| ---- | ------ | ----------- || MCP_CAPABILITY_UNSPECIFIED | 0 | || DISABLED | 1 | MCP connections are rejected. |-| READ_ONLY | 3 | MCP may inspect metadata and run read-only queries. Not enforceable yet: until per-tool enforcement ships, this fails closed and refuses all MCP connections, the same as DISABLED. |+| READ_ONLY | 3 | MCP may inspect metadata and run read-only queries. A session opens, and what it may do is decided per method by the capability gate and per statement by the SQL clamp: a request holding a statement that is not a read is refused whole, and where the engine's driver has one the database session is opened read-only as well. || READ_WRITE | 4 | MCP may perform mutations, still bounded by the user's RBAC. |diff --git a/proto/gen/grpc-doc/v1/index.html b/proto/gen/grpc-doc/v1/index.htmlindex f1961fc280..d5db70f452 100644--- a/proto/gen/grpc-doc/v1/index.html+++ b/proto/gen/grpc-doc/v1/index.html@@ -15181,9 +15181,11 @@ Default to this mode.</p></td><tr><td>READ_ONLY</td><td>3</td>- <td><p>MCP may inspect metadata and run read-only queries. Not enforceable yet:-until per-tool enforcement ships, this fails closed and refuses all MCP-connections, the same as DISABLED.</p></td>+ <td><p>MCP may inspect metadata and run read-only queries. A session opens, and+what it may do is decided per method by the capability gate and per+statement by the SQL clamp: a request holding a statement that is not a+read is refused whole, and where the engine's driver has one the+database session is opened read-only as well.</p></td></tr><tr>diff --git a/proto/v1/v1/setting_service.proto b/proto/v1/v1/setting_service.protoindex 41e31ab8b6..513504a8a4 100644--- a/proto/v1/v1/setting_service.proto+++ b/proto/v1/v1/setting_service.proto@@ -297,9 +297,11 @@ message WorkspaceProfileSetting {DISABLED = 1;// Was MCP_METADATA_ONLY; the Metadata-only tier is deferred out of the design.reserved 2;- // MCP may inspect metadata and run read-only queries. Not enforceable yet:- // until per-tool enforcement ships, this fails closed and refuses all MCP- // connections, the same as DISABLED.+ // MCP may inspect metadata and run read-only queries. A session opens, and+ // what it may do is decided per method by the capability gate and per+ // statement by the SQL clamp: a request holding a statement that is not a+ // read is refused whole, and where the engine's driver has one the+ // database session is opened read-only as well.READ_ONLY = 3;// MCP may perform mutations, still bounded by the user's RBAC.READ_WRITE = 4;diff --git a/proto/v1/v1/sql_service.proto b/proto/v1/v1/sql_service.protoindex 17f40d230b..de0837a61f 100644--- a/proto/v1/v1/sql_service.proto+++ b/proto/v1/v1/sql_service.proto@@ -30,9 +30,9 @@ service SQLService {// where the method is not the whole story: on every engine in// EngineSupportQueryNewACL this handler classifies each statement and// authorizes DML with bb.sql.dml and DDL with bb.sql.ddl, so what it does- // is decided by its argument. The ceiling PR that starts serving READ owes- // a statement-level clamp before a read-only session may call this; until- // then no session is admitted at that level at all.+ // is decided by its argument. That is what the SQL clamp in the handler+ // settles: under a read-only ceiling every statement in the request must+ // classify as a read, or the whole request is refused.option (bytebase.v1.mcp_method_class) = READ;}