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): say when no other person can approve an access request, and stop pointing agents at dead ends (#21649)
Vincent Huangc8e0b1fbcea9
diff --git a/backend/api/auth/mcp_ceiling.go b/backend/api/auth/mcp_ceiling.goindex 8048287bac..023606e466 100644--- a/backend/api/auth/mcp_ceiling.go+++ b/backend/api/auth/mcp_ceiling.go@@ -57,6 +57,9 @@ func ClassifyMCPCeiling(settings *storepb.MCPSetting, err error) MCPCeilingVerdi}}+// MCPCeilingLocation is where an admin changes the ceiling; every refusal names it.+const MCPCeilingLocation = "Integration > MCP > Access policy"+// Refusal is what a door tells the caller it is refusing: what is wrong with// this workspace's ceiling, and what an admin does about it. Empty for// MCPCeilingServes, which refuses nothing.@@ -74,13 +77,13 @@ func (v MCPCeilingVerdict) Refusal() string {switch v {case MCPCeilingDisabled:return "a workspace admin has turned MCP access off for this workspace. " +- "Ask them to raise the MCP ceiling in the workspace settings"+ "Ask them to raise the MCP ceiling under " + MCPCeilingLocationcase MCPCeilingUnserved:return "this workspace's stored MCP capability ceiling is not one this build serves. " +- "Ask a workspace admin to set the MCP ceiling to a supported value in the workspace settings"+ "Ask a workspace admin to set the MCP ceiling to a supported value under " + MCPCeilingLocationcase MCPCeilingUnavailable:return "this workspace's MCP capability ceiling could not be read. " +- "Retry shortly; if it persists, ask a workspace admin to check the workspace settings"+ "Retry shortly; if it persists, ask a workspace admin to check " + MCPCeilingLocationdefault:return ""}diff --git a/backend/api/auth/mcp_ceiling_test.go b/backend/api/auth/mcp_ceiling_test.goindex 9ec690ae9f..cebb93ec93 100644--- a/backend/api/auth/mcp_ceiling_test.go+++ b/backend/api/auth/mcp_ceiling_test.go@@ -69,7 +69,7 @@ func TestEveryVerdictThatRefusesHasWording(t *testing.T) {// Every refusal names the remedy, not only the fault. A denial an// operator cannot act on is the failure this series exists to fix.- require.Contains(t, refusal, "workspace settings", "%v must name where the fix is", v)+ require.Contains(t, refusal, MCPCeilingLocation, "%v must name where the fix is", v)}require.Empty(t, MCPCeilingServes.Refusal(), "serving refuses nothing")diff --git a/backend/api/mcp/connection_audit_test.go b/backend/api/mcp/connection_audit_test.goindex 57aefa9ab9..10a9c4f77e 100644--- a/backend/api/mcp/connection_audit_test.go+++ b/backend/api/mcp/connection_audit_test.go@@ -296,19 +296,3 @@ func mcpToken(t *testing.T, secret string, opts tokenOptions) string {require.NoError(t, err)return tokenStr}--// TestCeilingRefusalsAreRecognizedAsPolicy runs the real IsPolicyRefusal over-// the ceiling refusals that can reach a tool, rather than restating its phrase-// list somewhere it would drift.-//-// Only this verdict reaches it. A 403 is what the predicate is consulted for,-// and the per-request gate answers CodePermissionDenied for it; an-// outage answers CodeUnavailable, and DISABLED is refused at this door before-// any tool call and by the serving table at the per-request one. A refusal it-// stops recognizing gets "request a project role" appended — advice that cannot-// lift a workspace setting.-func TestCeilingRefusalsAreRecognizedAsPolicy(t *testing.T) {- verdict := auth.MCPCeilingUnserved- require.True(t, IsPolicyRefusal(verdict.Refusal()),- "%v reaches a tool as a 403 and must carry its own way out", verdict)-}diff --git a/backend/api/mcp/gen/openapi.yaml b/backend/api/mcp/gen/openapi.yamlindex 9237ac7175..6254382c97 100644--- a/backend/api/mcp/gen/openapi.yaml+++ b/backend/api/mcp/gen/openapi.yaml@@ -9285,8 +9285,9 @@ components:type: stringtitle: creatordescription: |-- The creator of the access grant.+ The creator of the access grant, the caller who requested it.Format: users/{email}+ readOnly: truestatus:allOf:- $ref: '#/components/schemas/bytebase.v1.AccessGrant.Status'@@ -9348,7 +9349,6 @@ components:description: The container name to execute the query against, used for CosmosDB only.title: AccessGrantrequired:- - creator- targetsbytebase.v1.AccessGrant.Status:type: stringdiff --git a/backend/api/mcp/server.go b/backend/api/mcp/server.goindex 6089ce75c8..055a7f3539 100644--- a/backend/api/mcp/server.go+++ b/backend/api/mcp/server.go@@ -22,6 +22,7 @@ import ("github.com/bytebase/bytebase/backend/common/log""github.com/bytebase/bytebase/backend/component/audit""github.com/bytebase/bytebase/backend/component/config"+ "github.com/bytebase/bytebase/backend/component/review"storepb "github.com/bytebase/bytebase/backend/generated-go/store""github.com/bytebase/bytebase/backend/store""github.com/bytebase/bytebase/backend/utils"@@ -43,6 +44,10 @@ type Server struct {revokedAccessTokens sync.Map // map[string]struct{}+ // findUnapprovableStep needs the concrete store, which serverStore hides,+ // so NewServer binds it and tests replace it.+ findUnapprovableStep func(ctx context.Context, workspace, issueName string) (*review.UnapprovableStep, error)+// planCheckPollBudgetOverride lets tests shorten the plan-check poll budget.// Zero means use the default (planCheckPollBudget).planCheckPollBudgetOverride time.Duration@@ -72,7 +77,14 @@ func NewServer(stores *store.Store, profile *config.Profile, secret string, inteif stores == nil {return nil, errors.New("store is required")}- return newServerWithStore(stores, profile, secret, internalAPI)+ s, err := newServerWithStore(stores, profile, secret, internalAPI)+ if err != nil {+ return nil, err+ }+ s.findUnapprovableStep = func(ctx context.Context, workspace, issueName string) (*review.UnapprovableStep, error) {+ return review.FindUnapprovableStep(ctx, stores, workspace, issueName)+ }+ return s, nil}func newServerWithStore(stores serverStore, profile *config.Profile, secret string, internalAPI http.Handler) (*Server, error) {@@ -141,6 +153,7 @@ func newServerWithStore(stores serverStore, profile *config.Profile, secret stri// principal.mcpServer.AddReceivingMiddleware(negotiateLegacyProtocol)mcpServer.AddReceivingMiddleware(liveRequestMetadata)+ mcpServer.AddReceivingMiddleware(nameSignedInAccount)// Pin each session to the identity it was opened with. The SDK captures// TokenInfo.UserID when a session is created and rejects later requests@@ -193,6 +206,22 @@ func negotiateLegacyProtocol(next mcp.MethodHandler) mcp.MethodHandler {}}+// nameSignedInAccount opens the initialize instructions with the session's+// Bytebase account: clients also show the model other accounts, such as their+// own sign-in. It goes first, so a client that cuts long instructions keeps it.+func nameSignedInAccount(next mcp.MethodHandler) mcp.MethodHandler {+ return func(ctx context.Context, method string, req mcp.Request) (mcp.Result, error) {+ result, err := next(ctx, method, req)+ // The SDK refuses a second initialize on a session with a nil result,+ // and a panic here would end the process.+ if initialized, ok := result.(*mcp.InitializeResult); ok && initialized != nil {+ account := fmt.Sprintf(`This session acts as the Bytebase account %s: every tool call runs with its permissions, and "you" in tool results means it. The user may have other accounts with other emails, such as the client's own sign-in.`, getUserEmail(ctx))+ initialized.Instructions = strings.TrimSpace(account + "\n\n" + initialized.Instructions)+ }+ return result, err+ }+}+// refuseSessionlessProtocol rejects requests announcing that revision or newer.//// The SDK refuses it for every method but server/discover, and answers discoverdiff --git a/backend/api/mcp/server_test.go b/backend/api/mcp/server_test.goindex 70b693a92b..8ef0351f80 100644--- a/backend/api/mcp/server_test.go+++ b/backend/api/mcp/server_test.go@@ -1,6 +1,7 @@package mcpimport (+ "context""io""net/http""net/http/httptest"@@ -594,3 +595,42 @@ func tokenForWorkspace(t *testing.T, secret, workspaceID string) string {require.NoError(t, err)return tokenStr}++func TestInitializeNamesTheSignedInAccount(t *testing.T) {+ endpoint, _, _ := newProbeServer(t)+ token := mintMCPToken(t, "[email protected]", "client-A", "ws-test", "mcp:read-write", time.Hour)++ session := connectLegacy(t, endpoint, token, nil)+ require.Equal(t, `This session acts as the Bytebase account [email protected]: every tool call runs with its permissions, `++ `and "you" in tool results means it. The user may have other accounts with other emails, such as the client's own sign-in.`,+ session.InitializeResult().Instructions)+}++// A second initialize on an open session is refused by the SDK with no result,+// which the instructions middleware must pass through untouched.+func TestDuplicateInitializeIsRefusedAndTheServerKeepsServing(t *testing.T) {+ endpoint, _, _ := newProbeServer(t)+ token := mintMCPToken(t, "[email protected]", "client-A", "ws-test", "mcp:read-write", time.Hour)+ session := connectLegacy(t, endpoint, token, nil)++ body := `{"jsonrpc":"2.0","id":99,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"dup","version":"0"}}}`+ req, err := http.NewRequest(http.MethodPost, endpoint, strings.NewReader(body))+ require.NoError(t, err)+ req.Header.Set("Authorization", "Bearer "+token)+ req.Header.Set("Content-Type", "application/json")+ req.Header.Set("Accept", "application/json, text/event-stream")+ req.Header.Set("Mcp-Session-Id", session.ID())+ req.Header.Set("Mcp-Protocol-Version", session.InitializeResult().ProtocolVersion)+ resp, err := (&http.Client{Timeout: 10 * time.Second}).Do(req)+ require.NoError(t, err)+ defer resp.Body.Close()+ reply, err := io.ReadAll(resp.Body)+ require.NoError(t, err)+ require.Contains(t, string(reply), `"error"`)+ require.Contains(t, string(reply), "duplicate", "the SDK refuses the second initialize")++ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)+ defer cancel()+ _, err = session.ListTools(ctx, nil)+ require.NoError(t, err, "the session must keep serving after the refused initialize")+}diff --git a/backend/api/mcp/tool_access_request.go b/backend/api/mcp/tool_access_request.goindex d5058ca311..ca64b78216 100644--- a/backend/api/mcp/tool_access_request.go+++ b/backend/api/mcp/tool_access_request.go@@ -4,10 +4,13 @@ import ("context""encoding/json""fmt"+ "log/slog""github.com/modelcontextprotocol/go-sdk/mcp""github.com/pkg/errors"+ "github.com/bytebase/bytebase/backend/common/log"+ "github.com/bytebase/bytebase/backend/component/review""github.com/bytebase/bytebase/backend/generated-go/v1/v1connect")@@ -95,9 +98,41 @@ func (s *Server) handleRequestAccessGrant(ctx context.Context, _ *mcp.CallToolReDurationHours: input.DurationHours,Link: link,}+ approval, next := "A person approves it in Bytebase before it takes effect.", useAfterApproval(input.Export)+ if step := s.unapprovableStep(ctx, grant.Issue); step != nil {+ approval, next = describeUnapprovableStep(step), wayAroundUnapprovableStep(input.Unmask)+ }return &mcp.CallToolResult{Content: []mcp.Content{&mcp.TextContent{Text: fmt.Sprintf(- "Requested %s: %s for %s from approval. A person approves it in Bytebase before it takes effect.\nIssue: %s\n%s",- grant.Name, describeRequestedAccess(input), hours(input.DurationHours), link, useAfterApproval(input.Export))}}}, output, nil+ "Requested %s: %s for %s from approval. %s\nIssue: %s\n%s",+ grant.Name, describeRequestedAccess(input), hours(input.DurationHours), approval, link, next)}}}, output, nil+}++// unapprovableStep drops the note on a failed read, not the result: an agent+// shown an error could file the request again.+func (s *Server) unapprovableStep(ctx context.Context, issue string) *review.UnapprovableStep {+ step, err := s.findUnapprovableStep(ctx, getWorkspaceID(ctx), issue)+ if err != nil {+ slog.Warn("failed to check whether anyone can approve an access grant request", slog.String("issue", issue), log.BBError(err))+ return nil+ }+ return step+}++func describeUnapprovableStep(step *review.UnapprovableStep) string {+ if step.CreatorHoldsRole {+ return fmt.Sprintf("No other person can approve it: step %d of its approval flow needs %s, which no other active workspace member holds, and this project does not allow self-approval.", step.Position, step.Role)+ }+ return fmt.Sprintf("No person can approve it: step %d of its approval flow needs %s, which no active workspace member holds.", step.Position, step.Role)+}++// wayAroundUnapprovableStep never suggests allowing self-approval: the setting+// covers every issue type in the project, not only this request.+func wayAroundUnapprovableStep(unmask bool) string {+ way := "An approver can be added only in the Bytebase console, by granting someone that role."+ if unmask {+ way += " If the statement already runs for you with the values masked, a project owner can grant a masking exemption with grant_masking_exemption to read them without this request."+ }+ return way}// useAfterApproval says how to run the statement once the grant applies. Onlydiff --git a/backend/api/mcp/tool_access_request_test.go b/backend/api/mcp/tool_access_request_test.goindex 0f72dd8232..ea45ca9271 100644--- a/backend/api/mcp/tool_access_request_test.go+++ b/backend/api/mcp/tool_access_request_test.go@@ -3,6 +3,7 @@ package mcpimport ("context""encoding/json"+ "errors""math""net/http""net/http/httptest"@@ -17,6 +18,7 @@ import ("github.com/bytebase/bytebase/backend/common""github.com/bytebase/bytebase/backend/component/config"+ "github.com/bytebase/bytebase/backend/component/review""github.com/bytebase/bytebase/backend/generated-go/v1/v1connect")@@ -32,8 +34,13 @@ type accessGrantMock struct {// refusalStatus and refusal, when set, are how the request is refused.refusalStatus intrefusal map[string]any- reads []string- requests []map[string]any+ // unapprovable and unapprovableErr are what the approval-flow check+ // reports for the filed request.+ unapprovable *review.UnapprovableStep+ unapprovableErr error+ reads []string+ requests []map[string]any+ checks []string}func (m *accessGrantMock) ServeHTTP(w http.ResponseWriter, r *http.Request) {@@ -69,6 +76,19 @@ func (m *accessGrantMock) ServeHTTP(w http.ResponseWriter, r *http.Request) {}}+func (m *accessGrantMock) findUnapprovableStep(_ context.Context, workspace, issue string) (*review.UnapprovableStep, error) {+ m.mu.Lock()+ defer m.mu.Unlock()+ m.checks = append(m.checks, workspace+" "+issue)+ return m.unapprovable, m.unapprovableErr+}++func (m *accessGrantMock) checked() []string {+ m.mu.Lock()+ defer m.mu.Unlock()+ return append([]string(nil), m.checks...)+}+func (m *accessGrantMock) calls() (reads []string, requests []map[string]any) {m.mu.Lock()defer m.mu.Unlock()@@ -80,6 +100,7 @@ func connectToAccessGrantServer(t *testing.T, mock *accessGrantMock) *mcp.Clientprofile := &config.Profile{Mode: common.ReleaseModeDev, ExternalURL: "https://bb.example.com"}s, err := newServerWithStore(newTestServerStore(), profile, revalidationSecret, mock)require.NoError(t, err)+ s.findUnapprovableStep = mock.findUnapprovableStepe := echo.New()s.RegisterRoutes(e)ts := httptest.NewServer(e)@@ -138,6 +159,63 @@ func TestRequestAccessGrantFilesTheRequest(t *testing.T) {require.NoError(t, err)require.JSONEq(t, `{"accessGrant":"projects/hr/accessGrants/g1","issue":"projects/hr/issues/7","durationHours":4,"link":"https://bb.example.com/projects/hr/issues/7"}`, string(output))+ require.Equal(t, []string{"ws-test projects/hr/issues/7"}, mock.checked(), "the filed issue's approval flow is checked in the session's workspace")+}++func TestRequestAccessGrantSaysWhenNoOneCanApprove(t *testing.T) {+ for name, tt := range map[string]struct {+ step *review.UnapprovableStep+ unmask bool+ want string+ }{+ "only the requester holds the role": {+ step: &review.UnapprovableStep{Position: 1, Role: "roles/projectOwner", CreatorHoldsRole: true},+ unmask: true,+ want: "Requested projects/hr/accessGrants/g1: run the statement on projects/hr/instances/prod/databases/hr, unmasked for 4 hours from approval. " ++ "No other person can approve it: step 1 of its approval flow needs roles/projectOwner, which no other active workspace member holds, and this project does not allow self-approval.\n" ++ "Issue: https://bb.example.com/projects/hr/issues/7\n" ++ "An approver can be added only in the Bytebase console, by granting someone that role. " ++ "If the statement already runs for you with the values masked, a project owner can grant a masking exemption with grant_masking_exemption to read them without this request.",+ },+ "no person holds the role": {+ step: &review.UnapprovableStep{Position: 2, Role: "roles/workspaceDBA"},+ want: "Requested projects/hr/accessGrants/g1: run the statement on projects/hr/instances/prod/databases/hr for 4 hours from approval. " ++ "No person can approve it: step 2 of its approval flow needs roles/workspaceDBA, which no active workspace member holds.\n" ++ "Issue: https://bb.example.com/projects/hr/issues/7\n" ++ "An approver can be added only in the Bytebase console, by granting someone that role.",+ },+ } {+ t.Run(name, func(t *testing.T) {+ mock := &accessGrantMock{project: "projects/hr", unapprovable: tt.step}+ session := connectToAccessGrantServer(t, mock)++ res := callRequestAccessGrant(t, session, map[string]any{+ "database": "projects/hr/instances/prod/databases/hr",+ "statement": "SELECT 1",+ "unmask": tt.unmask,+ "reason": "a look",+ "durationHours": 4,+ })+ require.False(t, res.IsError, resultText(t, res))+ require.Equal(t, tt.want, resultText(t, res))+ })+ }+}++func TestRequestAccessGrantKeepsItsResultWhenTheApprovalCheckFails(t *testing.T) {+ mock := &accessGrantMock{project: "projects/hr", unapprovableErr: errors.New("connection refused")}+ session := connectToAccessGrantServer(t, mock)++ res := callRequestAccessGrant(t, session, map[string]any{+ "database": "projects/hr/instances/prod/databases/hr",+ "statement": "SELECT 1",+ "reason": "a look",+ "durationHours": 4,+ })+ require.False(t, res.IsError, "the request is filed, so a failed check must not read as a failed request: %s", resultText(t, res))+ require.Contains(t, resultText(t, res), "A person approves it in Bytebase before it takes effect.")+ _, requests := mock.calls()+ require.Len(t, requests, 1)}func TestRequestAccessGrantFilesInTheDatabaseProject(t *testing.T) {@@ -212,26 +290,18 @@ func TestRequestAccessGrantFilesNothingWhenTheDatabaseReadFails(t *testing.T) {}func TestRequestAccessGrantPassesPermissionDenialsThrough(t *testing.T) {- for name, tt := range map[string]struct {- message string- suggestion string- }{- "a request no person would approve": {- "/bytebase.v1.AccessGrantService/CreateAccessGrant 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.",- "",- },- "a missing permission": {- `permission denied for method "/bytebase.v1.AccessGrantService/CreateAccessGrant", user does not have permission "bb.accessGrants.create", extra map[]`,- "ask your workspace admin to grant you the bb.accessGrants.create permission",- },+ for name, message := range map[string]string{+ "a request no person would approve": "/bytebase.v1.AccessGrantService/CreateAccessGrant 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.",+ "a missing permission": `permission denied for method "/bytebase.v1.AccessGrantService/CreateAccessGrant", user does not have permission "bb.accessGrants.create", extra map[]`,+ "a plan feature": "feature FEATURE_JIT is a ENTERPRISE feature, please upgrade to access it",} {t.Run(name, func(t *testing.T) {mock := &accessGrantMock{project: "projects/hr",refusalStatus: http.StatusForbidden,- refusal: map[string]any{"code": "permission_denied", "message": tt.message},+ refusal: map[string]any{"code": "permission_denied", "message": message},}session := connectToAccessGrantServer(t, mock)@@ -244,7 +314,7 @@ func TestRequestAccessGrantPassesPermissionDenialsThrough(t *testing.T) {require.True(t, res.IsError)var denial toolErrorrequire.NoError(t, json.Unmarshal([]byte(resultText(t, res)), &denial))- require.Equal(t, toolError{Code: "PERMISSION_DENIED", Message: tt.message, Suggestion: tt.suggestion}, denial)+ require.Equal(t, toolError{Code: "PERMISSION_DENIED", Message: message}, denial, "the server's message is the whole answer")})}}diff --git a/backend/api/mcp/tool_change.go b/backend/api/mcp/tool_change.goindex 2b9fdc851a..f68df7cc9f 100644--- a/backend/api/mcp/tool_change.go+++ b/backend/api/mcp/tool_change.go@@ -551,22 +551,14 @@ func (s *Server) callAPI(ctx context.Context, path, operation, permission string// Returns nil if the response is OK, or a structured error otherwise.func checkAPIResponse(resp *apiResponse, operation, permission string) error {if resp.Status == http.StatusForbidden || resp.Status == http.StatusUnauthorized {- // A 403 here is not always a missing permission: the MCP enforcement- // chain answers the same status for the method class, the ceiling, the- // request's own shape and the masked-write guard. No grant lifts a- // workspace setting, so those keep their own remedy and get no advice.+ // The server's message goes alone. A 403 is not always a missing+ // permission (a plan feature, the MCP ceiling, the request's own shape),+ // and the ACL refusal names the permission itself.message := parseError(resp.Body)- if IsPolicyRefusal(message) {- return &toolError{Code: "PERMISSION_DENIED", Message: message}- }if message == "" {- message = fmt.Sprintf("you don't have permission to %s", operation)- }- return &toolError{- Code: "PERMISSION_DENIED",- Message: message,- Suggestion: fmt.Sprintf("ask your workspace admin to grant you the %s permission", permission),+ message = fmt.Sprintf("you don't have permission to %s, which requires %s", operation, permission)}+ return &toolError{Code: "PERMISSION_DENIED", Message: message}}if resp.Status >= 400 {return errors.Errorf("%s failed: HTTP %d: %s", operation, resp.Status, parseError(resp.Body))@@ -594,12 +586,11 @@ func formatChangeStepError(err error, defaultCode string, partialRefs map[stringfunc formatChangeStepErrorWithHint(err error, defaultCode string, partialRefs map[string]string, hint string) *mcp.CallToolResult {var te *toolErrorif errors.As(err, &te) && te.Code == "PERMISSION_DENIED" {- // Passed through rather than re-derived: re-deriving overwrote a policy- // denial's own remedy with the permission advice.+ // A permission denial keeps its code and the server's words; the step's+ // hint is about something else.return formatChangeError(&changeError{Code: "PERMISSION_DENIED",Message: te.Message,- Suggestion: te.Suggestion,PartialRefs: partialRefs,})}diff --git a/backend/api/mcp/tool_change_test.go b/backend/api/mcp/tool_change_test.goindex 3d4e9f91f4..d20d4be350 100644--- a/backend/api/mcp/tool_change_test.go+++ b/backend/api/mcp/tool_change_test.go@@ -947,7 +947,7 @@ func TestChange_IssueCreateFailed_SqlReview(t *testing.T) {func TestChange_PermissionDenied_Sheet(t *testing.T) {mock := newChangeMock(employeeDB())mock.sheetStatus = http.StatusForbidden- mock.sheetResponse = map[string]any{"message": "permission denied"}+ mock.sheetResponse = map[string]any{"message": `user does not have permission "bb.sheets.create"`}s := newChangeTestServer(t, mock)result, _, err := s.handleChange(testContext(), nil, ChangeInput{@@ -961,12 +961,11 @@ func TestChange_PermissionDenied_Sheet(t *testing.T) {text := result.Content[0].(*mcpsdk.TextContent).Textrequire.Contains(t, text, "PERMISSION_DENIED")require.Contains(t, text, "bb.sheets.create")+ require.NotContains(t, text, "suggestion", "the server's message is the whole answer")}-// TestChange_PolicyDenialKeepsItsOwnRemedy is the other half of-// checkAPIResponse. An MCP policy refusal already says what to do, and no grant-// lifts a workspace setting, so appending the permission advice would send the-// agent at a dead end.+// TestChange_PolicyDenialKeepsItsOwnRemedy: an MCP policy refusal already says+// what to do, so it reaches the agent unchanged.func TestChange_PolicyDenialKeepsItsOwnRemedy(t *testing.T) {mock := newChangeMock(employeeDB())mock.sheetStatus = http.StatusForbidden@@ -993,7 +992,7 @@ func TestChange_PolicyDenialKeepsItsOwnRemedy(t *testing.T) {func TestChange_PermissionDenied_Plan(t *testing.T) {mock := newChangeMock(employeeDB())mock.planStatus = http.StatusForbidden- mock.planResponse = map[string]any{"message": "permission denied"}+ mock.planResponse = map[string]any{"message": `user does not have permission "bb.plans.create"`}s := newChangeTestServer(t, mock)result, _, err := s.handleChange(testContext(), nil, ChangeInput{@@ -1008,12 +1007,13 @@ func TestChange_PermissionDenied_Plan(t *testing.T) {require.Contains(t, text, "PERMISSION_DENIED")require.Contains(t, text, "bb.plans.create")require.Contains(t, text, "sheets/1001") // partialRefs+ require.NotContains(t, text, "suggestion", "the server's message is the whole answer")}func TestChange_PermissionDenied_Issue(t *testing.T) {mock := newChangeMock(employeeDB())mock.issueStatus = http.StatusForbidden- mock.issueResponse = map[string]any{"message": "permission denied"}+ mock.issueResponse = map[string]any{"message": `user does not have permission "bb.issues.create"`}s := newChangeTestServer(t, mock)result, _, err := s.handleChange(testContext(), nil, ChangeInput{@@ -1029,6 +1029,7 @@ func TestChange_PermissionDenied_Issue(t *testing.T) {require.Contains(t, text, "bb.issues.create")require.Contains(t, text, "sheets/1001") // partialRefsrequire.Contains(t, text, "plans/2002") // partialRefs+ require.NotContains(t, text, "suggestion", "the server's message is the whole answer")}// --- Link construction tests ---diff --git a/backend/api/mcp/tool_decide_test.go b/backend/api/mcp/tool_decide_test.goindex 48f78488e2..a7d79001c3 100644--- a/backend/api/mcp/tool_decide_test.go+++ b/backend/api/mcp/tool_decide_test.go@@ -677,7 +677,7 @@ func TestDecideIssueReportsTheRefusalInTheServersWords(t *testing.T) {for name, refusal := range map[string]string{"the workflow": "cannot approve because self-approval is not allowed for this project","the ceiling": "/bytebase.v1.IssueService/ApproveIssue is a WRITE method and this workspace's MCP capability ceiling is READ_ONLY, " +- "which serves READ methods. Ask a workspace admin to raise the MCP ceiling in the workspace settings, " ++ "which serves READ methods. Ask a workspace admin to raise the MCP ceiling under Integration > MCP > Access policy, " +"or perform this action signed in to the Bytebase console instead",} {t.Run(name, func(t *testing.T) {diff --git a/backend/api/mcp/tool_query.go b/backend/api/mcp/tool_query.goindex c625d6c0de..e41871f6bb 100644--- a/backend/api/mcp/tool_query.go+++ b/backend/api/mcp/tool_query.go@@ -10,6 +10,8 @@ import ("github.com/modelcontextprotocol/go-sdk/mcp""github.com/pkg/errors"++ "github.com/bytebase/bytebase/backend/common/permission")const (@@ -194,6 +196,11 @@ type queryResult struct {Error string `json:"error"`Statement string `json:"statement"`Masked []maskingReason `json:"masked"`+ // PermissionDenied is set when the SQL access check refused the statement.+ PermissionDenied *struct {+ RequiredPermissions []permission.Permission `json:"requiredPermissions"`+ Resources []string `json:"resources"`+ } `json:"permissionDenied"`}// maskingReason holds the MaskingReason fields the tool reports.@@ -234,16 +241,11 @@ func (s *Server) executeQuery(ctx context.Context, resolved *resolvedDatabase, iif errMsg == "" {errMsg = fmt.Sprintf("HTTP %d", resp.Status)}- suggestion := "check your SQL syntax and try again"- if resp.Status == http.StatusForbidden || resp.Status == http.StatusUnauthorized {- // A refusal that already names its own way out gets none added.- // Telling an agent to request a project role for one sends the- // person it acts for after a grant that cannot lift a workspace- // setting.- suggestion = ""- if !IsPolicyRefusal(errMsg) {- suggestion = "you may not have permission to query this database — request the SQL Editor role on the project"- }+ // A refusal at this level gets no advice: no access grant lifts a+ // missing bb.databases.get, which the ACL checks first, or an MCP policy.+ suggestion := ""+ if resp.Status != http.StatusForbidden && resp.Status != http.StatusUnauthorized {+ suggestion = "check your SQL syntax and try again"}return nil, &toolError{Code: "QUERY_ERROR",@@ -267,10 +269,18 @@ func (s *Server) executeQuery(ctx context.Context, resolved *resolvedDatabase, iresult := qr.Results[0]if result.Error != "" {+ suggestion := "check your SQL syntax and try again"+ if result.PermissionDenied != nil {+ // MCP sessions cannot file role requests, so the only advice is a grant.+ suggestion = ""+ if denied := result.PermissionDenied; grantLifts(denied.RequiredPermissions) && withinDatabase(denied.Resources, resolved.resourceName) {+ suggestion = grantAdvice(input.Statement, result.Statement)+ }+ }return nil, &toolError{Code: "QUERY_ERROR",Message: result.Error,- Suggestion: "check your SQL syntax and try again",+ Suggestion: suggestion,}}@@ -402,22 +412,46 @@ func parseLatencyMs(latency string) int64 {return d.Milliseconds()}-// IsPolicyRefusal reports whether a 403 came from the MCP enforcement chain-// rather than from the caller's own RBAC. It matches wording because the verdict-// crosses a process boundary as an error body and nothing else survives the-// trip; the producers call this, not a copy of it, in-// TestMCPRefusalsNameThemselvesToTheQueryTool (backend/api/v1).-func IsPolicyRefusal(message string) bool {- for _, phrase := range []string{- "MCP capability ceiling",- // Singular, so it also matches the plural the gate uses and the- // refusals taken in handlers.- "MCP session",- "MCP classification",- } {- if strings.Contains(message, phrase) {- return true+// grantLifts reports whether an approved access grant lifts a refusal that+// required these permissions. Writes and DDL cannot be granted, and a granted+// target still needs bb.sql.explain (SQLService.accessCheckWithGrantedTargets).+func grantLifts(required []permission.Permission) bool {+ if len(required) == 0 {+ return false+ }+ for _, p := range required {+ if p != permission.SQLSelect && p != permission.SQLInfo {+ return false}}- return false+ return true+}++// withinDatabase reports whether every denied resource is the database or lies+// inside it. request_access_grant files a grant for that one database, and a+// grant exempts only its own targets.+func withinDatabase(resources []string, database string) bool {+ if len(resources) == 0 {+ return false+ }+ for _, resource := range resources {+ if resource != database && !strings.HasPrefix(resource, database+"/") {+ return false+ }+ }+ return true+}++// grantAdvice names the refused statement when the input was a batch. Query+// runs a batch one statement at a time and stops at the first refusal+// (queryRetryStopOnError), and a grant applies only to the exact read-only+// statement it names (hashAccessGrantQuery).+func grantAdvice(input, refused string) string {+ const howTo = "(the project must allow just-in-time access); otherwise the user requests access in the SQL Editor"+ refused = strings.TrimSpace(refused)+ if refused == "" || refused == strings.TrimSpace(input) {+ return "in a Read-write session, request an access grant for this statement with request_access_grant " + howTo+ }+ return fmt.Sprintf("the batch stopped at %q: in a Read-write session, request an access grant for that statement alone "++ "with request_access_grant and, once approved, run it by itself %s", refused, howTo)}diff --git a/backend/api/mcp/tool_query_test.go b/backend/api/mcp/tool_query_test.goindex 749ec937f6..bd00c06b17 100644--- a/backend/api/mcp/tool_query_test.go+++ b/backend/api/mcp/tool_query_test.go@@ -316,7 +316,7 @@ func TestQueryDatabase_WorkspacePermissionDenied(t *testing.T) {w.Header().Set("Content-Type", "application/json")w.WriteHeader(http.StatusForbidden)_ = json.NewEncoder(w).Encode(map[string]any{- "message": "permission denied",+ "message": `user does not have permission "bb.databases.list"`,"code": "PERMISSION_DENIED",})})@@ -327,8 +327,8 @@ func TestQueryDatabase_WorkspacePermissionDenied(t *testing.T) {var te *toolErrorrequire.ErrorAs(t, err, &te)- require.Equal(t, "PERMISSION_DENIED", te.Code)- require.Contains(t, te.Suggestion, "bb.databases.list")+ require.Equal(t, toolError{Code: "PERMISSION_DENIED", Message: `user does not have permission "bb.databases.list"`}, *te,+ "the server's message names the permission, and nothing is added")}func TestQueryDatabase_Ambiguous(t *testing.T) {@@ -669,10 +669,10 @@ func TestQueryDatabase_QueryError(t *testing.T) {require.Contains(t, text, "syntax error")}-// TestQueryDatabase_PolicyDenialGetsNoRoleAdvice is the same contract on the-// read tool. The masked-write guard refuses through SQLService/Query, and a-// project role cannot lift a workspace setting.-func TestQueryDatabase_PolicyDenialGetsNoRoleAdvice(t *testing.T) {+// TestQueryDatabase_PolicyDenialGetsNoAccessAdvice: the masked-write guard+// refuses through SQLService/Query, and no access grant lifts a workspace+// setting.+func TestQueryDatabase_PolicyDenialGetsNoAccessAdvice(t *testing.T) {databases := []map[string]any{makeDatabase("instances/prod-pg/databases/employee_db", "instances/prod-pg", "projects/hr-system", "POSTGRES", "ds-admin-1"),}@@ -700,8 +700,7 @@ func TestQueryDatabase_PolicyDenialGetsNoRoleAdvice(t *testing.T) {text := result.Content[0].(*mcpsdk.TextContent).Textrequire.Contains(t, text, "******")- require.NotContains(t, text, "SQL Editor role",- "no project role lifts a workspace setting")+ require.NotContains(t, text, "suggestion", "the refusal names its own way out")}func TestQueryDatabase_PermissionDenied(t *testing.T) {@@ -731,6 +730,127 @@ func TestQueryDatabase_PermissionDenied(t *testing.T) {text := result.Content[0].(*mcpsdk.TextContent).Textrequire.Contains(t, text, "permission denied")+ require.NotContains(t, text, "suggestion", "the ACL refuses a missing bb.databases.get before any access grant applies")+}++// The SQL access check answers inside a 200 result, the shape the server+// returns when the caller can see the database but not read its tables.+func TestQueryDatabase_TableAccessDenialAdvisesAnAccessGrant(t *testing.T) {+ databases := []map[string]any{+ makeDatabase("projects/hr/instances/prod-pg/databases/employee_db", "projects/hr/instances/prod-pg", "projects/hr", "POSTGRES", "ds-admin-1"),+ }+ for name, tt := range map[string]struct {+ statement string+ result map[string]any+ want string+ }{+ "the access check refused the tables": {+ result: map[string]any{+ "error": "permission_denied: permission denied to access resources: [projects/hr/instances/prod-pg/databases/employee_db/schemas/public/tables/employee]",+ "statement": "SELECT first_name FROM employee",+ "permissionDenied": map[string]any{+ "requiredPermissions": []string{"bb.sql.select"},+ "resources": []string{"projects/hr/instances/prod-pg/databases/employee_db/schemas/public/tables/employee"},+ },+ },+ want: "in a Read-write session, request an access grant for this statement with request_access_grant " ++ "(the project must allow just-in-time access); otherwise the user requests access in the SQL Editor",+ },+ // A grant must name a read-only statement and applies only to that exact+ // statement, so the batch as a whole can neither be granted nor use the grant.+ "the access check refused a read in a batch that also writes": {+ statement: "SELECT first_name FROM employee; UPDATE employee SET first_name = 'x'",+ result: map[string]any{+ "error": "permission_denied: permission denied to access resources: [projects/hr/instances/prod-pg/databases/employee_db/schemas/public/tables/employee]",+ "statement": "SELECT first_name FROM employee;",+ "permissionDenied": map[string]any{+ "requiredPermissions": []string{"bb.sql.select"},+ "resources": []string{"projects/hr/instances/prod-pg/databases/employee_db/schemas/public/tables/employee"},+ },+ },+ want: `the batch stopped at "SELECT first_name FROM employee;": in a Read-write session, request an access grant for that statement alone ` ++ "with request_access_grant and, once approved, run it by itself " ++ "(the project must allow just-in-time access); otherwise the user requests access in the SQL Editor",+ },+ "the access check refused a metadata read": {+ result: map[string]any{+ "error": "permission_denied: permission denied to access resources: projects/hr/instances/prod-pg/databases/employee_db",+ "permissionDenied": map[string]any{+ "requiredPermissions": []string{"bb.sql.info"},+ "resources": []string{"projects/hr/instances/prod-pg/databases/employee_db"},+ },+ },+ want: "in a Read-write session, request an access grant for this statement with request_access_grant " ++ "(the project must allow just-in-time access); otherwise the user requests access in the SQL Editor",+ },+ // A grant from request_access_grant targets the queried database only.+ "the access check refused a table in another database": {+ result: map[string]any{+ "error": "permission_denied: permission denied to access resources: [projects/hr/instances/prod-pg/databases/payroll/schemas/public/tables/salary]",+ "permissionDenied": map[string]any{+ "requiredPermissions": []string{"bb.sql.select"},+ "resources": []string{"projects/hr/instances/prod-pg/databases/payroll/schemas/public/tables/salary"},+ },+ },+ },+ "the access check refused tables in this and another database": {+ result: map[string]any{+ "error": "permission_denied: permission denied to access resources: [two tables]",+ "permissionDenied": map[string]any{+ "requiredPermissions": []string{"bb.sql.select"},+ "resources": []string{+ "projects/hr/instances/prod-pg/databases/employee_db/schemas/public/tables/employee",+ "projects/hr/instances/prod-pg/databases/employee_db2/schemas/public/tables/salary",+ },+ },+ },+ },+ // No grant lifts these: a grant's statement must be read-only, and a+ // granted target still needs bb.sql.explain from IAM.+ "the access check refused a write": {+ result: map[string]any{+ "error": "permission_denied: permission denied to access resources: [projects/hr/instances/prod-pg/databases/employee_db/schemas/public/tables/employee]",+ "permissionDenied": map[string]any{"requiredPermissions": []string{"bb.sql.dml"}},+ },+ },+ "the access check refused an EXPLAIN": {+ result: map[string]any{+ "error": "permission_denied: permission denied to access resources: projects/hr/instances/prod-pg/databases/employee_db",+ "permissionDenied": map[string]any{"requiredPermissions": []string{"bb.sql.explain"}},+ },+ },+ "a statement the engine rejected": {+ result: map[string]any{"error": `syntax error at or near "SELEC"`},+ want: "check your SQL syntax and try again",+ },+ } {+ t.Run(name, func(t *testing.T) {+ handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if strings.Contains(r.URL.Path, "SQLService/Query") {+ w.Header().Set("Content-Type", "application/json")+ _ = json.NewEncoder(w).Encode(map[string]any{"results": []any{tt.result}})+ return+ }+ mockListDatabases(databases).ServeHTTP(w, r)+ })+ s := newTestServerWithMock(t, handler)+ statement := tt.statement+ if statement == "" {+ statement = "SELECT first_name FROM employee"+ }++ result, _, err := s.handleQueryDatabase(testContext(), nil, QueryInput{+ Database: "employee_db",+ Statement: statement,+ })+ require.NoError(t, err)+ require.True(t, result.IsError)+ var denial toolError+ require.NoError(t, json.Unmarshal([]byte(result.Content[0].(*mcpsdk.TextContent).Text), &denial))+ require.Equal(t, tt.result["error"], denial.Message)+ require.Equal(t, tt.want, denial.Suggestion)+ })+ }}// --- Task 6 tests: masked values and timeout ---diff --git a/backend/api/mcp/tool_resolve.go b/backend/api/mcp/tool_resolve.goindex 47299dc768..a8d768bfb8 100644--- a/backend/api/mcp/tool_resolve.go+++ b/backend/api/mcp/tool_resolve.go@@ -4,7 +4,6 @@ import ("context""encoding/json""fmt"- "net/http""strings""time"@@ -122,18 +121,8 @@ func (s *Server) listDatabases(ctx context.Context, filter string) ([]databaseEnif err != nil {return nil, errors.Wrap(err, "failed to list databases")}- if resp.Status == http.StatusForbidden {- if message := parseError(resp.Body); IsPolicyRefusal(message) {- return nil, &toolError{Code: "PERMISSION_DENIED", Message: message}- }- return nil, &toolError{- Code: "PERMISSION_DENIED",- Message: "you don't have permission to list databases in this workspace",- Suggestion: "ask your workspace admin to grant you the bb.databases.list permission",- }- }- if resp.Status >= 400 {- return nil, errors.Errorf("failed to list databases: HTTP %d: %s", resp.Status, parseError(resp.Body))+ if err := checkAPIResponse(resp, "list databases", "bb.databases.list"); err != nil {+ return nil, err}var listResp listDatabasesResponsediff --git a/backend/api/mcp/tool_resolve_test.go b/backend/api/mcp/tool_resolve_test.goindex 71cfc95ae9..7c88d2da4f 100644--- a/backend/api/mcp/tool_resolve_test.go+++ b/backend/api/mcp/tool_resolve_test.go@@ -90,11 +90,9 @@ func TestResolve_ProjectInstanceDatabaseAndFilter(t *testing.T) {)}-// TestResolve_PolicyDenialGetsNoRoleAdvice covers the resolve door. It answers-// 403 when the stored ceiling is unserved, which is exactly the case where-// telling the agent to ask for bb.databases.list would send the person it acts-// for after a grant that cannot fix a broken setting.-func TestResolve_PolicyDenialGetsNoRoleAdvice(t *testing.T) {+// TestResolve_PolicyDenialPassesThrough: an unserved ceiling refuses the lookup,+// and the refusal names its own way out.+func TestResolve_PolicyDenialPassesThrough(t *testing.T) {handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {if strings.Contains(r.URL.Path, "DatabaseService/ListDatabases") {w.Header().Set("Content-Type", "application/json")@@ -117,9 +115,9 @@ func TestResolve_PolicyDenialGetsNoRoleAdvice(t *testing.T) {require.Empty(t, te.Suggestion, "no grant fixes a stored ceiling this build does not serve")}-// TestTranslateMetadataError_PolicyDenialGetsNoRoleAdvice is the same contract-// on the get_schema door.-func TestTranslateMetadataError_PolicyDenialGetsNoRoleAdvice(t *testing.T) {+// TestTranslateMetadataError_PassesTheRefusalThrough is the same contract on+// the get_schema door.+func TestTranslateMetadataError_PassesTheRefusalThrough(t *testing.T) {body, err := json.Marshal(map[string]any{"message": "/bytebase.v1.DatabaseService/GetDatabaseMetadata is not available to MCP sessions",})@@ -131,10 +129,10 @@ func TestTranslateMetadataError_PolicyDenialGetsNoRoleAdvice(t *testing.T) {require.Contains(t, te.Message, "MCP sessions")require.Empty(t, te.Suggestion)- plain, err := json.Marshal(map[string]any{"message": "permission denied"})+ plain, err := json.Marshal(map[string]any{"message": `user does not have permission "bb.databases.getSchema"`})require.NoError(t, err)got = translateMetadataError(&apiResponse{Status: http.StatusForbidden, Body: plain})require.ErrorAs(t, got, &te)- require.Contains(t, te.Suggestion, "bb.databases.getSchema",- "a plain ACL denial keeps the permission advice")+ require.Equal(t, toolError{Code: "PERMISSION_DENIED", Message: `user does not have permission "bb.databases.getSchema"`}, *te,+ "an ACL denial names its permission, and nothing is added")}diff --git a/backend/api/mcp/tool_schema.go b/backend/api/mcp/tool_schema.goindex 0ce6e42b96..9a59807ec6 100644--- a/backend/api/mcp/tool_schema.go+++ b/backend/api/mcp/tool_schema.go@@ -402,14 +402,7 @@ func translateMetadataError(resp *apiResponse) error {Suggestion: "check the database name or use search_api to list available databases",}case http.StatusForbidden, http.StatusUnauthorized:- if IsPolicyRefusal(errMsg) {- return &toolError{Code: "PERMISSION_DENIED", Message: errMsg}- }- return &toolError{- Code: "PERMISSION_DENIED",- Message: "you don't have permission to read this database's schema",- Suggestion: "ask your workspace admin to grant you the bb.databases.getSchema permission",- }+ return checkAPIResponse(resp, "read this database's schema", "bb.databases.getSchema")case http.StatusInternalServerError:suggestion := "check instance connectivity in the Bytebase UI"if errMsg != "" {diff --git a/backend/api/mcp/tool_schema_test.go b/backend/api/mcp/tool_schema_test.goindex 45e94a386e..00c2705e64 100644--- a/backend/api/mcp/tool_schema_test.go+++ b/backend/api/mcp/tool_schema_test.go@@ -723,7 +723,7 @@ func TestGetSchema_PermissionDenied(t *testing.T) {w.Header().Set("Content-Type", "application/json")w.WriteHeader(http.StatusForbidden)_ = json.NewEncoder(w).Encode(map[string]any{- "message": "permission denied",+ "message": `user does not have permission "bb.databases.getSchema"`,"code": "PERMISSION_DENIED",})return@@ -741,6 +741,7 @@ func TestGetSchema_PermissionDenied(t *testing.T) {text := result.Content[0].(*mcpsdk.TextContent).Textrequire.Contains(t, text, "PERMISSION_DENIED")require.Contains(t, text, "bb.databases.getSchema")+ require.NotContains(t, text, "suggestion", "the server's message is the whole answer")}func TestGetSchema_InvalidIncludeValue(t *testing.T) {diff --git a/backend/api/oauth2/consent_audit_test.go b/backend/api/oauth2/consent_audit_test.goindex 5e9a5f236a..fe07c0067a 100644--- a/backend/api/oauth2/consent_audit_test.go+++ b/backend/api/oauth2/consent_audit_test.go@@ -35,7 +35,7 @@ func TestConsentRefusal(t *testing.T) {name: "MCP turned off",capability: storepb.MCPSetting_DISABLED,message: "turned MCP access off",- page: []string{"<title>MCP access is turned off</title>", "turned MCP access off for this workspace", "in the workspace settings"},+ page: []string{"<title>MCP access is turned off</title>", "turned MCP access off for this workspace", "Access policy"},},{name: "a ceiling this build does not serve",diff --git a/backend/api/v1/mcp_gate.go b/backend/api/v1/mcp_gate.goindex 226f73231a..edb0e1e8a4 100644--- a/backend/api/v1/mcp_gate.go+++ b/backend/api/v1/mcp_gate.go@@ -442,9 +442,9 @@ func (in *internalMCPGateInterceptor) refuseByCeiling(ctx context.Context, proce}return nil, true, connect.NewError(connect.CodePermissionDenied, errors.Errorf("%s is a %v method and this workspace's MCP capability ceiling is %v, which serves %s. "+- "Ask a workspace admin to raise the MCP ceiling in the workspace settings, "++ "Ask a workspace admin to raise the MCP ceiling under %s, "+"or perform this action signed in to the Bytebase console instead",- procedure, class, settings.Capability, describeServedClasses(served)))+ procedure, class, settings.Capability, describeServedClasses(served), auth.MCPCeilingLocation))}// describeServedClasses renders a mode's serving list for a denial message.@@ -583,9 +583,12 @@ func grantIssueRefusal(issueType v1pb.Issue_Type) (reason, wayOut string) {reason = fmt.Sprintf("an ACCESS_GRANT issue is filed by %s, not created directly",v1connect.AccessGrantServiceCreateAccessGrantProcedure)return reason, "Request the access with the request_access_grant tool instead"+ case v1pb.Issue_ROLE_GRANT:+ reason = "a ROLE_GRANT issue changes the project's IAM policy once approved, and MCP sessions " ++ "cannot change IAM policy, whatever the approval rules say"+ return reason, "To run a read-only statement, request an access grant with the request_access_grant tool; " ++ "to get a role, request it signed in to the Bytebase console"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", issueType), mcpConsoleWayOut+ return fmt.Sprintf("MCP sessions create DATABASE_CHANGE issues only, not %v", issueType), mcpConsoleWayOut}}diff --git a/backend/api/v1/mcp_gate_test.go b/backend/api/v1/mcp_gate_test.goindex 9c463719c3..dca73bf852 100644--- a/backend/api/v1/mcp_gate_test.go+++ b/backend/api/v1/mcp_gate_test.go@@ -1098,7 +1098,7 @@ func TestMCPGateUnderAReadOnlyCeiling(t *testing.T) {require.False(t, got.dispatched)require.Equal(t, connect.CodePermissionDenied, connect.CodeOf(got.err))require.Contains(t, got.err.Error(), "READ_ONLY", "the denial must name the ceiling in force")- require.Contains(t, got.err.Error(), "raise the MCP ceiling", "the denial must name the way out")+ require.Contains(t, got.err.Error(), "raise the MCP ceiling under "+auth.MCPCeilingLocation, "the denial must name the way out")require.True(t, got.auditMarked)})}@@ -1252,7 +1252,7 @@ func TestMCPGateRefusesGrantIssues(t *testing.T) {wayOut []stringnotWayOut string}{- v1pb.Issue_ROLE_GRANT: {[]string{mcpConsoleWayOut}, v1connect.AccessGrantServiceCreateAccessGrantProcedure},+ v1pb.Issue_ROLE_GRANT: {[]string{"whatever the approval rules say", "request_access_grant", "Bytebase console"}, v1connect.AccessGrantServiceCreateAccessGrantProcedure},v1pb.Issue_ACCESS_GRANT: {[]string{v1connect.AccessGrantServiceCreateAccessGrantProcedure, "request_access_grant"}, mcpConsoleWayOut},} {t.Run("CreateIssue refuses "+issueType.String(), func(t *testing.T) {@@ -1836,7 +1836,8 @@ func TestRejectMCPOriginatedGrantIssue(t *testing.T) {wayOut []stringnotWayOut string}{- "an MCP session may not create a role grant": {mcpCtx, v1pb.Issue_ROLE_GRANT, []string{mcpConsoleWayOut}, v1connect.AccessGrantServiceCreateAccessGrantProcedure},+ "an MCP session may not create a role grant": {mcpCtx, v1pb.Issue_ROLE_GRANT,+ []string{"whatever the approval rules say", "request_access_grant", "Bytebase console"}, v1connect.AccessGrantServiceCreateAccessGrantProcedure},"an MCP session may not create an access grant": {mcpCtx, v1pb.Issue_ACCESS_GRANT,[]string{v1connect.AccessGrantServiceCreateAccessGrantProcedure, "request_access_grant"}, mcpConsoleWayOut},"an MCP session may not create an unknown type": {mcpCtx, v1pb.Issue_Type(9999), []string{mcpConsoleWayOut}, v1connect.AccessGrantServiceCreateAccessGrantProcedure},diff --git a/backend/api/v1/mcp_masking_test.go b/backend/api/v1/mcp_masking_test.goindex 4ec6da3de7..9541cb6cc7 100644--- a/backend/api/v1/mcp_masking_test.go+++ b/backend/api/v1/mcp_masking_test.go@@ -9,13 +9,11 @@ import ("connectrpc.com/connect""github.com/stretchr/testify/require"- "github.com/bytebase/bytebase/backend/api/mcp""github.com/bytebase/bytebase/backend/common""github.com/bytebase/bytebase/backend/component/masker"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")// mcpSessionContext is a request as the gate hands it to a handler: a@@ -222,91 +220,6 @@ func TestMaskedWriteGuardCoversTheExecutionDoor(t *testing.T) {require.Contains(t, exported.err.Error(), masker.DefaultFullMaskSubstitution)}-// TestMCPRefusalsNameThemselvesToTheQueryTool is a contract between two-// processes that meet only over an error body.-//-// query_database drops its own "request the SQL Editor role" advice when it-// recognizes an MCP policy refusal, because no project role lifts a workspace-// setting. It recognizes one by wording, so every producer's wording has to stay-// inside the list the consumer keys on — including the masked-write guard, which-// is the newest producer and the one whose refusal names a literal rather than a-// policy.-func TestMCPRefusalsNameThemselvesToTheQueryTool(t *testing.T) {- readWrite := readWriteCeiling()- maskedWrite := "UPDATE employee SET secret = '" + masker.DefaultFullMaskSubstitution + "'"-- for _, row := range []struct {- name string- stores mcpGateStore- class v1pb.MCPMethodClass- request connect.AnyRequest- }{- {- name: "the masked-write guard",- stores: readWrite,- class: v1pb.MCPMethodClass_READ,- request: connect.NewRequest(&v1pb.QueryRequest{Statement: maskedWrite}),- },- {- name: "the ceiling gate",- stores: mcpGateStore{ceiling: storepb.MCPSetting_READ_ONLY},- class: v1pb.MCPMethodClass_WRITE,- request: connect.NewRequest(&v1pb.QueryRequest{}),- },- {- name: "an unclassified method",- stores: readWrite,- class: v1pb.MCPMethodClass_MCP_METHOD_CLASS_UNSPECIFIED,- request: connect.NewRequest(&v1pb.QueryRequest{}),- },- } {- t.Run(row.name, func(t *testing.T) {- got := invokeMCPGate(t, row.stores, &common.AuthContext{- MCPMethodClass: row.class,- DelegatedGrant: &common.DelegatedGrant{},- }, "/bytebase.v1.SQLService/Query", row.request)-- require.Error(t, got.err)- require.True(t, mcp.IsPolicyRefusal(got.err.Error()),- "query_database would append project-role advice to %q", got.err.Error())- })- }-- // Each producer that refuses outside the gate turns on a fact the request- // shape cannot carry, so each is checked on its own message.- clamped := refuseNonReadOnlyStatement(storepb.Engine_POSTGRES, "UPDATE employee SET id = 1")- require.Error(t, clamped)- require.True(t, mcp.IsPolicyRefusal(clamped.Error()))-- mcpCtx := contextWithAuth(&common.AuthContext{DelegatedGrant: &common.DelegatedGrant{}})- grantIssue := rejectMCPOriginatedGrantIssue(mcpCtx, v1pb.Issue_ROLE_GRANT)- require.Error(t, grantIssue)- require.True(t, mcp.IsPolicyRefusal(grantIssue.Error()))-- tokenMint := (&AuthService{}).rejectMCPOriginatedTokenMint(mcpCtx, nil, "switch workspaces")- require.Error(t, tokenMint)- require.True(t, mcp.IsPolicyRefusal(tokenMint.Error()))-- approvalProject := &store.ProjectMessage{- ResourceID: "p",- Setting: &storepb.Project{RequireIssueApproval: true},- }- 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()))-- unconfirmed := invokeMCPGate(t, readWrite, &common.AuthContext{- MCPMethodClass: v1pb.MCPMethodClass_WRITE,- DelegatedGrant: &common.DelegatedGrant{},- }, v1connect.IssueServiceApproveIssueProcedure, connect.NewRequest(&v1pb.ApproveIssueRequest{Name: "projects/p/issues/1"}))- require.Error(t, unconfirmed.err)- require.True(t, mcp.IsPolicyRefusal(unconfirmed.err.Error()))-}-// TestMaskPlaceholderMatchIsDeliberatelyBroad records which side of the trade// the guard sits on. It is a substring scan, so an asterisk banner is refused// and a placeholder abutting other characters is caught. The first is a messagediff --git a/backend/api/v1/mcp_sql_clamp.go b/backend/api/v1/mcp_sql_clamp.goindex f6ec01a520..2594a4fce6 100644--- a/backend/api/v1/mcp_sql_clamp.go+++ b/backend/api/v1/mcp_sql_clamp.go@@ -7,6 +7,7 @@ import ("connectrpc.com/connect""github.com/pkg/errors"+ "github.com/bytebase/bytebase/backend/api/auth""github.com/bytebase/bytebase/backend/common"storepb "github.com/bytebase/bytebase/backend/generated-go/store"parserbase "github.com/bytebase/bytebase/backend/plugin/parser/base"@@ -126,6 +127,6 @@ func describeClampUnit(index, total int) string {func refuseClampedStatement(reason string) error {return connect.NewError(connect.CodePermissionDenied, errors.Errorf("this workspace's MCP capability ceiling is READ_ONLY, so an MCP session may only run statements Bytebase can show are reads: %s. "+- "Ask a workspace admin to raise the MCP ceiling in the workspace settings, "+- "or run this statement signed in to the Bytebase console instead", reason))+ "Ask a workspace admin to raise the MCP ceiling under %s, "++ "or run this statement signed in to the Bytebase console instead", reason, auth.MCPCeilingLocation))}diff --git a/backend/api/v1/mcp_sql_clamp_test.go b/backend/api/v1/mcp_sql_clamp_test.goindex f0024df0c1..e5c6cf21c7 100644--- a/backend/api/v1/mcp_sql_clamp_test.go+++ b/backend/api/v1/mcp_sql_clamp_test.go@@ -7,6 +7,7 @@ import ("connectrpc.com/connect""github.com/stretchr/testify/require"+ "github.com/bytebase/bytebase/backend/api/auth""github.com/bytebase/bytebase/backend/common"storepb "github.com/bytebase/bytebase/backend/generated-go/store"v1pb "github.com/bytebase/bytebase/backend/generated-go/v1"@@ -378,7 +379,7 @@ func TestMCPClampRefusesWhatItCannotShowIsARead(t *testing.T) {require.Contains(t, err.Error(), row.reason)require.Contains(t, err.Error(), "READ_ONLY","the denial must name the ceiling that refused")- require.Contains(t, err.Error(), "raise the MCP ceiling",+ require.Contains(t, err.Error(), "raise the MCP ceiling under "+auth.MCPCeilingLocation,"the denial must name the way out")require.Contains(t, err.Error(), "Bytebase console","the denial must name where the human can do it instead")diff --git a/backend/component/review/evaluator.go b/backend/component/review/evaluator.goindex 10a871c66c..5f92a0e3e1 100644--- a/backend/component/review/evaluator.go+++ b/backend/component/review/evaluator.go@@ -1237,10 +1237,26 @@ func collectStatementTypes(celVarsList []map[string]any) []string {return result}-// getApproversForRole returns the people who hold the role in the project or-// workspace IAM policy, for a notification to mention. A service account or-// workload identity that holds the role can approve too, but has nobody to notify.+// getApproversForRole returns the people who hold the role, for a notification+// to mention. On an error it still returns the people who resolved.func getApproversForRole(ctx context.Context, stores *store.Store, projectID string, role string) ([]webhook.User, error) {+ people, err := activeRoleHolders(ctx, stores, projectID, role)+ approvers := make([]webhook.User, 0, len(people))+ for _, person := range people {+ approvers = append(approvers, webhook.User{+ Name: person.Name,+ Email: person.Email,+ Phone: person.Phone,+ })+ }+ return approvers, err+}++// activeRoleHolders returns the people who hold the role in the project or+// workspace IAM policy. Service accounts and workload identities can approve but+// are not people; a deactivated account keeps its bindings but cannot sign in.+// After a failed member lookup it returns the people who resolved and the error.+func activeRoleHolders(ctx context.Context, stores *store.Store, projectID string, role string) ([]*store.UserMessage, error) {// Get project to determine workspaceproject, err := stores.GetProjectByResourceID(ctx, projectID)if err != nil {@@ -1263,7 +1279,7 @@ func getApproversForRole(ctx context.Context, stores *store.Store, projectID str}// Get all users with the specified role- users := utils.GetUsersByRoleInIAMPolicy(+ users, lookupErr := utils.UsersByRoleInIAMPolicy(ctx,stores,project.Workspace,@@ -1275,21 +1291,14 @@ func getApproversForRole(ctx context.Context, stores *store.Store, projectID strworkspaceIAM.Policy,)- // Convert to webhook.User format, filtering by END_USER principal type- approvers := make([]webhook.User, 0, len(users))+ people := make([]*store.UserMessage, 0, len(users))for _, user := range users {- // Only include END_USER principals as approvers- if user.Type != storepb.PrincipalType_END_USER {+ if user.Type != storepb.PrincipalType_END_USER || user.MemberDeleted {continue}- approvers = append(approvers, webhook.User{- Name: user.Name,- Email: user.Email,- Phone: user.Phone,- })+ people = append(people, user)}-- return approvers, nil+ return people, lookupErr}// NotifyApprovalRequested sends the ISSUE_APPROVAL_REQUESTED webhook event for the next pending approval stage.@@ -1314,8 +1323,7 @@ func NotifyApprovalRequested(ctx context.Context, stores *store.Store, webhookMa// Get approvers for this roleapprovers, err := getApproversForRole(ctx, stores, issue.ProjectID, role)if err != nil {- slog.Warn("failed to get approvers", log.BBError(err))- approvers = []webhook.User{} // Continue with empty list+ slog.Warn("failed to get every approver", log.BBError(err))}if !project.Setting.GetAllowLastPlanEditorApproval() && issue.Type == storepb.Issue_DATABASE_CHANGE && issue.PlanUID != nil {plan, err := stores.GetPlan(ctx, &store.FindPlanMessage{ProjectID: issue.ProjectID, UID: issue.PlanUID})@@ -1350,6 +1358,64 @@ func NotifyApprovalRequested(ctx context.Context, stores *store.Store, webhookMa})}+// UnapprovableStep is a remaining approval step that no person can approve.+type UnapprovableStep struct {+ // Position counts the steps of the approval flow from 1.+ Position int+ // Role is the role the step requires, e.g. "roles/projectOwner".+ Role string+ // CreatorHoldsRole is set when the issue's creator holds the role and the+ // project refuses self-approval.+ CreatorHoldsRole bool+}++// FindUnapprovableStep returns the first remaining step of the issue's approval+// flow that no active person can approve, or nil. People are found as approval+// notifications find them. One with no workspace binding still counts, since+// sign-in can add one (self-hosted login, workspace SSO).+func FindUnapprovableStep(ctx context.Context, stores *store.Store, workspace, issueName string) (*UnapprovableStep, error) {+ projectID, issueUID, err := common.GetProjectIDIssueUID(issueName)+ if err != nil {+ return nil, err+ }+ project, err := stores.GetProject(ctx, &store.FindProjectMessage{Workspace: workspace, ResourceID: &projectID})+ if err != nil {+ return nil, errors.Wrapf(err, "failed to get project %s", projectID)+ }+ if project == nil {+ return nil, errors.Errorf("project %s not found", projectID)+ }+ issue, err := stores.GetIssue(ctx, &store.FindIssueMessage{Workspace: workspace, ProjectIDs: []string{projectID}, UID: &issueUID})+ if err != nil {+ return nil, errors.Wrapf(err, "failed to get issue %s", issueName)+ }+ if issue == nil {+ return nil, errors.Errorf("issue %s not found", issueName)+ }+ approval := issue.Payload.GetApproval()+ roles := approval.GetApprovalTemplate().GetFlow().GetRoles()+ for i := len(approval.GetApprovers()); i < len(roles); i++ {+ people, err := activeRoleHolders(ctx, stores, projectID, roles[i])+ if err != nil {+ return nil, err+ }+ approvable, creatorHoldsRole := false, false+ for _, person := range people {+ if person.Email == issue.CreatorEmail {+ creatorHoldsRole = true+ }+ if !refusesSelfApproval(project, issue.CreatorEmail, person.Email) {+ approvable = true+ }+ }+ if approvable {+ continue+ }+ return &UnapprovableStep{Position: i + 1, Role: roles[i], CreatorHoldsRole: creatorHoldsRole}, nil+ }+ return nil, nil+}+// NotifyIssueApproved sends the ISSUE_APPROVED webhook event when all approval steps complete.// It notifies the issue creator that their issue has been fully approved.func NotifyIssueApproved(ctx context.Context, stores *store.Store, webhookManager *webhook.Manager, issue *store.IssueMessage, project *store.ProjectMessage, approver *store.UserMessage) {diff --git a/backend/component/review/workflow.go b/backend/component/review/workflow.goindex d0c60c9e74..ee0230a1c7 100644--- a/backend/component/review/workflow.go+++ b/backend/component/review/workflow.go@@ -361,7 +361,7 @@ func (w *Workflow) applyReviewAction(ctx context.Context, project *store.Projectreturn nil, workflowReasonError(ErrorPermissionDenied, ReasonApproverRoleRequired,"cannot %s because the user does not have the required permission", verb)}- if !project.Setting.GetAllowSelfApproval() && issue.CreatorEmail == input.Actor.Email {+ if refusesSelfApproval(project, issue.CreatorEmail, input.Actor.Email) {return nil, workflowError(ErrorPermissionDenied, "cannot %s because self-approval is not allowed for this project", verb)}if input.Action == ActionApprove && !project.Setting.GetAllowLastPlanEditorApproval() && plan != nil {@@ -412,6 +412,12 @@ func (w *Workflow) applyReviewAction(ctx context.Context, project *store.Project}}+// refusesSelfApproval reports whether the project refuses the actor's review,+// approval or rejection, of an issue the actor created.+func refusesSelfApproval(project *store.ProjectMessage, creatorEmail, actorEmail string) bool {+ return !project.Setting.GetAllowSelfApproval() && creatorEmail == actorEmail+}+func effectiveLastPlanEditor(plan *store.PlanMessage) string {if plan.LastPlanEditor != nil {return *plan.LastPlanEditordiff --git a/backend/component/review/workflow_test.go b/backend/component/review/workflow_test.goindex 6679ae1a75..51d3a5ba15 100644--- a/backend/component/review/workflow_test.go+++ b/backend/component/review/workflow_test.go@@ -1437,6 +1437,228 @@ func TestApproverRoleRefusalCarriesItsReason(t *testing.T) {}}+func TestFindUnapprovableStep(t *testing.T) {+ const owner, releaser = "roles/projectOwner", "roles/projectReleaser"+ grant := func(member, role string) func(context.Context, *testing.T, *store.Store) {+ return func(ctx context.Context, t *testing.T, stores *store.Store) {+ _, err := stores.PatchWorkspaceIamPolicy(ctx, &store.PatchIamPolicyMessage{Workspace: "default", Member: member, Roles: []string{role}})+ require.NoError(t, err)+ }+ }+ // grantInProject binds the role in the project policy only, so the member+ // gets no workspace binding from it.+ grantInProject := func(member, role string) func(context.Context, *testing.T, *store.Store) {+ return func(ctx context.Context, t *testing.T, stores *store.Store) {+ _, err := stores.PatchIamPolicy(ctx, "default", storepb.Policy_PROJECT, common.FormatProject("project-a"), func(policy *storepb.IamPolicy) error {+ policy.Bindings = append(policy.Bindings, &storepb.Binding{Role: role, Members: []string{member}})+ return nil+ })+ require.NoError(t, err)+ }+ }+ for _, test := range []struct {+ name string+ flow []string+ setup []func(context.Context, *testing.T, *store.Store)+ // approved counts the steps approved before the check.+ approved int+ want *UnapprovableStep+ }{+ {+ name: "only the creator holds the role, and self-approval is off",+ flow: []string{owner},+ setup: []func(context.Context, *testing.T, *store.Store){grant("users/[email protected]", owner)},+ want: &UnapprovableStep{Position: 1, Role: owner, CreatorHoldsRole: true},+ },+ {+ name: "only the creator holds the role, and the project allows self-approval",+ flow: []string{owner},+ setup: []func(context.Context, *testing.T, *store.Store){+ grant("users/[email protected]", owner),+ func(ctx context.Context, t *testing.T, stores *store.Store) {+ require.NoError(t, stores.UpdateProjects(ctx, &store.UpdateProjectMessage{+ Workspace: "default", ResourceID: "project-a", Setting: &storepb.Project{AllowSelfApproval: true},+ }))+ },+ },+ },+ {+ name: "another person holds the role",+ flow: []string{owner},+ setup: []func(context.Context, *testing.T, *store.Store){grant("users/[email protected]", owner), grant("users/[email protected]", owner)},+ },+ {+ name: "another person holds the role through a group",+ flow: []string{owner},+ setup: []func(context.Context, *testing.T, *store.Store){+ func(ctx context.Context, t *testing.T, stores *store.Store) {+ _, err := stores.CreateGroup(ctx, &store.GroupMessage{+ Workspace: "default",+ Email: "[email protected]",+ Title: "Approvers",+ Payload: &storepb.GroupPayload{Members: []*storepb.GroupMember{{Member: "users/[email protected]", Role: storepb.GroupMember_MEMBER}}},+ })+ require.NoError(t, err)+ },+ grant("groups/[email protected]", owner),+ },+ },+ {+ name: "no person holds the role",+ flow: []string{owner},+ want: &UnapprovableStep{Position: 1, Role: owner},+ },+ {+ name: "a later step",+ flow: []string{owner, releaser},+ setup: []func(context.Context, *testing.T, *store.Store){grant("users/[email protected]", owner)},+ want: &UnapprovableStep{Position: 2, Role: releaser},+ },+ {+ name: "an approved step is not checked",+ flow: []string{releaser, owner},+ setup: []func(context.Context, *testing.T, *store.Store){grant("users/[email protected]", owner)},+ approved: 1,+ },+ {+ name: "the other holder is deactivated",+ flow: []string{owner},+ setup: []func(context.Context, *testing.T, *store.Store){+ grant("users/[email protected]", owner),+ grant("users/[email protected]", owner),+ func(ctx context.Context, t *testing.T, stores *store.Store) {+ reviewer, err := stores.GetUserByEmail(ctx, "[email protected]")+ require.NoError(t, err)+ _, err = stores.UpdateUser(ctx, reviewer, &store.UpdateUserMessage{Delete: new(true)})+ require.NoError(t, err)+ },+ },+ want: &UnapprovableStep{Position: 1, Role: owner, CreatorHoldsRole: true},+ },+ {+ name: "the other holder is bound under another principal type",+ flow: []string{owner},+ setup: []func(context.Context, *testing.T, *store.Store){+ grant("users/[email protected]", owner),+ grant(common.FormatServiceAccountEmail("[email protected]"), owner),+ },+ want: &UnapprovableStep{Position: 1, Role: owner, CreatorHoldsRole: true},+ },+ {+ name: "the other holder has a project binding and no workspace binding",+ flow: []string{owner},+ setup: []func(context.Context, *testing.T, *store.Store){+ grant("users/[email protected]", owner),+ grantInProject("users/[email protected]", owner),+ },+ },+ {+ name: "only a service account holds the role",+ flow: []string{owner},+ setup: []func(context.Context, *testing.T, *store.Store){+ func(ctx context.Context, t *testing.T, stores *store.Store) {+ _, err := stores.GetDB().ExecContext(ctx,+ `INSERT INTO service_account (name, email, workspace, service_key_hash) VALUES ('bot', '[email protected]', 'default', 'unused')`)+ require.NoError(t, err)+ account, err := stores.GetAccountByEmail(ctx, "[email protected]")+ require.NoError(t, err)+ require.Equal(t, storepb.PrincipalType_SERVICE_ACCOUNT, account.Type, "the holder must resolve to an account")+ },+ grant(common.FormatServiceAccountEmail("[email protected]"), owner),+ },+ want: &UnapprovableStep{Position: 1, Role: owner},+ },+ } {+ t.Run(test.name, func(t *testing.T) {+ ctx := context.Background()+ stores := setupWorkflowStore(ctx, t)+ for _, setup := range test.setup {+ setup(ctx, t, stores)+ }+ var approvers []*storepb.IssuePayloadApproval_Approver+ for range test.approved {+ approvers = append(approvers, &storepb.IssuePayloadApproval_Approver{+ Status: storepb.IssuePayloadApproval_Approver_APPROVED, Principal: "users/[email protected]",+ })+ }+ issue, err := stores.CreateIssue(ctx, &store.IssueMessage{+ ProjectID: "project-a",+ CreatorEmail: "[email protected]",+ Title: "access grant request",+ Type: storepb.Issue_ACCESS_GRANT,+ Payload: &storepb.Issue{Approval: &storepb.IssuePayloadApproval{+ ApprovalFindingDone: true,+ ApprovalTemplate: &storepb.ApprovalTemplate{Flow: &storepb.ApprovalFlow{Roles: test.flow}},+ Approvers: approvers,+ }},+ })+ require.NoError(t, err)++ got, err := FindUnapprovableStep(ctx, stores, "default", common.FormatIssue("project-a", issue.UID))+ require.NoError(t, err)+ require.Equal(t, test.want, got)+ })+ }+}++// The check counts a holder only where the approval check would let them+// approve: a binding names a typed principal, not an email.+func TestFindUnapprovableStepAgreesWithTheApprovalCheckOnPrincipalType(t *testing.T) {+ ctx := context.Background()+ stores := setupWorkflowStore(ctx, t)+ for member, role := range map[string]string{+ "users/[email protected]": "roles/projectOwner",+ common.FormatServiceAccountEmail("[email protected]"): "roles/projectOwner",+ } {+ _, err := stores.PatchWorkspaceIamPolicy(ctx, &store.PatchIamPolicyMessage{Workspace: "default", Member: member, Roles: []string{role}})+ require.NoError(t, err)+ }+ _, issue := createPendingDatabaseChangeApproval(ctx, t, stores, []string{"roles/projectOwner"})++ step, err := FindUnapprovableStep(ctx, stores, "default", common.FormatIssue("project-a", issue.UID))+ require.NoError(t, err)+ require.Equal(t, &UnapprovableStep{Position: 1, Role: "roles/projectOwner", CreatorHoldsRole: true}, step)++ reviewer, err := stores.GetUserByEmail(ctx, "[email protected]")+ require.NoError(t, err)+ _, err = NewWorkflow(stores).ReviewIssue(ctx, IssueInput{+ Workspace: "default",+ ProjectID: "project-a",+ IssueUID: issue.UID,+ Actor: reviewer,+ Action: ActionApprove,+ })+ var workflowErr *Error+ require.ErrorAs(t, err, &workflowErr)+ require.Equal(t, ReasonApproverRoleRequired, workflowErr.Reason, "the approval check refuses the same person")+}++// A holder the lookup cannot resolve leaves the answer unknown, so the check+// fails instead of reporting that no one else can approve.+func TestFindUnapprovableStepFailsWhenAHolderCannotBeResolved(t *testing.T) {+ ctx := context.Background()+ stores := setupWorkflowStore(ctx, t)+ for _, member := range []string{"users/[email protected]", "users/"} {+ _, err := stores.PatchWorkspaceIamPolicy(ctx, &store.PatchIamPolicyMessage{Workspace: "default", Member: member, Roles: []string{"roles/projectOwner"}})+ require.NoError(t, err)+ }+ issue, err := stores.CreateIssue(ctx, &store.IssueMessage{+ ProjectID: "project-a",+ CreatorEmail: "[email protected]",+ Title: "access grant request",+ Type: storepb.Issue_ACCESS_GRANT,+ Payload: &storepb.Issue{Approval: &storepb.IssuePayloadApproval{+ ApprovalFindingDone: true,+ ApprovalTemplate: &storepb.ApprovalTemplate{Flow: &storepb.ApprovalFlow{Roles: []string{"roles/projectOwner"}}},+ }},+ })+ require.NoError(t, err)++ step, err := FindUnapprovableStep(ctx, stores, "default", common.FormatIssue("project-a", issue.UID))+ require.ErrorContains(t, err, `failed to parse email from identifier users/`)+ require.Nil(t, step)+}+func TestApproverRoleLookupFailureIsNotARefusal(t *testing.T) {ctx := context.Background()db, stores := setupWorkflowStoreWithDB(ctx, t)diff --git a/backend/generated-go/v1/access_grant_service.pb.go b/backend/generated-go/v1/access_grant_service.pb.goindex 78f72d2e9f..72df64d3db 100644--- a/backend/generated-go/v1/access_grant_service.pb.go+++ b/backend/generated-go/v1/access_grant_service.pb.go@@ -87,7 +87,7 @@ type AccessGrant struct {// Format: projects/{project}/accessGrants/{access_grant}// The {access_grant} segment is a server-generated unique ID.Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"`- // The creator of the access grant.+ // The creator of the access grant, the caller who requested it.// Format: users/{email}Creator string `protobuf:"bytes,2,opt,name=creator,proto3" json:"creator,omitempty"`// The status of the access grant.@@ -800,7 +800,7 @@ const file_v1_access_grant_service_proto_rawDesc = "" +"\x1dv1/access_grant_service.proto\x12\vbytebase.v1\x1a\x1cgoogle/api/annotations.proto\x1a\x17google/api/client.proto\x1a\x1fgoogle/api/field_behavior.proto\x1a\x19google/api/resource.proto\x1a\x1egoogle/protobuf/duration.proto\x1a\x1fgoogle/protobuf/timestamp.proto\x1a\x13v1/annotation.proto\"\xe8\x05\n" +"\vAccessGrant\x12\x12\n" +"\x04name\x18\x01 \x01(\tR\x04name\x12\x1d\n" +- "\acreator\x18\x02 \x01(\tB\x03\xe0A\x02R\acreator\x12<\n" ++ "\acreator\x18\x02 \x01(\tB\x03\xe0A\x03R\acreator\x12<\n" +"\x06status\x18\x03 \x01(\x0e2\x1f.bytebase.v1.AccessGrant.StatusB\x03\xe0A\x03R\x06status\x12=\n" +"\vexpire_time\x18\x04 \x01(\v2\x1a.google.protobuf.TimestampH\x00R\n" +"expireTime\x122\n" +diff --git a/backend/tests/mcp_access_request_test.go b/backend/tests/mcp_access_request_test.goindex 710adb7c08..495b78b689 100644--- a/backend/tests/mcp_access_request_test.go+++ b/backend/tests/mcp_access_request_test.go@@ -90,4 +90,8 @@ func TestMCPRequestsAccessWithTheDedicatedTool(t *testing.T) {a.Equal(2*time.Hour, grant.GetTtl().AsDuration(), "a ttl starts at approval")a.Contains(text, "Requested "+grant.Name+":")a.Contains(text, grant.Issue)+ // The project's creator is its only owner, and new projects refuse self-approval.+ a.Contains(text, "No other person can approve it: step 1 of its approval flow needs roles/projectOwner, which no other active "++ "workspace member holds, and this project does not allow self-approval.", text)+ a.Contains(text, "grant_masking_exemption", "an unmask request names the exemption tool as the way around")}diff --git a/backend/tests/mcp_gate_test.go b/backend/tests/mcp_gate_test.goindex 2ad643cd13..27550fc140 100644--- a/backend/tests/mcp_gate_test.go+++ b/backend/tests/mcp_gate_test.go@@ -132,7 +132,8 @@ func TestMCPGrantIssuesAndAccessRequests(t *testing.T) {})a.Equal(http.StatusForbidden, grant.Status)a.Contains(grant.Error, "ROLE_GRANT", "the denial must name the issue type it refused")- a.Contains(grant.Error, "no human step")+ a.Contains(grant.Error, "whatever the approval rules say", "the denial must not read as if an approval rule would lift it")+ a.Contains(grant.Error, "request_access_grant", "the denial must name the way to run a statement")upsert := callAPIOnSession(ctx, t, session, "IssueService/UpdateIssue", map[string]any{"issue": map[string]any{diff --git a/backend/utils/member.go b/backend/utils/member.goindex 0f1e3dcfb8..95c4311261 100644--- a/backend/utils/member.go+++ b/backend/utils/member.go@@ -3,10 +3,13 @@ package utilsimport ("context"+ "errors""log/slog""strings""time"+ pkgerrors "github.com/pkg/errors"+"github.com/bytebase/bytebase/backend/common""github.com/bytebase/bytebase/backend/common/log"storepb "github.com/bytebase/bytebase/backend/generated-go/store"@@ -30,8 +33,9 @@ func FormatGroupName(group *store.GroupMessage) string {return common.FormatGroupEmail(group.ID)}-// GetUsersByRoleInIAMPolicy gets users in the iam policy.-// The role can be either with or without the "roles/" prefix.+// GetUsersByRoleInIAMPolicy returns the users bound to the role in the+// policies. A failed lookup is logged and its member skipped; a caller whose+// decision changes with a missing user uses UsersByRoleInIAMPolicy.func GetUsersByRoleInIAMPolicy(ctx context.Context,stores *store.Store,@@ -40,11 +44,30 @@ func GetUsersByRoleInIAMPolicy(allowAllUsers bool,policies ...*storepb.IamPolicy,) []*store.UserMessage {+ users, err := UsersByRoleInIAMPolicy(ctx, stores, workspace, role, allowAllUsers, policies...)+ if err != nil {+ slog.Error("failed to resolve every user bound to the role", slog.String("role", role), log.BBError(err))+ }+ return users+}++// UsersByRoleInIAMPolicy returns the users bound to the role in the policies,+// and the failed lookups joined into one error. The users that resolved are+// returned either way.+func UsersByRoleInIAMPolicy(+ ctx context.Context,+ stores *store.Store,+ workspace string,+ role string,+ allowAllUsers bool,+ policies ...*storepb.IamPolicy,+) ([]*store.UserMessage, error) {roleFullName := roleif !strings.HasPrefix(role, common.RolePrefix) {roleFullName = common.FormatRole(role)}var users []*store.UserMessage+ var failures []errorseen := map[string]bool{}for _, policy := range policies {@@ -64,12 +87,15 @@ func GetUsersByRoleInIAMPolicy(ShowDeleted: false,})if err != nil {- slog.Error("failed to list all users for role", slog.String("role", role), log.BBError(err))+ failures = append(failures, pkgerrors.Wrapf(err, "failed to list all users for role %s", role))continue}- return allUsers+ return allUsers, nil+ }+ userMessages, err := usersByMember(ctx, stores, workspace, member)+ if err != nil {+ failures = append(failures, err)}- userMessages := GetUsersByMember(ctx, stores, workspace, member)for _, user := range userMessages {if seen[user.Email] {@@ -82,78 +108,92 @@ func GetUsersByRoleInIAMPolicy(}}- return users+ return users, errors.Join(failures...)}// GetUsersByMember gets user messages by member.// The member should be in users/{email}, serviceAccounts/{email}, workloadIdentities/{email}, or groups/{email} format.+// A failed lookup is logged and skipped.func GetUsersByMember(ctx context.Context, stores *store.Store, workspace string, member string) []*store.UserMessage {- var users []*store.UserMessage- if strings.HasPrefix(member, common.UserNamePrefix) {- user := getUserByIdentifier(ctx, stores, member, common.UserNamePrefix)- if user != nil {- users = append(users, user)- }- } else if strings.HasPrefix(member, common.ServiceAccountNamePrefix) {- user := getUserByIdentifier(ctx, stores, member, common.ServiceAccountNamePrefix)- if user != nil {- users = append(users, user)- }- } else if strings.HasPrefix(member, common.WorkloadIdentityNamePrefix) {- user := getUserByIdentifier(ctx, stores, member, common.WorkloadIdentityNamePrefix)- if user != nil {- users = append(users, user)- }- } else if strings.HasPrefix(member, common.GroupPrefix) {+ users, err := usersByMember(ctx, stores, workspace, member)+ if err != nil {+ slog.Error("failed to resolve every user of the member", slog.String("member", member), log.BBError(err))+ }+ return users+}++func usersByMember(ctx context.Context, stores *store.Store, workspace string, member string) ([]*store.UserMessage, error) {+ prefix := ""+ switch {+ case strings.HasPrefix(member, common.UserNamePrefix):+ prefix = common.UserNamePrefix+ case strings.HasPrefix(member, common.ServiceAccountNamePrefix):+ prefix = common.ServiceAccountNamePrefix+ case strings.HasPrefix(member, common.WorkloadIdentityNamePrefix):+ prefix = common.WorkloadIdentityNamePrefix+ case strings.HasPrefix(member, common.GroupPrefix):group, err := stores.GetGroupByName(ctx, workspace, member)if err != nil {- slog.Error("failed to get group", slog.String("group", member), log.BBError(err))- return users+ return nil, pkgerrors.Wrapf(err, "failed to get group %s", member)}if group == nil {slog.Error("cannot found group", slog.String("group", member))- return users+ return nil, nil}+ var users []*store.UserMessage+ var failures []errorfor _, member := range group.Payload.Members {- user := getUserByIdentifier(ctx, stores, member.Member, common.UserNamePrefix)- if user != nil {+ user, err := userByIdentifier(ctx, stores, member.Member, common.UserNamePrefix)+ if err != nil {+ failures = append(failures, err)+ continue+ }+ if user != nil && formatMemberNameByType(user) == member.Member {users = append(users, user)}}+ return users, errors.Join(failures...)+ default:+ return nil, nil}- return users+ user, err := userByIdentifier(ctx, stores, member, prefix)+ if err != nil || user == nil {+ return nil, err+ }+ // The permission check matches a member by its typed name+ // (GetUserIAMPolicyBindings), so an account of another type that shares the+ // email is not this member.+ if formatMemberNameByType(user) != member {+ return nil, nil+ }+ return []*store.UserMessage{user}, nil}-// getUserByIdentifier gets user message by identifier.-// The identifier should be in {prefix}{email} format where prefix is one of:-// users/, serviceAccounts/, or workloadIdentities/-func getUserByIdentifier(ctx context.Context, stores *store.Store, identifier, prefix string) *store.UserMessage {+// userByIdentifier gets the user an identifier in {prefix}{email} format names,+// where prefix is users/, serviceAccounts/ or workloadIdentities/. A principal+// that does not exist is nil with no error.+func userByIdentifier(ctx context.Context, stores *store.Store, identifier, prefix string) (*store.UserMessage, error) {var email stringvar err errorswitch prefix {- case common.UserNamePrefix:- email, err = common.GetUserEmail(identifier)case common.ServiceAccountNamePrefix:email, err = common.GetServiceAccountEmail(identifier)case common.WorkloadIdentityNamePrefix:email, err = common.GetWorkloadIdentityEmail(identifier)default:- // Fallback to user email for backward compatibilityemail, err = common.GetUserEmail(identifier)}if err != nil {- slog.Error("failed to parse email from identifier", slog.String("identifier", identifier), log.BBError(err))- return nil+ return nil, pkgerrors.Wrapf(err, "failed to parse email from identifier %s", identifier)}account, err := stores.GetAccountByEmail(ctx, email)if err != nil {- slog.Error("failed to get principal by email", slog.String("identifier", identifier), log.BBError(err))- return nil+ return nil, pkgerrors.Wrapf(err, "failed to get principal %s", identifier)}if account == nil {- return nil+ return nil, nil}- return userMessageFromAccount(account)+ return userMessageFromAccount(account), nil}func userMessageFromAccount(account *store.AccountMessage) *store.UserMessage {diff --git a/frontend/src/types/proto-es/v1/access_grant_service_pb.d.ts b/frontend/src/types/proto-es/v1/access_grant_service_pb.d.tsindex 55b1f741b6..ed8bba3055 100644--- a/frontend/src/types/proto-es/v1/access_grant_service_pb.d.ts+++ b/frontend/src/types/proto-es/v1/access_grant_service_pb.d.ts@@ -25,7 +25,7 @@ export declare type AccessGrant = Message<"bytebase.v1.AccessGrant"> & {name: string;/**- * The creator of the access grant.+ * The creator of the access grant, the caller who requested it.* Format: users/{email}** @generated from field: string creator = 2;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 c7df5a8f3a..0b667b9d69 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+BBAxIUCgd0YXJnZXRzGAYgAygJQgPgQQISDQoFcXVlcnkYByABKAkSDgoGdW5tYXNrGAggASgIEjQKC2NyZWF0ZV90aW1lGAkgASgLMhouZ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Ynl0ZWJhc2UvYnl0ZWJhc2UvYmFja2VuZC9nZW5lcmF0ZWQtZ28vdjGiAgNCWFiqAgtCeXRlYmFzZS5WMcoCC0J5dGViYXNlXFYx4gIXQnl0ZWJhc2VcVjFcR1BCTWV0YWRhdGHqAgxCeXRlYmFzZTo6VjFiBnByb3RvMw", [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("Ch12MS9hY2Nlc3NfZ3JhbnRfc2VydmljZS5wcm90bxILYnl0ZWJhc2UudjEi5gQKC0FjY2Vzc0dyYW50EgwKBG5hbWUYASABKAkSFAoHY3JlYXRvchgCIAEoCUID4EEDEjQKBnN0YXR1cxgDIAEoDjIfLmJ5dGViYXNlLnYxLkFjY2Vzc0dyYW50LlN0YXR1c0ID4EEDEjEKC2V4cGlyZV90aW1lGAQgASgLMhouZ29vZ2xlLnByb3RvYnVmLlRpbWVzdGFtcEgAEi0KA3R0bBgLIAEoCzIZLmdvb2dsZS5wcm90b2J1Zi5EdXJhdGlvbkID4EEESAASEgoFaXNzdWUYBSABKAlCA+BBAxIUCgd0YXJnZXRzGAYgAygJQgPgQQISDQoFcXVlcnkYByABKAkSDgoGdW5tYXNrGAggASgIEjQKC2NyZWF0ZV90aW1lGAkgASgLMhouZ29vZ2xlLnByb3RvYnVmLlRpbWVzdGFtcEID4EEDEjQKC3VwZGF0ZV90aW1lGAogASgLMhouZ29vZ2xlLnByb3RvYnVmLlRpbWVzdGFtcEID4EEDEg4KBnJlYXNvbhgMIAEoCRIOCgZleHBvcnQYDSABKAgSDgoGc2NoZW1hGA4gASgJEhEKCWNvbnRhaW5lchgPIAEoCSJGCgZTdGF0dXMSFgoSU1RBVFVTX1VOU1BFQ0lGSUVEEAASCwoHUEVORElORxABEgoKBkFDVElWRRACEgsKB1JFVk9LRUQQAzpN6kFKChhieXRlYmFzZS5jb20vQWNjZXNzR3JhbnQSLnByb2plY3RzL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YmIuYWNjZXNzR3JhbnRzLmFjdGl2YXRlkOowAZjqMAGg6jADqOowCILT5JMCMjoBKiItL3YxL3tuYW1lPXByb2plY3RzLyovYWNjZXNzR3JhbnRzLyp9OmFjdGl2YXRlErkBChFSZXZva2VBY2Nlc3NHcmFudBIlLmJ5dGViYXNlLnYxLlJldm9rZUFjY2Vzc0dyYW50UmVxdWVzdBoYLmJ5dGViYXNlLnYxLkFjY2Vzc0dyYW50ImPaQQRuYW1liuowFmJiLmFjY2Vzc0dyYW50cy5yZXZva2WQ6jABmOowAaDqMAKC0+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/proto/gen/grpc-doc/openapi.yaml b/proto/gen/grpc-doc/openapi.yamlindex 62849a7933..65c8d6b324 100644--- a/proto/gen/grpc-doc/openapi.yaml+++ b/proto/gen/grpc-doc/openapi.yaml@@ -16788,8 +16788,9 @@ components:type: stringtitle: creatordescription: |-- The creator of the access grant.+ The creator of the access grant, the caller who requested it.Format: users/{email}+ readOnly: truestatus:allOf:- $ref: '#/components/schemas/bytebase.v1.AccessGrant.Status'@@ -16851,7 +16852,6 @@ components:description: The container name to execute the query against, used for CosmosDB only.title: AccessGrantrequired:- - creator- targetsbytebase.v1.AccessGrant.Status:type: stringdiff --git a/proto/gen/grpc-doc/v1/README.md b/proto/gen/grpc-doc/v1/README.mdindex 1aaf3124d7..482279a880 100644--- a/proto/gen/grpc-doc/v1/README.md+++ b/proto/gen/grpc-doc/v1/README.md@@ -968,7 +968,7 @@ The line against FORBIDDEN is reversibility. An admin-capable ceiling, if one is| Field | Type | Label | Description || ----- | ---- | ----- | ----------- || name | [string](#string) | | The name of the access grant, generated by the server. Format: projects/{project}/accessGrants/{access_grant} The {access_grant} segment is a server-generated unique ID. |-| creator | [string](#string) | | The creator of the access grant. Format: users/{email} |+| creator | [string](#string) | | The creator of the access grant, the caller who requested it. Format: users/{email} || status | [AccessGrant.Status](#bytebase-v1-AccessGrant-Status) | | The status of the access grant. An ACTIVE grant with `expire_time` in the past is effectively expired and no longer authorizes access. Use `expire_time` to determine whether an ACTIVE grant has expired. || expire_time | [google.protobuf.Timestamp](#google-protobuf-Timestamp) | | The expiration time of the access grant. || ttl | [google.protobuf.Duration](#google-protobuf-Duration) | | Input only. The time-to-live duration for the access grant. The server computes `expire_time` from this value at activation time. |diff --git a/proto/gen/grpc-doc/v1/index.html b/proto/gen/grpc-doc/v1/index.htmlindex c118ffcc75..7a6b2dc42f 100644--- a/proto/gen/grpc-doc/v1/index.html+++ b/proto/gen/grpc-doc/v1/index.html@@ -3692,7 +3692,7 @@ The {access_grant} segment is a server-generated unique ID. </p></td><td>creator</td><td><a href="#string">string</a></td><td></td>- <td><p>The creator of the access grant.+ <td><p>The creator of the access grant, the caller who requested it.Format: users/{email} </p></td></tr>diff --git a/proto/v1/v1/access_grant_service.proto b/proto/v1/v1/access_grant_service.protoindex 3ed2f53e2b..099b6f6b47 100644--- a/proto/v1/v1/access_grant_service.proto+++ b/proto/v1/v1/access_grant_service.proto@@ -97,9 +97,9 @@ message AccessGrant {// The {access_grant} segment is a server-generated unique ID.string name = 1;- // The creator of the access grant.+ // The creator of the access grant, the caller who requested it.// Format: users/{email}- string creator = 2 [(google.api.field_behavior) = REQUIRED];+ string creator = 2 [(google.api.field_behavior) = OUTPUT_ONLY];// The status of the access grant.// An ACTIVE grant with `expire_time` in the past is effectively expired