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): let Read-write sessions request access grants (#21585)
Vincent Huang105838cddf9f
diff --git a/backend/api/mcp/tool_query.go b/backend/api/mcp/tool_query.goindex 4680981b74..18b73fe37a 100644--- a/backend/api/mcp/tool_query.go+++ b/backend/api/mcp/tool_query.go@@ -341,9 +341,8 @@ func parseLatencyMs(latency string) int64 {func IsPolicyRefusal(message string) bool {for _, phrase := range []string{"MCP capability ceiling",- // Singular, so it also matches the plural the gate uses and the two- // refusals that live outside it (rejectMCPOriginatedGrantIssue,- // rejectMCPOriginatedIssuelessRollout).+ // Singular, so it also matches the plural the gate uses and the+ // refusals taken in handlers."MCP session","MCP classification",} {diff --git a/backend/api/v1/access_grant_service.go b/backend/api/v1/access_grant_service.goindex 3a6ec90165..871c1ae08a 100644--- a/backend/api/v1/access_grant_service.go+++ b/backend/api/v1/access_grant_service.go@@ -12,12 +12,14 @@ import ("github.com/bytebase/bytebase/backend/common""github.com/bytebase/bytebase/backend/component/bus"+ "github.com/bytebase/bytebase/backend/component/review""github.com/bytebase/bytebase/backend/component/webhook""github.com/bytebase/bytebase/backend/enterprise"storepb "github.com/bytebase/bytebase/backend/generated-go/store"v1pb "github.com/bytebase/bytebase/backend/generated-go/v1""github.com/bytebase/bytebase/backend/generated-go/v1/v1connect""github.com/bytebase/bytebase/backend/store"+ "github.com/bytebase/bytebase/backend/utils")// AccessGrantService implements the access grant service.@@ -149,11 +151,10 @@ func (s *AccessGrantService) CreateAccessGrant(ctx context.Context, request *con// Validate every target before creating any access-grant or issue rows.workspaceID := common.GetWorkspaceIDFromContext(ctx)- instance, err := s.validateAccessGrantTargets(ctx, projectID, ag.Targets)+ project, instance, err := s.validateAccessGrantTargets(ctx, projectID, ag.Targets)if err != nil {return nil, err}- // Validate the query is a read-only statement (SELECT).if ok, err := isReadOnlyStatementForAccessGrant(ctx, instance.Metadata.GetEngine(), ag.Query); err != nil {return nil, connect.NewError(connect.CodeInvalidArgument, errors.Wrapf(err, "invalid query"))} else if !ok {@@ -201,28 +202,37 @@ func (s *AccessGrantService) CreateAccessGrant(ctx context.Context, request *con}}- // Step 1: Create the access grant.+ payload := &storepb.AccessGrantPayload{+ Targets: ag.Targets,+ Query: ag.Query,+ Unmask: ag.Unmask,+ Export: ag.Export,+ Reason: ag.Reason,+ RequestedDuration: requestedDuration,+ Schema: ag.Schema,+ Container: ag.Container,+ }+ // Decided once and saved on the issue: the workflow skips a done finding, so+ // a later rule edit cannot change whether this request waits for a person.+ approval, riskLevel, err := review.EvaluateAccessGrantApproval(ctx, s.store, project, payload)+ if err != nil {+ return nil, connect.NewError(connect.CodeInternal, errors.Wrap(err, "failed to evaluate the approval rules for this access grant"))+ }+ if err := refuseUnattendedMCPAccessGrant(ctx, approval); err != nil {+ return nil, err+ }+grant, err := s.store.CreateAccessGrant(ctx, &store.AccessGrantMessage{ProjectID: projectID,Creator: creatorEmail,Status: storepb.AccessGrant_PENDING,ExpireTime: expireTime,- Payload: &storepb.AccessGrantPayload{- Targets: ag.Targets,- Query: ag.Query,- Unmask: ag.Unmask,- Export: ag.Export,- Reason: ag.Reason,- RequestedDuration: requestedDuration,- Schema: ag.Schema,- Container: ag.Container,- },+ Payload: payload,})if err != nil {return nil, connect.NewError(connect.CodeInternal, errors.Wrapf(err, "failed to create access grant"))}- // Step 2: Create the associated issue.issue, err := s.store.CreateIssue(ctx, &store.IssueMessage{ProjectID: projectID,CreatorEmail: creatorEmail,@@ -230,9 +240,8 @@ func (s *AccessGrantService) CreateAccessGrant(ctx context.Context, request *conType: storepb.Issue_ACCESS_GRANT,Description: ag.Reason,Payload: &storepb.Issue{- Approval: &storepb.IssuePayloadApproval{- ApprovalFindingDone: false,- },+ Approval: approval,+ RiskLevel: riskLevel,AccessGrantId: grant.ID,},})@@ -240,7 +249,6 @@ func (s *AccessGrantService) CreateAccessGrant(ctx context.Context, request *conreturn nil, connect.NewError(connect.CodeInternal, errors.Wrapf(err, "failed to create issue"))}- // Step 3: Update access grant payload with the issue ID.grant.Payload.IssueId = int64(issue.UID)grant, err = s.store.UpdateAccessGrant(ctx, grant.ID, &store.UpdateAccessGrantMessage{Payload: grant.Payload,@@ -249,52 +257,63 @@ func (s *AccessGrantService) CreateAccessGrant(ctx context.Context, request *conreturn nil, connect.NewError(connect.CodeInternal, errors.Wrapf(err, "failed to update access grant payload"))}- // Step 4: Post-create: webhook, approval finding, auto-approve.- project, err := s.store.GetProject(ctx, &store.FindProjectMessage{Workspace: workspaceID, ResourceID: &projectID})+ issue, err = startIssueWorkflow(ctx, s.store, s.webhookManager, s.licenseService, s.bus, project, creatorEmail, creatorEmail, issue)if err != nil {- return nil, connect.NewError(connect.CodeInternal, errors.Wrapf(err, "failed to get project %v", projectID))- }- if project != nil {- issue, err := startIssueWorkflow(ctx, s.store, s.webhookManager, s.licenseService, s.bus, project, creatorEmail, creatorEmail, issue)+ return nil, connect.NewError(connect.CodeInternal, err)+ }+ // A saved finding emits no approval event, so notify the approvers here.+ review.NotifyApprovalRequested(ctx, s.store, s.webhookManager, issue, project)+ if issue.Status == storepb.Issue_DONE {+ grant, err = s.store.GetAccessGrant(ctx, &store.FindAccessGrantMessage{+ Workspace: common.GetWorkspaceIDFromContext(ctx),+ ID: &grant.ID,+ })if err != nil {- return nil, connect.NewError(connect.CodeInternal, err)- }- if issue.Status == storepb.Issue_DONE {- // Refresh the grant if issue is completed.- grant, err = s.store.GetAccessGrant(ctx, &store.FindAccessGrantMessage{- Workspace: common.GetWorkspaceIDFromContext(ctx),- ID: &grant.ID,- })- if err != nil {- return nil, connect.NewError(connect.CodeInternal, errors.Wrapf(err, "failed to get access grant %v", grant.ID))- }+ return nil, connect.NewError(connect.CodeInternal, errors.Wrapf(err, "failed to get access grant %v", grant.ID))}}return connect.NewResponse(convertToAccessGrant(grant)), nil}-func (s *AccessGrantService) validateAccessGrantTargets(ctx context.Context, projectID string, targets []string) (*store.InstanceMessage, error) {+// refuseUnattendedMCPAccessGrant refuses an MCP session's request that would+// count as approved on creation: an approved grant takes effect at once.+func refuseUnattendedMCPAccessGrant(ctx context.Context, approval *storepb.IssuePayloadApproval) error {+ approved, err := utils.CheckApprovalApproved(approval)+ if err != nil {+ return connect.NewError(connect.CodeInternal, errors.Wrap(err, "failed to check the approval finding"))+ }+ if !approved || !mcpSession(ctx) {+ return nil+ }+ return permissionDeniedError(ctx, errors.Errorf(+ "%s is not available to MCP sessions for this request because no approval rule requires a person to approve it, "++ "so the access would be granted at once with no human step. Ask a workspace admin to give access requests "++ "an approval rule that names an approver, or request the access in the Bytebase console.",+ v1connect.AccessGrantServiceCreateAccessGrantProcedure))+}++func (s *AccessGrantService) validateAccessGrantTargets(ctx context.Context, projectID string, targets []string) (*store.ProjectMessage, *store.InstanceMessage, error) {workspaceID := common.GetWorkspaceIDFromContext(ctx)project, err := s.store.GetProject(ctx, &store.FindProjectMessage{Workspace: workspaceID,ResourceID: &projectID,})if err != nil {- return nil, connect.NewError(connect.CodeInternal, errors.Wrapf(err, "failed to get project %q", projectID))+ return nil, nil, connect.NewError(connect.CodeInternal, errors.Wrapf(err, "failed to get project %q", projectID))}if project == nil || project.Deleted {- return nil, connect.NewError(connect.CodeNotFound, errors.Errorf("project %q not found", projectID))+ return nil, nil, connect.NewError(connect.CodeNotFound, errors.Errorf("project %q not found", projectID))}var firstInstance *store.InstanceMessagefor _, target := range targets {targetProjectID, instanceID, databaseName, err := common.GetDatabaseResourceName(target)if err != nil {- return nil, connect.NewError(connect.CodeInvalidArgument, errors.Wrapf(err, "invalid target %q", target))+ return nil, nil, connect.NewError(connect.CodeInvalidArgument, errors.Wrapf(err, "invalid target %q", target))}if targetProjectID != nil && *targetProjectID != projectID {- return nil, connect.NewError(connect.CodeNotFound, errors.Errorf("database %q not found in project %q", target, projectID))+ return nil, nil, connect.NewError(connect.CodeNotFound, errors.Errorf("database %q not found in project %q", target, projectID))}database, err := s.store.GetDatabase(ctx, &store.FindDatabaseMessage{Workspace: workspaceID,@@ -302,27 +321,27 @@ func (s *AccessGrantService) validateAccessGrantTargets(ctx context.Context, proDatabaseName: &databaseName,})if err != nil {- return nil, connect.NewError(connect.CodeInternal, errors.Wrapf(err, "failed to get database"))+ return nil, nil, connect.NewError(connect.CodeInternal, errors.Wrapf(err, "failed to get database"))}if database == nil || database.ProjectID != projectID {- return nil, connect.NewError(connect.CodeNotFound, errors.Errorf("database %q not found in project %q", target, projectID))+ return nil, nil, connect.NewError(connect.CodeNotFound, errors.Errorf("database %q not found in project %q", target, projectID))}instance, err := s.store.GetInstance(ctx, &store.FindInstanceMessage{Workspace: workspaceID, ResourceID: &instanceID})if err != nil {- return nil, connect.NewError(connect.CodeInternal, errors.Wrapf(err, "failed to get instance %q", instanceID))+ return nil, nil, connect.NewError(connect.CodeInternal, errors.Wrapf(err, "failed to get instance %q", instanceID))}if instance == nil || instance.Deleted {- return nil, connect.NewError(connect.CodeNotFound, errors.Errorf("instance %q not found", instanceID))+ return nil, nil, connect.NewError(connect.CodeNotFound, errors.Errorf("instance %q not found", instanceID))}if (targetProjectID == nil) != (instance.ProjectID == nil) ||targetProjectID != nil && *targetProjectID != *instance.ProjectID {- return nil, connect.NewError(connect.CodeInvalidArgument, errors.Errorf("target %q is not canonical for its instance", target))+ return nil, nil, connect.NewError(connect.CodeInvalidArgument, errors.Errorf("target %q is not canonical for its instance", target))}if firstInstance == nil {firstInstance = instance}}- return firstInstance, nil+ return project, firstInstance, nil}// ActivateAccessGrant activates a pending access grant.diff --git a/backend/api/v1/access_grant_service_test.go b/backend/api/v1/access_grant_service_test.goindex 5b8eb4701a..018aff2295 100644--- a/backend/api/v1/access_grant_service_test.go+++ b/backend/api/v1/access_grant_service_test.go@@ -200,3 +200,48 @@ func TestConvertToAccessGrantNilPayloadIsSafe(t *testing.T) {require.Empty(t, ag.Schema)require.Empty(t, ag.Container)}++func TestRefuseUnattendedMCPAccessGrant(t *testing.T) {+ t.Parallel()+ mcpCtx := context.WithValue(context.Background(), common.AuthContextKey,+ &common.AuthContext{DelegatedGrant: &common.DelegatedGrant{CorrelationID: "corr-grant"}})+ console := context.WithValue(context.Background(), common.AuthContextKey, &common.AuthContext{})+ noTemplate := &storepb.IssuePayloadApproval{ApprovalFindingDone: true}+ noApprover := &storepb.IssuePayloadApproval{+ ApprovalFindingDone: true,+ ApprovalTemplate: &storepb.ApprovalTemplate{Flow: &storepb.ApprovalFlow{}},+ }+ ownerApproves := &storepb.IssuePayloadApproval{+ ApprovalFindingDone: true,+ ApprovalTemplate: &storepb.ApprovalTemplate{Flow: &storepb.ApprovalFlow{Roles: []string{"roles/projectOwner"}}},+ }++ for name, tt := range map[string]struct {+ ctx context.Context+ approval *storepb.IssuePayloadApproval+ code connect.Code+ }{+ "an MCP request no rule sends to a person": {mcpCtx, noTemplate, connect.CodePermissionDenied},+ "an MCP request whose rule names no approver": {mcpCtx, noApprover, connect.CodePermissionDenied},+ "an MCP request a project owner approves": {mcpCtx, ownerApproves, 0},+ "a console request no rule sends to a person": {console, noTemplate, 0},+ "a request with no auth context": {context.Background(), noTemplate, 0},+ "a template with no flow is an error, not a pass": {mcpCtx, &storepb.IssuePayloadApproval{ApprovalFindingDone: true, ApprovalTemplate: &storepb.ApprovalTemplate{}}, connect.CodeInternal},+ } {+ t.Run(name, func(t *testing.T) {+ t.Parallel()+ marked := false+ err := refuseUnattendedMCPAccessGrant(withSetPermissionDenied(tt.ctx, func() { marked = true }), tt.approval)+ require.Equal(t, tt.code == connect.CodePermissionDenied, marked, "only a policy refusal marks the request")+ if tt.code == 0 {+ require.NoError(t, err)+ return+ }+ require.Equal(t, tt.code, connect.CodeOf(err))+ if tt.code == connect.CodePermissionDenied {+ require.Contains(t, err.Error(), "no approval rule requires a person")+ require.Contains(t, err.Error(), "an approval rule that names an approver")+ }+ })+ }+}diff --git a/backend/api/v1/issue_service.go b/backend/api/v1/issue_service.goindex 909e089701..2331bed420 100644--- a/backend/api/v1/issue_service.go+++ b/backend/api/v1/issue_service.go@@ -591,44 +591,18 @@ func linkedIssueForCreate(planUID int64, existing, issue *store.IssueMessage) (*return existing, nil}-// rejectMCPOriginatedGrantIssue refuses an MCP session creating an issue of any-// type but the database change an agent exists to compose (an unset type is-// left to the handler, as the gate leaves it). A ROLE_GRANT issue-// completes on creation whenever the workspace approval rule produces no-// template, and completing it writes the project IAM binding for whichever-// grantee the request named — which is ProjectService/SetIamPolicy, a method-// the MCP ceiling refuses outright. The session would end up granting access-// with no human step.-//-// It lives here rather than only in the ceiling gate because CREATION is the-// fact it turns on, and the gate cannot see that fact. UpdateIssue with-// allow_missing is the same creation under another name, but only when the-// issue does not exist: the handler reaches this function through that branch-// alone, so an ordinary AIP upsert of an issue that DOES exist never arrives-// here — and it must not be refused, since the type in a full-resource PATCH-// says nothing about whether the call creates anything. The gate keeps its own-// refusal for CreateIssue, where the request shape IS the whole story and the-// denial can land before dispatch; this one covers the delegation the gate-// cannot follow, the same way rejectMCPOriginatedTokenMint sits at the mint-// rather than only at its callers.-//-// Presence of the delegated grant is the MCP-origin marker, never a field-// value (common.DelegatedGrant).+// rejectMCPOriginatedGrantIssue applies grantIssueRefusal where the issue is+// created, so it also covers UpdateIssue with allow_missing, which creates only+// when the issue is missing and so cannot be refused at the gate.func rejectMCPOriginatedGrantIssue(ctx context.Context, issueType v1pb.Issue_Type) error {- authCtx, ok := common.GetAuthContextFromContext(ctx)- if !ok || authCtx.DelegatedGrant == nil {+ if !mcpSession(ctx) {return nil}- if issueType == v1pb.Issue_DATABASE_CHANGE || issueType == v1pb.Issue_TYPE_UNSPECIFIED {- // An unset type is the handler's invalid argument, not a policy- // verdict: buildIssueMessage refuses it, and the gate admits it for the- // same reason (refuseGrantIssueCreation).+ reason, wayOut := grantIssueRefusal(issueType)+ if reason == "" {return nil}- return permissionDeniedError(ctx, errors.Errorf(- "an MCP session may not create a %v issue: that issue type completes on creation whenever the "+- "workspace approval rule produces no template, which grants access with no human step. "+- "Create it signed in to the Bytebase console instead", issueType))+ return permissionDeniedError(ctx, errors.Errorf("an MCP session may not create this issue: %s. %s", reason, wayOut))}func (s *IssueService) buildIssueMessage(ctx context.Context, project *store.ProjectMessage, userEmail string, request *v1pb.CreateIssueRequest, labels []string) (*store.IssueMessage, error) {diff --git a/backend/api/v1/mcp_gate.go b/backend/api/v1/mcp_gate.goindex faa0aac663..cc07022c9a 100644--- a/backend/api/v1/mcp_gate.go+++ b/backend/api/v1/mcp_gate.go@@ -156,50 +156,7 @@ var mcpDenialReasons = map[v1pb.MCPDenialReason]mcpDenialWording{// follow-up (BOT-53); disallowing first is the deliberate order.v1pb.MCPDenialReason_REWRITES_SESSION_BOUNDARY: {v1pb.MCPMethodClass_FORBIDDEN, "it rewrites the workspace settings that bound this session, including the switch meant to contain it"},- // The four approval methods. ApproveIssue and RejectIssue are two actions of- // one handler (issue_review.go reviewIssue), and that handler records the- // review decision itself: applyReviewAction requires an approver role via- // canReview, enforces the self-approval guard, and appends an APPROVED or- // REJECTED approver (component/review/workflow.go). An agent composes a- // change; it does not move its own change through the gate. That is the- // whole claim,- // and it is deliberately narrower than "an agent only executes approved work",- // which this classification does NOT deliver: CreatePlan, CreateRollout and- // BatchRunTasks are all WRITE, and both approval checks on the execution- // path are guarded on an issue existing, so a plan created without one- // reaches execution with no approval at all. Whether an issueless rollout- // belongs in WRITE is the gate PR's decision to take deliberately rather- // than inherit.- //- // RequestIssue is the third action of the same handler and is deliberately- // NOT here — it is WRITE. Spec §1b-1 named four approval methods; that line- // grouped by RPC family rather than by mechanism, and the mechanism does not- // agree. This action requires the issue to be already rejected, requires the- // actor to be the issue CREATOR, never calls canReview, and records no- // decision: it strips the REJECTED approvers and returns the issue to- // PENDING for a fresh human decision. It cannot approve anything, so- // refusing it protects nothing the other two do not, and it costs the- // propose-fix-resubmit loop, since while a rejection stands Approve and- // Reject both hard-fail and this is the only exit from that state. The- // reasoning is on the RPC in issue_service.proto. Raised by the Codex- // review; Vincent took the call.- //- // RetryIssueApproval is the near miss and is in deliberately. It casts no- // vote — it re-runs approval-template finding for an issue stuck in- // CHECKING, and only the issue creator may call it (issue_service.go- // canRequestIssue) — but it is the other half of the reason's wording- // rather than an exception to it: on an auto-approved result the same call- // activates the grant and enqueues the rollout (issue_service.go:789,796),- // so it moves an issue through the gate without any human acting. What it- // does not buy is containment of re-derivation in general: UpdatePlan with- // a specs mask, and UpdateIssue on a label change, both reset- // ApprovalFindingDone and force the template to be found again against the- // current workspace rule (component/review/plan.go, metadata.go), and both- // stay WRITE. That is the intended line — editing a proposal is the agent's- // job, and re-review after an edit is the system working — not an oversight.- // Refusing RetryIssueApproval costs an agent the self-service recovery for- // its own stuck issue; the operator retries from the console.- v1pb.MCPDenialReason_DRIVES_THE_APPROVAL_DECISION: {v1pb.MCPMethodClass_FORBIDDEN, "it works the approval step meant to gate the change, and an agent does not move its own change through that gate"},+ v1pb.MCPDenialReason_DRIVES_THE_APPROVAL_DECISION: {v1pb.MCPMethodClass_FORBIDDEN, "it decides whether a change or an access request passes its human approval, and an agent does not decide that for its own work"},// The other refused class. An EXCLUDED method is out of scope for the modes// this release ships and an admin-capable ceiling could legitimately serve@@ -326,22 +283,9 @@ func mcpSettingsForCurrentWorkspace(ctx context.Context, reader mcpSettingsReade// cannot resolve the token audience. Both refuse — an unknown policy never// permits — and neither is allowed to describe itself as the other.//-// One gap survives, and it is worth knowing because nothing in the annotations-// shows it.-//-// - Two refusals this gate is the right slot for the CLASS of, but not the-// right place for the decision, because the fact they turn on is not in the-// request. Both are guarded at the point where the fact is loaded, and both-// key on the delegated grant so the console is untouched:-// rejectMCPOriginatedGrantIssue (issue_service.go), for the issue types-// that complete into a permission grant, and-// rejectMCPOriginatedIssuelessRollout (rollout_service.go), for the-// issueless plan that reaches execution without ever meeting the approval-// the three FORBIDDEN approval methods exist to protect. Without the-// second, those three are decorative in the change lane: an agent that-// cannot clear the gate could skip it instead. The gate keeps the half it-// can decide — CreateIssue, where the request shape IS the whole story —-// so the denial still lands before dispatch wherever that is possible.+// A refusal that turns on a fact the request does not carry, such as whether an+// issue exists, is taken in the handler that loads the fact and keyed on MCP+// origin; TestMCPRefusalsNameThemselvesToTheQueryTool checks each one.type internalMCPGateInterceptor struct {store mcpSettingsReader}@@ -412,12 +356,12 @@ func (in *internalMCPGateInterceptor) refuse(ctx context.Context, req connect.Answitch authCtx.MCPMethodClass {case v1pb.MCPMethodClass_FORBIDDEN: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)))+ "%s is not available to MCP sessions because %s. %s",+ procedure, denialReason(authCtx.MCPMethodClass, authCtx.MCPDenialReason, reasonForbiddenClass), mcpConsoleWayOut))case v1pb.MCPMethodClass_EXCLUDED: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)))+ "%s is served by no MCP capability ceiling because %s. %s",+ procedure, denialReason(authCtx.MCPMethodClass, authCtx.MCPDenialReason, reasonExcludedClass), mcpConsoleWayOut))case v1pb.MCPMethodClass_READ, v1pb.MCPMethodClass_WRITE:default:return ctx, true, connect.NewError(connect.CodePermissionDenied, errors.Errorf(@@ -514,32 +458,28 @@ func describeServedClasses(served []v1pb.MCPMethodClass) string {return strings.Join(names, " and ") + " methods"}+const mcpConsoleWayOut = "Perform this action signed in to the Bytebase console instead"+// mcpRequestShapeRefusals holds the refusals a per-method class cannot express,-// because what the call does depends on a field of the request rather than on-// which method it is. Each entry returns the reason to refuse for, or "" to-// allow.-//-// This lives inside the gate rather than beside it. The decision is the same-// decision — may this MCP session make this call? — and it has to be taken at-// the same point in the chain, so that the denial is marked the same way, is-// worded the same way, and reaches the caller before any handler side effect-// can land. A second interceptor would duplicate the slot, the message, and the-// audit mark to serve one method, and it would put the exception somewhere the-// next person reading the class rule would not find it.-//-// The table is deliberately small and expected to stay that way. A method that-// needs one is a method whose class annotation is not the whole truth, and the-// better fix is usually to split the RPC.-var mcpRequestShapeRefusals = map[string]func(ctx context.Context, msg any) string{+// because what the call does depends on a request field. Each entry returns the+// reason and the way out, or an empty reason to allow. It lives in the gate so a+// refusal is audited and worded like a class refusal, before the handler runs.+var mcpRequestShapeRefusals = map[string]func(ctx context.Context, msg any) (reason, wayOut string){v1connect.IssueServiceCreateIssueProcedure: refuseGrantIssueCreation,- v1connect.SheetServiceCreateSheetProcedure: refuseMaskedWriteSheet,- v1connect.SheetServiceBatchCreateSheetsProcedure: refuseMaskedWriteSheetBatch,- v1connect.ReleaseServiceCreateReleaseProcedure: refuseMaskedWriteRelease,- v1connect.SQLServiceQueryProcedure: refuseMaskedWriteQuery,- v1connect.SQLServiceExportProcedure: refuseMaskedWriteExport,-- v1connect.SavedQueryServiceCreateSavedQueryProcedure: refuseMaskedWriteSavedQuery,- v1connect.SavedQueryServiceUpdateSavedQueryProcedure: refuseMaskedWriteSavedQueryUpdate,+ v1connect.SheetServiceCreateSheetProcedure: inTheConsole(refuseMaskedWriteSheet),+ v1connect.SheetServiceBatchCreateSheetsProcedure: inTheConsole(refuseMaskedWriteSheetBatch),+ v1connect.ReleaseServiceCreateReleaseProcedure: inTheConsole(refuseMaskedWriteRelease),+ v1connect.SQLServiceQueryProcedure: inTheConsole(refuseMaskedWriteQuery),+ v1connect.SQLServiceExportProcedure: inTheConsole(refuseMaskedWriteExport),++ v1connect.SavedQueryServiceCreateSavedQueryProcedure: inTheConsole(refuseMaskedWriteSavedQuery),+ v1connect.SavedQueryServiceUpdateSavedQueryProcedure: inTheConsole(refuseMaskedWriteSavedQueryUpdate),+}++func inTheConsole(refuse func(context.Context, any) string) func(context.Context, any) (string, string) {+ return func(ctx context.Context, msg any) (string, string) {+ return refuse(ctx, msg), mcpConsoleWayOut+ }}// refuseByRequestShape applies the table above. The context carries what the@@ -549,59 +489,41 @@ func refuseByRequestShape(ctx context.Context, procedure string, msg any) errorif !ok {return nil}- reason := refuse(ctx, msg)+ reason, wayOut := refuse(ctx, msg)if reason == "" {return nil}return connect.NewError(connect.CodePermissionDenied, errors.Errorf(- "%s is not available to MCP sessions for this request because %s. "+- "Perform this action signed in to the Bytebase console instead", procedure, reason))+ "%s is not available to MCP sessions for this request because %s. %s", procedure, reason, wayOut))}-// refuseGrantIssueCreation is the CreateIssue carve-out. CreateIssue is WRITE-// for the database-change issue it exists for, and an agent composing a change-// is the whole point of the MCP surface. A ROLE_GRANT issue is a different-// method wearing the same name: it completes on creation whenever the workspace-// approval rule produces no template, and completing it writes the project IAM-// binding for whichever grantee the request names — which is-// ProjectService/SetIamPolicy, EXCLUDED for exactly that outcome. The session-// ends up granting access with no human step.-//-// It is an allow-list of the type the class covers, not a deny-list of the ones-// that reach past it. A deny-list would silently admit the next issue type-// somebody adds, and adding an issue type is not where anyone would think to-// re-read the MCP ceiling. ACCESS_GRANT is refused by that allow-list and never-// reaches the handler in the first place: buildIssueMessage has no arm for it,-// so the type is an invalid argument there, and those issues are written by-// AccessGrantService/CreateAccessGrant, which is EXCLUDED.-//-// An unset type is NOT refused: nothing can be created from it, since-// buildIssueMessage's default arm rejects an unspecified type as an invalid-// argument, so refusing it here would protect nothing and would answer a-// mechanism that does not apply.-//-// UpdateIssue is deliberately NOT in this table, and the reason is the limit of-// what a request shape can decide. allow_missing makes UpdateIssue create the-// issue — but only when it does not already exist, which is not a field of the-// request. An AIP upsert sends the complete resource, so a caller PATCHing an-// existing ROLE_GRANT issue carries type=ROLE_GRANT in a body the handler-// ignores, and refusing on that would refuse an ordinary edit for a mechanism-// that is not running. The creation it really does reach is guarded where the-// creation happens instead: rejectMCPOriginatedGrantIssue in issue_service.go.-func refuseGrantIssueCreation(_ context.Context, msg any) string {+// refuseGrantIssueCreation applies grantIssueRefusal to CreateIssue. UpdateIssue's+// allow_missing creation is guarded in its handler (rejectMCPOriginatedGrantIssue).+func refuseGrantIssueCreation(_ context.Context, msg any) (string, string) {request, ok := msg.(*v1pb.CreateIssueRequest)if !ok {// The table is keyed by procedure, so the request type is fixed. A// mismatch is a wiring bug, and a wiring bug on a refusal path fails// closed.- return fmt.Sprintf("its request could not be read as an issue (%T)", msg)+ return fmt.Sprintf("its request could not be read as an issue (%T)", msg), mcpConsoleWayOut}- switch request.GetIssue().GetType() {+ return grantIssueRefusal(request.GetIssue().GetType())+}++// grantIssueRefusal is the issue-type allow-list both MCP creation guards share,+// so a type added later is refused until someone decides otherwise. An unset+// type is left to buildIssueMessage, which rejects it as invalid.+func grantIssueRefusal(issueType v1pb.Issue_Type) (reason, wayOut string) {+ switch issueType {case v1pb.Issue_DATABASE_CHANGE, v1pb.Issue_TYPE_UNSPECIFIED:- return ""+ return "", ""+ case v1pb.Issue_ACCESS_GRANT:+ reason = fmt.Sprintf("an ACCESS_GRANT issue is filed by %s, not created directly",+ v1connect.AccessGrantServiceCreateAccessGrantProcedure)+ return reason, "Request the access with that method instead"default:return fmt.Sprintf("a %v issue completes on creation whenever the workspace approval rule produces no template, "+- "which grants access with no human step", request.GetIssue().GetType())+ "which grants access with no human step", issueType), mcpConsoleWayOut}}diff --git a/backend/api/v1/mcp_gate_test.go b/backend/api/v1/mcp_gate_test.goindex 25fa83772c..7c533fb1e3 100644--- a/backend/api/v1/mcp_gate_test.go+++ b/backend/api/v1/mcp_gate_test.go@@ -126,6 +126,7 @@ func TestForbiddenClassMembership(t *testing.T) {v1connect.IssueServiceApproveIssueProcedure,v1connect.IssueServiceRejectIssueProcedure,v1connect.IssueServiceRetryIssueApprovalProcedure,+ v1connect.AccessGrantServiceActivateAccessGrantProcedure,v1connect.UserServiceChangePasswordProcedure,v1connect.UserServiceStartMFAEnrollmentProcedure,v1connect.UserServiceEnableMFAProcedure,@@ -184,6 +185,7 @@ func TestForbiddenClassMembership(t *testing.T) {v1connect.IssueServiceApproveIssueProcedure: v1pb.MCPDenialReason_DRIVES_THE_APPROVAL_DECISION,v1connect.IssueServiceRejectIssueProcedure: v1pb.MCPDenialReason_DRIVES_THE_APPROVAL_DECISION,v1connect.IssueServiceRetryIssueApprovalProcedure: v1pb.MCPDenialReason_DRIVES_THE_APPROVAL_DECISION,+ v1connect.AccessGrantServiceActivateAccessGrantProcedure: v1pb.MCPDenialReason_DRIVES_THE_APPROVAL_DECISION,}// Wording for every mechanism in use is checkReasonsMatchTheClass's job, over// every class rather than only the ones enumerated here.@@ -1079,11 +1081,8 @@ func TestMCPGateFailsClosedWithoutAnAuthContext(t *testing.T) {require.Equal(t, connect.CodeInternal, connect.CodeOf(got.err))}-// TestMCPGateRefusesGrantIssues pins the one refusal a per-method class cannot-// express. CreateIssue is WRITE for the database-change issue an agent exists-// to compose; the grant types complete on creation and hand out access with no-// human step. UpdateIssue is the same method under another name whenever-// allow_missing is set.+// TestMCPGateRefusesGrantIssues pins the gate's issue-type allow-list for+// CreateIssue and the way out each refusal names.func TestMCPGateRefusesGrantIssues(t *testing.T) {write := classContext(v1pb.MCPMethodClass_WRITE)@@ -1097,9 +1096,9 @@ func TestMCPGateRefusesGrantIssues(t *testing.T) {require.True(t, got.dispatched)})- for _, issueType := range []v1pb.Issue_Type{- v1pb.Issue_ROLE_GRANT,- v1pb.Issue_ACCESS_GRANT,+ for issueType, tt := range map[v1pb.Issue_Type]struct{ wayOut, notWayOut string }{+ v1pb.Issue_ROLE_GRANT: {mcpConsoleWayOut, v1connect.AccessGrantServiceCreateAccessGrantProcedure},+ v1pb.Issue_ACCESS_GRANT: {v1connect.AccessGrantServiceCreateAccessGrantProcedure, mcpConsoleWayOut},} {t.Run("CreateIssue refuses "+issueType.String(), func(t *testing.T) {got := invokeMCPGate(t, readWriteCeiling(), write, v1connect.IssueServiceCreateIssueProcedure,@@ -1111,6 +1110,8 @@ func TestMCPGateRefusesGrantIssues(t *testing.T) {require.False(t, got.dispatched)require.Equal(t, connect.CodePermissionDenied, connect.CodeOf(got.err))require.Contains(t, got.err.Error(), issueType.String())+ require.Contains(t, got.err.Error(), tt.wayOut)+ require.NotContains(t, got.err.Error(), tt.notWayOut)require.True(t, got.auditMarked)})}@@ -1143,14 +1144,8 @@ func TestMCPGateRefusesGrantIssues(t *testing.T) {require.True(t, got.dispatched)})- // UpdateIssue reaches the gate unrefused whatever its body says, including- // allow_missing with a grant type. The gate cannot tell an upsert that- // creates from one that edits — "the issue does not exist" is not a field- // of the request — and an AIP upsert sends the complete resource, so a- // caller PATCHing an existing ROLE_GRANT issue carries that type in a body- // the handler ignores. rejectMCPOriginatedGrantIssue guards the creation- // where the creation happens; TestMCPGateRefusesGrantIssues (backend/tests)- // is the end-to-end proof that the bypass stays closed.+ // UpdateIssue passes the gate whatever its body says;+ // rejectMCPOriginatedGrantIssue guards its allow_missing creation.for name, request := range map[string]*v1pb.UpdateIssueRequest{"allow_missing with a grant type": {Issue: &v1pb.Issue{Name: "projects/p/issues/1", Type: v1pb.Issue_ROLE_GRANT},@@ -1598,43 +1593,36 @@ func TestLintDenialRequestsAreReviewedForRedaction(t *testing.T) {require.Empty(t, stale, "these no longer need a redaction decision; drop them so the list keeps meaning something")}-// TestRejectMCPOriginatedGrantIssue pins the guard that sits at the creation-// rather than at the gate, and in particular pins the half that makes putting-// MCP policy inside a service handler safe: a human in the console is a request-// with no delegated grant, and must be untouched by it.-//-// The gate cannot take this decision. UpdateIssue creates only when the issue is-// missing, which is not a field of the request, and an AIP upsert sends the-// complete resource — so a caller PATCHing an existing ROLE_GRANT issue carries-// that type in a body the handler ignores. Refusing on the request shape there-// would refuse an ordinary edit for a mechanism that is not running.func TestRejectMCPOriginatedGrantIssue(t *testing.T) {- mcpSession := context.WithValue(context.Background(), common.AuthContextKey,+ mcpCtx := context.WithValue(context.Background(), common.AuthContextKey,&common.AuthContext{DelegatedGrant: &common.DelegatedGrant{CorrelationID: "corr-issue"}})console := context.WithValue(context.Background(), common.AuthContextKey, &common.AuthContext{})for name, tt := range map[string]struct {ctx context.ContextissueType v1pb.Issue_Type- refused bool+ // wayOut is empty for a creation the guard allows.+ wayOut, notWayOut string}{- "an MCP session may not create a role grant": {mcpSession, v1pb.Issue_ROLE_GRANT, true},- "an MCP session may not create an access grant": {mcpSession, v1pb.Issue_ACCESS_GRANT, true},- "an MCP session may not create an unknown type": {mcpSession, v1pb.Issue_Type(9999), true},- "an MCP session composes database changes": {mcpSession, v1pb.Issue_DATABASE_CHANGE, false},- "an unset type is left to buildIssueMessage": {mcpSession, v1pb.Issue_TYPE_UNSPECIFIED, false},- "the console creates a role grant": {console, v1pb.Issue_ROLE_GRANT, false},- "a request with no auth context at all": {context.Background(), v1pb.Issue_ROLE_GRANT, false},+ "an MCP session may not create a role grant": {mcpCtx, v1pb.Issue_ROLE_GRANT, mcpConsoleWayOut, v1connect.AccessGrantServiceCreateAccessGrantProcedure},+ "an MCP session may not create an access grant": {mcpCtx, v1pb.Issue_ACCESS_GRANT, v1connect.AccessGrantServiceCreateAccessGrantProcedure, mcpConsoleWayOut},+ "an MCP session may not create an unknown type": {mcpCtx, v1pb.Issue_Type(9999), mcpConsoleWayOut, v1connect.AccessGrantServiceCreateAccessGrantProcedure},+ "an MCP session composes database changes": {mcpCtx, v1pb.Issue_DATABASE_CHANGE, "", ""},+ "an unset type is left to buildIssueMessage": {mcpCtx, v1pb.Issue_TYPE_UNSPECIFIED, "", ""},+ "the console creates a role grant": {console, v1pb.Issue_ROLE_GRANT, "", ""},+ "a request with no auth context at all": {context.Background(), v1pb.Issue_ROLE_GRANT, "", ""},} {t.Run(name, func(t *testing.T) {err := rejectMCPOriginatedGrantIssue(tt.ctx, tt.issueType)- if !tt.refused {+ if tt.wayOut == "" {require.NoError(t, err, "this guard binds MCP sessions and nothing else")return}require.Error(t, err)require.Equal(t, connect.CodePermissionDenied, connect.CodeOf(err))require.Contains(t, err.Error(), tt.issueType.String(), "the denial must name the type it refused")+ require.Contains(t, err.Error(), tt.wayOut)+ require.NotContains(t, err.Error(), tt.notWayOut)})}}diff --git a/backend/api/v1/mcp_masking_test.go b/backend/api/v1/mcp_masking_test.goindex 430e75f08c..a43d2bd508 100644--- a/backend/api/v1/mcp_masking_test.go+++ b/backend/api/v1/mcp_masking_test.go@@ -162,6 +162,7 @@ func TestMaskedWriteGuardIsWiredIntoTheGate(t *testing.T) {require.False(t, got.dispatched, "the refusal must land before anything is written")require.Equal(t, connect.CodePermissionDenied, connect.CodeOf(got.err))require.Contains(t, got.err.Error(), masker.DefaultFullMaskSubstitution)+ require.Contains(t, got.err.Error(), mcpConsoleWayOut)require.True(t, got.auditMarked, "every policy denial is an audited outcome")})}@@ -279,6 +280,10 @@ func TestMCPRefusalsNameThemselvesToTheQueryTool(t *testing.T) {issueless := rejectMCPOriginatedIssuelessRollout(mcpCtx, approvalProject, nil, "create a rollout")require.Error(t, issueless)require.True(t, mcp.IsPolicyRefusal(issueless.Error()))++ unattended := refuseUnattendedMCPAccessGrant(mcpCtx, &storepb.IssuePayloadApproval{ApprovalFindingDone: true})+ require.Error(t, unattended)+ require.True(t, mcp.IsPolicyRefusal(unattended.Error()))}// TestMaskPlaceholderMatchIsDeliberatelyBroad records which side of the tradediff --git a/backend/api/v1/rollout_service.go b/backend/api/v1/rollout_service.goindex 6ce7cfde8d..8f7e4833fb 100644--- a/backend/api/v1/rollout_service.go+++ b/backend/api/v1/rollout_service.go@@ -1419,34 +1419,14 @@ func (s *RolloutService) canUserCancelEnvironmentTaskRun(ctx context.Context, us// to execution when the project requires issue approval and the plan carries no// linked issue.//-// Both approval checks on this path are guarded on a linked issue existing, so-// a plan created without one reaches task creation with no approval whatever-// require_issue_approval says. That is not a defect for every caller — the-// shipped GitOps Service Agent role holds no issue permission at all, so-// issueless deployment is a supported product contract, and READ_WRITE-// preserves supported contracts. It is a defect for an MCP session, because-// without this rule the three FORBIDDEN approval methods are decorative in the-// change lane: an agent that cannot clear the gate can skip it instead, which-// is the same end state the self-approval guard exists to prevent. The rule is-// the one rollout_service.proto states the gate PR owes.-//-// It cannot live in the ceiling gate. "The plan has no linked issue" is not a-// field of either request, so the interceptor would have to read the store to-// find out — a lookup it has no business doing and one that would race the-// handler's own. The guard sits where the fact is already loaded.-//-// It must bite BEFORE the rollout exists: once an issueless rollout is created,-// approval finding refuses outright ("rollout already started"), so a rule that-// only covered BatchRunTasks would leave the change stranded rather than-// gated. Hence both callers, CreateRollout first.-//-// Presence of the delegated grant is the MCP-origin marker, never a field value-// (common.DelegatedGrant), so the console and the GitOps agent are untouched.-// BOT-71 tracks whether the product should close this for every caller; if it-// does, this guard becomes redundant rather than wrong.+// Both approval checks on this path need a linked issue, so without this guard+// a session could skip the issue approval it may not give. Other callers keep+// issueless deployment, which the GitOps Service Agent role relies on; BOT-71+// tracks whether to close it for everyone. It must refuse before the rollout exists,+// because approval finding then refuses outright and strands the change, so+// CreateRollout is guarded as well as BatchRunTasks.func rejectMCPOriginatedIssuelessRollout(ctx context.Context, project *store.ProjectMessage, issue *store.IssueMessage, action string) error {- authCtx, ok := common.GetAuthContextFromContext(ctx)- if !ok || authCtx.DelegatedGrant == nil {+ if !mcpSession(ctx) {return nil}if !project.Setting.GetRequireIssueApproval() || issue != nil {diff --git a/backend/api/v1/testdata/mcp_method_classification.md b/backend/api/v1/testdata/mcp_method_classification.mdindex 4d043c4d79..809a17672b 100644--- a/backend/api/v1/testdata/mcp_method_classification.md+++ b/backend/api/v1/testdata/mcp_method_classification.md@@ -17,17 +17,17 @@ served by no ceiling.| Class | Methods | Meaning ||---|---|---|| READ | 56 | served to a read-only session and above |-| WRITE | 36 | served to a read-write session only |-| EXCLUDED | 91 | served by no ceiling this phase ships |-| FORBIDDEN | 35 | never served, whatever the ceiling |+| WRITE | 37 | served to a read-write session only |+| EXCLUDED | 89 | served by no ceiling this phase ships |+| FORBIDDEN | 36 | never served, whatever the ceiling || MCP_METHOD_CLASS_UNSPECIFIED | 0 | unclassified — CI rejects this, and the gate refuses it || **total** | **218** | || Method | Class | Reason | Permission ||---|---|---|---|| AIService/Chat | EXCLUDED | SENDS_DATA_TO_A_THIRD_PARTY | — |-| AccessGrantService/ActivateAccessGrant | EXCLUDED | ADMINISTERS_THE_WORKSPACE | bb.accessGrants.activate |-| AccessGrantService/CreateAccessGrant | EXCLUDED | ADMINISTERS_THE_WORKSPACE | bb.accessGrants.create |+| AccessGrantService/ActivateAccessGrant | FORBIDDEN | DRIVES_THE_APPROVAL_DECISION | bb.accessGrants.activate |+| AccessGrantService/CreateAccessGrant | WRITE | — | bb.accessGrants.create || AccessGrantService/GetAccessGrant | EXCLUDED | ADMINISTERS_THE_WORKSPACE | bb.accessGrants.get || AccessGrantService/ListAccessGrants | EXCLUDED | ADMINISTERS_THE_WORKSPACE | bb.accessGrants.list || AccessGrantService/RevokeAccessGrant | EXCLUDED | ADMINISTERS_THE_WORKSPACE | bb.accessGrants.revoke |diff --git a/backend/component/review/evaluator.go b/backend/component/review/evaluator.goindex e515d05037..10a871c66c 100644--- a/backend/component/review/evaluator.go+++ b/backend/component/review/evaluator.go@@ -864,15 +864,6 @@ func buildCELVariablesForRoleGrant(ctx context.Context, stores *store.Store, iss}// buildCELVariablesForAccessGrant builds CEL variables for ACCESS_GRANT issues.-//-// Emits one CEL variable map per (target database, schema, table) referenced-// by the grant's query, so REQUEST_ACCESS rules can key on-// `resource.db_engine / resource.database_name / resource.schema_name /-// resource.table_name` attributes.-//-// Statement parsing failures fall back to per-target vars without-// schema/table info — rules keyed on db_engine / database_name / env-// still evaluate.func buildCELVariablesForAccessGrant(ctx context.Context, stores *store.Store, issue *store.IssueMessage) ([]map[string]any, bool, error) {payload := issue.Payloadif payload.AccessGrantId == "" {@@ -887,16 +878,48 @@ func buildCELVariablesForAccessGrant(ctx context.Context, stores *store.Store, iif accessGrant == nil {return nil, false, errors.Errorf("access grant %s not found", accessGrantID)}+ celVarsList, err := buildCELVariablesForAccessGrantPayload(ctx, stores, issue.ProjectID, accessGrant.Payload)+ if err != nil {+ return nil, false, err+ }+ return celVarsList, true, nil+}+// EvaluateAccessGrantApproval returns the approval finding an access grant+// request gets, from the request itself, so the caller can decide before any row+// is written. Unlike the workflow, it skips the FEATURE_APPROVAL_WORKFLOW check:+// its caller requires FEATURE_JIT, which plan.yaml grants only with that feature.+func EvaluateAccessGrantApproval(ctx context.Context, stores *store.Store, project *store.ProjectMessage, grant *storepb.AccessGrantPayload) (*storepb.IssuePayloadApproval, storepb.RiskLevel, error) {+ finding := &storepb.IssuePayloadApproval{ApprovalFindingDone: true}+ approvalSetting, err := stores.GetWorkspaceApprovalSetting(ctx, project.Workspace)+ if err != nil {+ return nil, storepb.RiskLevel_RISK_LEVEL_UNSPECIFIED, errors.Wrap(err, "failed to get workspace approval setting")+ }+ celVarsList, err := buildCELVariablesForAccessGrantPayload(ctx, stores, project.ResourceID, grant)+ if err != nil {+ return nil, storepb.RiskLevel_RISK_LEVEL_UNSPECIFIED, errors.Wrap(err, "failed to build CEL variables for access grant")+ }+ finding.ApprovalTemplate, err = getApprovalTemplate(approvalSetting, storepb.WorkspaceApprovalSetting_Rule_REQUEST_ACCESS, celVarsList)+ if err != nil {+ return nil, storepb.RiskLevel_RISK_LEVEL_UNSPECIFIED, errors.Wrapf(err, "failed to get approval template for source: %v", storepb.WorkspaceApprovalSetting_Rule_REQUEST_ACCESS)+ }+ return finding, calculateRiskLevelFromCELVars(celVarsList), nil+}++// buildCELVariablesForAccessGrantPayload emits one CEL variable map per target+// database, schema and table the query reads. A statement that does not parse+// yields one map per target, so rules on its engine, database or environment+// still evaluate.+func buildCELVariablesForAccessGrantPayload(ctx context.Context, stores *store.Store, projectID string, grant *storepb.AccessGrantPayload) ([]map[string]any, error) {baseVars := map[string]any{- common.CELAttributeResourceProjectID: issue.ProjectID,- common.CELAttributeRequestUnmask: accessGrant.Payload.Unmask,- common.CELAttributeRequestExport: accessGrant.Payload.Export,+ common.CELAttributeResourceProjectID: projectID,+ common.CELAttributeRequestUnmask: grant.Unmask,+ common.CELAttributeRequestExport: grant.Export,}- targets := accessGrant.Payload.Targets+ targets := grant.Targetsif len(targets) == 0 {- return []map[string]any{baseVars}, true, nil+ return []map[string]any{baseVars}, nil}type databaseKey struct {@@ -913,10 +936,10 @@ func buildCELVariablesForAccessGrant(ctx context.Context, stores *store.Store, ifor _, target := range targets {targetProjectID, instanceID, databaseName, err := common.GetDatabaseResourceName(target)if err != nil {- return nil, false, errors.Wrapf(err, "failed to parse target %q", target)+ return nil, errors.Wrapf(err, "failed to parse target %q", target)}- if targetProjectID != nil && *targetProjectID != issue.ProjectID {- return nil, false, errors.Errorf("target %q does not belong to project %q", target, issue.ProjectID)+ if targetProjectID != nil && *targetProjectID != projectID {+ return nil, errors.Errorf("target %q does not belong to project %q", target, projectID)}key := databaseKey{instanceID: instanceID, databaseName: databaseName}parsedTargets = append(parsedTargets, parsedTarget{name: target, key: key})@@ -926,16 +949,16 @@ func buildCELVariablesForAccessGrant(ctx context.Context, stores *store.Store, iinstanceByID, err := getActiveTargetInstances(ctx, stores, instanceTargets)if err != nil {- return nil, false, err+ return nil, err}workspaceID := common.GetWorkspaceIDFromContext(ctx)databases, err := stores.ListDatabases(ctx, &store.FindDatabaseMessage{Workspace: workspaceID,- ProjectID: &issue.ProjectID,+ ProjectID: &projectID,})if err != nil {- return nil, false, errors.Wrapf(err, "failed to list databases for project %q", issue.ProjectID)+ return nil, errors.Wrapf(err, "failed to list databases for project %q", projectID)}databaseByKey := make(map[databaseKey]*store.DatabaseMessage, len(requestedDatabases))for _, database := range databases {@@ -955,7 +978,7 @@ func buildCELVariablesForAccessGrant(ctx context.Context, stores *store.Store, icontinue}if database.ResourceName() != target.name {- return nil, false, errors.Errorf("database target %q is not canonical for its instance", target.name)+ return nil, errors.Errorf("database target %q is not canonical for its instance", target.name)}resolvedTargets = append(resolvedTargets, struct {name string@@ -963,7 +986,7 @@ func buildCELVariablesForAccessGrant(ctx context.Context, stores *store.Store, i}{name: target.name, database: database})}- statement := accessGrant.Payload.Query+ statement := grant.Queryvar celVarsList []map[string]anyfor _, target := range resolvedTargets {@@ -1027,7 +1050,7 @@ func buildCELVariablesForAccessGrant(ctx context.Context, stores *store.Store, icelVarsList = append(celVarsList, baseVars)}- return celVarsList, true, nil+ return celVarsList, nil}// getDatabasesForRoleGrant fetches database messages for the given database identifiers.diff --git a/backend/component/review/evaluator_test.go b/backend/component/review/evaluator_test.goindex ca3b632537..edde5f1d84 100644--- a/backend/component/review/evaluator_test.go+++ b/backend/component/review/evaluator_test.go@@ -788,6 +788,56 @@ func TestBuildCELVariablesForAccessGrantResolvesProjectInstanceWithoutCache(t *trequire.Equal(t, "prod", variables[0][common.CELAttributeResourceEnvironmentID])}+func TestEvaluateAccessGrantApproval(t *testing.T) {+ ctx := context.Background()+ const workspaceID = "workspace-a"+ s := setupApprovalRunnerStoreInWorkspace(ctx, t, workspaceID)+ projectID := "project-a"+ setupApprovalProjectInstanceDatabase(ctx, t, s)+ project, err := s.GetProject(ctx, &store.FindProjectMessage{Workspace: workspaceID, ResourceID: &projectID})+ require.NoError(t, err)+ ctx = context.WithValue(ctx, common.WorkspaceIDContextKey, workspaceID)+ request := func(unmask bool) *storepb.AccessGrantPayload {+ return &storepb.AccessGrantPayload{+ Targets: []string{"projects/project-a/instances/prod/databases/app"},+ Query: "SELECT 1",+ Unmask: unmask,+ }+ }++ _, _, err = EvaluateAccessGrantApproval(ctx, s, project, request(true))+ require.ErrorContains(t, err, "WORKSPACE_APPROVAL")++ _, err = s.UpsertSetting(ctx, &store.SettingMessage{+ Name: storepb.SettingName_WORKSPACE_APPROVAL,+ Workspace: workspaceID,+ Value: &storepb.WorkspaceApprovalSetting{Rules: []*storepb.WorkspaceApprovalSetting_Rule{+ {+ Source: storepb.WorkspaceApprovalSetting_Rule_CHANGE_DATABASE,+ Condition: &expr.Expr{Expression: "true"},+ Template: &storepb.ApprovalTemplate{Flow: &storepb.ApprovalFlow{Roles: []string{"roles/projectOwner"}}},+ },+ {+ Source: storepb.WorkspaceApprovalSetting_Rule_REQUEST_ACCESS,+ Condition: &expr.Expr{Expression: `resource.database_name == "app" && request.unmask`},+ Template: &storepb.ApprovalTemplate{Flow: &storepb.ApprovalFlow{Roles: []string{"roles/workspaceDBA"}}},+ },+ }},+ })+ require.NoError(t, err)++ unmasked, _, err := EvaluateAccessGrantApproval(ctx, s, project, request(true))+ require.NoError(t, err)+ require.True(t, unmasked.GetApprovalFindingDone())+ require.Equal(t, []string{"roles/workspaceDBA"}, unmasked.GetApprovalTemplate().GetFlow().GetRoles())++ plain, riskLevel, err := EvaluateAccessGrantApproval(ctx, s, project, request(false))+ require.NoError(t, err)+ require.True(t, plain.GetApprovalFindingDone())+ require.Nil(t, plain.GetApprovalTemplate(), "a rule for another source does not apply to an access request")+ require.Equal(t, storepb.RiskLevel_LOW, riskLevel)+}+func TestBuildCELVariablesForAccessGrantRejectsArchivedProjectInstanceWithoutCache(t *testing.T) {ctx := context.Background()const workspaceID = "workspace-a"diff --git a/backend/generated-go/v1/access_grant_service.pb.go b/backend/generated-go/v1/access_grant_service.pb.goindex 091da91b35..771cc0a7d1 100644--- a/backend/generated-go/v1/access_grant_service.pb.go+++ b/backend/generated-go/v1/access_grant_service.pb.go@@ -861,12 +861,12 @@ const file_v1_access_grant_service_proto_rawDesc = "" +"\border_by\x18\x05 \x01(\tR\aorderBy\"\x85\x01\n" +"\x1cSearchMyAccessGrantsResponse\x12=\n" +"\raccess_grants\x18\x01 \x03(\v2\x18.bytebase.v1.AccessGrantR\faccessGrants\x12&\n" +- "\x0fnext_page_token\x18\x02 \x01(\tR\rnextPageToken2\x9c\t\n" ++ "\x0fnext_page_token\x18\x02 \x01(\tR\rnextPageToken2\x98\t\n" +"\x12AccessGrantService\x12\xa6\x01\n" +"\x0eGetAccessGrant\x12\".bytebase.v1.GetAccessGrantRequest\x1a\x18.bytebase.v1.AccessGrant\"V\xdaA\x04name\x8a\xea0\x13bb.accessGrants.get\x90\xea0\x01\xa0\xea0\x04\xa8\xea0\t\x82\xd3\xe4\x93\x02&\x12$/v1/{name=projects/*/accessGrants/*}\x12\xba\x01\n" +- "\x10ListAccessGrants\x12$.bytebase.v1.ListAccessGrantsRequest\x1a%.bytebase.v1.ListAccessGrantsResponse\"Y\xdaA\x06parent\x8a\xea0\x14bb.accessGrants.list\x90\xea0\x01\xa0\xea0\x04\xa8\xea0\t\x82\xd3\xe4\x93\x02&\x12$/v1/{parent=projects/*}/accessGrants\x12\xd0\x01\n" +- "\x11CreateAccessGrant\x12%.bytebase.v1.CreateAccessGrantRequest\x1a\x18.bytebase.v1.AccessGrant\"z\xdaA\x13parent,access_grant\x8a\xea0\x16bb.accessGrants.create\x90\xea0\x01\x98\xea0\x01\xa0\xea0\x04\xa8\xea0\t\x82\xd3\xe4\x93\x024:\faccess_grant\"$/v1/{parent=projects/*}/accessGrants\x12\xc5\x01\n" +- "\x13ActivateAccessGrant\x12'.bytebase.v1.ActivateAccessGrantRequest\x1a\x18.bytebase.v1.AccessGrant\"k\xdaA\x04name\x8a\xea0\x18bb.accessGrants.activate\x90\xea0\x01\x98\xea0\x01\xa0\xea0\x04\xa8\xea0\t\x82\xd3\xe4\x93\x022:\x01*\"-/v1/{name=projects/*/accessGrants/*}:activate\x12\xbd\x01\n" ++ "\x10ListAccessGrants\x12$.bytebase.v1.ListAccessGrantsRequest\x1a%.bytebase.v1.ListAccessGrantsResponse\"Y\xdaA\x06parent\x8a\xea0\x14bb.accessGrants.list\x90\xea0\x01\xa0\xea0\x04\xa8\xea0\t\x82\xd3\xe4\x93\x02&\x12$/v1/{parent=projects/*}/accessGrants\x12\xcc\x01\n" ++ "\x11CreateAccessGrant\x12%.bytebase.v1.CreateAccessGrantRequest\x1a\x18.bytebase.v1.AccessGrant\"v\xdaA\x13parent,access_grant\x8a\xea0\x16bb.accessGrants.create\x90\xea0\x01\x98\xea0\x01\xa0\xea0\x02\x82\xd3\xe4\x93\x024:\faccess_grant\"$/v1/{parent=projects/*}/accessGrants\x12\xc5\x01\n" ++ "\x13ActivateAccessGrant\x12'.bytebase.v1.ActivateAccessGrantRequest\x1a\x18.bytebase.v1.AccessGrant\"k\xdaA\x04name\x8a\xea0\x18bb.accessGrants.activate\x90\xea0\x01\x98\xea0\x01\xa0\xea0\x03\xa8\xea0\b\x82\xd3\xe4\x93\x022:\x01*\"-/v1/{name=projects/*/accessGrants/*}:activate\x12\xbd\x01\n" +"\x11RevokeAccessGrant\x12%.bytebase.v1.RevokeAccessGrantRequest\x1a\x18.bytebase.v1.AccessGrant\"g\xdaA\x04name\x8a\xea0\x16bb.accessGrants.revoke\x90\xea0\x01\x98\xea0\x01\xa0\xea0\x04\xa8\xea0\t\x82\xd3\xe4\x93\x020:\x01*\"+/v1/{name=projects/*/accessGrants/*}:revoke\x12\xc4\x01\n" +"\x14SearchMyAccessGrants\x12(.bytebase.v1.SearchMyAccessGrantsRequest\x1a).bytebase.v1.SearchMyAccessGrantsResponse\"W\x8a\xea0\x13bb.accessGrants.get\x90\xea0\x02\xa0\xea0\x01\x82\xd3\xe4\x93\x022:\x01*\"-/v1/{parent=projects/*}/accessGrants:searchMyB\xad\x01\n" +"\x0fcom.bytebase.v1B\x17AccessGrantServiceProtoP\x01Z4github.com/bytebase/bytebase/backend/generated-go/v1\xa2\x02\x03BXX\xaa\x02\vBytebase.V1\xca\x02\vBytebase\\V1\xe2\x02\x17Bytebase\\V1\\GPBMetadata\xea\x02\fBytebase::V1b\x06proto3"diff --git a/backend/generated-go/v1/annotation.pb.go b/backend/generated-go/v1/annotation.pb.goindex 9bff16d5a6..6de460a645 100644--- a/backend/generated-go/v1/annotation.pb.go+++ b/backend/generated-go/v1/annotation.pb.go@@ -272,10 +272,11 @@ const (// key is sent to. A session that can widen its own ceiling is not bounded// by it.MCPDenialReason_REWRITES_SESSION_BOUNDARY MCPDenialReason = 7- // Works the human approval step that gates the change: recording the review- // decision, or re-running the finding that sets it and can clear the issue- // outright. An agent composes a change; it does not move its own change- // through the gate.+ // Decides whether a change or an access request passes its human approval:+ // recording the review decision, re-running the finding that sets it and can+ // clear the issue outright, or activating an access grant without it. An+ // agent composes a change or files a request; it does not decide that for its+ // own work.MCPDenialReason_DRIVES_THE_APPROVAL_DECISION MCPDenialReason = 8// Administers the workspace rather than doing database work: identity,// credentials, access control, governance policy, billing, workspace anddiff --git a/backend/tests/mcp_gate_test.go b/backend/tests/mcp_gate_test.goindex 89c2c0d91c..44ccd4a45e 100644--- a/backend/tests/mcp_gate_test.go+++ b/backend/tests/mcp_gate_test.go@@ -6,12 +6,16 @@ import ("fmt""net/http""testing"+ "time""connectrpc.com/connect""github.com/google/uuid""github.com/stretchr/testify/require"+ "google.golang.org/genproto/googleapis/type/expr"+ "google.golang.org/protobuf/types/known/durationpb""google.golang.org/protobuf/types/known/fieldmaskpb"+ "github.com/bytebase/bytebase/backend/common"v1pb "github.com/bytebase/bytebase/backend/generated-go/v1")@@ -80,11 +84,8 @@ func TestMCPGateServesAndRefusesByClass(t *testing.T) {"a served, audited MCP call is stored")}-// TestMCPGateRefusesGrantIssues is the one refusal a per-method class cannot-// express, over the live handler. CreateIssue is WRITE for the database-change-// issue an agent exists to compose; a ROLE_GRANT issue completes on creation-// when the workspace rule produces no approval template and writes the project-// IAM binding the request named, with no human in it.+// TestMCPGateRefusesGrantIssues covers, over one live MCP session, the grant+// issues a session may not create and the access request it may file instead.func TestMCPGateRefusesGrantIssues(t *testing.T) {t.Parallel()a := require.New(t)@@ -98,9 +99,8 @@ func TestMCPGateRefusesGrantIssues(t *testing.T) {a.NoError(err)projectName := project.Msg.Name- // CreateIssue is WRITE and the refusal under test is the one the class- // cannot express. Pinned so this test does not depend on the resolved- // default.+ // CreateIssue and CreateAccessGrant are WRITE. Pinned so this test does not+ // depend on the resolved default.a.NoError(ctl.setMCPCapability(ctx, v1pb.MCPSetting_READ_WRITE))session := openMCPSession(ctx, t, ctl, ctl.authInterceptor.token)@@ -121,12 +121,6 @@ func TestMCPGateRefusesGrantIssues(t *testing.T) {a.Contains(grant.Error, "ROLE_GRANT", "the denial must name the issue type it refused")a.Contains(grant.Error, "no human step")- // The bypass: UpdateIssue with allow_missing creates the issue when it does- // not exist, by calling CreateIssue directly — a Go call, so the ceiling- // gate never sees it. The gate deliberately does not refuse UpdateIssue,- // because an AIP upsert sends the complete resource and the request cannot- // say whether it will create anything; the guard sits at the creation- // instead, and this is what proves it is there.upsert := callAPIOnSession(ctx, t, session, "IssueService/UpdateIssue", map[string]any{"issue": map[string]any{"name": projectName + "/issues/999999",@@ -142,7 +136,8 @@ func TestMCPGateRefusesGrantIssues(t *testing.T) {})a.Equal(http.StatusForbidden, upsert.Status,"allow_missing on a missing issue is a creation, and the guard must reach it: %s", upsert.Error)- a.Contains(upsert.Error, "may not create a ROLE_GRANT issue")+ a.Contains(upsert.Error, "may not create this issue")+ a.Contains(upsert.Error, "ROLE_GRANT", "the denial must name the issue type it refused")// The same upsert for the type an agent is allowed to create reaches the// handler, which then asks for the plan it has no way to do without. The@@ -180,25 +175,123 @@ func TestMCPGateRefusesGrantIssues(t *testing.T) {a.Equal(http.StatusBadRequest, untyped.Status,"an unset type is the handler's invalid argument: %s", untyped.Error)a.NotContains(untyped.Error, "MCP session")++ accessGrantIssue := callAPIOnSession(ctx, t, session, "IssueService/CreateIssue", map[string]any{+ "parent": projectName,+ "issue": map[string]any{"type": "ACCESS_GRANT", "title": "let me read the table"},+ })+ a.Equal(http.StatusForbidden, accessGrantIssue.Status)+ a.Contains(accessGrantIssue.Error, "AccessGrantService/CreateAccessGrant",+ "the refusal must name the method that files the request")+ a.NotContains(accessGrantIssue.Error, "Bytebase console")++ pgContainer := sharedPgTarget(t)+ instance, err := ctl.instanceServiceClient.CreateInstance(ctx, connect.NewRequest(&v1pb.CreateInstanceRequest{+ InstanceId: generateRandomString("inst"),+ Instance: &v1pb.Instance{+ SyncDatabases: &v1pb.SyncDatabases{},+ Title: "MCP access grant instance",+ Engine: v1pb.Engine_POSTGRES,+ Environment: new("environments/prod"),+ Activation: true,+ DataSources: []*v1pb.DataSource{pgContainer.adminDataSource()},+ },+ }))+ a.NoError(err)+ dbName := generateRandomString("db")+ a.NoError(ctl.createDatabase(ctx, project.Msg, instance.Msg, nil, dbName, ""))+ target := fmt.Sprintf("%s/databases/%s", instance.Msg.Name, dbName)+ requestAccess := map[string]any{+ "parent": projectName,+ "accessGrant": map[string]any{+ "targets": []string{target},+ "query": "SELECT 1",+ "reason": "the agent needs one read",+ "ttl": "3600s",+ },+ }++ // The seeded fallback rule sends the request to a project owner.+ filed := callAPIOnSession(ctx, t, session, "AccessGrantService/CreateAccessGrant", requestAccess)+ a.Equal(http.StatusOK, filed.Status, filed.Error)+ var pending v1pb.AccessGrant+ a.NoError(common.ProtojsonUnmarshaler.Unmarshal([]byte(filed.RawResponse), &pending))+ a.Equal(v1pb.AccessGrant_PENDING, pending.Status)+ issue, err := ctl.issueServiceClient.GetIssue(ctx, connect.NewRequest(&v1pb.GetIssueRequest{Name: pending.Issue}))+ a.NoError(err)+ a.Equal([]string{"roles/projectOwner"}, issue.Msg.GetApprovalTemplate().GetFlow().GetRoles())+ a.Equal(v1pb.ApprovalStatus_PENDING, issue.Msg.ApprovalStatus)++ activate := callAPIOnSession(ctx, t, session, "AccessGrantService/ActivateAccessGrant", map[string]any{+ "name": pending.Name,+ })+ a.Equal(http.StatusForbidden, activate.Status)+ a.Contains(activate.Error, "approv", "refused as an approval decision, not as workspace administration")+ still, err := ctl.accessGrantServiceClient.GetAccessGrant(ctx, connect.NewRequest(&v1pb.GetAccessGrantRequest{Name: pending.Name}))+ a.NoError(err)+ a.Equal(v1pb.AccessGrant_PENDING, still.Msg.Status)++ consoleRequest := func() *v1pb.AccessGrant {+ granted, err := ctl.accessGrantServiceClient.CreateAccessGrant(ctx, connect.NewRequest(&v1pb.CreateAccessGrantRequest{+ Parent: projectName,+ AccessGrant: &v1pb.AccessGrant{+ Targets: []string{target},+ Query: "SELECT 1",+ Reason: "a person asks the same",+ Expiration: &v1pb.AccessGrant_Ttl{Ttl: durationpb.New(time.Hour)},+ },+ }))+ a.NoError(err)+ return granted.Msg+ }+ consolePending := consoleRequest()+ a.Equal(v1pb.AccessGrant_PENDING, consolePending.Status, "under the seeded rule, a console request waits as before")+ consoleIssue, err := ctl.issueServiceClient.GetIssue(ctx, connect.NewRequest(&v1pb.GetIssueRequest{Name: consolePending.Issue}))+ a.NoError(err)+ a.Equal([]string{"roles/projectOwner"}, consoleIssue.Msg.GetApprovalTemplate().GetFlow().GetRoles())++ rowCounts := func() (int, int) {+ grants, err := ctl.accessGrantServiceClient.ListAccessGrants(ctx, connect.NewRequest(&v1pb.ListAccessGrantsRequest{Parent: projectName}))+ a.NoError(err)+ issues, err := ctl.issueServiceClient.ListIssues(ctx, connect.NewRequest(&v1pb.ListIssuesRequest{Parent: projectName}))+ a.NoError(err)+ return len(grants.Msg.AccessGrants), len(issues.Msg.Issues)+ }+ for _, tc := range []struct {+ name string+ rules []*v1pb.WorkspaceApprovalSetting_Rule+ }{+ {"a rule that names no approver", []*v1pb.WorkspaceApprovalSetting_Rule{{+ Source: v1pb.WorkspaceApprovalSetting_Rule_REQUEST_ACCESS,+ Condition: &expr.Expr{Expression: "true"},+ Template: &v1pb.ApprovalTemplate{Flow: &v1pb.ApprovalFlow{}},+ }}},+ {"no rule at all", nil},+ } {+ _, err := ctl.settingServiceClient.UpdateSetting(ctx, connect.NewRequest(&v1pb.UpdateSettingRequest{+ AllowMissing: true,+ Setting: &v1pb.Setting{+ Name: "settings/WORKSPACE_APPROVAL",+ Value: &v1pb.SettingValue{Value: &v1pb.SettingValue_WorkspaceApproval{+ WorkspaceApproval: &v1pb.WorkspaceApprovalSetting{Rules: tc.rules},+ }},+ },+ }))+ a.NoError(err, tc.name)+ grantsBefore, issuesBefore := rowCounts()+ refused := callAPIOnSession(ctx, t, session, "AccessGrantService/CreateAccessGrant", requestAccess)+ a.Equal(http.StatusForbidden, refused.Status, tc.name)+ a.Contains(refused.Error, "no approval rule requires a person to approve it", tc.name)+ a.Contains(refused.Error, "an approval rule that names an approver", tc.name)+ grantsAfter, issuesAfter := rowCounts()+ a.Equal(grantsBefore, grantsAfter, "%s: a refused request leaves no access grant", tc.name)+ a.Equal(issuesBefore, issuesAfter, "%s: a refused request leaves no issue", tc.name)+ a.Equal(v1pb.AccessGrant_ACTIVE, consoleRequest().Status, "%s: a console request is granted at once, as before", tc.name)+ }}-// TestMCPCannotRunAnIssuelessRollout is the rule rollout_service.proto says the-// gate PR owes, and the reason it is a rule rather than a classification.-//-// Three approval RPCs are FORBIDDEN so an agent cannot move its own change-// through the human gate. That buys nothing if the agent can go round it: both-// approval checks on the execution path are guarded on a LINKED ISSUE existing,-// so a plan created without one reaches task creation with no approval whatever-// require_issue_approval says. CreatePlan, CreateRollout and BatchRunTasks are-// all WRITE and stay WRITE — issueless deployment is a supported contract, the-// shipped GitOps Service Agent role holds no issue permission at all — so the-// refusal is per session, not per method.-//-// The ceiling gate cannot take it: "the plan has no linked issue" is not a-// field of either request. The guard sits where the fact is loaded, and the-// control that matters most is the last one — a human doing the identical thing-// must be unaffected, because that is the risk of putting MCP policy in a-// handler at all.+// TestMCPCannotRunAnIssuelessRollout pins rejectMCPOriginatedIssuelessRollout+// over a live session, and that a console user doing the same is unaffected.func TestMCPCannotRunAnIssuelessRollout(t *testing.T) {t.Parallel()a := require.New(t)diff --git a/backend/tests/webhook_test.go b/backend/tests/webhook_test.goindex be7143e6d0..936ab2ce46 100644--- a/backend/tests/webhook_test.go+++ b/backend/tests/webhook_test.go@@ -16,6 +16,7 @@ import ("connectrpc.com/connect""github.com/google/uuid""github.com/stretchr/testify/require"+ "google.golang.org/protobuf/types/known/durationpb""google.golang.org/protobuf/types/known/fieldmaskpb"v1pb "github.com/bytebase/bytebase/backend/generated-go/v1"@@ -680,6 +681,48 @@ func TestWebhookIntegration(t *testing.T) {requireWebhookCount(t, collector, project.Name, "Approval required", 0)})+ t.Run("IssueApprovalRequested_FiresOnceForAnAccessGrant", func(t *testing.T) {+ collector.reset()+ project := ctl.createTestProject(ctx, t, "access-grant-approval")+ require.NoError(t, ctl.createDatabase(ctx, project, instance, nil, "access_grant_approval_db", ""))++ clearWorkspaceApprovalRules(ctx, t, ctl)+ disableSelfApproval(ctx, t, ctl, project)+ installWorkspaceApprovalRule(ctx, t, ctl, project, []string{"roles/projectOwner"})+ appr := provisionApprover(ctx, t, ctl, project, "access-grant", "roles/projectOwner")++ collector.reset()+ addWebhookForEvents(ctx, t, ctl, project, webhookServer.URL, []v1pb.Activity_Type{+ v1pb.Activity_ISSUE_APPROVAL_REQUESTED,+ v1pb.Activity_ISSUE_APPROVED,+ })++ grant, err := ctl.accessGrantServiceClient.CreateAccessGrant(ctx, connect.NewRequest(&v1pb.CreateAccessGrantRequest{+ Parent: project.Name,+ AccessGrant: &v1pb.AccessGrant{+ Targets: []string{dbTargetName(instance, "access_grant_approval_db")},+ Query: "SELECT 1",+ Reason: "one read",+ Expiration: &v1pb.AccessGrant_Ttl{Ttl: durationpb.New(time.Hour)},+ },+ }))+ require.NoError(t, err)+ require.Equal(t, v1pb.AccessGrant_PENDING, grant.Msg.Status)+ waitForWebhookCount(t, collector, project.Name, "Approval required", 1)++ issue, err := ctl.issueServiceClient.GetIssue(ctx, connect.NewRequest(&v1pb.GetIssueRequest{Name: grant.Msg.Issue}))+ require.NoError(t, err)+ approveIssueAs(ctx, t, ctl, issue.Msg, appr)+ // The approval's webhook is sent after CreateAccessGrant returned, so+ // waiting for it gives a second "Approval required" time to arrive.+ waitForWebhookCount(t, collector, project.Name, "Issue approved", 1)+ requireWebhookCount(t, collector, project.Name, "Approval required", 1)++ active, err := ctl.accessGrantServiceClient.GetAccessGrant(ctx, connect.NewRequest(&v1pb.GetAccessGrantRequest{Name: grant.Msg.Name}))+ require.NoError(t, err)+ require.Equal(t, v1pb.AccessGrant_ACTIVE, active.Msg.Status)+ })+t.Run("IssueApproved_SingleStep", func(t *testing.T) {collector.reset()project := ctl.createTestProject(ctx, t, "byt9398-ap1")diff --git a/docs/design/mcp-capability-ladder.md b/docs/design/mcp-capability-ladder.mdindex 95863d939b..74f3b60bc9 100644--- a/docs/design/mcp-capability-ladder.md+++ b/docs/design/mcp-capability-ladder.md@@ -6,7 +6,7 @@ The MCP settings page offers three modes (Disabled, Read-only, Read-write) and done sentence. Since [#21324](https://github.com/bytebase/bytebase/pull/21324) removed the per-modemethod drawer, nothing on the page says what a mode actually serves, and an admin choosing betweenRead-only and Read-write has nothing to compare beyond two sentences. The rule this doc lands on:-**show capabilities, not methods or permissions — one ordered list of eight capability rows in+**show capabilities, not methods or permissions — one ordered list of nine capability rows inwhich each mode is a prefix, collapsed by default inside the existing Access policy section, andfollowing the picked mode while editing.** The page also gets shorter: the mode cards shrink to anicon, a label and a three-word caption, with the selected mode's "Best for" under them; the@@ -59,7 +59,7 @@ What follows from it:## The rows-Eight rows: three read, five write. Each has a title and a one-line list of sub-items in plain+Nine rows: three read, six write. Each has a title and a one-line list of sub-items in plainwords. The right column records which classified methods the row's wording has to cover; it isdocumentation for whoever rereads these rows after a classification change, and never appears inthe product.@@ -71,16 +71,17 @@ the product.| read | Read the change workflow | Issues and comments · Plans and plan checks · Rollouts, task runs and logs · Releases · Rollback previews | 16 READ methods: issue, plan, rollout and release reads || — | *Read-only stops here* | | 56 methods || write | Propose changes | Create sheets · Create and edit plans and issues · Run plan checks and reviews · Create, delete and restore releases · Create and delete revisions · Generate schema diffs. An agent never approves its own change; the project's approval policy decides whether a human must | 22 WRITE methods: sheet, plan, issue, release and revision writes, `RequestIssue`, `RunReview`, `DiffSchema`, `DiffMetadata` |+| write | Request access grants | Ask for a time-boxed grant to run a specific statement, optionally with results unmasked or exported; the statement must be a read as far as the engine can check it · The grant starts only after a person approves it, and a request that would need no one's approval is refused · A grant applies only where the project allows access grants | 1 WRITE method: `AccessGrantService/CreateAccessGrant` || write | Run rollouts and tasks | Create a rollout · Run, skip or cancel its tasks, under the project's approval policy | 4 WRITE methods: `CreateRollout`, `BatchRunTasks`, `BatchSkipTasks`, `BatchCancelTaskRuns` || write | Run DML and DDL statements | INSERT, UPDATE, DELETE, CREATE, ALTER, DROP through queries, as far as the engine and the user's own permissions allow | Not a method: the statement clamp in `mcp_sql_clamp.go`, which Read-write lifts || write | Export query results | Download results as a file. Data leaves Bytebase | 1 WRITE method: `SQLService/Export` || write | Manage database housekeeping | Sync instances and databases · Saved queries | 9 WRITE methods: sync, saved-query writes |-| — | *Read-write stops here* | | 92 methods |-| floor | Never, in any mode: approve issues, administer the workspace, handle credentials, open an Admin mode session, or read anyone else's query history. | | 126 methods: 35 FORBIDDEN, 91 EXCLUDED |+| — | *Read-write stops here* | | 93 methods |+| floor | Never, in any mode: approve issues, administer the workspace, handle credentials, open an Admin mode session, or read anyone else's query history. | | 125 methods: 36 FORBIDDEN, 89 EXCLUDED |Every row is displayed under every mode — served, or muted with a `—` — and against every engine aworkspace happens to hold, so **every line on this card must be true on both axes: mode and engine.**-That covers the eight rows, and equally the collapsed summary, the card captions and the "Best for"+That covers the nine rows, and equally the collapsed summary, the card captions and the "Best for"lines, which are not rows and were missed the first time the rule was applied. The summary is theline most admins read and often the only one. Aclaim whose truth depends on the mode names the mode as a condition; a claim whose truth depends on@@ -89,8 +90,8 @@ the engine says so without naming engines, because per-engine depth is out of scBoth axes have caught lines here, and the engine axis caught the same line twice. On the mode axis,the read-only clamp holds only under Read-only (`mcpReadOnlyClampApplies`), so without its qualifier-row 2 promised a whole-request refusal under Read-write while row 6 on the same screen offered INSERT-and DROP.+row 2 promised a whole-request refusal under Read-write while the DML and DDL row on the same screen+offered INSERT and DROP.On the engine axis, three drafts failed in three different ways, and the shape of the failure is thelesson. Naming engines (PostgreSQL, CockroachDB, Redshift) went stale against the Redshift datashare@@ -166,9 +167,9 @@ outcome. Parallelism between the two is broken on purpose.Two choices in the wording are deliberate. Row 2 says *Read data by running queries* rather than"Run queries" so the verb stays Read and the sub-item carries the rule that keeps it true under-Read-only. Row 6 is not a method at all: it names the statement clamp being lifted, because that is-a real difference between the modes that no method name shows, and a future custom policy will want-it as its own switch.+Read-only. The DML and DDL row is not a method at all: it names the statement clamp being lifted,+because that is a real difference between the modes that no method name shows, and a future custom+policy will want it as its own switch.Every sub-item names only what the served methods can do. Sheets are created, never edited: thereis no update RPC. Releases and revisions are created and deleted: `ReleaseService/UpdateRelease` is@@ -192,31 +193,45 @@ under that same flag, and an issue whose approval finding produced no template cwith no human acting. The console turns the flag on for new projects; the API default is off. A rowthat said "of an approved change" would therefore promise more than the gate enforces, and thewording an admin reads while choosing Read-write is the wrong place to be generous. What holds-unconditionally is that an agent never approves its own change, because the three approval methods-are FORBIDDEN, and that is the half the rows state. Whether MCP-originated rollouts should require+unconditionally is that an agent never approves its own change, because the approval methods are+FORBIDDEN: approving, rejecting and re-checking an issue, and activating an access grant. That is+the half the rows state. Whether MCP-originated rollouts should requireapproval regardless of the project flag is a product question tracked separately (BOT-71), not onethis doc decides.+Access requests are the exception, and the request row states the person's approval+unconditionally. An approved access grant is active at once, so an MCP session's request that would+count as approved on creation, with no approval template or one that names no approver, is refused+before any row is written (`refuseUnattendedMCPAccessGrant` in+`backend/api/v1/access_grant_service.go`). The finding is saved on the request's issue at+creation, so an approval-rule edit afterwards cannot change it. Every other way a request becomes+active is an approval method above, FORBIDDEN to the session. The person who approves can be the+requester, signed in to the console; the rows promise a person, not a second one.+### The verb ruleThe verb names the row's effect on the customer's databases. *Read*: none. *Propose*: none until a-human approves. *Run*: direct. *Export*: data leaves the product. *Manage*: configuration only, no-data path. Within a tier the verb repeats; it changes only where the effect changes.+human approves. *Request*: none until a person approves, and then access to one statement's results,+unmasked or exported if asked for. *Run*: direct. *Export*: data leaves the product. *Manage*:+configuration only, no data path. Within a tier the verb repeats; it changes only where the effect+changes.One verb for the whole write tier was tried and rejected:-- **Write** for all five: "Write query results" (export writes nothing to a database), "Write+- **Write** for every write row: "Write query results" (export writes nothing to a database), "Writechange proposals" (nothing reaches a database until approval), "Write rollouts" (not English),"Write database housekeeping" (reads as a data change).-- **Change** for all five: fails for exports and rollouts, and makes "Change proposals" and+- **Change** for every write row: fails for exports and rollouts, and makes "Change proposals" and"Change data with SQL" read as the same thing — the distinction the FORBIDDEN approval methodsexist to protect.-- **Manage** for all five: hides the hazard on exports and on SQL.+- **Manage** for every write row: hides the hazard on exports and on SQL.Per row: *Propose* over Create (Create fits the method names but hides that the project's approvalpolicy may still require a human); *Export* over Read or Download (Read hides the egress hazard,which is why Export is WRITE-class in the first place); *Manage* over Update or Maintain (Update-reads as a data change, Maintain is vague). Rollouts and DML/DDL both take *Run* and stay two rows,+reads as a data change, Maintain is vague); *Request* over Propose (a proposal waits for a person+only when the project's approval policy says so, a session's request always does, and what an approved request+gives is access to data, not a change). Rollouts and DML/DDL both take *Run* and stay two rows,because a custom policy will want "run approved rollouts, but no ad-hoc SQL" — the workflow theproduct exists for.@@ -226,9 +241,9 @@ The tier is named once, by the dividers, so no row repeats it in its title.**D1 — Placement: a disclosure inside the Access policy section, collapsed by default.**Not a drawer (a second surface, one mode at a time) and not a separate section (it belongs to the-policy it describes). Collapsed, the trigger line *is* the mode's description: "▸ Read schemas, data-and the change workflow; propose, run, export and manage". The read half is the same phrase in-both modes, because Read-write serves exactly the read rows Read-only serves; the EXCLUDED reads+policy it describes). Collapsed, the trigger line *is* the mode's description, the summary under+Copy. The read half is the same phrase in both modes, because Read-write serves exactly the read+rows Read-only serves; the EXCLUDED reads(audit logs, users, roles, IAM policies, other people's query history, task-run sessions) arerefused in every mode, so no summary may say "read everything". The line never repeats the modename, which the chip (view) or the@@ -241,10 +256,10 @@ machinery than a settings page visited this rarely earns.**D2 — Content: rows first, sub-items behind one toggle.** Expanded, each row shows its title andits tier tag, nothing else. "Show details" reveals the sub-item line for every row at once, so-there is one second-level control rather than eight; per-row expanders were rejected as fiddly. No+there is one second-level control rather than one per row; per-row expanders were rejected as fiddly. Nomethod names, no permission names, no counts, no link to a method list. The floor is kept as oneshort line because it is what a security-minded admin reads first, and it is what keeps the list-honest about the 126 methods no mode reaches. There is no constants line under the list; the facts+honest about the 125 methods no mode reaches. There is no constants line under the list; the factsit would carry (capped by the user's own permissions, refusals audited) move into the sectiondescription.@@ -316,7 +331,7 @@ same icon as the settings page's. One wording table serves both surfaces.Titles alone carry no caveats, and the caveats live in the row details this screen does not render —so on a workspace whose engine refuses every statement, an unqualified "Read data by running queries-✓" promises a capability the session does not have. The screen cannot carry eight detail lines and+✓" promises a capability the session does not have. The screen cannot carry a detail line for every row andstay an approval screen, so it bounds the whole list once instead, on the line that already limits itby the reader's own permissions. That bound is per mode, because the statement clamp it describesruns only under Read-only: "Capped by your own Bytebase permissions, and by what Bytebase can check on each database engine — where it cannot show a statement is a read, no query runs at all" against@@ -327,7 +342,7 @@ once (see the complement and method axes in The rows). It states the bound and sread as what the policy admits rather than what will succeed. It carries a neutral glyph and no"Allowed" mark, so a bound is not counted as a further grant.-**D11 — The wording is bound to the classification by instruction, not by a lint.** The eight+**D11 — The wording is bound to the classification by instruction, not by a lint.** The rowtitles claim to cover every READ and WRITE method, and a method annotated into either class isserved the moment it is annotated, whether or not a row names it. The first draft closed that witha row table in `backend/api/v1/mcp_gate.go` and a lint in `mcp_gate_test.go`, so a class change@@ -385,7 +400,7 @@ under- Section description: "The most any MCP session may do here. Sessions are also capped by each user's permissions, and policy refusals are streamed to stdout when audit logging to stdout is enabled."- Disclosure line, collapsed — Read-only: "Read schemas, data and the change workflow; a request carrying anything that cannot be shown to be a read is refused, and nothing is exported".- Read-write: "Read schemas, data and the change workflow; propose, run, export and manage".+ Read-write: "Read schemas, data and the change workflow; propose, request access, run, export and manage".Expanded heading: "{mode} allows". Details control: "Show details" / "Hide details".- Disabled — view sentence: "No MCP session can connect to this workspace." Edit static line:"Nothing is allowed; no MCP session can connect."@@ -520,7 +535,7 @@ to live in the bound line there (D10), not in a row's sub-items.so the rows and the floor line are absent from the DOM until the disclosure is opened, and`hiddenUntilFound` would keep them mounted instead. Declined: collapsing by default is D1'sdecision, the summary line states what the mode allows and the trigger is beside it, and the- attribute's browser support is uneven — the unmount also keeps eight rows out of the accessibility+ attribute's browser support is uneven — the unmount also keeps the rows out of the accessibilitytree while they are not shown. Revisit if the list stops being a disclosure.- Per-engine read-only depth and masking coverage. The removed drawer showed both; they belong indocs, not on the policy card.diff --git a/frontend/src/components/mcp/mcpCapabilityRows.ts b/frontend/src/components/mcp/mcpCapabilityRows.tsindex 1aa100ee9c..c76a663d65 100644--- a/frontend/src/components/mcp/mcpCapabilityRows.ts+++ b/frontend/src/components/mcp/mcpCapabilityRows.ts@@ -20,6 +20,7 @@ export type MCPCapabilityRowId =| "read-data"| "read-workflow"| "propose"+ | "request-access"| "run-rollouts"| "run-statements"| "export"@@ -51,6 +52,7 @@ export const MCP_CAPABILITY_ROWS: readonly MCPCapabilityRow[] = [{ id: "read-data", tier: "read" },{ id: "read-workflow", tier: "read" },{ id: "propose", tier: "write" },+ { id: "request-access", tier: "write" },{ id: "run-rollouts", tier: "write" },{ id: "run-statements", tier: "write" },{ id: "export", tier: "write" },diff --git a/frontend/src/locales/en-US.json b/frontend/src/locales/en-US.jsonindex a4fa96961d..1b6dcc2e6f 100644--- a/frontend/src/locales/en-US.json+++ b/frontend/src/locales/en-US.json@@ -2785,6 +2785,10 @@"details": "Issues and comments · Plans and plan checks · Rollouts, task runs and logs · Releases · Rollback previews","title": "Read the change workflow"},+ "request-access": {+ "details": "Ask for a time-boxed grant to run a specific statement, optionally with results unmasked or exported; the statement must be a read as far as the engine can check it · The grant starts only after a person approves it, and a request that would need no one's approval is refused · A grant applies only where the project allows access grants",+ "title": "Request access grants"+ },"run-rollouts": {"details": "Create a rollout · Run, skip or cancel its tasks, under the project's approval policy","title": "Run rollouts and tasks"@@ -2801,7 +2805,7 @@},"summary": {"read-only": "Read schemas, data and the change workflow; a request carrying anything that cannot be shown to be a read is refused, and nothing is exported",- "read-write": "Read schemas, data and the change workflow; propose, run, export and manage"+ "read-write": "Read schemas, data and the change workflow; propose, request access, run, export and manage"},"tier": {"read": "read",diff --git a/frontend/src/locales/es-ES.json b/frontend/src/locales/es-ES.jsonindex 9d52778604..cdd5a85d97 100644--- a/frontend/src/locales/es-ES.json+++ b/frontend/src/locales/es-ES.json@@ -2785,6 +2785,10 @@"details": "Issues y comentarios · Plans y comprobaciones de plan · Despliegues, ejecuciones de tareas y registros · Versiones · Vistas previas de reversión","title": "Leer el flujo de cambios"},+ "request-access": {+ "details": "Pedir una concesión con límite de tiempo para ejecutar una sentencia concreta, opcionalmente con resultados sin enmascarar o exportados; la sentencia debe ser una lectura hasta donde el motor pueda comprobarlo · La concesión solo empieza después de que una persona la apruebe, y se rechaza una solicitud que no necesitaría la aprobación de nadie · Una concesión solo se aplica donde el proyecto permite concesiones de acceso",+ "title": "Solicitar concesiones de acceso"+ },"run-rollouts": {"details": "Crear un despliegue · Ejecutar, omitir o cancelar sus tareas, bajo la política de aprobación del proyecto","title": "Ejecutar despliegues y tareas"@@ -2801,7 +2805,7 @@},"summary": {"read-only": "Leer esquemas, datos y el flujo de cambios; una solicitud que lleve algo que no pueda demostrarse que es una lectura se rechaza, y no se exporta nada",- "read-write": "Leer esquemas, datos y el flujo de cambios; proponer, ejecutar, exportar y gestionar"+ "read-write": "Leer esquemas, datos y el flujo de cambios; proponer, solicitar acceso, ejecutar, exportar y gestionar"},"tier": {"read": "lectura",diff --git a/frontend/src/locales/ja-JP.json b/frontend/src/locales/ja-JP.jsonindex 0c47e5719b..e96702a2e5 100644--- a/frontend/src/locales/ja-JP.json+++ b/frontend/src/locales/ja-JP.json@@ -2785,6 +2785,10 @@"details": "Issue とコメント · Plan とプランチェック · ロールアウト・タスク実行・ログ · リリース · ロールバックのプレビュー","title": "変更ワークフローの読み取り"},+ "request-access": {+ "details": "特定のステートメントを実行するための期限付きアクセス付与をリクエストします。結果のマスク解除やエクスポートも含められます。エンジンが確認できる範囲で、ステートメントは読み取りでなければなりません · 付与は人が承認した後にのみ有効になり、誰の承認も必要としないリクエストは拒否されます · 付与は、プロジェクトがアクセス付与を許可している場合にのみ適用されます",+ "title": "アクセス付与をリクエストする"+ },"run-rollouts": {"details": "ロールアウトの作成 · プロジェクトの承認ポリシーのもとでタスクを実行・スキップ・キャンセル","title": "ロールアウトとタスクを実行する"@@ -2801,7 +2805,7 @@},"summary": {"read-only": "スキーマ・データ・変更ワークフローの読み取り。読み取りだと確認できないものを含むリクエストは拒否され、エクスポートもできません",- "read-write": "スキーマ・データ・変更ワークフローの読み取り。提案・実行・エクスポート・管理"+ "read-write": "スキーマ・データ・変更ワークフローの読み取り。提案・アクセスのリクエスト・実行・エクスポート・管理"},"tier": {"read": "読み取り",diff --git a/frontend/src/locales/vi-VN.json b/frontend/src/locales/vi-VN.jsonindex f519ab74c9..0d7fa0fc12 100644--- a/frontend/src/locales/vi-VN.json+++ b/frontend/src/locales/vi-VN.json@@ -2785,6 +2785,10 @@"details": "Issue và bình luận · Plan và kiểm tra plan · Triển khai, lần chạy tác vụ và nhật ký · Bản phát hành · Xem trước khôi phục","title": "Đọc quy trình thay đổi"},+ "request-access": {+ "details": "Xin cấp quyền truy cập có thời hạn để chạy một câu lệnh cụ thể, có thể kèm xem kết quả chưa che hoặc xuất kết quả; câu lệnh phải là lệnh đọc trong phạm vi engine kiểm tra được · Quyền chỉ bắt đầu sau khi một người phê duyệt, và yêu cầu không cần ai phê duyệt sẽ bị từ chối · Quyền chỉ áp dụng khi dự án cho phép cấp quyền truy cập",+ "title": "Yêu cầu cấp quyền truy cập"+ },"run-rollouts": {"details": "Tạo một triển khai · Chạy, bỏ qua hoặc hủy các tác vụ của nó, theo chính sách phê duyệt của dự án","title": "Chạy triển khai và tác vụ"@@ -2801,7 +2805,7 @@},"summary": {"read-only": "Đọc lược đồ, dữ liệu và quy trình thay đổi; yêu cầu chứa bất kỳ thứ gì không thể chứng minh là đọc đều bị từ chối, và không xuất được gì",- "read-write": "Đọc lược đồ, dữ liệu và quy trình thay đổi; đề xuất, chạy, xuất và quản lý"+ "read-write": "Đọc lược đồ, dữ liệu và quy trình thay đổi; đề xuất, yêu cầu truy cập, chạy, xuất và quản lý"},"tier": {"read": "đọc",diff --git a/frontend/src/locales/zh-CN.json b/frontend/src/locales/zh-CN.jsonindex 1da362b99c..ca4e40d551 100644--- a/frontend/src/locales/zh-CN.json+++ b/frontend/src/locales/zh-CN.json@@ -2785,6 +2785,10 @@"details": "工单和评论 · Plan 和计划检查 · 部署、任务运行和日志 · 发布 · 回滚预览","title": "读取变更流程"},+ "request-access": {+ "details": "为特定语句申请限时访问授权,可选择查看未脱敏结果或导出结果;在引擎能检查的范围内,该语句必须是读取 · 只有在有人审批后授权才会生效;无需任何人审批的申请会被拒绝 · 授权仅在项目允许访问授权时适用",+ "title": "申请访问授权"+ },"run-rollouts": {"details": "创建部署 · 在项目审批策略之下执行、跳过或取消其任务","title": "执行部署和任务"@@ -2801,7 +2805,7 @@},"summary": {"read-only": "读取模式、数据和变更流程;只要请求中含有无法被确认为读取的内容就会被拒绝,也不能导出",- "read-write": "读取模式、数据和变更流程;提议、执行、导出和管理"+ "read-write": "读取模式、数据和变更流程;提议、申请访问、执行、导出和管理"},"tier": {"read": "读取",diff --git a/frontend/src/routes/workspace/mcp/MCPCapabilityLadder.test.tsx b/frontend/src/routes/workspace/mcp/MCPCapabilityLadder.test.tsxindex a99f300f08..23ba292340 100644--- a/frontend/src/routes/workspace/mcp/MCPCapabilityLadder.test.tsx+++ b/frontend/src/routes/workspace/mcp/MCPCapabilityLadder.test.tsx@@ -168,7 +168,7 @@ describe("MCPCapabilityLadder", () => {unmount();});- // One second-level control rather than eight: the toggle reveals the+ // One second-level control rather than one per row: the toggle reveals the// sub-item line on every row at once.test("the details toggle reveals sub-items on every row at once", () => {const { container, rerender, unmount } = renderIntoContainer(ladder({}));@@ -252,7 +252,7 @@ describe("MCPCapabilityLadder", () => {);expect(divider).toBeDefined();// Its own item, and presentational: not content inside the row it closes,- // and not an item of the eight.+ // and not one of the rows.expect(divider?.getAttribute("role")).toBe("presentation");expect(divider?.textContent).not.toContain("settings.mcp.ladder.row.");}diff --git a/frontend/src/types/proto-es/v1/access_grant_service_pb.js b/frontend/src/types/proto-es/v1/access_grant_service_pb.jsindex d930ad9a9b..91134aa743 100644--- a/frontend/src/types/proto-es/v1/access_grant_service_pb.js+++ b/frontend/src/types/proto-es/v1/access_grant_service_pb.js@@ -14,7 +14,7 @@ import { file_v1_annotation } from "./annotation_pb";* Describes the file v1/access_grant_service.proto.*/export const file_v1_access_grant_service = /*@__PURE__*/- fileDesc("Ch12MS9hY2Nlc3NfZ3JhbnRfc2VydmljZS5wcm90bxILYnl0ZWJhc2UudjEi5gQKC0FjY2Vzc0dyYW50EgwKBG5hbWUYASABKAkSFAoHY3JlYXRvchgCIAEoCUID4EECEjQKBnN0YXR1cxgDIAEoDjIfLmJ5dGViYXNlLnYxLkFjY2Vzc0dyYW50LlN0YXR1c0ID4EEDEjEKC2V4cGlyZV90aW1lGAQgASgLMhouZ29vZ2xlLnByb3RvYnVmLlRpbWVzdGFtcEgAEi0KA3R0bBgLIAEoCzIZLmdvb2dsZS5wcm90b2J1Zi5EdXJhdGlvbkID4EEESAASEgoFaXNzdWUYBSABKAlCA+BBAxIUCgd0YXJnZXRzGAYgAygJQgPgQQISDQoFcXVlcnkYByABKAkSDgoGdW5tYXNrGAggASgIEjQKC2NyZWF0ZV90aW1lGAkgASgLMhouZ29vZ2xlLnByb3RvYnVmLlRpbWVzdGFtcEID4EEDEjQKC3VwZGF0ZV90aW1lGAogASgLMhouZ29vZ2xlLnByb3RvYnVmLlRpbWVzdGFtcEID4EEDEg4KBnJlYXNvbhgMIAEoCRIOCgZleHBvcnQYDSABKAgSDgoGc2NoZW1hGA4gASgJEhEKCWNvbnRhaW5lchgPIAEoCSJGCgZTdGF0dXMSFgoSU1RBVFVTX1VOU1BFQ0lGSUVEEAASCwoHUEVORElORxABEgoKBkFDVElWRRACEgsKB1JFVk9LRUQQAzpN6kFKChhieXRlYmFzZS5jb20vQWNjZXNzR3JhbnQSLnByb2plY3RzL3twcm9qZWN0fS9hY2Nlc3NHcmFudHMve2FjY2Vzc19ncmFudH1CDAoKZXhwaXJhdGlvbiJHChVHZXRBY2Nlc3NHcmFudFJlcXVlc3QSLgoEbmFtZRgBIAEoCUIg4EEC+kEaChhieXRlYmFzZS5jb20vQWNjZXNzR3JhbnQikAEKF0xpc3RBY2Nlc3NHcmFudHNSZXF1ZXN0EiwKBnBhcmVudBgBIAEoCUIc4EEC+kEWChRieXRlYmFzZS5jb20vUHJvamVjdBIRCglwYWdlX3NpemUYAiABKAUSEgoKcGFnZV90b2tlbhgDIAEoCRIOCgZmaWx0ZXIYBCABKAkSEAoIb3JkZXJfYnkYBSABKAkiZAoYTGlzdEFjY2Vzc0dyYW50c1Jlc3BvbnNlEi8KDWFjY2Vzc19ncmFudHMYASADKAsyGC5ieXRlYmFzZS52MS5BY2Nlc3NHcmFudBIXCg9uZXh0X3BhZ2VfdG9rZW4YAiABKAkifQoYQ3JlYXRlQWNjZXNzR3JhbnRSZXF1ZXN0EiwKBnBhcmVudBgBIAEoCUIc4EEC+kEWChRieXRlYmFzZS5jb20vUHJvamVjdBIzCgxhY2Nlc3NfZ3JhbnQYAiABKAsyGC5ieXRlYmFzZS52MS5BY2Nlc3NHcmFudEID4EECIkwKGkFjdGl2YXRlQWNjZXNzR3JhbnRSZXF1ZXN0Ei4KBG5hbWUYASABKAlCIOBBAvpBGgoYYnl0ZWJhc2UuY29tL0FjY2Vzc0dyYW50IkoKGFJldm9rZUFjY2Vzc0dyYW50UmVxdWVzdBIuCgRuYW1lGAEgASgJQiDgQQL6QRoKGGJ5dGViYXNlLmNvbS9BY2Nlc3NHcmFudCKUAQobU2VhcmNoTXlBY2Nlc3NHcmFudHNSZXF1ZXN0EiwKBnBhcmVudBgBIAEoCUIc4EEC+kEWChRieXRlYmFzZS5jb20vUHJvamVjdBIRCglwYWdlX3NpemUYAiABKAUSEgoKcGFnZV90b2tlbhgDIAEoCRIOCgZmaWx0ZXIYBCABKAkSEAoIb3JkZXJfYnkYBSABKAkiaAocU2VhcmNoTXlBY2Nlc3NHcmFudHNSZXNwb25zZRIvCg1hY2Nlc3NfZ3JhbnRzGAEgAygLMhguYnl0ZWJhc2UudjEuQWNjZXNzR3JhbnQSFwoPbmV4dF9wYWdlX3Rva2VuGAIgASgJMpwJChJBY2Nlc3NHcmFudFNlcnZpY2USpgEKDkdldEFjY2Vzc0dyYW50EiIuYnl0ZWJhc2UudjEuR2V0QWNjZXNzR3JhbnRSZXF1ZXN0GhguYnl0ZWJhc2UudjEuQWNjZXNzR3JhbnQiVtpBBG5hbWWK6jATYmIuYWNjZXNzR3JhbnRzLmdldJDqMAGg6jAEqOowCYLT5JMCJhIkL3YxL3tuYW1lPXByb2plY3RzLyovYWNjZXNzR3JhbnRzLyp9EroBChBMaXN0QWNjZXNzR3JhbnRzEiQuYnl0ZWJhc2UudjEuTGlzdEFjY2Vzc0dyYW50c1JlcXVlc3QaJS5ieXRlYmFzZS52MS5MaXN0QWNjZXNzR3JhbnRzUmVzcG9uc2UiWdpBBnBhcmVudIrqMBRiYi5hY2Nlc3NHcmFudHMubGlzdJDqMAGg6jAEqOowCYLT5JMCJhIkL3YxL3twYXJlbnQ9cHJvamVjdHMvKn0vYWNjZXNzR3JhbnRzEtABChFDcmVhdGVBY2Nlc3NHcmFudBIlLmJ5dGViYXNlLnYxLkNyZWF0ZUFjY2Vzc0dyYW50UmVxdWVzdBoYLmJ5dGViYXNlLnYxLkFjY2Vzc0dyYW50InraQRNwYXJlbnQsYWNjZXNzX2dyYW50iuowFmJiLmFjY2Vzc0dyYW50cy5jcmVhdGWQ6jABmOowAaDqMASo6jAJgtPkkwI0OgxhY2Nlc3NfZ3JhbnQiJC92MS97cGFyZW50PXByb2plY3RzLyp9L2FjY2Vzc0dyYW50cxLFAQoTQWN0aXZhdGVBY2Nlc3NHcmFudBInLmJ5dGViYXNlLnYxLkFjdGl2YXRlQWNjZXNzR3JhbnRSZXF1ZXN0GhguYnl0ZWJhc2UudjEuQWNjZXNzR3JhbnQia9pBBG5hbWWK6jAYYmIuYWNjZXNzR3JhbnRzLmFjdGl2YXRlkOowAZjqMAGg6jAEqOowCYLT5JMCMjoBKiItL3YxL3tuYW1lPXByb2plY3RzLyovYWNjZXNzR3JhbnRzLyp9OmFjdGl2YXRlEr0BChFSZXZva2VBY2Nlc3NHcmFudBIlLmJ5dGViYXNlLnYxLlJldm9rZUFjY2Vzc0dyYW50UmVxdWVzdBoYLmJ5dGViYXNlLnYxLkFjY2Vzc0dyYW50ImfaQQRuYW1liuowFmJiLmFjY2Vzc0dyYW50cy5yZXZva2WQ6jABmOowAaDqMASo6jAJgtPkkwIwOgEqIisvdjEve25hbWU9cHJvamVjdHMvKi9hY2Nlc3NHcmFudHMvKn06cmV2b2tlEsQBChRTZWFyY2hNeUFjY2Vzc0dyYW50cxIoLmJ5dGViYXNlLnYxLlNlYXJjaE15QWNjZXNzR3JhbnRzUmVxdWVzdBopLmJ5dGViYXNlLnYxLlNlYXJjaE15QWNjZXNzR3JhbnRzUmVzcG9uc2UiV4rqMBNiYi5hY2Nlc3NHcmFudHMuZ2V0kOowAqDqMAGC0+STAjI6ASoiLS92MS97cGFyZW50PXByb2plY3RzLyp9L2FjY2Vzc0dyYW50czpzZWFyY2hNeUKtAQoPY29tLmJ5dGViYXNlLnYxQhdBY2Nlc3NHcmFudFNlcnZpY2VQcm90b1ABWjRnaXRodWIuY29tL2J5dGViYXNlL2J5dGViYXNlL2JhY2tlbmQvZ2VuZXJhdGVkLWdvL3YxogIDQlhYqgILQnl0ZWJhc2UuVjHKAgtCeXRlYmFzZVxWMeICF0J5dGViYXNlXFYxXEdQQk1ldGFkYXRh6gIMQnl0ZWJhc2U6OlYxYgZwcm90bzM", [file_google_api_annotations, file_google_api_client, file_google_api_field_behavior, file_google_api_resource, file_google_protobuf_duration, file_google_protobuf_timestamp, file_v1_annotation]);+ fileDesc("Ch12MS9hY2Nlc3NfZ3JhbnRfc2VydmljZS5wcm90bxILYnl0ZWJhc2UudjEi5gQKC0FjY2Vzc0dyYW50EgwKBG5hbWUYASABKAkSFAoHY3JlYXRvchgCIAEoCUID4EECEjQKBnN0YXR1cxgDIAEoDjIfLmJ5dGViYXNlLnYxLkFjY2Vzc0dyYW50LlN0YXR1c0ID4EEDEjEKC2V4cGlyZV90aW1lGAQgASgLMhouZ29vZ2xlLnByb3RvYnVmLlRpbWVzdGFtcEgAEi0KA3R0bBgLIAEoCzIZLmdvb2dsZS5wcm90b2J1Zi5EdXJhdGlvbkID4EEESAASEgoFaXNzdWUYBSABKAlCA+BBAxIUCgd0YXJnZXRzGAYgAygJQgPgQQISDQoFcXVlcnkYByABKAkSDgoGdW5tYXNrGAggASgIEjQKC2NyZWF0ZV90aW1lGAkgASgLMhouZ29vZ2xlLnByb3RvYnVmLlRpbWVzdGFtcEID4EEDEjQKC3VwZGF0ZV90aW1lGAogASgLMhouZ29vZ2xlLnByb3RvYnVmLlRpbWVzdGFtcEID4EEDEg4KBnJlYXNvbhgMIAEoCRIOCgZleHBvcnQYDSABKAgSDgoGc2NoZW1hGA4gASgJEhEKCWNvbnRhaW5lchgPIAEoCSJGCgZTdGF0dXMSFgoSU1RBVFVTX1VOU1BFQ0lGSUVEEAASCwoHUEVORElORxABEgoKBkFDVElWRRACEgsKB1JFVk9LRUQQAzpN6kFKChhieXRlYmFzZS5jb20vQWNjZXNzR3JhbnQSLnByb2plY3RzL3twcm9qZWN0fS9hY2Nlc3NHcmFudHMve2FjY2Vzc19ncmFudH1CDAoKZXhwaXJhdGlvbiJHChVHZXRBY2Nlc3NHcmFudFJlcXVlc3QSLgoEbmFtZRgBIAEoCUIg4EEC+kEaChhieXRlYmFzZS5jb20vQWNjZXNzR3JhbnQikAEKF0xpc3RBY2Nlc3NHcmFudHNSZXF1ZXN0EiwKBnBhcmVudBgBIAEoCUIc4EEC+kEWChRieXRlYmFzZS5jb20vUHJvamVjdBIRCglwYWdlX3NpemUYAiABKAUSEgoKcGFnZV90b2tlbhgDIAEoCRIOCgZmaWx0ZXIYBCABKAkSEAoIb3JkZXJfYnkYBSABKAkiZAoYTGlzdEFjY2Vzc0dyYW50c1Jlc3BvbnNlEi8KDWFjY2Vzc19ncmFudHMYASADKAsyGC5ieXRlYmFzZS52MS5BY2Nlc3NHcmFudBIXCg9uZXh0X3BhZ2VfdG9rZW4YAiABKAkifQoYQ3JlYXRlQWNjZXNzR3JhbnRSZXF1ZXN0EiwKBnBhcmVudBgBIAEoCUIc4EEC+kEWChRieXRlYmFzZS5jb20vUHJvamVjdBIzCgxhY2Nlc3NfZ3JhbnQYAiABKAsyGC5ieXRlYmFzZS52MS5BY2Nlc3NHcmFudEID4EECIkwKGkFjdGl2YXRlQWNjZXNzR3JhbnRSZXF1ZXN0Ei4KBG5hbWUYASABKAlCIOBBAvpBGgoYYnl0ZWJhc2UuY29tL0FjY2Vzc0dyYW50IkoKGFJldm9rZUFjY2Vzc0dyYW50UmVxdWVzdBIuCgRuYW1lGAEgASgJQiDgQQL6QRoKGGJ5dGViYXNlLmNvbS9BY2Nlc3NHcmFudCKUAQobU2VhcmNoTXlBY2Nlc3NHcmFudHNSZXF1ZXN0EiwKBnBhcmVudBgBIAEoCUIc4EEC+kEWChRieXRlYmFzZS5jb20vUHJvamVjdBIRCglwYWdlX3NpemUYAiABKAUSEgoKcGFnZV90b2tlbhgDIAEoCRIOCgZmaWx0ZXIYBCABKAkSEAoIb3JkZXJfYnkYBSABKAkiaAocU2VhcmNoTXlBY2Nlc3NHcmFudHNSZXNwb25zZRIvCg1hY2Nlc3NfZ3JhbnRzGAEgAygLMhguYnl0ZWJhc2UudjEuQWNjZXNzR3JhbnQSFwoPbmV4dF9wYWdlX3Rva2VuGAIgASgJMpgJChJBY2Nlc3NHcmFudFNlcnZpY2USpgEKDkdldEFjY2Vzc0dyYW50EiIuYnl0ZWJhc2UudjEuR2V0QWNjZXNzR3JhbnRSZXF1ZXN0GhguYnl0ZWJhc2UudjEuQWNjZXNzR3JhbnQiVtpBBG5hbWWK6jATYmIuYWNjZXNzR3JhbnRzLmdldJDqMAGg6jAEqOowCYLT5JMCJhIkL3YxL3tuYW1lPXByb2plY3RzLyovYWNjZXNzR3JhbnRzLyp9EroBChBMaXN0QWNjZXNzR3JhbnRzEiQuYnl0ZWJhc2UudjEuTGlzdEFjY2Vzc0dyYW50c1JlcXVlc3QaJS5ieXRlYmFzZS52MS5MaXN0QWNjZXNzR3JhbnRzUmVzcG9uc2UiWdpBBnBhcmVudIrqMBRiYi5hY2Nlc3NHcmFudHMubGlzdJDqMAGg6jAEqOowCYLT5JMCJhIkL3YxL3twYXJlbnQ9cHJvamVjdHMvKn0vYWNjZXNzR3JhbnRzEswBChFDcmVhdGVBY2Nlc3NHcmFudBIlLmJ5dGViYXNlLnYxLkNyZWF0ZUFjY2Vzc0dyYW50UmVxdWVzdBoYLmJ5dGViYXNlLnYxLkFjY2Vzc0dyYW50InbaQRNwYXJlbnQsYWNjZXNzX2dyYW50iuowFmJiLmFjY2Vzc0dyYW50cy5jcmVhdGWQ6jABmOowAaDqMAKC0+STAjQ6DGFjY2Vzc19ncmFudCIkL3YxL3twYXJlbnQ9cHJvamVjdHMvKn0vYWNjZXNzR3JhbnRzEsUBChNBY3RpdmF0ZUFjY2Vzc0dyYW50EicuYnl0ZWJhc2UudjEuQWN0aXZhdGVBY2Nlc3NHcmFudFJlcXVlc3QaGC5ieXRlYmFzZS52MS5BY2Nlc3NHcmFudCJr2kEEbmFtZYrqMBhiYi5hY2Nlc3NHcmFudHMuYWN0aXZhdGWQ6jABmOowAaDqMAOo6jAIgtPkkwIyOgEqIi0vdjEve25hbWU9cHJvamVjdHMvKi9hY2Nlc3NHcmFudHMvKn06YWN0aXZhdGUSvQEKEVJldm9rZUFjY2Vzc0dyYW50EiUuYnl0ZWJhc2UudjEuUmV2b2tlQWNjZXNzR3JhbnRSZXF1ZXN0GhguYnl0ZWJhc2UudjEuQWNjZXNzR3JhbnQiZ9pBBG5hbWWK6jAWYmIuYWNjZXNzR3JhbnRzLnJldm9rZZDqMAGY6jABoOowBKjqMAmC0+STAjA6ASoiKy92MS97bmFtZT1wcm9qZWN0cy8qL2FjY2Vzc0dyYW50cy8qfTpyZXZva2USxAEKFFNlYXJjaE15QWNjZXNzR3JhbnRzEiguYnl0ZWJhc2UudjEuU2VhcmNoTXlBY2Nlc3NHcmFudHNSZXF1ZXN0GikuYnl0ZWJhc2UudjEuU2VhcmNoTXlBY2Nlc3NHcmFudHNSZXNwb25zZSJXiuowE2JiLmFjY2Vzc0dyYW50cy5nZXSQ6jACoOowAYLT5JMCMjoBKiItL3YxL3twYXJlbnQ9cHJvamVjdHMvKn0vYWNjZXNzR3JhbnRzOnNlYXJjaE15Qq0BCg9jb20uYnl0ZWJhc2UudjFCF0FjY2Vzc0dyYW50U2VydmljZVByb3RvUAFaNGdpdGh1Yi5jb20vYnl0ZWJhc2UvYnl0ZWJhc2UvYmFja2VuZC9nZW5lcmF0ZWQtZ28vdjGiAgNCWFiqAgtCeXRlYmFzZS5WMcoCC0J5dGViYXNlXFYx4gIXQnl0ZWJhc2VcVjFcR1BCTWV0YWRhdGHqAgxCeXRlYmFzZTo6VjFiBnByb3RvMw", [file_google_api_annotations, file_google_api_client, file_google_api_field_behavior, file_google_api_resource, file_google_protobuf_duration, file_google_protobuf_timestamp, file_v1_annotation]);/*** Describes the message bytebase.v1.AccessGrant.diff --git a/frontend/src/types/proto-es/v1/annotation_pb.d.ts b/frontend/src/types/proto-es/v1/annotation_pb.d.tsindex c108b79526..b394a2e457 100644--- a/frontend/src/types/proto-es/v1/annotation_pb.d.ts+++ b/frontend/src/types/proto-es/v1/annotation_pb.d.ts@@ -249,10 +249,11 @@ export enum MCPDenialReason {REWRITES_SESSION_BOUNDARY = 7,/**- * Works the human approval step that gates the change: recording the review- * decision, or re-running the finding that sets it and can clear the issue- * outright. An agent composes a change; it does not move its own change- * through the gate.+ * Decides whether a change or an access request passes its human approval:+ * recording the review decision, re-running the finding that sets it and can+ * clear the issue outright, or activating an access grant without it. An+ * agent composes a change or files a request; it does not decide that for its+ * own work.** @generated from enum value: DRIVES_THE_APPROVAL_DECISION = 8;*/diff --git a/frontend/tests/e2e/workspace/workspace-mcp-policy.spec.ts b/frontend/tests/e2e/workspace/workspace-mcp-policy.spec.tsindex 4f3d8fc993..f54d88cd75 100644--- a/frontend/tests/e2e/workspace/workspace-mcp-policy.spec.ts+++ b/frontend/tests/e2e/workspace/workspace-mcp-policy.spec.ts@@ -199,7 +199,7 @@ test.describe("MCP access policy capability ladder", () => {await expect(page.getByText(COPY.ladder.stops.write)).toBeVisible();await expect(page.getByText(COPY.ladder.floor.text)).toBeVisible();- // One second-level control for all eight rows, not eight expanders.+ // One second-level control for all the rows, not one expander per row.await expect(page.getByText(EXPORT_DETAILS)).toHaveCount(0);await page.getByRole("button", { name: "Show details" }).click();await expect(page.getByText(EXPORT_DETAILS)).toBeVisible();diff --git a/proto/gen/grpc-doc/v1/README.md b/proto/gen/grpc-doc/v1/README.mdindex dc5fa23b4e..2271ffd15c 100644--- a/proto/gen/grpc-doc/v1/README.md+++ b/proto/gen/grpc-doc/v1/README.md@@ -887,7 +887,7 @@ already keeps for the wording.| ENDS_MEMBERSHIP | 5 | Destroys the caller's own workspace membership and mints a plain workspace token on the way out. || MINTS_CREDENTIAL_FOR_OTHERS | 6 | Leaves someone holding a principal the caller is not — by issuing its credential, carrying an existing one out to a host the caller named, choosing what will later be trusted to mint one, or redirecting where one gets delivered. || REWRITES_SESSION_BOUNDARY | 7 | Rewrites the workspace configuration that governs the session making the call — the MCP switch itself, the sign-in and SSO settings, the mail relay that carries credential resets, and the AI endpoint the stored API key is sent to. A session that can widen its own ceiling is not bounded by it. |-| DRIVES_THE_APPROVAL_DECISION | 8 | Works the human approval step that gates the change: recording the review decision, or re-running the finding that sets it and can clear the issue outright. An agent composes a change; it does not move its own change through the gate. |+| DRIVES_THE_APPROVAL_DECISION | 8 | Decides whether a change or an access request passes its human approval: recording the review decision, re-running the finding that sets it and can clear the issue outright, or activating an access grant without it. An agent composes a change or files a request; it does not decide that for its own work. || ADMINISTERS_THE_WORKSPACE | 9 | Administers the workspace rather than doing database work: identity, credentials, access control, governance policy, billing, workspace and instance configuration, project lifecycle, and the operator's own audit trail. Reading is administration too where the read returns the privilege topology or a stored secret rather than the state of a database. || READS_OTHER_USERS_SQL | 10 | Returns SQL that other people wrote. The permission gating it reads as an ordinary list permission, so the exclusion is per method rather than per permission: these methods span the workspace or ignore the per-object sharing that keeps a saved query private. || OPENS_AN_ADMIN_CONNECTION | 11 | Opens an admin-credentialed connection to the customer's database and returns live session state from it — including other sessions' in-flight, unmasked SQL. It shares a plain read permission with sibling methods that only read Bytebase's own store. |diff --git a/proto/gen/grpc-doc/v1/index.html b/proto/gen/grpc-doc/v1/index.htmlindex e438ae262d..486ca1e81f 100644--- a/proto/gen/grpc-doc/v1/index.html+++ b/proto/gen/grpc-doc/v1/index.html@@ -3439,10 +3439,11 @@ by it.</p></td><tr><td>DRIVES_THE_APPROVAL_DECISION</td><td>8</td>- <td><p>Works the human approval step that gates the change: recording the review-decision, or re-running the finding that sets it and can clear the issue-outright. An agent composes a change; it does not move its own change-through the gate.</p></td>+ <td><p>Decides whether a change or an access request passes its human approval:+recording the review decision, re-running the finding that sets it and can+clear the issue outright, or activating an access grant without it. An+agent composes a change or files a request; it does not decide that for its+own work.</p></td></tr><tr>diff --git a/proto/v1/v1/access_grant_service.proto b/proto/v1/v1/access_grant_service.protoindex 4c85174b0b..6a26b97be2 100644--- a/proto/v1/v1/access_grant_service.proto+++ b/proto/v1/v1/access_grant_service.proto@@ -44,8 +44,9 @@ service AccessGrantService {option (bytebase.v1.permission) = "bb.accessGrants.create";option (bytebase.v1.auth_method) = IAM;option (bytebase.v1.audit) = true;- option (bytebase.v1.mcp_method_class) = EXCLUDED;- option (bytebase.v1.mcp_denial_reason) = ADMINISTERS_THE_WORKSPACE;+ // WRITE, but an MCP session is refused a request that no approval rule+ // sends to a person (refuseUnattendedMCPAccessGrant).+ option (bytebase.v1.mcp_method_class) = WRITE;}// Activates a pending access grant.@@ -58,8 +59,8 @@ service AccessGrantService {option (bytebase.v1.permission) = "bb.accessGrants.activate";option (bytebase.v1.auth_method) = IAM;option (bytebase.v1.audit) = true;- option (bytebase.v1.mcp_method_class) = EXCLUDED;- option (bytebase.v1.mcp_denial_reason) = ADMINISTERS_THE_WORKSPACE;+ option (bytebase.v1.mcp_method_class) = FORBIDDEN;+ option (bytebase.v1.mcp_denial_reason) = DRIVES_THE_APPROVAL_DECISION;}// Revokes an active access grant.diff --git a/proto/v1/v1/annotation.proto b/proto/v1/v1/annotation.protoindex 0b120c82b1..7258b7a5b5 100644--- a/proto/v1/v1/annotation.proto+++ b/proto/v1/v1/annotation.proto@@ -159,10 +159,11 @@ enum MCPDenialReason {// key is sent to. A session that can widen its own ceiling is not bounded// by it.REWRITES_SESSION_BOUNDARY = 7;- // Works the human approval step that gates the change: recording the review- // decision, or re-running the finding that sets it and can clear the issue- // outright. An agent composes a change; it does not move its own change- // through the gate.+ // Decides whether a change or an access request passes its human approval:+ // recording the review decision, re-running the finding that sets it and can+ // clear the issue outright, or activating an access grant without it. An+ // agent composes a change or files a request; it does not decide that for its+ // own work.DRIVES_THE_APPROVAL_DECISION = 8;// 9-14: EXCLUDED. The method is out because this phase ships two modes anddiff --git a/proto/v1/v1/issue_service.proto b/proto/v1/v1/issue_service.protoindex 8b308904b3..9d8bdf3fcc 100644--- a/proto/v1/v1/issue_service.proto+++ b/proto/v1/v1/issue_service.proto@@ -42,21 +42,11 @@ service IssueService {option (bytebase.v1.permission) = "bb.issues.create";option (bytebase.v1.auth_method) = IAM;option (bytebase.v1.audit) = true;- // WRITE covers the DATABASE_CHANGE issue this method exists for. It does- // not cover a ROLE_GRANT issue, which completes on creation whenever the- // workspace rule produces no approval template and then writes the project- // IAM binding for a grantee the request names — which is- // ProjectService/SetIamPolicy, EXCLUDED for exactly that outcome. A class- // annotation cannot split by request field, so the MCP gate carries a- // request-shape refusal for this method: it admits DATABASE_CHANGE and- // refuses every other type (backend/api/v1/mcp_gate.go,- // mcpRequestShapeRefusals). UpdateIssue reaches the same creation through- // allow_missing and is refused with it.- //- // An ACCESS_GRANT issue is refused by the same allow-list and does not- // reach this handler in the first place: buildIssueMessage has no arm for- // it, so the type is an invalid argument here. Those issues are written by- // AccessGrantService/CreateAccessGrant, which is EXCLUDED.+ // WRITE covers the DATABASE_CHANGE issue this method exists for. MCP+ // sessions are refused every other type (grantIssueRefusal in+ // backend/api/v1/mcp_gate.go): a ROLE_GRANT issue can complete on creation+ // with no human step, and an access request goes through+ // AccessGrantService/CreateAccessGrant instead.option (bytebase.v1.mcp_method_class) = WRITE;}@@ -93,12 +83,9 @@ service IssueService {option (bytebase.v1.permission) = "bb.issues.update";option (bytebase.v1.auth_method) = IAM;option (bytebase.v1.audit) = true;- // WRITE, and editing an issue is an agent's job — including an edit that- // resets approval finding and sends the issue back for review. What this- // does not cover is creation: with allow_missing set on an issue that does- // not exist, the handler calls CreateIssue with the request's own issue, so- // the MCP gate applies CreateIssue's request-shape refusal here too- // whenever allow_missing is set.+ // WRITE, and editing an issue is an agent's job, including an edit that+ // sends the issue back for review. With allow_missing on a missing issue it+ // creates one, which rejectMCPOriginatedGrantIssue guards as CreateIssue is.option (bytebase.v1.mcp_method_class) = WRITE;}