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: control SQL export with bb.sql.export and remove disable_export (#21690)
p0ny70ecee263e86
diff --git a/CONTEXT.md b/CONTEXT.mdindex cf39040c8b..ad1c39182c 100644--- a/CONTEXT.md+++ b/CONTEXT.md@@ -87,3 +87,19 @@ _Avoid_: Work queue, activity feed**Composite Type**:A PostgreSQL-family standalone named row type (`CREATE TYPE x AS (...)`, `pg_type.typtype = 'c'` excluding table row types). Distinct from enums, domains, ranges, Oracle object types, and SQL Server table/alias types — each is its own concept with its own name._Avoid_: UDT, user-defined type, custom type, object type++**Export Permission**:+The permission to export query results from specific databases, schemas, or tables. It decides who may export, and on its own it lets the holder read the data it covers through export.+_Avoid_: Exporter role, export right, export approval++**Access Grant**:+An approved, time-limited permission for one user to run one specific query on its target databases. A grant that includes export satisfies the Export Permission for that query.+_Avoid_: JIT access, temporary role, export ticket++**Export Destination**:+A place exported query results may go. Local Export is the only destination today.+_Avoid_: Export target, export format++**Local Export**:+An export whose results are returned to the requester as a file.+_Avoid_: Download, data exportdiff --git a/backend/api/mcp/gen/openapi.yaml b/backend/api/mcp/gen/openapi.yamlindex 45fd21640b..6c8bda817a 100644--- a/backend/api/mcp/gen/openapi.yaml+++ b/backend/api/mcp/gen/openapi.yaml@@ -6166,7 +6166,8 @@ paths:summary: Exportdescription: |-Exports query results to a file format.- Permissions required: bb.databases.get+ Permissions required: bb.databases.get, and bb.sql.export on the data the statement reads.+ An active access grant with export=true for the statement satisfies bb.sql.export on its target databases.operationId: bytebase.v1.SQLService.Exportparameters:- name: Connect-Protocol-Version@@ -9338,7 +9339,9 @@ components:export:type: booleantitle: export- description: Whether export the query result.+ description: |-+ Whether the grant allows exporting the query result.+ An active grant with export=true grants bb.sql.export for this query until the grant expires.schema:type: stringtitle: schema@@ -10768,9 +10771,9 @@ components:The syntax and semantics of CEL are documented at https://github.com/google/cel-specSupport variables:- resource.database: the canonical database full name in "instances/{instance}/databases/{database}" or "projects/{project}/instances/{instance}/databases/{database}" format, used by any role with SQL Editor read (e.g. "roles/sqlEditorUser", "roles/sqlEditorReadUser") or write (bb.sql.ddl / bb.sql.dml) access, support "==" operator.- resource.schema_name: the schema name, used by any role with SQL Editor read or write (bb.sql.ddl / bb.sql.dml) access; for writes it is evaluated per write-target table, support "==" operator.- resource.table_name: the table name, used by any role with SQL Editor read or write (bb.sql.ddl / bb.sql.dml) access; for writes it is evaluated per write-target table, support "==" operator.+ resource.database: the canonical database full name in "instances/{instance}/databases/{database}" or "projects/{project}/instances/{instance}/databases/{database}" format, used by any role with SQL Editor read (e.g. "roles/sqlEditorUser", "roles/sqlEditorReadUser"), export (bb.sql.export, e.g. "roles/sqlEditorExporter") or write (bb.sql.ddl / bb.sql.dml) access, support "==" operator.+ resource.schema_name: the schema name, used by any role with SQL Editor read, export (bb.sql.export) or write (bb.sql.ddl / bb.sql.dml) access; for writes it is evaluated per write-target table, support "==" operator.+ resource.table_name: the table name, used by any role with SQL Editor read, export (bb.sql.export) or write (bb.sql.ddl / bb.sql.dml) access; for writes it is evaluated per write-target table, support "==" operator.resource.environment_id: the environment to allow the DDL/DML operation in the SQL Editor, only works for the role with bb.sql.ddl or bb.sql.dml permissions. Support "in" operator.request.time: the expiration. Only support "<" operation in `request.time < timestamp("{ISO datetime string format}")`.@@ -18631,9 +18634,8 @@ components:disableExport:type: booleantitle: disable_export- description: |-- workspace-level policy- Disable data export in the SQL editor.+ description: 'Deprecated: export is controlled by the bb.sql.export permission. Always false; setting it to true is rejected.'+ deprecated: truedisableCopyData:type: booleantitle: disable_copy_data@@ -19747,7 +19749,7 @@ components:title: roledescription: |-The requested role.- Format: roles/EXPORTER.+ Format: roles/{role}.user:type: stringtitle: userdiff --git a/backend/api/v1/org_policy_service.go b/backend/api/v1/org_policy_service.goindex 98e62e6bc9..2beff47b70 100644--- a/backend/api/v1/org_policy_service.go+++ b/backend/api/v1/org_policy_service.go@@ -682,6 +682,10 @@ func (s *OrgPolicyService) convertPolicyPayloadToString(ctx context.Context, pol}return string(payloadBytes), nilcase v1pb.PolicyType_DATA_QUERY:+ payload, err := convertToQueryDataPolicyPayload(policy.GetQueryDataPolicy())+ if err != nil {+ return "", err+ }// Check license for both query policy and restrict copying data featuresif policy.GetQueryDataPolicy() != nil && policy.GetQueryDataPolicy().DisableCopyData {if err := s.licenseService.IsFeatureEnabled(ctx, common.GetWorkspaceIDFromContext(ctx), v1pb.PlanFeature_FEATURE_RESTRICT_COPYING_DATA); err != nil {@@ -691,7 +695,6 @@ func (s *OrgPolicyService) convertPolicyPayloadToString(ctx context.Context, polif err := s.licenseService.IsFeatureEnabled(ctx, common.GetWorkspaceIDFromContext(ctx), v1pb.PlanFeature_FEATURE_QUERY_POLICY); err != nil {return "", connect.NewError(connect.CodePermissionDenied, err)}- payload := convertToQueryDataPolicyPayload(policy.GetQueryDataPolicy())payloadBytes, err := protojson.Marshal(payload)if err != nil {return "", errors.Wrap(err, "failed to marshal policy")diff --git a/backend/api/v1/org_policy_service_converter.go b/backend/api/v1/org_policy_service_converter.goindex aab3537fa5..3bd70a922a 100644--- a/backend/api/v1/org_policy_service_converter.go+++ b/backend/api/v1/org_policy_service_converter.go@@ -1,6 +1,7 @@package v1import (+ "connectrpc.com/connect""github.com/pkg/errors""google.golang.org/genproto/googleapis/type/expr"@@ -170,7 +171,6 @@ func convertToV1PBQueryDataPolicy(payloadStr string) (*v1pb.Policy_QueryDataPoli}return &v1pb.Policy_QueryDataPolicy{QueryDataPolicy: &v1pb.QueryDataPolicy{- DisableExport: payload.DisableExport,MaximumResultRows: payload.MaximumResultRows,DisableCopyData: payload.DisableCopyData,AllowAdminDataSource: payload.AllowAdminDataSource,@@ -178,13 +178,17 @@ func convertToV1PBQueryDataPolicy(payloadStr string) (*v1pb.Policy_QueryDataPoli}, nil}-func convertToQueryDataPolicyPayload(policy *v1pb.QueryDataPolicy) *storepb.QueryDataPolicy {- return &storepb.QueryDataPolicy{- DisableExport: policy.DisableExport,- MaximumResultRows: policy.MaximumResultRows,- DisableCopyData: policy.DisableCopyData,- AllowAdminDataSource: policy.AllowAdminDataSource,+// convertToQueryDataPolicyPayload rejects disable_export=true so stale configs learn the+// setting is gone; false is accepted and dropped.+func convertToQueryDataPolicyPayload(policy *v1pb.QueryDataPolicy) (*storepb.QueryDataPolicy, error) {+ if policy.GetDisableExport() { //nolint:staticcheck // The deprecated field is read only to reject it.+ return nil, connect.NewError(connect.CodeInvalidArgument, errors.New("disable_export is removed. Export requires the bb.sql.export permission; to require approval for export, assign roles without it.")) //nolint:revive // The message is an API contract.}+ return &storepb.QueryDataPolicy{+ MaximumResultRows: policy.GetMaximumResultRows(),+ DisableCopyData: policy.GetDisableCopyData(),+ AllowAdminDataSource: policy.GetAllowAdminDataSource(),+ }, nil}func convertToV1PBReviewRulePolicy(payloadStr string) (*v1pb.Policy_ReviewRulePolicy, error) {diff --git a/backend/api/v1/org_policy_service_query_data_test.go b/backend/api/v1/org_policy_service_query_data_test.gonew file mode 100644index 0000000000..29505b58a8--- /dev/null+++ b/backend/api/v1/org_policy_service_query_data_test.go@@ -0,0 +1,62 @@+package v1++import (+ "context"+ "testing"++ "connectrpc.com/connect"+ "github.com/stretchr/testify/require"++ storepb "github.com/bytebase/bytebase/backend/generated-go/store"+ v1pb "github.com/bytebase/bytebase/backend/generated-go/v1"+ "github.com/bytebase/bytebase/backend/store"+)++func TestQueryDataPolicyWriteRejectsDisableExport(t *testing.T) {+ t.Parallel()+ // The rejection runs before the license check, so a zero service is enough.+ s := &OrgPolicyService{}+ _, err := s.convertPolicyPayloadToString(context.Background(), &v1pb.Policy{+ Type: v1pb.PolicyType_DATA_QUERY,+ Policy: &v1pb.Policy_QueryDataPolicy{QueryDataPolicy: &v1pb.QueryDataPolicy{+ DisableExport: true, //nolint:staticcheck+ MaximumResultRows: 10,+ }},+ })+ require.Error(t, err)+ connectErr := new(connect.Error)+ require.ErrorAs(t, err, &connectErr)+ require.Equal(t, connect.CodeInvalidArgument, connectErr.Code())+ require.Equal(t, "disable_export is removed. Export requires the bb.sql.export permission; to require approval for export, assign roles without it.", connectErr.Message())+}++func TestConvertToQueryDataPolicyPayloadDropsDisableExportFalse(t *testing.T) {+ t.Parallel()+ payload, err := convertToQueryDataPolicyPayload(&v1pb.QueryDataPolicy{+ DisableExport: false, //nolint:staticcheck+ MaximumResultRows: 10,+ DisableCopyData: true,+ AllowAdminDataSource: true,+ })+ require.NoError(t, err)+ require.Equal(t, int32(10), payload.GetMaximumResultRows())+ require.True(t, payload.GetDisableCopyData())+ require.True(t, payload.GetAllowAdminDataSource())+}++func TestConvertToPolicyQueryDataIgnoresStoredDisableExport(t *testing.T) {+ t.Parallel()+ policy, err := convertToPolicy(&store.PolicyMessage{+ Resource: "workspaces/example",+ ResourceType: storepb.Policy_WORKSPACE,+ Type: storepb.Policy_QUERY_DATA,+ Payload: `{"disableExport":true,"maximumResultRows":10,"disableCopyData":true}`,+ Enforce: true,+ })+ require.NoError(t, err)+ queryData := policy.GetQueryDataPolicy()+ require.NotNil(t, queryData)+ require.False(t, queryData.GetDisableExport()) //nolint:staticcheck+ require.Equal(t, int32(10), queryData.GetMaximumResultRows())+ require.True(t, queryData.GetDisableCopyData())+}diff --git a/backend/api/v1/sql_service.go b/backend/api/v1/sql_service.goindex 5f9628cae4..bf6bac381c 100644--- a/backend/api/v1/sql_service.go+++ b/backend/api/v1/sql_service.go@@ -420,7 +420,7 @@ func (s *SQLService) Query(ctx context.Context, req *connect.Request[v1pb.QueryR// (e.g. `SELECT * FROM db_b.secret` from a grant on `db_a`) still has// to clear the regular IAM check on the foreign database. See PR// #20487 review for the cross-DB exfiltration scenario this guards.- optionalAccessCheck := s.accessCheckWithGrant(accessGrant)+ optionalAccessCheck := s.accessCheckWithGrant(accessGrant, false /* export */)results, _, duration, queryErr := queryRetryStopOnError(ctx,s.store,@@ -1241,10 +1241,9 @@ func (s *SQLService) Export(ctx context.Context, req *connect.Request[v1pb.Exporreturn nil, err}- // Same cross-database guardrail as Query: the JIT grant authorizes only- // its target databases, so span-level ACL still runs and only the- // granted targets are exempted from IAM. See PR #20487 review.- optionalAccessCheck := s.accessCheckWithGrant(accessGrant)+ // The JIT grant satisfies bb.sql.export only on its target databases, so+ // span-level ACL still runs for every other database.+ optionalAccessCheck := s.accessCheckWithGrant(accessGrant, true /* export */)skipMasking := falseif accessGrant != nil {skipMasking = accessGrant.Payload.Unmask@@ -1254,11 +1253,7 @@ func (s *SQLService) Export(ctx context.Context, req *connect.Request[v1pb.Expors.createQueryHistory(instance, database, store.QueryHistoryTypeExport, statement, user.Email, duration, exportErr)if exportErr != nil {- var connectErr *connect.Error- if errors.As(exportErr, &connectErr) {- return nil, connectErr- }- return nil, connect.NewError(connect.CodeInternal, exportErr)+ return nil, exportConnectError(exportErr)}exportResponse := &v1pb.ExportResponse{@@ -1271,8 +1266,22 @@ func (s *SQLService) Export(ctx context.Context, req *connect.Request[v1pb.Exporreturn connect.NewResponse(exportResponse), nil}+// exportConnectError returns the connect error Export answers with. A refusal+// from the access check arrives as a queryError, which errors.As cannot see+// through, so its own connect error (such as PERMISSION_DENIED) is returned.+func exportConnectError(err error) *connect.Error {+ var connectErr *connect.Error+ var qe *queryError+ if errors.As(err, &qe) && errors.As(qe.err, &connectErr) {+ return connectErr+ }+ if errors.As(err, &connectErr) {+ return connectErr+ }+ return connect.NewError(connect.CodeInternal, err)+}+// doExport performs SQL Editor exports with masking applied.-// This is used for ad-hoc exports where users have the EXPORTER role.func doExport(ctx context.Context,stores *store.Store,@@ -1539,44 +1548,27 @@ func (s *SQLService) GetQueryHistory(ctx context.Context, req *connect.Request[v// without an import cycle. See parsercontext.BuildGetDatabaseMetadataFunc,// BuildListDatabaseNamesFunc, BuildGetLinkedDatabaseMetadataFunc.-// accessCheck check the access for the database. Do not support cross-project resources.-func (s *SQLService) accessCheck(- ctx context.Context,- instance *store.InstanceMessage,- database *store.DatabaseMessage,- user *store.UserMessage,- spans []*parserbase.QuerySpan,- isExplain bool,- statements []parserbase.Statement,- requestSchema string,- multiStatement bool,-) error {- return s.accessCheckWithGrantedTargets(ctx, instance, database, user, spans, isExplain, statements, nil, requestSchema, multiStatement)-}--// accessCheckWithGrant returns an accessCheckFunc that exempts the access-// grant's target databases from IAM checks while keeping span-level checks for-// every other source database. This preserves JIT-grant behavior for the-// grant's target (the user is already authorized there) but blocks cross--// database exfiltration via cross-DB references like `SELECT * FROM db_b.t`-// from a grant targeting `db_a` — see PR #20487 review. The exemption is for-// data access only; see checkDatabaseAccess for why explain stays with IAM.-//-// Pass `accessGrant == nil` to skip wrapping; callers in that case should-// reference `s.accessCheck` directly.-func (s *SQLService) accessCheckWithGrant(accessGrant *store.AccessGrantMessage) accessCheckFunc {- if accessGrant == nil || accessGrant.Payload == nil {- return s.accessCheck- }- grantedTargets := make(map[string]struct{}, len(accessGrant.Payload.Targets))- for _, t := range accessGrant.Payload.Targets {- grantedTargets[t] = struct{}{}+// accessCheckWithGrant returns the per-statement access check for Query, or for+// Export when export is true. accessGrant, which may be nil, applies only to its+// target databases; every other source database keeps its span-level IAM check,+// which blocks cross-database exfiltration like `SELECT * FROM db_b.t` through+// a grant on `db_a`. Cross-project resources are not supported.+func (s *SQLService) accessCheckWithGrant(accessGrant *store.AccessGrantMessage, export bool) accessCheckFunc {+ var grantedTargets map[string]struct{}+ if accessGrant != nil && accessGrant.Payload != nil {+ grantedTargets = make(map[string]struct{}, len(accessGrant.Payload.Targets))+ for _, t := range accessGrant.Payload.Targets {+ grantedTargets[t] = struct{}{}+ }}return func(ctx context.Context, instance *store.InstanceMessage, database *store.DatabaseMessage, user *store.UserMessage, spans []*parserbase.QuerySpan, isExplain bool, statements []parserbase.Statement, requestSchema string, multiStatement bool) error {- return s.accessCheckWithGrantedTargets(ctx, instance, database, user, spans, isExplain, statements, grantedTargets, requestSchema, multiStatement)+ return s.accessCheckWithGrantedTargets(ctx, instance, database, user, spans, isExplain, statements, grantedTargets, export, requestSchema, multiStatement)}}+// accessCheckWithGrantedTargets authorizes each statement span. For Export,+// reading data, including info-schema output, requires bb.sql.export in place+// of bb.sql.select or bb.sql.info; explain, DML and DDL keep their permissions.func (s *SQLService) accessCheckWithGrantedTargets(ctx context.Context,instance *store.InstanceMessage,@@ -1586,6 +1578,7 @@ func (s *SQLService) accessCheckWithGrantedTargets(isExplain bool,statements []parserbase.Statement,grantedTargets map[string]struct{},+ export bool,requestSchema string,multiStatement bool,) error {@@ -1607,14 +1600,31 @@ func (s *SQLService) accessCheckWithGrantedTargets(return connect.NewError(connect.CodeInternal, errors.New(err.Error()))}+ readPermission := func(perm permission.Permission) permission.Permission {+ if export && (perm == permission.SQLSelect || perm == permission.SQLInfo) {+ return permission.SQLExport+ }+ return perm+ }++ // grantSatisfies reports whether the access grant satisfies perm on target.+ // A grant approves one read-only statement on its target databases: for+ // Export it satisfies bb.sql.export, and for Query the statement's own+ // permission. Reading the statement's plan is a separate capability, so+ // bb.sql.explain always comes from IAM.+ grantSatisfies := func(target string, perm permission.Permission) bool {+ if _, granted := grantedTargets[target]; !granted {+ return false+ }+ if export {+ return perm == permission.SQLExport+ }+ return perm != permission.SQLExplain+ }+checkDatabaseAccess := func(perm permission.Permission) error {databaseFullName := formatDatabaseResourceName(instance, database)- // A grant approves reading one statement's data on its target databases, so- // the holder needs no IAM role there for that statement. Reading the- // statement's plan is a separate capability: the approved statement can- // arrive with the explain flag, or be a typed EXPLAIN, and either way- // bb.sql.explain still comes from IAM.- if _, granted := grantedTargets[databaseFullName]; granted && perm != permission.SQLExplain {+ if grantSatisfies(databaseFullName, perm) {return nil}attributes := map[string]any{@@ -1659,7 +1669,7 @@ func (s *SQLService) accessCheckWithGrantedTargets(// No spans: an engine without a span extractor. Check at the database level,// with the explain permission for an explain request.if len(spans) == 0 {- perm := permission.SQLSelect+ perm := readPermission(permission.SQLSelect)if isExplain {perm = permission.SQLExplain}@@ -1701,6 +1711,7 @@ func (s *SQLService) accessCheckWithGrantedTargets(// always fallback to bb.sql.selectperm = permission.SQLSelect}+ perm = readPermission(perm)// A plan names the tables it reads, so reading one needs bb.sql.explain on// every database the statement references, not only the connected one.@@ -1749,7 +1760,12 @@ func (s *SQLService) accessCheckWithGrantedTargets(continue}databaseLevelOnly := multiStatement || len(nonEmptyStatements) != 1- deniedResources, err := s.authorizeWriteTargets(ctx, user, instance, database, perm, targets, grantedTargets, databaseLevelOnly, workspacePolicy.Policy, projectPolicy.Policy)+ writeGrantedTargets := grantedTargets+ if export {+ // An export grant satisfies only bb.sql.export; see grantSatisfies.+ writeGrantedTargets = nil+ }+ deniedResources, err := s.authorizeWriteTargets(ctx, user, instance, database, perm, targets, writeGrantedTargets, databaseLevelOnly, workspacePolicy.Policy, projectPolicy.Policy)if err != nil {return err}@@ -1803,7 +1819,7 @@ func (s *SQLService) accessCheckWithGrantedTargets(InstanceID: instance.ResourceID,DatabaseName: column.Database,})- if _, granted := grantedTargets[grantTargetName]; granted {+ if grantSatisfies(grantTargetName, perm) {continue}attributes := map[string]any{diff --git a/backend/api/v1/sql_service_access_grant_test.go b/backend/api/v1/sql_service_access_grant_test.goindex f1d008fd53..7fb01a56c9 100644--- a/backend/api/v1/sql_service_access_grant_test.go+++ b/backend/api/v1/sql_service_access_grant_test.go@@ -122,7 +122,7 @@ func TestAccessGrantDoesNotExemptExplain(t *testing.T) {granted := map[string]struct{}{"instances/test/databases/db": {}}check := func(email string, isExplain bool) error {user := &store.UserMessage{Email: email}- return service.accessCheckWithGrantedTargets(ctx, instance, database, user, nil, isExplain, nil, granted, "", false)+ return service.accessCheckWithGrantedTargets(ctx, instance, database, user, nil, isExplain, nil, granted, false, "", false)}require.NoError(t, check("[email protected]", false), "the grant covers select")diff --git a/backend/api/v1/sql_service_export_permission_test.go b/backend/api/v1/sql_service_export_permission_test.gonew file mode 100644index 0000000000..69e5fcae81--- /dev/null+++ b/backend/api/v1/sql_service_export_permission_test.go@@ -0,0 +1,195 @@+package v1++import (+ "context"+ "testing"++ "connectrpc.com/connect"+ "github.com/pkg/errors"+ "github.com/stretchr/testify/require"+ "google.golang.org/genproto/googleapis/type/expr"++ "github.com/bytebase/bytebase/backend/common"+ "github.com/bytebase/bytebase/backend/common/permission"+ "github.com/bytebase/bytebase/backend/common/testcontainer"+ "github.com/bytebase/bytebase/backend/component/iam"+ storepb "github.com/bytebase/bytebase/backend/generated-go/store"+ parserbase "github.com/bytebase/bytebase/backend/plugin/parser/base"+ "github.com/bytebase/bytebase/backend/store"+)++// exportAccessFixture is a MySQL database db whose users hold different mixes+// of read, export and write permissions on it.+type exportAccessFixture struct {+ service *SQLService+ instance *store.InstanceMessage+ database *store.DatabaseMessage+}++func newExportAccessFixture(ctx context.Context, t *testing.T) *exportAccessFixture {+ t.Helper()+ db, stores, _ := testcontainer.NewMetadataDB(t)+ _, err := db.ExecContext(ctx, `+ INSERT INTO workspace (resource_id) VALUES ('default');+ INSERT INTO principal (name, email, password_hash) VALUES+ ('reader', '[email protected]', 'unused'),+ ('exporter', '[email protected]', 'unused'),+ ('table-exporter', '[email protected]', 'unused'),+ ('explain-exporter', '[email protected]', 'unused'),+ ('writer', '[email protected]', 'unused'),+ ('grantee', '[email protected]', 'unused');+ INSERT INTO project (resource_id, workspace, name) VALUES ('project-a', 'default', 'A');`)+ require.NoError(t, err)+ for _, role := range []struct {+ id string+ perms map[permission.Permission]bool+ }{+ {id: "reader", perms: map[permission.Permission]bool{permission.SQLSelect: true, permission.SQLInfo: true, permission.SQLExplain: true}},+ {id: "exporter", perms: map[permission.Permission]bool{permission.SQLExport: true}},+ {id: "writer", perms: map[permission.Permission]bool{permission.SQLDml: true}},+ } {+ _, err = stores.CreateRole(ctx, &store.RoleMessage{+ ResourceID: role.id, Workspace: "default", Name: role.id, Permissions: role.perms,+ })+ require.NoError(t, err)+ }+ bindings := []*storepb.Binding{+ {Role: "roles/reader", Members: []string{common.FormatUserEmail("[email protected]"), common.FormatUserEmail("[email protected]")}},+ {Role: "roles/exporter", Members: []string{common.FormatUserEmail("[email protected]"), common.FormatUserEmail("[email protected]")}},+ {+ Role: "roles/exporter",+ Members: []string{common.FormatUserEmail("[email protected]")},+ Condition: &expr.Expr{Expression: `resource.database == "instances/test/databases/db" && resource.table_name in ["t1"]`},+ },+ {Role: "roles/writer", Members: []string{common.FormatUserEmail("[email protected]")}},+ }+ _, err = stores.PatchIamPolicy(ctx, "default", storepb.Policy_PROJECT, common.FormatProject("project-a"), func(policy *storepb.IamPolicy) error {+ policy.Bindings = append(policy.Bindings, bindings...)+ return nil+ })+ require.NoError(t, err)+ instance, err := stores.CreateInstance(ctx, &store.InstanceMessage{+ ResourceID: "test", Workspace: "default",+ Metadata: &storepb.Instance{Engine: storepb.Engine_MYSQL, Activation: true, DataSources: []*storepb.DataSource{{Id: "admin", Type: storepb.DataSourceType_ADMIN}}},+ })+ require.NoError(t, err)+ database, err := stores.UpsertDatabase(ctx, &store.DatabaseMessage{+ InstanceID: "test", DatabaseName: "db", ProjectID: "project-a", Metadata: &storepb.DatabaseMetadata{},+ })+ require.NoError(t, err)+ iamManager, err := iam.NewManager(stores, nil, false)+ require.NoError(t, err)+ return &exportAccessFixture{+ service: &SQLService{store: stores, iamManager: iamManager},+ instance: instance,+ database: database,+ }+}++func (f *exportAccessFixture) check(ctx context.Context, email string, export bool, grant *store.AccessGrantMessage, statement string, spans ...*parserbase.QuerySpan) error {+ user := &store.UserMessage{Email: email}+ return f.service.accessCheckWithGrant(grant, export)(ctx, f.instance, f.database, user, spans, false, []parserbase.Statement{{Text: statement}}, "", false)+}++func readsTable(database, table string) *parserbase.QuerySpan {+ return &parserbase.QuerySpan{Type: parserbase.Select, SourceColumns: parserbase.SourceColumnSet{{Database: database, Table: table}: true}}+}++func requireDenied(t *testing.T, err error, perm permission.Permission, resources ...string) {+ t.Helper()+ var denied *queryError+ require.ErrorAs(t, err, &denied)+ require.Equal(t, connect.CodePermissionDenied, connect.CodeOf(denied.err))+ require.Equal(t, perm, denied.permission)+ require.Equal(t, resources, denied.resources)+}++func TestExportRequiresExportPermission(t *testing.T) {+ t.Parallel()+ ctx := context.WithValue(context.Background(), common.WorkspaceIDContextKey, "default")+ f := newExportAccessFixture(ctx, t)+ const (+ db = "instances/test/databases/db"+ t1 = db + "/tables/t1"+ t2 = db + "/tables/t2"+ query = false+ export = true+ selectT1 = "SELECT * FROM t1"+ )++ t.Run("select alone does not export", func(t *testing.T) {+ t.Parallel()+ require.NoError(t, f.check(ctx, "[email protected]", query, nil, selectT1, readsTable("db", "t1")))+ requireDenied(t, f.check(ctx, "[email protected]", export, nil, selectT1, readsTable("db", "t1")), permission.SQLExport, t1)+ })++ t.Run("export scoped to one table", func(t *testing.T) {+ t.Parallel()+ require.NoError(t, f.check(ctx, "[email protected]", export, nil, selectT1, readsTable("db", "t1")))+ requireDenied(t, f.check(ctx, "[email protected]", export, nil, "SELECT * FROM t2", readsTable("db", "t2")), permission.SQLExport, t2)+ requireDenied(t, f.check(ctx, "[email protected]", query, nil, selectT1, readsTable("db", "t1")), permission.SQLSelect, t1)+ })++ t.Run("info schema and engines without spans", func(t *testing.T) {+ t.Parallel()+ info := &parserbase.QuerySpan{Type: parserbase.SelectInfoSchema}+ require.NoError(t, f.check(ctx, "[email protected]", query, nil, "SHOW TABLES", info))+ requireDenied(t, f.check(ctx, "[email protected]", export, nil, "SHOW TABLES", info), permission.SQLExport, db)+ require.NoError(t, f.check(ctx, "[email protected]", export, nil, "SHOW TABLES", info))++ require.NoError(t, f.check(ctx, "[email protected]", query, nil, selectT1))+ requireDenied(t, f.check(ctx, "[email protected]", export, nil, selectT1), permission.SQLExport, db)+ require.NoError(t, f.check(ctx, "[email protected]", export, nil, selectT1))+ })++ t.Run("explain keeps bb.sql.explain", func(t *testing.T) {+ t.Parallel()+ plan := &parserbase.QuerySpan{Type: parserbase.Explain, SourceColumns: parserbase.SourceColumnSet{{Database: "db", Table: "t1"}: true}}+ require.NoError(t, f.check(ctx, "[email protected]", export, nil, "EXPLAIN SELECT * FROM t1", plan))+ requireDenied(t, f.check(ctx, "[email protected]", export, nil, "EXPLAIN SELECT * FROM t1", plan), permission.SQLExplain, db)++ analyze := readsTable("db", "t1")+ analyze.ExplainAnalyze = true+ requireDenied(t, f.check(ctx, "[email protected]", export, nil, "EXPLAIN ANALYZE SELECT * FROM t1", analyze), permission.SQLExport, t1)+ require.NoError(t, f.check(ctx, "[email protected]", export, nil, "EXPLAIN ANALYZE SELECT * FROM t1", analyze))+ })++ t.Run("export grant", func(t *testing.T) {+ t.Parallel()+ grant := &store.AccessGrantMessage{Payload: &storepb.AccessGrantPayload{Targets: []string{db}, Export: true}}+ requireDenied(t, f.check(ctx, "[email protected]", export, nil, selectT1, readsTable("db", "t1")), permission.SQLExport, t1)+ require.NoError(t, f.check(ctx, "[email protected]", export, grant, selectT1, readsTable("db", "t1")))+ require.NoError(t, f.check(ctx, "[email protected]", export, grant, selectT1))+ requireDenied(t, f.check(ctx, "[email protected]", export, grant, "SELECT * FROM other.t1", readsTable("other", "t1")), permission.SQLExport, "instances/test/databases/other/tables/t1")+ require.NoError(t, f.check(ctx, "[email protected]", query, grant, selectT1, readsTable("db", "t1")))+ })++ t.Run("DML keeps bb.sql.dml", func(t *testing.T) {+ t.Parallel()+ const insert = "INSERT INTO t1 VALUES (1)"+ write := &parserbase.QuerySpan{Type: parserbase.DML}+ requireDenied(t, f.check(ctx, "[email protected]", export, nil, insert, write), permission.SQLDml, db)+ require.NoError(t, f.check(ctx, "[email protected]", export, nil, insert, write))+ grant := &store.AccessGrantMessage{Payload: &storepb.AccessGrantPayload{Targets: []string{db}, Export: true}}+ requireDenied(t, f.check(ctx, "[email protected]", export, grant, insert, write), permission.SQLDml, db)+ })+}++func TestExportRefusalIsPermissionDenied(t *testing.T) {+ t.Parallel()+ ctx := context.WithValue(context.Background(), common.WorkspaceIDContextKey, "default")+ f := newExportAccessFixture(ctx, t)++ denied := false+ ctx = withSetPermissionDenied(ctx, func() { denied = true })+ refusal := f.check(ctx, "[email protected]", true /* export */, nil, "SELECT * FROM t1", readsTable("db", "t1"))+ require.Error(t, refusal)+ require.True(t, denied, "the refusal marks the request for the audit log")++ err := exportConnectError(refusal)+ require.Equal(t, connect.CodePermissionDenied, err.Code())+ require.Equal(t, "permission denied to access resources: [instances/test/databases/db/tables/t1]", err.Message())++ require.Equal(t, connect.CodeNotFound, exportConnectError(connect.NewError(connect.CodeNotFound, errors.New("missing"))).Code())+ require.Equal(t, connect.CodeInternal, exportConnectError(errors.New("driver failed")).Code())+}diff --git a/backend/api/v1/sql_service_test.go b/backend/api/v1/sql_service_test.goindex ccea1a3ae0..0bb75e3e05 100644--- a/backend/api/v1/sql_service_test.go+++ b/backend/api/v1/sql_service_test.go@@ -633,7 +633,7 @@ func newExplainAccessFixture(ctx context.Context, t *testing.T, engine storepb.Efunc (f *explainAccessFixture) check(ctx context.Context, email string, isExplain bool, statement string, span *parserbase.QuerySpan) error {user := &store.UserMessage{Email: email}- return f.service.accessCheckWithGrantedTargets(ctx, f.instance, f.database, user, []*parserbase.QuerySpan{span}, isExplain, []parserbase.Statement{{Text: statement}}, nil, "", false)+ return f.service.accessCheckWithGrantedTargets(ctx, f.instance, f.database, user, []*parserbase.QuerySpan{span}, isExplain, []parserbase.Statement{{Text: statement}}, nil, false, "", false)}func reads(databases ...string) parserbase.SourceColumnSet {diff --git a/backend/common/permission/permission.go b/backend/common/permission/permission.goindex c87e4297ca..7109a50fa2 100644--- a/backend/common/permission/permission.go+++ b/backend/common/permission/permission.go@@ -135,6 +135,7 @@ const (SheetsCreate Permission = "bb.sheets.create"SheetsGet Permission = "bb.sheets.get"SQLSelect Permission = "bb.sql.select"+ SQLExport Permission = "bb.sql.export"SQLDdl Permission = "bb.sql.ddl"SQLDml Permission = "bb.sql.dml"SQLExplain Permission = "bb.sql.explain"diff --git a/backend/common/permission/permission.yaml b/backend/common/permission/permission.yamlindex d25a358c40..d401ef6a09 100644--- a/backend/common/permission/permission.yaml+++ b/backend/common/permission/permission.yaml@@ -127,6 +127,7 @@ permissions:- bb.sheets.get- bb.subscription.manage- bb.sql.select+ - bb.sql.export- bb.sql.ddl- bb.sql.dml- bb.sql.explaindiff --git a/backend/generated-go/store/issue.pb.go b/backend/generated-go/store/issue.pb.goindex 6110be7d6a..6f8419e3ca 100644--- a/backend/generated-go/store/issue.pb.go+++ b/backend/generated-go/store/issue.pb.go@@ -231,7 +231,7 @@ func (x *Issue) GetDraft() bool {type RoleGrant struct {state protoimpl.MessageState `protogen:"open.v1"`// The role being requested for the user.- // Format: roles/EXPORTER.+ // Format: roles/{role}.Role string `protobuf:"bytes,1,opt,name=role,proto3" json:"role,omitempty"`// The user who will receive the role.// Format: users/{email}.diff --git a/backend/generated-go/store/policy.pb.go b/backend/generated-go/store/policy.pb.goindex b281b33cb2..b4e718ec1c 100644--- a/backend/generated-go/store/policy.pb.go+++ b/backend/generated-go/store/policy.pb.go@@ -575,9 +575,6 @@ func (x *IamPolicy) GetBindings() []*Binding {// QueryDataPolicy is the policy configuration for querying data in the SQL Editor.type QueryDataPolicy struct {state protoimpl.MessageState `protogen:"open.v1"`- // workspace-level policy- // Disable exporting data in the SQL editor.- DisableExport bool `protobuf:"varint,2,opt,name=disable_export,json=disableExport,proto3" json:"disable_export,omitempty"`// Support both project-level and workspace-level.// The maximum number of rows to return in the SQL editor.// The default value <= 0, means no limit.@@ -628,13 +625,6 @@ func (*QueryDataPolicy) Descriptor() ([]byte, []int) {return file_store_policy_proto_rawDescGZIP(), []int{9}}-func (x *QueryDataPolicy) GetDisableExport() bool {- if x != nil {- return x.DisableExport- }- return false-}-func (x *QueryDataPolicy) GetMaximumResultRows() int32 {if x != nil {return x.MaximumResultRows@@ -854,14 +844,13 @@ const file_store_policy_proto_rawDesc = "" +"\amembers\x18\x02 \x03(\tR\amembers\x12/\n" +"\tcondition\x18\x03 \x01(\v2\x11.google.type.ExprR\tcondition\"@\n" +"\tIamPolicy\x123\n" +- "\bbindings\x18\x01 \x03(\v2\x17.bytebase.store.BindingR\bbindings\"\xa3\x02\n" +- "\x0fQueryDataPolicy\x12%\n" +- "\x0edisable_export\x18\x02 \x01(\bR\rdisableExport\x12.\n" ++ "\bbindings\x18\x01 \x03(\v2\x17.bytebase.store.BindingR\bbindings\"\x92\x02\n" ++ "\x0fQueryDataPolicy\x12.\n" +"\x13maximum_result_rows\x18\x04 \x01(\x05R\x11maximumResultRows\x12*\n" +"\x11disable_copy_data\x18\x05 \x01(\bR\x0fdisableCopyData\x125\n" +"\x17allow_admin_data_source\x18\t \x01(\bR\x14allowAdminDataSource\x12!\n" +"\fdisallow_ddl\x18\a \x01(\bR\vdisallowDdl\x12!\n" +- "\fdisallow_dml\x18\b \x01(\bR\vdisallowDmlJ\x04\b\x06\x10\aJ\x04\b\x01\x10\x02J\x04\b\x03\x10\x04B\x8e\x01\n" ++ "\fdisallow_dml\x18\b \x01(\bR\vdisallowDmlJ\x04\b\x06\x10\aJ\x04\b\x01\x10\x02J\x04\b\x03\x10\x04J\x04\b\x02\x10\x03R\x0edisable_exportB\x8e\x01\n" +"\x12com.bytebase.storeB\vPolicyProtoP\x01Z\x12generated-go/store\xa2\x02\x03BSX\xaa\x02\x0eBytebase.Store\xca\x02\x0eBytebase\\Store\xe2\x02\x1aBytebase\\Store\\GPBMetadata\xea\x02\x0fBytebase::Storeb\x06proto3"var (diff --git a/backend/generated-go/store/policy_equal.pb.go b/backend/generated-go/store/policy_equal.pb.goindex eb6f3a9095..d6be015505 100644--- a/backend/generated-go/store/policy_equal.pb.go+++ b/backend/generated-go/store/policy_equal.pb.go@@ -223,9 +223,6 @@ func (x *QueryDataPolicy) Equal(y *QueryDataPolicy) bool {if x == nil || y == nil {return x == nil && y == nil}- if x.DisableExport != y.DisableExport {- return false- }if x.MaximumResultRows != y.MaximumResultRows {return false}diff --git a/backend/generated-go/v1/access_grant_service.pb.go b/backend/generated-go/v1/access_grant_service.pb.goindex 72df64d3db..61ffb941e2 100644--- a/backend/generated-go/v1/access_grant_service.pb.go+++ b/backend/generated-go/v1/access_grant_service.pb.go@@ -118,7 +118,8 @@ type AccessGrant struct {CreateTime *timestamppb.Timestamp `protobuf:"bytes,9,opt,name=create_time,json=createTime,proto3" json:"create_time,omitempty"`UpdateTime *timestamppb.Timestamp `protobuf:"bytes,10,opt,name=update_time,json=updateTime,proto3" json:"update_time,omitempty"`Reason string `protobuf:"bytes,12,opt,name=reason,proto3" json:"reason,omitempty"`- // Whether export the query result.+ // Whether the grant allows exporting the query result.+ // An active grant with export=true grants bb.sql.export for this query until the grant expires.Export bool `protobuf:"varint,13,opt,name=export,proto3" json:"export,omitempty"`// The default schema to execute the query.Schema string `protobuf:"bytes,14,opt,name=schema,proto3" json:"schema,omitempty"`diff --git a/backend/generated-go/v1/iam_policy.pb.go b/backend/generated-go/v1/iam_policy.pb.goindex 2d2aa1bd31..d54e3a3e6d 100644--- a/backend/generated-go/v1/iam_policy.pb.go+++ b/backend/generated-go/v1/iam_policy.pb.go@@ -268,9 +268,9 @@ type Binding struct {// The syntax and semantics of CEL are documented at https://github.com/google/cel-spec//// Support variables:- // resource.database: the canonical database full name in "instances/{instance}/databases/{database}" or "projects/{project}/instances/{instance}/databases/{database}" format, used by any role with SQL Editor read (e.g. "roles/sqlEditorUser", "roles/sqlEditorReadUser") or write (bb.sql.ddl / bb.sql.dml) access, support "==" operator.- // resource.schema_name: the schema name, used by any role with SQL Editor read or write (bb.sql.ddl / bb.sql.dml) access; for writes it is evaluated per write-target table, support "==" operator.- // resource.table_name: the table name, used by any role with SQL Editor read or write (bb.sql.ddl / bb.sql.dml) access; for writes it is evaluated per write-target table, support "==" operator.+ // resource.database: the canonical database full name in "instances/{instance}/databases/{database}" or "projects/{project}/instances/{instance}/databases/{database}" format, used by any role with SQL Editor read (e.g. "roles/sqlEditorUser", "roles/sqlEditorReadUser"), export (bb.sql.export, e.g. "roles/sqlEditorExporter") or write (bb.sql.ddl / bb.sql.dml) access, support "==" operator.+ // resource.schema_name: the schema name, used by any role with SQL Editor read, export (bb.sql.export) or write (bb.sql.ddl / bb.sql.dml) access; for writes it is evaluated per write-target table, support "==" operator.+ // resource.table_name: the table name, used by any role with SQL Editor read, export (bb.sql.export) or write (bb.sql.ddl / bb.sql.dml) access; for writes it is evaluated per write-target table, support "==" operator.// resource.environment_id: the environment to allow the DDL/DML operation in the SQL Editor, only works for the role with bb.sql.ddl or bb.sql.dml permissions. Support "in" operator.// request.time: the expiration. Only support "<" operation in `request.time < timestamp("{ISO datetime string format}")`.//diff --git a/backend/generated-go/v1/issue_service.pb.go b/backend/generated-go/v1/issue_service.pb.goindex 9c9934520c..6186e35d2f 100644--- a/backend/generated-go/v1/issue_service.pb.go+++ b/backend/generated-go/v1/issue_service.pb.go@@ -1456,7 +1456,7 @@ func (x *Issue) GetDraft() bool {type RoleGrant struct {state protoimpl.MessageState `protogen:"open.v1"`// The requested role.- // Format: roles/EXPORTER.+ // Format: roles/{role}.Role string `protobuf:"bytes,1,opt,name=role,proto3" json:"role,omitempty"`// The user to be granted.// Format: users/{email}.diff --git a/backend/generated-go/v1/org_policy_service.pb.go b/backend/generated-go/v1/org_policy_service.pb.goindex fd4ab9735e..cdf40c0b62 100644--- a/backend/generated-go/v1/org_policy_service.pb.go+++ b/backend/generated-go/v1/org_policy_service.pb.go@@ -871,8 +871,9 @@ type QueryDataPolicy struct {// The maximum number of rows to return in the SQL editor.// The default value <= 0, means no limit.MaximumResultRows int32 `protobuf:"varint,1,opt,name=maximum_result_rows,json=maximumResultRows,proto3" json:"maximum_result_rows,omitempty"`- // workspace-level policy- // Disable data export in the SQL editor.+ // Deprecated: export is controlled by the bb.sql.export permission. Always false; setting it to true is rejected.+ //+ // Deprecated: Marked as deprecated in v1/org_policy_service.proto.DisableExport bool `protobuf:"varint,2,opt,name=disable_export,json=disableExport,proto3" json:"disable_export,omitempty"`// workspace-level policy// Disable copying query results in the SQL editor.@@ -925,6 +926,7 @@ func (x *QueryDataPolicy) GetMaximumResultRows() int32 {return 0}+// Deprecated: Marked as deprecated in v1/org_policy_service.proto.func (x *QueryDataPolicy) GetDisableExport() bool {if x != nil {return x.DisableExport@@ -1295,10 +1297,10 @@ const file_v1_org_policy_service_proto_rawDesc = "" +"\acontent\x18\x01 \x01(\tR\acontent\"C\n" +"\rRolloutPolicy\x12\x1c\n" +"\tautomatic\x18\x01 \x01(\bR\tautomatic\x12\x14\n" +- "\x05roles\x18\x02 \x03(\tR\x05roles\"\xcb\x01\n" ++ "\x05roles\x18\x02 \x03(\tR\x05roles\"\xcf\x01\n" +"\x0fQueryDataPolicy\x12.\n" +- "\x13maximum_result_rows\x18\x01 \x01(\x05R\x11maximumResultRows\x12%\n" +- "\x0edisable_export\x18\x02 \x01(\bR\rdisableExport\x12*\n" ++ "\x13maximum_result_rows\x18\x01 \x01(\x05R\x11maximumResultRows\x12)\n" ++ "\x0edisable_export\x18\x02 \x01(\bB\x02\x18\x01R\rdisableExport\x12*\n" +"\x11disable_copy_data\x18\x03 \x01(\bR\x0fdisableCopyData\x125\n" +"\x17allow_admin_data_source\x18\x04 \x01(\bR\x14allowAdminDataSource\"\xbf\x01\n" +"\x16MaskingExemptionPolicy\x12M\n" +diff --git a/backend/generated-go/v1/sql_service_grpc.pb.go b/backend/generated-go/v1/sql_service_grpc.pb.goindex ec70c07e84..4a6e9c539e 100644--- a/backend/generated-go/v1/sql_service_grpc.pb.go+++ b/backend/generated-go/v1/sql_service_grpc.pb.go@@ -58,7 +58,8 @@ type SQLServiceClient interface {// Permissions required: None (only returns the caller's own query history)GetQueryHistory(ctx context.Context, in *GetQueryHistoryRequest, opts ...grpc.CallOption) (*QueryHistory, error)// Exports query results to a file format.- // Permissions required: bb.databases.get+ // Permissions required: bb.databases.get, and bb.sql.export on the data the statement reads.+ // An active access grant with export=true for the statement satisfies bb.sql.export on its target databases.Export(ctx context.Context, in *ExportRequest, opts ...grpc.CallOption) (*ExportResponse, error)}@@ -167,7 +168,8 @@ type SQLServiceServer interface {// Permissions required: None (only returns the caller's own query history)GetQueryHistory(context.Context, *GetQueryHistoryRequest) (*QueryHistory, error)// Exports query results to a file format.- // Permissions required: bb.databases.get+ // Permissions required: bb.databases.get, and bb.sql.export on the data the statement reads.+ // An active access grant with export=true for the statement satisfies bb.sql.export on its target databases.Export(context.Context, *ExportRequest) (*ExportResponse, error)mustEmbedUnimplementedSQLServiceServer()}diff --git a/backend/generated-go/v1/v1connect/sql_service.connect.go b/backend/generated-go/v1/v1connect/sql_service.connect.goindex cc7fde62a1..d0370fdee9 100644--- a/backend/generated-go/v1/v1connect/sql_service.connect.go+++ b/backend/generated-go/v1/v1connect/sql_service.connect.go@@ -80,7 +80,8 @@ type SQLServiceClient interface {// Deprecated: do not use.GetQueryHistory(context.Context, *connect.Request[v1.GetQueryHistoryRequest]) (*connect.Response[v1.QueryHistory], error)// Exports query results to a file format.- // Permissions required: bb.databases.get+ // Permissions required: bb.databases.get, and bb.sql.export on the data the statement reads.+ // An active access grant with export=true for the statement satisfies bb.sql.export on its target databases.Export(context.Context, *connect.Request[v1.ExportRequest]) (*connect.Response[v1.ExportResponse], error)}@@ -210,7 +211,8 @@ type SQLServiceHandler interface {// Deprecated: do not use.GetQueryHistory(context.Context, *connect.Request[v1.GetQueryHistoryRequest]) (*connect.Response[v1.QueryHistory], error)// Exports query results to a file format.- // Permissions required: bb.databases.get+ // Permissions required: bb.databases.get, and bb.sql.export on the data the statement reads.+ // An active access grant with export=true for the statement satisfies bb.sql.export on its target databases.Export(context.Context, *connect.Request[v1.ExportRequest]) (*connect.Response[v1.ExportResponse], error)}diff --git a/backend/migrator/migration/3.25/0000##sql_export_permission.sql b/backend/migrator/migration/3.25/0000##sql_export_permission.sqlnew file mode 100644index 0000000000..4c1532c2c5--- /dev/null+++ b/backend/migrator/migration/3.25/0000##sql_export_permission.sql@@ -0,0 +1,35 @@+DO $$+DECLARE+ conflicting_workspace text;+BEGIN+ SELECT workspace INTO conflicting_workspace FROM role WHERE resource_id = 'sqlEditorExporter';+ IF FOUND THEN+ RAISE EXCEPTION 'custom role "sqlEditorExporter" in workspace "%" conflicts with a new built-in role. On the previous Bytebase version, create a replacement custom role, move its bindings, and delete "sqlEditorExporter".', conflicting_workspace;+ END IF;+END $$;++CREATE TEMP TABLE approval_only_workspace ON COMMIT DROP AS+SELECT workspace FROM policy+WHERE resource_type = 'WORKSPACE' AND type = 'QUERY_DATA'+ AND COALESCE((payload ->> 'disableExport')::boolean, false);++WITH added AS (+ SELECT p.workspace, p.resource_type, p.resource,+ jsonb_agg(jsonb_set(b, '{role}', '"roles/sqlEditorExporter"') ORDER BY ord) AS bindings+ FROM policy p,+ jsonb_array_elements(p.payload -> 'bindings') WITH ORDINALITY AS t(b, ord)+ WHERE p.type = 'IAM'+ AND p.resource_type IN ('WORKSPACE', 'PROJECT')+ AND p.workspace NOT IN (SELECT workspace FROM approval_only_workspace)+ AND b ->> 'role' IN ('roles/sqlEditorUser', 'roles/sqlEditorReadUser')+ GROUP BY p.workspace, p.resource_type, p.resource+)+UPDATE policy p+SET payload = jsonb_set(p.payload, '{bindings}', (p.payload -> 'bindings') || added.bindings)+FROM added+WHERE p.type = 'IAM' AND p.workspace = added.workspace+ AND p.resource_type = added.resource_type AND p.resource = added.resource;++UPDATE policy+SET payload = payload - 'disableExport'+WHERE type = 'QUERY_DATA' AND payload ? 'disableExport';diff --git a/backend/migrator/migration_test.go b/backend/migrator/migration_test.goindex ca5e5f2863..05e13c0027 100644--- a/backend/migrator/migration_test.go+++ b/backend/migrator/migration_test.go@@ -2,6 +2,7 @@ package migrator_testimport ("context"+ "database/sql""testing""github.com/stretchr/testify/require"@@ -89,3 +90,167 @@ func TestMigration3_24_2_OracleTLSOff(t *testing.T) {require.JSONEq(t, want, got, resourceID)}}++func TestMigration3_25_0_SQLExportPermission(t *testing.T) {+ ctx := context.Background()+ _, db := testcontainer.NewPgDatabase(t)+ createMigration3_25_0Tables(ctx, t, db)+ _, err := db.ExecContext(ctx, `+ INSERT INTO role (resource_id, workspace, permissions) VALUES+ ('export-select', 'ws-export', '{"permissions":["bb.databases.get","bb.sql.select"]}'),+ ('export-no-select', 'ws-export', '{"permissions":["bb.databases.get","bb.sql.info"]}'),+ ('export-already', 'ws-export', '{"permissions":["bb.sql.select","bb.sql.export"]}'),+ ('approval-select', 'ws-approval', '{"permissions":["bb.databases.get","bb.sql.select"]}'),+ ('approval-no-select', 'ws-approval', '{"permissions":["bb.databases.get"]}'),+ ('unenforced-select', 'ws-unenforced', '{"permissions":["bb.sql.select"]}'),+ ('unchanged-no-select', 'ws-unchanged', '{"permissions":["bb.databases.get"]}');+ `)+ require.NoError(t, err)+ _, err = db.ExecContext(ctx, `+ INSERT INTO policy (workspace, resource_type, resource, type, enforce, payload) VALUES+ ('ws-export', 'WORKSPACE', 'workspaces/ws-export', 'IAM', true, $1),+ ('ws-export', 'PROJECT', 'projects/export-project', 'IAM', true, $2),+ ('ws-export', 'WORKSPACE', 'workspaces/ws-export', 'QUERY_DATA', true, '{"maximumResultRows":100,"disableCopyData":true}'),+ ('ws-export', 'PROJECT', 'projects/export-project', 'QUERY_DATA', true, '{"maximumResultRows":50,"disableExport":true}'),+ ('ws-approval', 'WORKSPACE', 'workspaces/ws-approval', 'IAM', true, $3),+ ('ws-approval', 'PROJECT', 'projects/approval-project', 'IAM', true, $4),+ ('ws-approval', 'WORKSPACE', 'workspaces/ws-approval', 'QUERY_DATA', true, '{"disableExport":true,"maximumResultRows":10,"allowAdminDataSource":true}'),+ ('ws-unenforced', 'PROJECT', 'projects/unenforced-project', 'IAM', true, $5),+ ('ws-unenforced', 'WORKSPACE', 'workspaces/ws-unenforced', 'QUERY_DATA', false, '{"disableExport":true,"disableCopyData":true}'),+ ('ws-unchanged', 'WORKSPACE', 'workspaces/ws-unchanged', 'IAM', true, $6),+ ('ws-unchanged', 'WORKSPACE', 'workspaces/ws-unchanged', 'QUERY_DATA', true, '{"maximumResultRows":5}');+ `,+ migration3_25_0WorkspaceIAM,+ migration3_25_0ProjectIAM,+ migration3_25_0WorkspaceIAM,+ migration3_25_0ProjectIAM,+ `{"bindings":[{"role":"roles/sqlEditorReadUser","members":["groups/[email protected]"]}]}`,+ `{"bindings":[{"role":"roles/workspaceMember","members":["allUsers"]}]}`,+ )+ require.NoError(t, err)++ rolePermissions := func() map[string]string {+ rows, err := db.QueryContext(ctx, `SELECT resource_id, permissions::text FROM role`)+ require.NoError(t, err)+ defer rows.Close()+ permissions := map[string]string{}+ for rows.Next() {+ var role, text string+ require.NoError(t, rows.Scan(&role, &text))+ permissions[role] = text+ }+ require.NoError(t, rows.Err())+ return permissions+ }+ rolesBefore := rolePermissions()+ require.Len(t, rolesBefore, 7)++ require.NoError(t, runMigration3_25_0SQL(ctx, db))++ require.Equal(t, rolesBefore, rolePermissions(), "the migration does not change custom roles")++ type policyKey struct{ workspace, resource, policyType string }+ type policyWant struct {+ enforce bool+ payload string+ }+ for key, want := range map[policyKey]policyWant{+ {"ws-export", "workspaces/ws-export", "IAM"}: {true, `{"bindings":[+ {"role":"roles/workspaceMember","members":["allUsers"]},+ {"role":"roles/sqlEditorUser","members":["users/[email protected]"],"condition":{"title":"prod app","expression":"resource.database in [\"instances/prod/databases/app\"] && request.time < timestamp(\"2027-01-01T00:00:00Z\")"}},+ {"role":"roles/sqlEditorReadUser","members":["groups/[email protected]"]},+ {"role":"roles/sqlEditorExporter","members":["users/[email protected]"],"condition":{"title":"prod app","expression":"resource.database in [\"instances/prod/databases/app\"] && request.time < timestamp(\"2027-01-01T00:00:00Z\")"}},+ {"role":"roles/sqlEditorExporter","members":["groups/[email protected]"]}]}`},+ {"ws-export", "projects/export-project", "IAM"}: {true, `{"bindings":[+ {"role":"roles/projectDeveloper","members":["users/[email protected]"]},+ {"role":"roles/sqlEditorReadUser","members":["groups/[email protected]"]},+ {"role":"roles/sqlEditorUser","members":["users/[email protected]","allUsers"],"condition":{"expression":"resource.database == \"instances/prod/databases/app\" && resource.schema_name == \"public\" && resource.table_name in [\"orders\"]"}},+ {"role":"roles/sqlEditorExporter","members":["groups/[email protected]"]},+ {"role":"roles/sqlEditorExporter","members":["users/[email protected]","allUsers"],"condition":{"expression":"resource.database == \"instances/prod/databases/app\" && resource.schema_name == \"public\" && resource.table_name in [\"orders\"]"}}]}`},+ {"ws-export", "workspaces/ws-export", "QUERY_DATA"}: {true, `{"maximumResultRows":100,"disableCopyData":true}`},+ {"ws-export", "projects/export-project", "QUERY_DATA"}: {true, `{"maximumResultRows":50}`},+ {"ws-approval", "workspaces/ws-approval", "IAM"}: {true, migration3_25_0WorkspaceIAM},+ {"ws-approval", "projects/approval-project", "IAM"}: {true, migration3_25_0ProjectIAM},+ {"ws-approval", "workspaces/ws-approval", "QUERY_DATA"}: {true, `{"maximumResultRows":10,"allowAdminDataSource":true}`},+ {"ws-unenforced", "projects/unenforced-project", "IAM"}: {true, `{"bindings":[{"role":"roles/sqlEditorReadUser","members":["groups/[email protected]"]}]}`},+ {"ws-unenforced", "workspaces/ws-unenforced", "QUERY_DATA"}: {false, `{"disableCopyData":true}`},+ {"ws-unchanged", "workspaces/ws-unchanged", "IAM"}: {true, `{"bindings":[{"role":"roles/workspaceMember","members":["allUsers"]}]}`},+ {"ws-unchanged", "workspaces/ws-unchanged", "QUERY_DATA"}: {true, `{"maximumResultRows":5}`},+ } {+ var enforce bool+ var payload string+ require.NoError(t, db.QueryRowContext(ctx,+ `SELECT enforce, payload::text FROM policy WHERE workspace = $1 AND resource = $2 AND type = $3`,+ key.workspace, key.resource, key.policyType,+ ).Scan(&enforce, &payload))+ require.Equal(t, want.enforce, enforce, key)+ require.JSONEq(t, want.payload, payload, key)+ }+}++func TestMigration3_25_0_SQLEditorExporterIDCollision(t *testing.T) {+ ctx := context.Background()+ _, db := testcontainer.NewPgDatabase(t)+ createMigration3_25_0Tables(ctx, t, db)+ _, err := db.ExecContext(ctx, `+ INSERT INTO role (resource_id, workspace, permissions) VALUES+ ('sqlEditorExporter', 'ws-export', '{"permissions":["bb.sql.select"]}');+ `)+ require.NoError(t, err)++ err = runMigration3_25_0SQL(ctx, db)+ require.ErrorContains(t, err, `custom role "sqlEditorExporter" in workspace "ws-export" conflicts with a new built-in role`)++ var got string+ require.NoError(t, db.QueryRowContext(ctx, `SELECT permissions::text FROM role WHERE resource_id = 'sqlEditorExporter'`).Scan(&got))+ require.JSONEq(t, `{"permissions":["bb.sql.select"]}`, got)+}++const (+ migration3_25_0WorkspaceIAM = `{"bindings":[+ {"role":"roles/workspaceMember","members":["allUsers"]},+ {"role":"roles/sqlEditorUser","members":["users/[email protected]"],"condition":{"title":"prod app","expression":"resource.database in [\"instances/prod/databases/app\"] && request.time < timestamp(\"2027-01-01T00:00:00Z\")"}},+ {"role":"roles/sqlEditorReadUser","members":["groups/[email protected]"]}]}`+ migration3_25_0ProjectIAM = `{"bindings":[+ {"role":"roles/projectDeveloper","members":["users/[email protected]"]},+ {"role":"roles/sqlEditorReadUser","members":["groups/[email protected]"]},+ {"role":"roles/sqlEditorUser","members":["users/[email protected]","allUsers"],"condition":{"expression":"resource.database == \"instances/prod/databases/app\" && resource.schema_name == \"public\" && resource.table_name in [\"orders\"]"}}]}`+)++func createMigration3_25_0Tables(ctx context.Context, t *testing.T, db *sql.DB) {+ t.Helper()+ _, err := db.ExecContext(ctx, `+ CREATE TABLE role (+ resource_id text NOT NULL PRIMARY KEY,+ workspace text NOT NULL,+ permissions jsonb NOT NULL DEFAULT '{}'+ );+ CREATE TABLE policy (+ enforce boolean NOT NULL DEFAULT TRUE,+ workspace text NOT NULL,+ resource_type text NOT NULL,+ resource text NOT NULL,+ type text NOT NULL,+ payload jsonb NOT NULL DEFAULT '{}',+ PRIMARY KEY (workspace, resource_type, resource, type)+ );+ `)+ require.NoError(t, err)+}++// runMigration3_25_0SQL runs the file in one transaction, as the migrator does.+func runMigration3_25_0SQL(ctx context.Context, db *sql.DB) error {+ statement, err := migrator.MigrationFS.ReadFile("migration/3.25/0000##sql_export_permission.sql")+ if err != nil {+ return err+ }+ tx, err := db.BeginTx(ctx, nil)+ if err != nil {+ return err+ }+ defer tx.Rollback()+ if _, err := tx.ExecContext(ctx, string(statement)); err != nil {+ return err+ }+ return tx.Commit()+}diff --git a/backend/migrator/migrator_test.go b/backend/migrator/migrator_test.goindex 8f04edd61c..d2de4902ef 100644--- a/backend/migrator/migrator_test.go+++ b/backend/migrator/migrator_test.go@@ -10,8 +10,8 @@ import (func TestLatestVersion(t *testing.T) {files, err := getSortedVersionedFiles()require.NoError(t, err)- require.Equal(t, semver.MustParse("3.24.2"), *files[len(files)-1].version)- require.Equal(t, "migration/3.24/0002##oracle_tls_off.sql", files[len(files)-1].path)+ require.Equal(t, semver.MustParse("3.25.0"), *files[len(files)-1].version)+ require.Equal(t, "migration/3.25/0000##sql_export_permission.sql", files[len(files)-1].path)}func TestVersionUnique(t *testing.T) {diff --git a/backend/store/policy.go b/backend/store/policy.goindex 6862bb2dff..8ff42cccd0 100644--- a/backend/store/policy.go+++ b/backend/store/policy.go@@ -384,7 +384,6 @@ type EffectiveQueryDataPolicy struct {MaximumResultSize int64MaximumResultRows int32DisableCopyData bool- DisableExport boolMaxQueryTimeoutInSeconds int64AllowAdminDataSource bool}@@ -398,7 +397,6 @@ func formatEffectiveQueryDataPolicy(policy *storepb.QueryDataPolicy) *EffectiveQreturn &EffectiveQueryDataPolicy{MaximumResultRows: maximumResultRows,DisableCopyData: policy.GetDisableCopyData(),- DisableExport: policy.GetDisableExport(),AllowAdminDataSource: policy.GetAllowAdminDataSource(),}}@@ -429,7 +427,6 @@ func (s *Store) GetEffectiveQueryDataPolicy(ctx context.Context, workspaceID strreturn &EffectiveQueryDataPolicy{DisableCopyData: formatWorkspacePolicy.DisableCopyData,- DisableExport: formatWorkspacePolicy.DisableExport,MaximumResultRows: min(formatWorkspacePolicy.MaximumResultRows, formatProjectPolicy.MaximumResultRows),MaximumResultSize: maximumResultSize,MaxQueryTimeoutInSeconds: queryTimeout,diff --git a/backend/store/predefined_roles.go b/backend/store/predefined_roles.goindex 5a2c9a4edd..ed0cc452ec 100644--- a/backend/store/predefined_roles.go+++ b/backend/store/predefined_roles.go@@ -11,6 +11,7 @@ const (ProjectDeveloperRole = "projectDeveloper"SQLEditorUserRole = "sqlEditorUser"SQLEditorReadUserRole = "sqlEditorReadUser"+ SQLEditorExporterRole = "sqlEditorExporter"ProjectReleaserRole = "projectReleaser"GitOpsServiceAgentRole = "gitopsServiceAgent"ProjectViewerRole = "projectViewer"@@ -149,6 +150,7 @@ var PredefinedRoles = []*RoleMessage{permission.SQLDdl,permission.SQLDml,permission.SQLExplain,+ permission.SQLExport,permission.SQLInfo,permission.SQLSelect,permission.UsersCreate,@@ -295,6 +297,7 @@ var PredefinedRoles = []*RoleMessage{permission.SQLDdl,permission.SQLDml,permission.SQLExplain,+ permission.SQLExport,permission.SQLInfo,permission.SQLSelect,permission.UsersGet,@@ -431,6 +434,7 @@ var PredefinedRoles = []*RoleMessage{permission.SQLDdl,permission.SQLDml,permission.SQLExplain,+ permission.SQLExport,permission.SQLInfo,permission.SQLSelect,permission.UsersGet,@@ -551,6 +555,29 @@ var PredefinedRoles = []*RoleMessage{permission.SavedQueriesSearch,),},+ {+ ResourceID: SQLEditorExporterRole,+ Name: "SQL Editor Exporter",+ Predefined: true,+ Permissions: permissionSet(+ permission.DatabaseCatalogsGet,+ permission.DatabaseGroupsGet,+ permission.DatabaseGroupsList,+ permission.DatabasesCheck,+ permission.DatabasesGet,+ permission.DatabasesGetSchema,+ permission.DatabasesList,+ permission.DatabasesSync,+ permission.ProjectsGet,+ permission.ProjectsGetIAMPolicy,+ permission.SQLExplain,+ permission.SQLExport,+ permission.SQLInfo,+ permission.SQLSelect,+ permission.SavedQueriesCreate,+ permission.SavedQueriesSearch,+ ),+ },{ResourceID: ProjectReleaserRole,Name: "Project releaser",diff --git a/backend/store/predefined_roles_test.go b/backend/store/predefined_roles_test.goindex 47eb9764df..526c91c97c 100644--- a/backend/store/predefined_roles_test.go+++ b/backend/store/predefined_roles_test.go@@ -1,6 +1,7 @@package storeimport (+ "maps""testing""github.com/stretchr/testify/require"@@ -27,6 +28,34 @@ func TestProjectOwnerInstancePermissions(t *testing.T) {}}+func TestSQLEditorExporterRole(t *testing.T) {+ t.Parallel()+ exporter := GetPredefinedRole(SQLEditorExporterRole)+ require.NotNil(t, exporter)+ require.Equal(t, "SQL Editor Exporter", exporter.Name)++ want := maps.Clone(GetPredefinedRole(SQLEditorReadUserRole).Permissions)+ want[permission.SQLExport] = true+ require.Equal(t, want, exporter.Permissions)+ for p := range exporter.Permissions {+ require.Truef(t, permission.Exists(p), "permission %s is not defined in permission.yaml", p)+ }+}++func TestPredefinedRolesSQLExport(t *testing.T) {+ t.Parallel()+ for roleID, want := range map[string]bool{+ WorkspaceAdminRole: true,+ WorkspaceDBARole: true,+ ProjectOwnerRole: true,+ SQLEditorExporterRole: true,+ SQLEditorUserRole: false,+ SQLEditorReadUserRole: false,+ } {+ require.Equalf(t, want, GetPredefinedRole(roleID).Permissions[permission.SQLExport], "role %s", roleID)+ }+}+// Test that every permission in predefined roles is also defined in permission.yaml.func TestPredefinedRolesPermissionsExist(t *testing.T) {t.Parallel()diff --git a/backend/tests/mcp_sql_export_test.go b/backend/tests/mcp_sql_export_test.gonew file mode 100644index 0000000000..6c56b376c1--- /dev/null+++ b/backend/tests/mcp_sql_export_test.go@@ -0,0 +1,52 @@+package tests++import (+ "context"+ "net/http"+ "testing"++ "connectrpc.com/connect"+ "github.com/stretchr/testify/require"++ v1pb "github.com/bytebase/bytebase/backend/generated-go/v1"+)++func TestMCPExportRefusalIsPermissionDenied(t *testing.T) {+ t.Parallel()+ a := require.New(t)+ ctl, ctx := startWorkspace(context.Background(), t)+ f := setupMCPClampFixture(ctx, t, ctl)+ // Export is a WRITE-class method.+ a.NoError(ctl.setMCPCapability(ctx, v1pb.MCPSetting_READ_WRITE))++ const readerEmail = "[email protected]"+ const readerPassword = "1024bytebase"+ reader, err := ctl.userServiceClient.CreateUser(ctx, connect.NewRequest(&v1pb.CreateUserRequest{+ User: &v1pb.User{Title: "export reader", Email: readerEmail, Password: readerPassword},+ }))+ a.NoError(err)+ _, err = ctl.addMemberToWorkspaceIAM(ctx, reader.Msg.Workspace, "user:"+readerEmail, "roles/workspaceMember")+ a.NoError(err)+ addProjectRole := func(role string) {+ policy, err := ctl.projectServiceClient.GetIamPolicy(ctx, connect.NewRequest(&v1pb.GetIamPolicyRequest{Resource: ctl.project.Name}))+ a.NoError(err)+ policy.Msg.Bindings = append(policy.Msg.Bindings, &v1pb.Binding{Role: role, Members: []string{"user:" + readerEmail}})+ _, err = ctl.projectServiceClient.SetIamPolicy(ctx, connect.NewRequest(&v1pb.SetIamPolicyRequest{Resource: ctl.project.Name, Policy: policy.Msg}))+ a.NoError(err)+ }+ addProjectRole("roles/sqlEditorReadUser")++ login, err := ctl.authServiceClient.Login(ctx, connect.NewRequest(&v1pb.LoginRequest{Email: readerEmail, Password: readerPassword}))+ a.NoError(err)+ session := openMCPSession(ctx, t, ctl, login.Msg.Token)+ defer session.Close()++ export := map[string]any{"name": f.database, "statement": "SELECT id FROM employee", "format": "CSV"}+ refused := callAPIOnSession(ctx, t, session, "SQLService/Export", export)+ a.Equal(http.StatusForbidden, refused.Status, refused.Error)+ a.Contains(refused.Error, "permission denied to access resources")++ addProjectRole("roles/sqlEditorExporter")+ served := callAPIOnSession(ctx, t, session, "SQLService/Export", export)+ a.Equal(http.StatusOK, served.Status, served.Error)+}diff --git a/docs/adr/0006-control-export-with-a-permission.md b/docs/adr/0006-control-export-with-a-permission.mdnew file mode 100644index 0000000000..7044bc6174--- /dev/null+++ b/docs/adr/0006-control-export-with-a-permission.md@@ -0,0 +1,19 @@+# Control export with a permission and remove disable_export++Design: [sql-export-permission.md](../design/sql-export-permission.md)++The Export Permission (`bb.sql.export`) is the only control over who may export, held through a role binding or an Access Grant. The workspace flag `disable_export`, which meant "export requires approval", is removed: requiring approval is now expressed by assigning roles without the permission, so the flag would be a second control for the same decision. If a switch that stops all export is ever needed, it gets a new field rather than a new meaning for `disable_export`.++The upgrade keeps export for SQL Editor users. Workspaces whose workspace-level policy sets `disable_export = true` get no new standing export, so approval stays the only export path for ordinary users. Every other workspace gets a SQL Editor Exporter binding beside each SQL Editor binding, so SQL Editor users keep export. Custom roles are not changed.++## Considered options++- **Keep `disable_export` and redefine it as "no export at all".** Rejected because export would have two overlapping controls, and a stale write of `true`, which meant "approval required", would silently stop all export.+- **Turn export off where the flag was `true`.** Rejected because those administrators chose approval-gated export.+- **Ignore writes of `disable_export = true`.** Rejected because a stale config would never learn the setting is gone. The server rejects them instead.++## Consequences++- Workspace Admin, Workspace DBA and Project Owner hold the Export Permission in every workspace. Where `disable_export` was `true`, they used to need an approved grant, which they could approve themselves, and now export directly. The release note must state this.+- No single switch stops all export in a workspace.+- Where `disable_export` was not set, holders of custom roles with `bb.sql.select` lose export until an administrator adds the Export Permission to the role. The release note must state this.diff --git a/docs/design/mcp-capability-ladder.md b/docs/design/mcp-capability-ladder.mdindex a23fb6b58a..bb07600e8f 100644--- a/docs/design/mcp-capability-ladder.md+++ b/docs/design/mcp-capability-ladder.md@@ -77,7 +77,7 @@ the product.| write | Approve or reject issues | Each decision is confirmed in the user's MCP client before it is made · Role requests are decided in the console · The approval rules and the project's self-approval setting apply, as in the console | 2 WRITE methods: `ApproveIssue`, `RejectIssue`, served only through the `decide_issue` tool, which asks the user to confirm each decision and refuses role requests || 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 | Export query results | Download results as a file. Data leaves Bytebase | 1 WRITE method: `SQLService/Export`, which requires the user's own `bb.sql.export` on the data it reads, from a role or a matching export grant || write | Manage database housekeeping | Sync instances and databases · Saved queries | 9 WRITE methods: sync, saved-query writes || — | *Read-write stops here* | | 110 methods || floor | Never, in any mode: administer the workspace, handle credentials, open an Admin mode session, or read anyone else's query history. | | 109 methods: 34 FORBIDDEN, 75 EXCLUDED |diff --git a/docs/design/sql-export-permission.md b/docs/design/sql-export-permission.mdnew file mode 100644index 0000000000..2c18e67e33--- /dev/null+++ b/docs/design/sql-export-permission.md@@ -0,0 +1,473 @@+# Restore `bb.sql.export` and remove `disable_export`++- Status: proposal for review+- Date: 2026-10-28+- Tracking issue: TBD+- Decision record: [ADR 0006](../adr/0006-control-export-with-a-permission.md)+- Line references point at `afffc8914a`.++## Decision++- **Who** may export is controlled by `bb.sql.export` alone. `SQLService.Export` requires it on+ the data it reads, checked with the same database, schema, table and expiration conditions as+ `bb.sql.select`. Export does not also require `bb.sql.select`.+- A user holds `bb.sql.export` through a role binding (standing) or through an active access+ grant with `export: true` for the exact query (temporary, approved).+- `disable_export` is removed. The workspace setting disappears from the UI, the server stops+ storing the value, and the migration strips it from stored policies. The v1 field stays,+ deprecated, until a later release deletes it: reads return `false`, and writes that set it to+ `true` are rejected with a message that points to export roles.+- A new built-in role, **SQL Editor Exporter** (`roles/sqlEditorExporter`), holds SQL Editor Read+ User's permissions plus `bb.sql.export`. Workspace Admin, Workspace DBA and Project Owner also+ hold `bb.sql.export`. SQL Editor User and SQL Editor Read User do not.+- The server enforces the permission for every caller: console, API and MCP.+- A one-time migration keeps export for users who export today through SQL Editor User or SQL+ Editor Read User. Workspaces that allow export without approval give those users a SQL Editor+ Exporter binding. Workspaces that require approval get no new standing export, so approved+ access grants stay the only export path for ordinary users. The migration does not change+ custom roles: holders of custom roles with `bb.sql.select` lose export until an administrator+ adds `bb.sql.export` to the role.++## Background++Bytebase removed `bb.sql.export` and `roles/projectExporter` in #17470. Today:++- `Export` is gated at the interceptor by `bb.databases.get` only+ (`proto/v1/v1/sql_service.proto:89`). Past that, it runs the same per-statement check as+ `Query` (`backend/api/v1/sql_service.go:1629`), so anyone who can run a `SELECT` can export+ its result.+- `disable_export` is a workspace-level flag, labeled "Allow data export without approval" in+ workspace settings. Turning that toggle off sets the flag. With the flag set, the SQL Editor+ hides the Export button unless the user holds an active export grant for the query, and offers+ "Request export" instead (`frontend/src/modules/sql-editor/components/ResultView/ResultView.tsx:154`,+ `ResultPanel/BatchQuerySelect.tsx:167`). There is no administrator exemption. The flag therefore+ means "export requires approval", and it is only a UI rule: the backend never reads it, so the+ API and MCP export with it set. The 2026-09 API audit lists this as X1+ (`docs/design/v1-api-audit-2026-09.md:116`).+- An access grant with `export: true` skips the role check on its target databases+ (`sql_service.go:1176`, `:1564`). The `export` field exists because there was no export+ permission for the grant to stand in for.++An administrator therefore cannot say "this person may query but not export". The one export+control that exists applies to every user at once and is not enforced. Once `bb.sql.export`+exists, "export requires approval" is expressed by assigning roles without it, and the flag has+nothing left to decide.++## Goals++- Control who may export per person and per database, schema and table, like query access.+- Enforce it on the server for every caller.+- Keep one control for export: role bindings and access grants, with no workspace flag that+ overlaps them.+- On upgrade, keep export for users who export through SQL Editor User or SQL Editor Read User:+ standing export where the workspace allows export without approval, and approval-only export+ where it requires approval. Holders of custom roles with `bb.sql.select` lose export until an+ administrator adds `bb.sql.export` to the role.++## Non-goals++- A workspace switch that turns off all export. If customers ask for one, it gets a new field;+ `disable_export` is not reused.+- Non-local export destinations and their settings, such as `disable_local_export`.+- Per-export row limits as a role condition (`request.row_limit` in the 2025 model). Row and+ size caps stay in `QueryDataPolicy`.+- Changing how `Query` is authorized.+- Downgrading after the migration. It is not supported.++## Product behavior++### Who can export++| Role | `bb.sql.export` | Reason |+|---|---|---|+| Workspace Admin, Workspace DBA, Project Owner | Yes | All three hold `bb.projects.setIamPolicy` and could grant it to themselves. Withholding it would be cosmetic. |+| SQL Editor User, SQL Editor Read User | No | Export becomes an explicit grant. |+| SQL Editor Exporter (new) | Yes | "Query databases and export results, without DDL or DML access." |+| Custom roles | As configured | The migration does not change custom roles. |++SQL Editor Exporter can be stacked on SQL Editor User to add export to someone who can write.++A custom role with `bb.sql.export` but no `bb.sql.select` is valid. Its holder can export through+the API or MCP but not from the SQL Editor, where Export works on a query result.++To require approval for export, an administrator assigns roles without `bb.sql.export`. Users+then request export through an access grant in projects with just-in-time access enabled+(Enterprise plan).++### Removing the workspace setting++- The workspace SQL Editor setting "Allow data export without approval" is removed.+- `GetPolicy` returns `disable_export = false` for every query data policy.+- `UpdatePolicy` accepts `disable_export = false` and ignores it. It rejects `true` with+ `INVALID_ARGUMENT`: "disable_export is removed. Export requires the bb.sql.export permission;+ to require approval for export, assign roles without it." A stale Terraform config or script+ therefore fails at apply with instructions, instead of showing a diff that never converges.++### SQL Editor++| Holds `bb.sql.export` (role or matching grant) | Project allows just-in-time access | Result panel shows |+|---|---|---|+| Yes | Either | Export |+| No | Yes | Request export |+| No | No | Neither |++The SQL Editor checks `bb.sql.export` per database, including database-scoped binding conditions.+Schema and table conditions are checked only by the server, and a denied export shows its error.++### Access grants++An approved grant with `export: true` gives `bb.sql.export` for one read-only query on its target+databases until it expires. Requests follow existing rules:++- Creating a request needs `bb.accessGrants.create` (held by Workspace Member, so every user) and+ a project with just-in-time access enabled.+- Approval rules can route export requests with `request.data_export`.+- Activating a grant directly needs `bb.accessGrants.activate`. Only Admin, DBA and Project Owner+ hold it, and all three already hold `bb.sql.export`.++### Assigning roles++- Member forms offer database scoping for roles with `bb.sql.export`, as they do for+ `bb.sql.select`.+- Workspace setup gives invitees SQL Editor Exporter instead of SQL Editor Read User, alongside+ Project Developer, so invitees in new workspaces export as they do today+ (`frontend/src/routes/auth/workspace-setup/finish.ts:90`).+- "Request query" keeps requesting SQL Editor Read User.++## Technical design++### Permission and roles++- Add `SQLExport = "bb.sql.export"` to `backend/common/permission/permission.go` and+ `permission.yaml`. Custom-role validation reads the YAML, so `CreateRole` and `UpdateRole`+ accept it with no further change.+- In `backend/store/predefined_roles.go`, add `SQLExport` to Workspace Admin, Workspace DBA and+ Project Owner, and add `SQLEditorExporterRole = "sqlEditorExporter"`.+- The frontend permission union is generated from the YAML+ (`frontend/src/types/iam/permission-generated.ts`).++### Export check++The per-statement access check runs with an export flag, captured in the `accessCheckWithGrant`+closure so `accessCheckFunc` keeps its signature.++| Statement type | `Query` (unchanged) | `Export` |+|---|---|---|+| Select, including column-level checks | `bb.sql.select` | `bb.sql.export` |+| Info schema (`SHOW` and similar) | `bb.sql.info` | `bb.sql.export` |+| Unknown on engines without the new ACL (select fallback) | `bb.sql.select` | `bb.sql.export` |+| No spans (engines without a span extractor, `sql_service.go:1613`) | `bb.sql.select` | `bb.sql.export` |+| Explain | `bb.sql.explain` | `bb.sql.explain` |+| DML, DDL | `bb.sql.dml`, `bb.sql.ddl` | Unchanged |++Explain keeps `bb.sql.explain` because its output is a plan, not table data, and grants still do+not cover it. `EXPLAIN ANALYZE` checks its statement, so its reads require `bb.sql.export`.++On engines that classify statements, DML and DDL keep their own permissions, so `Export` does+not become a way to change data. This matters on MySQL, where `Export` skips read-only+validation (`sql_service.go:1180`). Engines with neither statement classification nor a+validator are an existing exception: on Databricks, a write produces no spans and passes the+database-level select check through both `Query` and `Export` today+(`docs/design/mcp-capability-ladder.md:160`). Under this design `Export` checks `bb.sql.export`+there, so an export-only custom role can run such a write through `Export`, as a select role can+today. The read-only clamp on `Export` that the ladder doc tracks closes it for both.++The CEL input is unchanged: database, schema and table per source column (`sql_service.go:1756`),+and the database-level fallback. `hasDatabaseAccessRights` strips the environment condition for+non-DDL/DML permissions today, and `bb.sql.export` is treated the same way.++An export grant satisfies `bb.sql.export` on its target databases. It is looked up with+`requireExport=true`, as today. The code should express this as "the grant satisfies+`bb.sql.export`" rather than "the grant skips the role check", so a later export rule applies to+grant holders too.++### API and docs++- `proto/v1/v1/org_policy_service.proto`: mark `disable_export` `[deprecated = true]` with the comment+ "Deprecated: export is controlled by the bb.sql.export permission. Always false; setting it to+ true is rejected." `convertToQueryDataPolicyPayload` rejects `true` and drops the value. Delete+ the field in a later release, after the provider stops sending it.+- `proto/store/store/policy.proto`: delete `disable_export` and reserve field 2 and its name. Remove+ `DisableExport` from `store.EffectiveQueryDataPolicy` and the v1 converter.+- `proto/v1/v1/sql_service.proto`: document that `Export` requires `bb.sql.export`.+- `proto/v1/v1/access_grant_service.proto`: the `export` field "grants `bb.sql.export` for this+ query until the grant expires."+- `proto/v1/v1/iam_policy.proto`: list export in the roles that `resource.*` conditions apply to.+- Remove the stale `roles/EXPORTER` examples in `issue_service.proto` and `store/issue.proto`,+ and the "EXPORTER role" comment at `sql_service.go:1227`.+- Mark X1 resolved and update line 680 of `docs/design/v1-api-audit-2026-09.md`.+- `Export` stays a WRITE-class MCP method. The export row in+ `docs/design/mcp-capability-ladder.md` should say the user's own `bb.sql.export` applies.++### Frontend++- Export gates in `ResultView.tsx` and `BatchQuerySelect.tsx` follow the SQL Editor table above.+ Standing export is decided per database with `isDatabaseV1Queryable(database, ["bb.sql.export"])`,+ and `useExportGrantBypass` runs for the databases that lack it, instead of when the flag is set.+- Remove the toggle from `routes/workspace/general/SQLEditorSection.tsx`, its "data-export"+ strings in all five locales (`frontend/src/locales/en-US.json`), and its tests.+- Remove `disableExport` from `useSQLEditorQueryDataPolicy`+ (`modules/sql-editor/hooks/useSQLEditorState.ts`).+- Add the new role to `types/iam/role.ts`, `lib/role.ts` and `utils/role.ts`, with strings in all+ five locales.+- Add `roles/sqlEditorExporter` to the role table in the agent's grant-permission skill+ (`modules/agent/logic/skills/grantPermission.ts`), so the agent can grant export.+- Add `bb.sql.export` to `roleHasDatabaseLimitation` in `lib/project-member/utils.ts`.+- Replace SQL Editor Read User with SQL Editor Exporter in `INVITEE_PROJECT_ROLES`+ (`routes/auth/workspace-setup/finish.ts`).++## Migration++One SQL file, `backend/migrator/migration/3.25/0000##sql_export_permission.sql`; 3.24.0 shipped+with `3.24/0000` to `0002`. Update `TestLatestVersion`. `LATEST.sql` does not change because+role permissions, IAM bindings and policies are JSONB. The migrator runs the file in one+transaction (`backend/migrator/migrator.go:227`).++A workspace is **approval-only** when its workspace-level `QUERY_DATA` policy stores+`disableExport = true`, whether or not it is enforced: `GetPolicy` ignores `enforce`+(`backend/store/policy.go:751`), so the SQL Editor honored the value either way. Every other+workspace is **export-enabled**.++Steps:++1. Fail if a custom role already uses the id `sqlEditorExporter`. Role ids are unique across+ workspaces (`LATEST.sql:98`), and built-in roles shadow custom roles with the same id+ (`backend/store/role.go:152`), so continuing would silently change that role's meaning. The+ new server cannot start until the conflict is gone, and a role id cannot be renamed, so the+ error message gives the fix: on the previous version, create a replacement custom role, move+ its bindings, and delete the conflicting role. Check Cloud data for the id before release.+2. In export-enabled workspaces, for every workspace or project IAM binding of SQL Editor User+ or SQL Editor Read User, add a SQL Editor Exporter binding with the same members and+ condition.+3. Remove the `disableExport` key from every `QUERY_DATA` policy, at workspace and project+ level, enforced or not.++Approval-only workspaces get no new bindings. Ordinary users there keep exporting only through+approved grants. Custom roles are not changed in any workspace. Built-in role definitions live in+Go and need no migration.++```sql+DO $$+DECLARE+ conflicting_workspace text;+BEGIN+ SELECT workspace INTO conflicting_workspace FROM role WHERE resource_id = 'sqlEditorExporter';+ IF FOUND THEN+ RAISE EXCEPTION 'custom role "sqlEditorExporter" in workspace "%" conflicts with a new built-in role. On the previous Bytebase version, create a replacement custom role, move its bindings, and delete "sqlEditorExporter".', conflicting_workspace;+ END IF;+END $$;++CREATE TEMP TABLE approval_only_workspace ON COMMIT DROP AS+SELECT workspace FROM policy+WHERE resource_type = 'WORKSPACE' AND type = 'QUERY_DATA'+ AND COALESCE((payload ->> 'disableExport')::boolean, false);++WITH added AS (+ SELECT p.workspace, p.resource_type, p.resource,+ jsonb_agg(jsonb_set(b, '{role}', '"roles/sqlEditorExporter"') ORDER BY ord) AS bindings+ FROM policy p,+ jsonb_array_elements(p.payload -> 'bindings') WITH ORDINALITY AS t(b, ord)+ WHERE p.type = 'IAM'+ AND p.resource_type IN ('WORKSPACE', 'PROJECT')+ AND p.workspace NOT IN (SELECT workspace FROM approval_only_workspace)+ AND b ->> 'role' IN ('roles/sqlEditorUser', 'roles/sqlEditorReadUser')+ GROUP BY p.workspace, p.resource_type, p.resource+)+UPDATE policy p+SET payload = jsonb_set(p.payload, '{bindings}', (p.payload -> 'bindings') || added.bindings)+FROM added+WHERE p.type = 'IAM' AND p.workspace = added.workspace+ AND p.resource_type = added.resource_type AND p.resource = added.resource;++UPDATE policy+SET payload = payload - 'disableExport'+WHERE type = 'QUERY_DATA' AND payload ? 'disableExport';+```++Copying the binding and changing only the role carries members (users, groups, `allUsers`) and+the condition over exactly, including database, schema, table and expiration scope. A member who+holds both SQL Editor roles receives two exporter bindings, which is harmless. Access grants and+approval rules are not touched.++### Resulting behavior++| Who | Export-enabled workspace | Approval-only workspace |+|---|---|---|+| SQL Editor User, SQL Editor Read User | Export, through the added binding | Request export, then export after approval (unchanged)* |+| Custom roles with `bb.sql.select` | No export until an admin adds `bb.sql.export` to the role | Request export (unchanged)* |+| Admin, DBA, Project Owner | Export | **Export without a grant** |+| Export grant holders | Export | Export (unchanged) |+| API and MCP callers | Same as the SQL Editor | **Same as the SQL Editor** |++\* In projects with just-in-time access enabled (Enterprise plan). Elsewhere, Request export is not+offered, as today.++### Accepted behavior changes++- Workspace Admin, Workspace DBA and Project Owner hold `bb.sql.export` in every workspace. In+ export-enabled workspaces they could already export, so nothing changes. In approval-only+ workspaces they needed an approved grant, which they could approve themselves, and now export+ directly. The release note must state this.+- In approval-only workspaces, API and MCP callers need `bb.sql.export` or a matching export+ grant, where before anyone with select could export. This closes X1.+- In export-enabled workspaces, holders of custom roles with `bb.sql.select` lose export until an+ administrator adds `bb.sql.export` to the role. The release note must state this.+- The workspace export setting is gone. To stop a user exporting, remove export from their+ roles; to stop export through grants in a project, turn off just-in-time access there. The+ release note must state this.+- Writes that set `disable_export = true` are rejected.+- Custom roles with `bb.sql.info` or `bb.sql.explain` but not `bb.sql.select` could export `SHOW`+ output before and cannot after. Giving them `bb.sql.export` would grant export of all data,+ which is broader than what they had.+- New SQL Editor User or Read User assignments, and role requests approved after the upgrade, do+ not include export. Assign SQL Editor Exporter as well.++## Terraform and compatibility++The Terraform provider manages the whole IAM policy of a parent through `bytebase_iam_policy`,+custom roles and their permission sets through `bytebase_role`, and `disable_export` through+`bytebase_policy`. The migration changes IAM policies and query data policies, so+`bytebase_iam_policy` and `bytebase_policy` can drift. It does not change custom roles.++- **IAM drift (export-enabled workspaces).** `terraform plan` wants to remove the added exporter+ bindings. Applying it takes export away from SQL Editor users. This failure removes access and+ never adds it, which is why the migration adds bindings instead of rewriting roles.+- **`disable_export` (approval-only workspaces).** A config that sets `disable_export = true` shows a+ `false → true` change, and applying it fails with the rejection message. A config that sets+ `false` keeps applying until the provider drops the attribute.+- **Order of operations.** A config cannot reference `roles/sqlEditorExporter` before the server+ knows the role.++Provider release, shipped with the server release:++- Mark `disable_export` deprecated in the provider schema, stop sending it, and document its+ removal.+- Document the paired binding pattern below and remove the obsolete export row-limit condition.+- Confirm that role names are not validated against a fixed list.++Upgrade runbook for Terraform users:++1. Pause automatic `terraform apply`.+2. Upgrade Bytebase.+3. Run `terraform plan`.+4. In export-enabled workspaces, add every exporter binding the plan wants to remove: for each+ SQL Editor binding that should keep export, a binding with the same members and condition and+ `role = "roles/sqlEditorExporter"`.+5. Remove `disable_export` from every `bytebase_policy` config.+6. Resume automatic apply when the plan is clean.++```hcl+binding {+ role = "roles/sqlEditorUser"+ members = ["group:[email protected]"]+ condition { database = "instances/prod/databases/app" }+}+binding {+ role = "roles/sqlEditorExporter"+ members = ["group:[email protected]"]+ condition { database = "instances/prod/databases/app" }+}+```++## Testing++- **Migration** (`backend/migrator/migration_test.go`): one export-enabled and one approval-only+ workspace, each with a custom role with and without `bb.sql.select`, a conditioned SQL Editor+ User binding, a group SQL Editor Read User binding, and workspace and project IAM policies.+ Include a third workspace with a non-enforced disabled policy, and a project-level query data+ policy that stores `disableExport`. Assert exact payloads: the approval-only workspace has no+ new bindings; the export-enabled workspace has the added bindings; the third workspace is+ treated as approval-only; every custom role, with or without `bb.sql.select`, is unchanged in+ every workspace; no query data policy keeps a `disableExport` key, their other fields and+ `enforce` are unchanged. Assert that the id collision raises.+- **Export authorization** (`backend/api/v1`):+ - A select-only user cannot export.+ - A user with only `bb.sql.export`, scoped to one table, exports that table, is refused on+ another table, and cannot `Query`.+ - An export grant allows export without the permission.+ - A role with `bb.sql.export` but no `bb.sql.dml` cannot run DML through `Export` on MySQL.+ - `Query` is unaffected.+- **Policy API** (`backend/api/v1`): `UpdatePolicy` rejects `disable_export = true` and accepts+ `false`; `GetPolicy` returns `false`.+- **Roles** (`backend/store`): the new built-in role exists and its permissions are valid.+- **Frontend**: `ResultView`, `BatchQuerySelect`, `useExportGrantBypass`, `RequestExportButton`,+ `SQLEditorSection`, the project-member utils and workspace setup. `ResultView.test.tsx` mocks+ every permission check as false today, so its cases need updating.+- **Provider**: a migrated binding round-trips through `bytebase_iam_policy`, and its CEL condition+ parses back into the same `database`, `schema` and `tables` fields.++## Alternatives considered++### Keep `disable_export` as a switch that turns off all export++The field would keep its name and change meaning from "export requires approval" to "no export+for anyone", including administrators and grant holders, with per-destination settings added+beside it later. This keeps a one-click stop for all export. It also gives export two controls+whose overlap administrators must reason about, and it changes what an existing field means: a+stale config or script that writes `true`, meaning "approval required" before the upgrade, would+silently stop all export after it. A kill switch can come later as a new field if customers ask.++### Enforce `disable_export` on the server with its current meaning++With the flag set, only grant holders could export, for every caller. This closes X1 without a+migration. It keeps a workspace-wide rule that decides who may export beside the role bindings+that also decide it, so "can this person export" would depend on both, and it still could not+express "this person may query but not export" in a workspace that allows export.++### Ignore writes of `disable_export = true`++Accepting and dropping the value keeps old configs applying. `terraform plan` would then show a+`false → true` change on every run, and the administrator is never told the setting is gone.++### Give `bb.sql.export` in every workspace++The migration could add exporter bindings in approval-only workspaces too. That would hand+standing export to every SQL Editor user in workspaces that chose to require approval.++### Add `bb.sql.export` to custom roles with select++This keeps export for holders of custom roles in export-enabled workspaces. It also rewrites+roles that administrators own, often through Terraform `bytebase_role`, whose next plan would+want to undo the change.++### Add an Exporter binding beside custom-role bindings++This keeps export without touching the roles. It also grants the rest of SQL Editor Exporter's+permissions (database sync, IAM policy read, explain, info, saved queries, database groups and+catalogs), which a narrow custom role may not include.++### Require `bb.sql.select` and `bb.sql.export`++Export would only narrow select, so "who can read this table" stays one question. We chose export+alone because it gives administrators one permission to reason about for export, and it matches+the 2025 model. The cost is that `bb.sql.export` is itself a read grant.++### Remove export from access grants++Users who need export would request SQL Editor Exporter through role requests, so bindings alone+answer who can export. An approved role covers every query in its scope rather than one, which+is broader than today's per-query grant. It also removes the "Request export" flow, which is the+only export path in approval-only workspaces, and empties `request.data_export` approval rules.++### Swap roles, or create per-workspace role copies++Built-in roles carry meaning beyond their permissions. Approval flows route to+`roles/projectOwner` by name (`backend/store/workspace.go:128`), Workspace Admin lookup protects the+last admin (`backend/api/v1/user_service.go:495`), and "Request query" asks for a built-in role by+name. Copies would drift from the built-in definitions and require the custom-roles license. A+Terraform apply would also revert a swap.++### Bring back `roles/projectExporter`++Customers may have created a custom role with that id since 2025, and a built-in role would+shadow it. A new id also avoids confusion with the 2025 role, whose permission set differs from+SQL Editor Exporter.++## Open items++1. **Cloud id check.** Confirm before release that no Cloud workspace has a custom role with the+ id `sqlEditorExporter`.+2. **Provider role names.** Confirm that the provider does not validate role names against a+ fixed list.+3. **Opting out of export requests.** If a customer wants grants for query but not export, add a+ project setting such as "allow export in access grant requests". Not planned until asked.diff --git a/docs/design/v1-api-audit-2026-09.md b/docs/design/v1-api-audit-2026-09.mdindex 3915508b16..e1685ea6ed 100644--- a/docs/design/v1-api-audit-2026-09.md+++ b/docs/design/v1-api-audit-2026-09.md@@ -13,7 +13,7 @@ relative to `backend/api/v1/` and proto paths to `proto/v1/v1/` unless they carr| | Problem | Severity ||---|---|---|-| X1 | The "disable export" policy is enforced by the browser, not the server | HIGH |+| X1 | The "disable export" policy is enforced by the browser, not the server. Resolved: `Export` requires `bb.sql.export`, enforced on the server, and `disable_export` is removed | HIGH || X2 | `ListInstanceDatabase` with an inline instance skips every SaaS credential guard the create path has | HIGH || X3 | `CreateRollout` with `target: ""` deploys every stage; the proto says none | HIGH || U1 | `Instance` and `Project` are rewritten whole from a cached copy with no lock — a rotated password can silently revert | HIGH |@@ -113,7 +113,7 @@ increase — is one workflow step and holds the line while the 211 are burned do## Custom methods that do something other than what they say-### X1 · `Export` ignores the export policy — HIGH+### X1 · `Export` ignores the export policy — HIGH, resolved`QueryDataPolicy.disable_export` is documented as "Disable data export in the SQL editor"(`proto/v1/v1/org_policy_service.proto:272`). The backend never reads it: the only references are@@ -125,6 +125,10 @@ Anyone holding `bb.databases.get` and `bb.sql.select` on a database exports it twith the policy on, and read-write MCP sessions get `Export` as a WRITE-class method. Bytebase'sown principle is that governance is enforced, not displayed. One refusal in the handler closes it.+**Resolved.** `Export` now requires `bb.sql.export` on the data it reads, held through a role or+a matching export grant, and the server enforces it for every caller: console, API and MCP.+`disable_export` is removed. See [sql-export-permission.md](sql-export-permission.md).+### X2 · `ListInstanceDatabase` is a connection probe that skips the create guards — HIGHWith `instance` set, the handler builds an unsaved instance from the request body and hands it@@ -676,8 +680,9 @@ descriptor walk that pins A1 and A3 can require the line.- `Query`/`Export` beyond the interceptor: per-statement `bb.sql.select|dml|ddl|explain|info` onthe new-ACL engines with CEL conditions, data-source selection by policy, masking unlessexplaining or under an unmasking grant, row/size/timeout caps (`sql_service.go:1466-1520`,- `:2068-2187`, `:733-750`). `Export` adds only the `export == true` narrowing on JIT grants and a- forced read-only session (`:1020-1033`, `:1097`); there is no `bb.sql.export`, and X1.+ `:2068-2187`, `:733-750`). `Export` requires `bb.sql.export` where `Query` requires+ `bb.sql.select` or `bb.sql.info`, which a JIT grant with `export == true` satisfies on its+ targets, and forces a read-only session (`:1020-1033`, `:1097`).- Anonymous surface: eleven RPCs accept a call with no credential, and none serves per-callerdata. `GetAuthenticationInfo` and `Login` resolve an explicit `workspace` regardless ofmembership (`auth_service.go:141`, `:152-154`), so a real workspace id answers 200 and a fake@@ -749,8 +754,8 @@ follow.## What I'd do, in order-1. **The three HIGH handler fixes, one PR each.** `Export` refuses when `disable_export` is set- (X1). `ListInstanceDatabase`'s inline mode runs `validateAndSanitizeDataSourceTLS` and+1. **The three HIGH handler fixes, one PR each.** X1 is resolved: `Export` requires+ `bb.sql.export`. `ListInstanceDatabase`'s inline mode runs `validateAndSanitizeDataSourceTLS` and`checkInstanceDataSources` before it dials (X2). `CreateRollout` with `target: ""` createsnothing, or rejects the value (X3). Each is a few lines and a test.2. **Row locks under the three read-modify-write paths** (U1, U5): instance `metadata`, projectdiff --git a/frontend/scripts/check-i18n.mjs b/frontend/scripts/check-i18n.mjsindex f2431deab4..a747f410c0 100644--- a/frontend/scripts/check-i18n.mjs+++ b/frontend/scripts/check-i18n.mjs@@ -468,21 +468,11 @@ for (const locale of LOCALES) {// ---------------------------------------------------------------------------// Check 7: linked wording// ----------------------------------------------------------------------------// The data-export setting's description quotes the "Request export" button-// label so admins can connect the policy to what users see; the label has-// been renamed before (#21081, #21200). The unmask capability is a different-// mechanism from the Masking Exemptions feature, so its strings must not-// reuse the feature's name (zh once shipped 脱敏豁免 on the unmask button).+// The unmask capability is a different mechanism from the Masking Exemptions+// feature, so its strings must not reuse the feature's name (zh once shipped+// 脱敏豁免 on the unmask button).for (const locale of LOCALES) {const values = localeValues(locale);- const label = values["sql-editor.request-export"] ?? "";- const description =- values["settings.general.workspace.data-export.description"] ?? "";- if (!label || !description.includes(label)) {- error(- `${locale}: settings.general.workspace.data-export.description must quote sql-editor.request-export (${JSON.stringify(label)})`- );- }const featureName = values["project.masking-exemption.self"] ?? "";for (const key of ["sql-editor.request-unmask", "sql-editor.grant-type-unmask"]) {const value = values[key] ?? "";diff --git a/frontend/src/lib/project-member/utils.test.ts b/frontend/src/lib/project-member/utils.test.tsindex 9c5f143b97..a263f31101 100644--- a/frontend/src/lib/project-member/utils.test.ts+++ b/frontend/src/lib/project-member/utils.test.ts@@ -3,6 +3,7 @@ import { describe, expect, test, vi } from "vitest";import {getRoleEnvironmentLimitationKind,getRolesEnvironmentLimitationKind,+ roleHasDatabaseLimitation,} from "./utils";const fixtures: Record<string, string[]> = {@@ -10,6 +11,7 @@ const fixtures: Record<string, string[]> = {"roles/sqlEditorDDLOnly": ["bb.sql.ddl"],"roles/sqlEditorDMLOnly": ["bb.sql.dml"],"roles/queryOnly": ["bb.sql.select"],+ "roles/exportOnly": ["bb.sql.export"],"roles/projectViewer": [],};vi.mock("@/stores/app", () => ({@@ -21,6 +23,17 @@ vi.mock("@/utils", () => ({permissions.some((permission) => fixtures[role]?.includes(permission)),}));+describe("roleHasDatabaseLimitation", () => {+ test("offers database scoping for roles that read or export data", () => {+ expect(roleHasDatabaseLimitation("roles/queryOnly")).toBe(true);+ expect(roleHasDatabaseLimitation("roles/exportOnly")).toBe(true);+ });++ test("offers no database scoping for roles without SQL permissions", () => {+ expect(roleHasDatabaseLimitation("roles/projectViewer")).toBe(false);+ });+});+describe("getRoleEnvironmentLimitationKind", () => {test("returns 'DDL/DML' when role has both ddl and dml", () => {expect(getRoleEnvironmentLimitationKind("roles/sqlEditorUser")).toBe(diff --git a/frontend/src/lib/project-member/utils.ts b/frontend/src/lib/project-member/utils.tsindex 28b960bb05..2c4ea5783a 100644--- a/frontend/src/lib/project-member/utils.ts+++ b/frontend/src/lib/project-member/utils.ts@@ -21,7 +21,8 @@ export const roleHasDatabaseLimitation = (role: string) => {"bb.sql.ddl","bb.sql.dml","bb.sql.explain",- "bb.sql.info"+ "bb.sql.info",+ "bb.sql.export");};diff --git a/frontend/src/lib/role.ts b/frontend/src/lib/role.tsindex 18c22db98e..7da1bdf417 100644--- a/frontend/src/lib/role.ts+++ b/frontend/src/lib/role.ts@@ -9,6 +9,7 @@ const PresetRoleType = {PROJECT_DEVELOPER: "roles/projectDeveloper",SQL_EDITOR_USER: "roles/sqlEditorUser",SQL_EDITOR_READ_USER: "roles/sqlEditorReadUser",+ SQL_EDITOR_EXPORTER: "roles/sqlEditorExporter",PROJECT_RELEASER: "roles/projectReleaser",GITOPS_SERVICE_AGENT: "roles/gitopsServiceAgent",PROJECT_VIEWER: "roles/projectViewer",@@ -25,6 +26,7 @@ const PRESET_ROLE_TITLE_KEYS: Record<string, string> = {[PresetRoleType.PROJECT_RELEASER]: "role.project-releaser.self",[PresetRoleType.SQL_EDITOR_USER]: "role.sql-editor-user.self",[PresetRoleType.SQL_EDITOR_READ_USER]: "role.sql-editor-read-user.self",+ [PresetRoleType.SQL_EDITOR_EXPORTER]: "role.sql-editor-exporter.self",[PresetRoleType.GITOPS_SERVICE_AGENT]: "role.gitops-service-agent.self",[PresetRoleType.PROJECT_VIEWER]: "role.project-viewer.self",};@@ -39,6 +41,7 @@ const PRESET_ROLE_DESCRIPTION_KEYS: Record<string, string> = {[PresetRoleType.SQL_EDITOR_USER]: "role.sql-editor-user.description",[PresetRoleType.SQL_EDITOR_READ_USER]:"role.sql-editor-read-user.description",+ [PresetRoleType.SQL_EDITOR_EXPORTER]: "role.sql-editor-exporter.description",[PresetRoleType.GITOPS_SERVICE_AGENT]:"role.gitops-service-agent.description",[PresetRoleType.PROJECT_VIEWER]: "role.project-viewer.description",diff --git a/frontend/src/locales/en-US.json b/frontend/src/locales/en-US.jsonindex c5e69a42f5..bb23276c1c 100644--- a/frontend/src/locales/en-US.json+++ b/frontend/src/locales/en-US.json@@ -2559,6 +2559,10 @@"description-placeholder": "Input role description","title-placeholder": "Input role title"},+ "sql-editor-exporter": {+ "description": "Query databases and export results, without DDL or DML access.",+ "self": "SQL Editor Exporter"+ },"sql-editor-read-user": {"description": "Read-only permissions for querying database data, without DDL or DML access.","self": "SQL Editor Read User"@@ -2819,10 +2823,6 @@"exiting": "Exiting..."},"data-copy": "Enable data copying",- "data-export": {- "description": "When disabled, users cannot export query results directly. In projects that allow access grants, users can still click \"Request export\" to submit an access grant request and export after approval.",- "self": "Allow data export without approval"- },"default-landing-page": {"default-view-changed-to-sql-editor": "The workspace's default view has been changed to SQL Editor.","go-to-sql-editor": "Go to SQL Editor",diff --git a/frontend/src/locales/es-ES.json b/frontend/src/locales/es-ES.jsonindex a06ec89077..31ae84165b 100644--- a/frontend/src/locales/es-ES.json+++ b/frontend/src/locales/es-ES.json@@ -2559,6 +2559,10 @@"description-placeholder": "Ingrese la descripción del rol","title-placeholder": "Ingrese el título del rol"},+ "sql-editor-exporter": {+ "description": "Consultar bases de datos y exportar resultados, sin acceso DDL o DML.",+ "self": "Exportador del editor SQL"+ },"sql-editor-read-user": {"description": "Permisos de solo lectura para consultar datos de la base de datos, sin acceso DDL o DML.","self": "Usuario de solo lectura del editor SQL"@@ -2819,10 +2823,6 @@"exiting": "Saliendo..."},"data-copy": "Habilitar la copia de datos",- "data-export": {- "description": "Si está deshabilitado, los usuarios no pueden exportar directamente los resultados de las consultas. En los proyectos que permiten concesiones de acceso, aún pueden pulsar \"Solicitar exportación\" para enviar una solicitud de concesión de acceso y exportar tras la aprobación.",- "self": "Permitir la exportación de datos sin aprobación"- },"default-landing-page": {"default-view-changed-to-sql-editor": "La vista predeterminada del espacio de trabajo se ha cambiado al Editor SQL.","go-to-sql-editor": "Ir al Editor SQL",diff --git a/frontend/src/locales/ja-JP.json b/frontend/src/locales/ja-JP.jsonindex 933b864304..fe290c1f8d 100644--- a/frontend/src/locales/ja-JP.json+++ b/frontend/src/locales/ja-JP.json@@ -2559,6 +2559,10 @@"description-placeholder": "ロールの説明を入力してください","title-placeholder": "ロールのタイトルを入力してください"},+ "sql-editor-exporter": {+ "description": "DDLまたはDMLアクセスなしで、データベースをクエリして結果をエクスポートできます。",+ "self": "SQLエディタエクスポートユーザー"+ },"sql-editor-read-user": {"description": "DDLまたはDMLアクセスなしで、データベースデータのクエリのための読み取り専用権限。","self": "SQLエディタ読み取り専用ユーザー"@@ -2819,10 +2823,6 @@"exiting": "退出中..."},"data-copy": "データのコピーを有効にする",- "data-export": {- "description": "無効にすると、ユーザーはクエリ結果を直接エクスポートできません。アクセス付与が有効なプロジェクトでは、「エクスポートをリクエスト」からアクセス付与をリクエストし、承認後にエクスポートできます。",- "self": "承認なしのデータエクスポートを許可"- },"default-landing-page": {"default-view-changed-to-sql-editor": "ワークスペースのデフォルト ビューが SQL エディターに変更されました。","go-to-sql-editor": "SQLエディタに移動",diff --git a/frontend/src/locales/vi-VN.json b/frontend/src/locales/vi-VN.jsonindex 7894b13a75..efb6af5f73 100644--- a/frontend/src/locales/vi-VN.json+++ b/frontend/src/locales/vi-VN.json@@ -2559,6 +2559,10 @@"description-placeholder": "Nhập mô tả vai trò","title-placeholder": "Nhập tiêu đề vai trò"},+ "sql-editor-exporter": {+ "description": "Truy vấn cơ sở dữ liệu và xuất kết quả, không có quyền DDL hoặc DML.",+ "self": "Người xuất dữ liệu Trình soạn thảo SQL"+ },"sql-editor-read-user": {"description": "Quyền chỉ đọc để truy vấn dữ liệu cơ sở dữ liệu, không có quyền DDL hoặc DML.","self": "Người dùng Trình soạn thảo SQL chỉ đọc"@@ -2819,10 +2823,6 @@"exiting": "Đang rời..."},"data-copy": "Bật sao chép dữ liệu",- "data-export": {- "description": "Khi tắt, người dùng không thể xuất trực tiếp kết quả truy vấn. Trong các dự án cho phép cấp quyền truy cập, người dùng vẫn có thể nhấn \"Yêu cầu xuất dữ liệu\" để gửi yêu cầu cấp quyền truy cập và xuất sau khi được phê duyệt.",- "self": "Cho phép xuất dữ liệu mà không cần phê duyệt"- },"default-landing-page": {"default-view-changed-to-sql-editor": "Chế độ xem mặc định của không gian làm việc đã được thay đổi thành SQL Editor.","go-to-sql-editor": "Đi tới Trình soạn thảo SQL",diff --git a/frontend/src/locales/zh-CN.json b/frontend/src/locales/zh-CN.jsonindex 7d27342b4a..a2f132c4ed 100644--- a/frontend/src/locales/zh-CN.json+++ b/frontend/src/locales/zh-CN.json@@ -2559,6 +2559,10 @@"description-placeholder": "输入角色描述","title-placeholder": "输入角色称谓"},+ "sql-editor-exporter": {+ "description": "可查询数据库数据并导出结果,不包含 DDL 或 DML 访问权限。",+ "self": "SQL 编辑器导出用户"+ },"sql-editor-read-user": {"description": "只读权限,可查询数据库数据,不包含 DDL 或 DML 访问权限。","self": "SQL 编辑器只读用户"@@ -2819,10 +2823,6 @@"exiting": "退出中..."},"data-copy": "启用复制数据",- "data-export": {- "description": "关闭后,用户无法直接导出查询结果。在启用访问授权的项目中,用户仍可点击“申请导出”提交访问授权申请,审批通过后即可导出。",- "self": "允许无需审批导出数据"- },"default-landing-page": {"default-view-changed-to-sql-editor": "工作区的默认视图已更改为 SQL 编辑器。","go-to-sql-editor": "转到 SQL 编辑器",diff --git a/frontend/src/modules/agent/logic/skills/grantPermission.ts b/frontend/src/modules/agent/logic/skills/grantPermission.tsindex eb4d9f8b3a..fb8349d4b2 100644--- a/frontend/src/modules/agent/logic/skills/grantPermission.ts+++ b/frontend/src/modules/agent/logic/skills/grantPermission.ts@@ -42,6 +42,7 @@ call_api(operationId="RoleService/ListRoles", body={})| \`roles/projectDeveloper\` | Development access (create issues, plans) || \`roles/projectReleaser\` | Execute rollouts || \`roles/sqlEditorUser\` | SQL Editor access only |+| \`roles/sqlEditorExporter\` | Query and export results (\`bb.sql.export\`), without DDL or DML || \`roles/projectViewer\` | Read-only access || \`roles/gitopsServiceAgent\` | GitOps automation |@@ -152,7 +153,7 @@ call_api(operationId="ProjectService/SetIamPolicy", body={})\`\`\`-**CEL variables for sqlEditorUser:**+**CEL variables for sqlEditorUser and sqlEditorExporter:**- \`resource.database\`: Canonical database name (\`instances/{id}/databases/{name}\` or \`projects/{project}/instances/{id}/databases/{name}\`)- \`resource.schema_name\`: Schema name- \`resource.table_name\`: Table namediff --git a/frontend/src/modules/sql-editor/components/RequestExportButton.test.tsx b/frontend/src/modules/sql-editor/components/RequestExportButton.test.tsxindex 78426b9122..6c8c549364 100644--- a/frontend/src/modules/sql-editor/components/RequestExportButton.test.tsx+++ b/frontend/src/modules/sql-editor/components/RequestExportButton.test.tsx@@ -1,9 +1,10 @@import { render, screen } from "@testing-library/react";-import { describe, expect, test, vi } from "vitest";+import { beforeEach, describe, expect, test, vi } from "vitest";import { RequestExportButton } from "./RequestExportButton";const mocks = vi.hoisted(() => ({loadSubscription: vi.fn(),+ allowJustInTimeAccess: true,}));vi.mock("react-i18next", () => ({@@ -25,7 +26,7 @@ vi.mock("@/components/PermissionGuard", () => ({vi.mock("@/hooks/useAppProject", () => ({useAppProject: () => ({name: "projects/proj1",- allowJustInTimeAccess: true,+ allowJustInTimeAccess: mocks.allowJustInTimeAccess,}),}));@@ -56,6 +57,10 @@ vi.mock("./RequestDrawerHost", () => ({}));describe("RequestExportButton", () => {+ beforeEach(() => {+ mocks.allowJustInTimeAccess = true;+ });+test("labels the export action instead of the access-grant mechanism", () => {render(<RequestExportButton@@ -71,4 +76,16 @@ describe("RequestExportButton", () => {"sql-editor.request-access-grant");});++ test("is hidden when the project does not allow just-in-time access", () => {+ mocks.allowJustInTimeAccess = false;+ const { container } = render(+ <RequestExportButton+ statement="SELECT * FROM t"+ targets={["instances/i/databases/d"]}+ />+ );++ expect(container).toBeEmptyDOMElement();+ });});diff --git a/frontend/src/modules/sql-editor/components/RequestExportButton.tsx b/frontend/src/modules/sql-editor/components/RequestExportButton.tsxindex b90ee872a9..f1175be6a3 100644--- a/frontend/src/modules/sql-editor/components/RequestExportButton.tsx+++ b/frontend/src/modules/sql-editor/components/RequestExportButton.tsx@@ -19,10 +19,10 @@ interface Props {}/**- * Shown in the result panel when the query-data policy disables export but- * the project allows access grants. Clicking it opens the access-grant- * drawer pre-filled with the current database, statement, and the export- * capability checked (unmask is left unchecked — see #20516).+ * Shown in the result panel when the user lacks bb.sql.export for the query+ * and the project allows just-in-time access. Clicking it opens the+ * access-grant drawer pre-filled with the current database, statement, and+ * the export capability checked (unmask is left unchecked — see #20516).*/export function RequestExportButton({size = "sm",diff --git a/frontend/src/modules/sql-editor/components/ResultPanel/BatchQuerySelect.test.tsx b/frontend/src/modules/sql-editor/components/ResultPanel/BatchQuerySelect.test.tsxindex 80d0ca06b6..979f647fac 100644--- a/frontend/src/modules/sql-editor/components/ResultPanel/BatchQuerySelect.test.tsx+++ b/frontend/src/modules/sql-editor/components/ResultPanel/BatchQuerySelect.test.tsx@@ -21,6 +21,8 @@ const mocks = vi.hoisted(() => ({tags: {},},deleteDatabaseQueryContext: vi.fn(),+ databasesWithExport: [] as string[],+ useExportGrantBypass: vi.fn(),}));vi.mock("react-i18next", () => ({@@ -29,11 +31,26 @@ vi.mock("react-i18next", () => ({}));vi.mock("@/components/DataExportButton", () => ({- DataExportButton: () => null,+ DataExportButton: ({+ formContent,+ text,+ }: {+ formContent: ReactNode;+ text: string;+ }) => (+ <div data-testid="batch-export">+ <span>{text}</span>+ {formContent}+ </div>+ ),}));vi.mock("@/components/database", () => ({- DatabaseTableView: () => null,+ DatabaseTableView: ({ databases }: { databases: Database[] }) => (+ <span data-testid="exportable">+ {databases.map((database) => database.name).join(",")}+ </span>+ ),}));vi.mock("@/components/EngineIcon", () => ({@@ -61,23 +78,23 @@ vi.mock("@/components/ui/ellipsis-text", () => ({}));vi.mock("@/modules/sql-editor/components/RequestExportButton", () => ({- RequestExportButton: () => null,+ RequestExportButton: ({ targets }: { targets: string[] }) => (+ <div data-testid="request-export">{targets.join(",")}</div>+ ),}));vi.mock("@/modules/sql-editor/components/useExportGrantBypass", () => ({- useExportGrantBypass: () => ({- loading: false,- failedDatabases: [],- unmatchedDatabases: [],- retry: vi.fn(),- matchedDatabases: [],- tooltip: undefined,- }),+ useExportGrantBypass: mocks.useExportGrantBypass,}));vi.mock("@/modules/sql-editor/hooks/useSQLEditorState", () => ({+ useSQLEditorDatabasesWithExport: (databases: Database[]) =>+ new Set(+ databases+ .map((database) => database.name)+ .filter((name) => mocks.databasesWithExport.includes(name))+ ),useSQLEditorQueryDataPolicy: () => ({- disableExport: true,maximumResultRows: 100,}),}));@@ -136,11 +153,25 @@ describe("BatchQuerySelect", () => {let container: HTMLDivElement;let root: ReturnType<typeof createRoot>;let cellA: Database;+ let cellB: Database;++ const grantLookup = (matched: string[], unmatched: string[]) =>+ mocks.useExportGrantBypass.mockReturnValue({+ loading: false,+ failedDatabases: [],+ matchedDatabases: matched,+ unmatchedDatabases: unmatched,+ retry: vi.fn(),+ grantName: "",+ tooltip: undefined,+ });beforeEach(() => {container = document.createElement("div");document.body.append(container);root = createRoot(container);+ mocks.databasesWithExport = [];+ grantLookup([], []);cellA = {name: "instances/cell-a/databases/linear",@@ -151,7 +182,7 @@ describe("BatchQuerySelect", () => {title: "cell-a",},} as Database;- const cellB = {+ cellB = {name: "instances/cell-b/databases/linear",effectiveEnvironment: mocks.environment.name,instanceResource: {@@ -224,4 +255,65 @@ describe("BatchQuerySelect", () => {expect(buttons[0].className).toContain("shrink-0");expect(buttons[1].className).toContain("shrink-0");});++ const testId = (id: string) =>+ container.querySelector(`[data-testid="${id}"]`);++ it("offers export of every database with bb.sql.export, without a grant lookup", () => {+ mocks.databasesWithExport = [cellA.name, cellB.name];+ render();++ expect(testId("batch-export")?.textContent).toContain(+ "sql-editor.batch-export.self"+ );+ expect(testId("exportable")?.textContent).toBe(+ `${cellA.name},${cellB.name}`+ );+ expect(testId("request-export")).toBeNull();+ expect(mocks.useExportGrantBypass).toHaveBeenLastCalledWith(+ expect.objectContaining({ enabled: false, targets: [] })+ );+ });++ it("exports the database with bb.sql.export and requests export for the other", () => {+ mocks.databasesWithExport = [cellA.name];+ grantLookup([], [cellB.name]);+ render();++ expect(testId("batch-export")?.textContent).toContain(+ "sql-editor.batch-export.partial"+ );+ expect(testId("exportable")?.textContent).toBe(cellA.name);+ expect(testId("request-export")?.textContent).toBe(cellB.name);+ expect(mocks.useExportGrantBypass).toHaveBeenLastCalledWith(+ expect.objectContaining({+ enabled: true,+ targets: [expect.objectContaining({ database: cellB.name })],+ })+ );+ });++ it("without bb.sql.export, exports granted databases and requests the rest", () => {+ grantLookup([cellA.name], [cellB.name]);+ render();++ expect(testId("batch-export")?.textContent).toContain(+ "sql-editor.batch-export.partial"+ );+ expect(testId("exportable")?.textContent).toBe(cellA.name);+ expect(testId("request-export")?.textContent).toBe(cellB.name);+ expect(mocks.useExportGrantBypass).toHaveBeenLastCalledWith(+ expect.objectContaining({ enabled: true, project: "projects/p" })+ );+ });++ it("without bb.sql.export or grants, offers only Request export", () => {+ grantLookup([], [cellA.name, cellB.name]);+ render();++ expect(testId("batch-export")).toBeNull();+ expect(testId("request-export")?.textContent).toBe(+ `${cellA.name},${cellB.name}`+ );+ });});diff --git a/frontend/src/modules/sql-editor/components/ResultPanel/BatchQuerySelect.tsx b/frontend/src/modules/sql-editor/components/ResultPanel/BatchQuerySelect.tsxindex b4ce4c8462..87344d9891 100644--- a/frontend/src/modules/sql-editor/components/ResultPanel/BatchQuerySelect.tsx+++ b/frontend/src/modules/sql-editor/components/ResultPanel/BatchQuerySelect.tsx@@ -16,7 +16,10 @@ import { Tooltip } from "@/components/ui/tooltip";import { cn } from "@/lib/utils";import { RequestExportButton } from "@/modules/sql-editor/components/RequestExportButton";import { useExportGrantBypass } from "@/modules/sql-editor/components/useExportGrantBypass";-import { useSQLEditorQueryDataPolicy } from "@/modules/sql-editor/hooks/useSQLEditorState";+import {+ useSQLEditorDatabasesWithExport,+ useSQLEditorQueryDataPolicy,+} from "@/modules/sql-editor/hooks/useSQLEditorState";import { useSQLEditorEditorState } from "@/modules/sql-editor/store/editor";import {getSQLEditorTabsState,@@ -151,7 +154,7 @@ export function BatchQuerySelect({// The batch was run from a single user-typed statement against many// databases — pull it from any one context (they all carry the same// params.statement). Used as the request-export drawer seed when the- // policy disables direct export.+ // user lacks bb.sql.export.const batchStatement = useMemo(() => {for (const context of contextsByDatabase.values()) {if (context?.params.statement) return context.params.statement;@@ -159,12 +162,31 @@ export function BatchQuerySelect({return "";}, [contextsByDatabase]);- // Per-DB grant lookup. When the policy disables direct export, the- // hook reports which of the queried DBs are covered by an active- // export grant (matched) and which are not (unmatched). Both lists- // feed the partial-coverage UX: Export operates on the matched set- // only, Request Export pre-seeds the unmatched set.- const policyAllowsExport = !queryDataPolicy?.disableExport;+ const queriedDatabases = useMemo(+ () => items.map((item) => item.database),+ [items]+ );+ const databasesWithExport = useSQLEditorDatabasesWithExport(queriedDatabases);++ // Per-DB grant lookup for the queried DBs without bb.sql.export from a+ // role. The hook reports which of them are covered by an active export+ // grant (matched) and which are not (unmatched). Both lists feed the+ // partial-coverage UX: Export operates on the authorized set only,+ // Request Export pre-seeds the unmatched set.+ const grantTargets = queriedDatabaseNames.flatMap((database) => {+ if (databasesWithExport.has(database)) return [];+ const params = contextsByDatabase.get(database)?.params;+ return params?.statement+ ? [+ {+ database,+ statement: params.statement,+ schema: params.connection.schema ?? "",+ container: params.connection.table ?? "",+ },+ ]+ : [];+ });const {matchedDatabases,unmatchedDatabases,@@ -173,31 +195,23 @@ export function BatchQuerySelect({failedDatabases,retry,} = useExportGrantBypass({- enabled: !policyAllowsExport,+ enabled: grantTargets.length > 0,project,- targets: queriedDatabaseNames.flatMap((database) => {- const params = contextsByDatabase.get(database)?.params;- return params?.statement- ? [- {- database,- statement: params.statement,- schema: params.connection.schema ?? "",- container: params.connection.table ?? "",- },- ]- : [];- }),+ targets: grantTargets,});- // When the policy allows export, every queried DB is authorized;- // otherwise only the JIT-matched subset. The Export drawer's- // `DatabaseTableView` is filtered to this list so users can't- // physically pick an unauthorized DB — eliminating the partial-- // failure toast storm.- const exportableDatabaseNames = policyAllowsExport- ? queriedDatabaseNames- : matchedDatabases;+ // A queried DB is authorized by bb.sql.export from a role or by a+ // matching grant. The Export drawer's `DatabaseTableView` is filtered+ // to this list so users can't physically pick an unauthorized DB —+ // eliminating the partial-failure toast storm.+ const exportableDatabaseNames = useMemo(+ () =>+ queriedDatabaseNames.filter(+ (name) =>+ databasesWithExport.has(name) || matchedDatabases.includes(name)+ ),+ [queriedDatabaseNames, databasesWithExport, matchedDatabases]+ );const exportableDatabaseList = useMemo(() => exportableDatabaseNames.map((name) => getDatabaseByName(name)),[exportableDatabaseNames, getDatabaseByName]@@ -208,15 +222,12 @@ export function BatchQuerySelect({// Visible alongside Export in the partial-coverage case (e.g. 2 of 5// covered) so users can request grants for the missing ones without// losing the immediate export of the covered set.- const showRequestExport =- !policyAllowsExport && unmatchedDatabases.length > 0;+ const showRequestExport = unmatchedDatabases.length > 0;// Partial-coverage flag: some matched, some not. Drives the Export// button label change from "Batch export" to "Partial batch export"// so the user knows up-front the action operates on a strict subset.const isPartialExport =- showExport &&- !policyAllowsExport &&- matchedDatabases.length < queriedDatabaseNames.length;+ showExport && exportableDatabaseNames.length < queriedDatabaseNames.length;const handleCloseSingleResultView = (item: BatchQueryItem) => {const contexts = currentTab?.databaseQueryContexts?.get(item.database.name);@@ -356,7 +367,7 @@ export function BatchQuerySelect({)}{/*- Partial-coverage UX: when the policy disables export and only a+ Partial-coverage UX: when the user lacks bb.sql.export and only asubset of the queried DBs has an active grant, both buttons canappear — Export operates on the covered set, Request Exportpre-seeds the uncovered set so the user can extend coveragediff --git a/frontend/src/modules/sql-editor/components/ResultView/ResultView.test.tsx b/frontend/src/modules/sql-editor/components/ResultView/ResultView.test.tsxindex 46f8f4f229..301d57d818 100644--- a/frontend/src/modules/sql-editor/components/ResultView/ResultView.test.tsx+++ b/frontend/src/modules/sql-editor/components/ResultView/ResultView.test.tsx@@ -12,8 +12,10 @@ import {} from "@/types/proto-es/v1/sql_service_pb";import { ResultView } from "./ResultView";-const { exportData } = vi.hoisted(() => ({+const { exportData, exportAccess, useExportGrantBypass } = vi.hoisted(() => ({exportData: vi.fn(),+ exportAccess: { databasesWithExport: [] as string[] },+ useExportGrantBypass: vi.fn(),}));vi.mock("react-i18next", () => ({@@ -29,7 +31,9 @@ vi.mock("@/components/DataExportButton", () => ({}));vi.mock("@/modules/sql-editor/components/RequestExportButton", () => ({- RequestExportButton: () => null,+ RequestExportButton: ({ targets }: { targets: string[] }) => (+ <div data-testid="request-export">{targets.join(",")}</div>+ ),}));vi.mock("@/modules/sql-editor/components/RequestQueryButton", () => ({@@ -37,17 +41,16 @@ vi.mock("@/modules/sql-editor/components/RequestQueryButton", () => ({}));vi.mock("@/modules/sql-editor/components/useExportGrantBypass", () => ({- useExportGrantBypass: () => ({- loading: false,- failedDatabases: [],- unmatchedDatabases: [],- retry: vi.fn(),- grantName: undefined,- tooltip: undefined,- }),+ useExportGrantBypass,}));vi.mock("@/modules/sql-editor/hooks/useSQLEditorState", () => ({+ useSQLEditorDatabasesWithExport: (databases: Database[]) =>+ new Set(+ databases+ .map((database) => database.name)+ .filter((name) => exportAccess.databasesWithExport.includes(name))+ ),useSQLEditorQueryDataPolicy: () => undefined,}));@@ -102,21 +105,32 @@ vi.mock("./ErrorView", () => ({}));vi.mock("./SingleResultView", () => ({- SingleResultView: ({ onExport }: { onExport: (request: unknown) => void }) => (- <button- type="button"- onClick={() =>- onExport({- options: { format: ExportFormat.CSV, limit: 100, password: "" },- resolve: vi.fn(),- reject: vi.fn(),- statement: "SELECT * FROM c",- })- }- >- export- </button>- ),+ SingleResultView: ({+ onExport,+ requestExportSlot,+ showExport,+ }: {+ onExport: (request: unknown) => void;+ requestExportSlot?: React.ReactNode;+ showExport: boolean;+ }) =>+ showExport ? (+ <button+ type="button"+ onClick={() =>+ onExport({+ options: { format: ExportFormat.CSV, limit: 100, password: "" },+ resolve: vi.fn(),+ reject: vi.fn(),+ statement: "SELECT * FROM c",+ })+ }+ >+ export+ </button>+ ) : (+ requestExportSlot+ ),}));const executeParams: SQLEditorQueryParams = {@@ -136,10 +150,26 @@ const database = {project: "projects/prod",} as Database;+const grantLookup = ({+ grantName = "",+ unmatchedDatabases = [] as string[],+}) =>+ useExportGrantBypass.mockReturnValue({+ loading: false,+ failedDatabases: [],+ matchedDatabases: [],+ unmatchedDatabases,+ retry: vi.fn(),+ grantName,+ tooltip: undefined,+ });+describe("ResultView", () => {beforeEach(() => {exportData.mockReset();exportData.mockResolvedValue(new Uint8Array());+ exportAccess.databasesWithExport = [];+ grantLookup({});});test("blocks analytics recording for query results", () => {@@ -151,6 +181,7 @@ describe("ResultView", () => {});test("includes the selected CosmosDB container in export requests", async () => {+ exportAccess.databasesWithExport = [database.name];render(<ResultViewexecuteParams={{@@ -182,6 +213,100 @@ describe("ResultView", () => {});});+ const queryResult = {+ error: "",+ results: [create(QueryResultSchema, { statement: "SELECT 1" })],+ };++ test("bb.sql.export offers Export without looking up a grant", () => {+ exportAccess.databasesWithExport = [database.name];+ render(+ <ResultView+ executeParams={executeParams}+ database={database}+ resultSet={queryResult}+ />+ );++ expect(screen.getByRole("button", { name: "export" })).toBeInTheDocument();+ expect(screen.queryByTestId("request-export")).not.toBeInTheDocument();+ expect(useExportGrantBypass).toHaveBeenLastCalledWith(+ expect.objectContaining({ enabled: false })+ );+ });++ test("a matching export grant offers Export without bb.sql.export", () => {+ grantLookup({ grantName: "projects/prod/accessGrants/g" });+ render(+ <ResultView+ executeParams={executeParams}+ database={database}+ resultSet={queryResult}+ />+ );++ expect(screen.getByRole("button", { name: "export" })).toBeInTheDocument();+ expect(useExportGrantBypass).toHaveBeenLastCalledWith(+ expect.objectContaining({ enabled: true, project: "projects/prod" })+ );+ });++ test("without bb.sql.export or a grant, offers Request export", () => {+ grantLookup({ unmatchedDatabases: [database.name] });+ render(+ <ResultView+ executeParams={executeParams}+ database={database}+ resultSet={queryResult}+ />+ );++ expect(+ screen.queryByRole("button", { name: "export" })+ ).not.toBeInTheDocument();+ expect(screen.getByTestId("request-export")).toHaveTextContent(+ database.name+ );+ });++ test("bb.sql.export scoped to one database offers Export there and Request export elsewhere", () => {+ const other = {+ ...database,+ name: "instances/prod/databases/other",+ } as Database;+ exportAccess.databasesWithExport = [database.name];+ grantLookup({ unmatchedDatabases: [other.name] });++ const { unmount } = render(+ <ResultView+ executeParams={executeParams}+ database={database}+ resultSet={queryResult}+ />+ );+ expect(screen.getByRole("button", { name: "export" })).toBeInTheDocument();+ expect(screen.queryByTestId("request-export")).not.toBeInTheDocument();+ unmount();++ render(+ <ResultView+ executeParams={executeParams}+ database={other}+ resultSet={queryResult}+ />+ );+ expect(+ screen.queryByRole("button", { name: "export" })+ ).not.toBeInTheDocument();+ expect(screen.getByTestId("request-export")).toHaveTextContent(other.name);+ expect(useExportGrantBypass).toHaveBeenLastCalledWith(+ expect.objectContaining({+ enabled: true,+ targets: [expect.objectContaining({ database: other.name })],+ })+ );+ });+/** A PostgreSQL plan result whose root costs `totalCost`. */const planResult = (totalCost: number) =>create(QueryResultSchema, {diff --git a/frontend/src/modules/sql-editor/components/ResultView/ResultView.tsx b/frontend/src/modules/sql-editor/components/ResultView/ResultView.tsxindex 040d8b8fa1..297aa98670 100644--- a/frontend/src/modules/sql-editor/components/ResultView/ResultView.tsx+++ b/frontend/src/modules/sql-editor/components/ResultView/ResultView.tsx@@ -17,7 +17,10 @@ import { cn } from "@/lib/utils";import { RequestExportButton } from "@/modules/sql-editor/components/RequestExportButton";import { RequestQueryButton } from "@/modules/sql-editor/components/RequestQueryButton";import { useExportGrantBypass } from "@/modules/sql-editor/components/useExportGrantBypass";-import { useSQLEditorQueryDataPolicy } from "@/modules/sql-editor/hooks/useSQLEditorState";+import {+ useSQLEditorDatabasesWithExport,+ useSQLEditorQueryDataPolicy,+} from "@/modules/sql-editor/hooks/useSQLEditorState";import { useSQLEditorEditorState } from "@/modules/sql-editor/store/editor";import { getSQLEditorTabsState } from "@/modules/sql-editor/store/tab";import { useAppStore } from "@/stores/app";@@ -132,8 +135,14 @@ export function ResultView({return false;}, [queryDataPolicy, envQueryDataPolicy]);- // Export discovery is independent of the grant applied during Query, which- // may permit unmasking without export.+ const exportDatabases = useMemo(() => [database], [database]);+ const allowExport = useSQLEditorDatabasesWithExport(exportDatabases).has(+ database.name+ );++ // Without bb.sql.export from a role, an active export grant for this query+ // enables Export. Export discovery is independent of the grant applied+ // during Query, which may permit unmasking without export.const {grantName: exportGrantName,tooltip: exportTooltip,@@ -142,7 +151,7 @@ export function ResultView({retry,unmatchedDatabases,} = useExportGrantBypass({- enabled: !!queryDataPolicy?.disableExport && !!executeParams?.statement,+ enabled: !allowExport && !!executeParams?.statement,project: database.project,targets: [{@@ -154,7 +163,7 @@ export function ResultView({],});- const showExport = !queryDataPolicy?.disableExport || !!exportGrantName;+ const showExport = allowExport || !!exportGrantName;// When direct export is unavailable, offer a "Request export" affordance that// opens the access-grant drawer (pre-filled with this database, statement,diff --git a/frontend/src/modules/sql-editor/components/ResultView/SingleResultView.tsx b/frontend/src/modules/sql-editor/components/ResultView/SingleResultView.tsxindex c204c80aa6..26ac77c509 100644--- a/frontend/src/modules/sql-editor/components/ResultView/SingleResultView.tsx+++ b/frontend/src/modules/sql-editor/components/ResultView/SingleResultView.tsx@@ -121,12 +121,12 @@ export interface SingleResultViewProps {resultIndex?: number;showExport: boolean;// Optional tooltip shown on the export button — used to explain when the- // export is enabled by a JIT access grant despite the policy disabling it.+ // export is enabled by a JIT access grant rather than bb.sql.export.exportTooltip?: ReactNode;maximumExportCount?: number;onExport?: (req: DataExportRequest & { statement: string }) => void;// Rendered in the toolbar when `showExport` is false — e.g. a- // "Request export" affordance when the policy disables direct export.+ // "Request export" affordance when the user lacks bb.sql.export.requestExportSlot?: ReactNode;// Compact layout (fixed-height, non-growing body) used by the terminal /// admin result panel. Defaults to the flex-grow saved query layout.diff --git a/frontend/src/modules/sql-editor/components/useExportGrantBypass.test.tsx b/frontend/src/modules/sql-editor/components/useExportGrantBypass.test.tsxindex ab76349419..2e8c18718c 100644--- a/frontend/src/modules/sql-editor/components/useExportGrantBypass.test.tsx+++ b/frontend/src/modules/sql-editor/components/useExportGrantBypass.test.tsx@@ -20,6 +20,23 @@ const args = {enabled: true, project: "projects/p", targets: [target]};beforeEach(() => vi.resetAllMocks());afterEach(() => vi.restoreAllMocks());+test("users with bb.sql.export skip the grant lookup", async () => {+ searchMyAccessGrants.mockResolvedValue({accessGrants: [grant]});+ const {result} = renderHook(() => useExportGrantBypass({...args, enabled: false}));+ await act(async () => {});+ expect(searchMyAccessGrants).not.toHaveBeenCalled();+ expect(result.current).toMatchObject({loading: false, grantName: "", matchedDatabases: [], unmatchedDatabases: [], failedDatabases: []});+ expect(result.current.tooltip).toBeUndefined();+});++test("users without bb.sql.export find a matching export grant", async () => {+ searchMyAccessGrants.mockResolvedValue({accessGrants: [grant]});+ const {result} = renderHook(() => useExportGrantBypass(args));+ await waitFor(() => expect(result.current.grantName).toBe(grant.name));+ expect(result.current.matchedDatabases).toEqual([target.database]);+ expect(searchMyAccessGrants).toHaveBeenCalledWith(expect.objectContaining({filter: expect.objectContaining({export: true, status: ["ACTIVE"]})}));+});+test("large batches keep render keys compact and reuse hashes across renders", async () => {const hash = vi.spyOn(queryHashUtils, "hashAccessGrantQuery");const stringify = JSON.stringify;diff --git a/frontend/src/modules/sql-editor/hooks/useSQLEditorState.test.ts b/frontend/src/modules/sql-editor/hooks/useSQLEditorState.test.tsnew file mode 100644index 0000000000..8c5b074a7f--- /dev/null+++ b/frontend/src/modules/sql-editor/hooks/useSQLEditorState.test.ts@@ -0,0 +1,101 @@+import { create } from "@bufbuild/protobuf";+import { renderHook } from "@testing-library/react";+import { beforeEach, describe, expect, test, vi } from "vitest";+import { useAppStore } from "@/stores/app";+import {+ type Expr,+ ExprSchema,+} from "@/types/proto-es/google/api/expr/v1alpha1/syntax_pb";+import type { Database } from "@/types/proto-es/v1/database_service_pb";+import {+ BindingSchema,+ IamPolicySchema,+} from "@/types/proto-es/v1/iam_policy_pb";+import { ProjectSchema } from "@/types/proto-es/v1/project_service_pb";+import { RoleSchema } from "@/types/proto-es/v1/role_service_pb";+import { UserSchema } from "@/types/proto-es/v1/user_service_pb";+import { useSQLEditorDatabasesWithExport } from "./useSQLEditorState";++const ident = (name: string) =>+ create(ExprSchema, { exprKind: { case: "identExpr", value: { name } } });+const databaseIs = (name: string): Expr =>+ create(ExprSchema, {+ exprKind: {+ case: "callExpr",+ value: {+ function: "_==_",+ args: [+ create(ExprSchema, {+ exprKind: {+ case: "selectExpr",+ value: { operand: ident("resource"), field: "database" },+ },+ }),+ create(ExprSchema, {+ exprKind: {+ case: "constExpr",+ value: { constantKind: { case: "stringValue", value: name } },+ },+ }),+ ],+ },+ },+ });++const project = "projects/p";+const databaseA = { name: "instances/i/databases/a", project } as Database;+const databaseB = { name: "instances/i/databases/b", project } as Database;+const roles = [+ create(RoleSchema, {+ name: "roles/sqlEditorExporter",+ permissions: ["bb.sql.select", "bb.sql.export"],+ }),+ create(RoleSchema, {+ name: "roles/sqlEditorReadUser",+ permissions: ["bb.sql.select"],+ }),+];++describe("useSQLEditorDatabasesWithExport", () => {+ beforeEach(() => {+ useAppStore.setState({+ currentUser: create(UserSchema, {+ name: "users/[email protected]",+ email: "[email protected]",+ }),+ roles,+ roleList: roles,+ workspacePolicy: create(IamPolicySchema, {}),+ projectsByName: { [project]: create(ProjectSchema, { name: project }) },+ projectPoliciesByName: {+ [project]: create(IamPolicySchema, {+ bindings: [+ create(BindingSchema, {+ role: "roles/sqlEditorExporter",+ members: ["user:[email protected]"],+ condition: {+ expression: `resource.database == "${databaseA.name}"`,+ },+ parsedExpr: databaseIs(databaseA.name),+ }),+ create(BindingSchema, {+ role: "roles/sqlEditorReadUser",+ members: ["user:[email protected]"],+ }),+ ],+ }),+ },+ fetchProject: vi.fn(),+ loadProjectIamPolicy: vi.fn(),+ } as never);+ });++ test("an Exporter binding scoped to one database grants export there only", () => {+ const databases = [databaseA, databaseB];+ const { result } = renderHook(() =>+ useSQLEditorDatabasesWithExport(databases)+ );++ expect([...result.current]).toEqual([databaseA.name]);+ });+});diff --git a/frontend/src/modules/sql-editor/hooks/useSQLEditorState.ts b/frontend/src/modules/sql-editor/hooks/useSQLEditorState.tsindex e130c3476c..7804aa59e6 100644--- a/frontend/src/modules/sql-editor/hooks/useSQLEditorState.ts+++ b/frontend/src/modules/sql-editor/hooks/useSQLEditorState.ts@@ -8,6 +8,7 @@ import { useSQLEditorTabsStore } from "@/modules/sql-editor/store/tab";import { useAppStore } from "@/stores/app";import type { SQLEditorConnection } from "@/types";import { isValidDatabaseName, isValidProjectName } from "@/types";+import type { Permission } from "@/types/iam";import type { Database } from "@/types/proto-es/v1/database_service_pb";import type { InstanceResource } from "@/types/proto-es/v1/instance_service_pb";import {@@ -16,7 +17,11 @@ import {} from "@/types/proto-es/v1/org_policy_service_pb";import type { PlanFeature } from "@/types/proto-es/v1/subscription_service_pb";import type { Environment } from "@/types/v1/environment";-import { getDatabaseEnvironment, getInstanceResource } from "@/utils";+import {+ getDatabaseEnvironment,+ getInstanceResource,+ isDatabaseV1Queryable,+} from "@/utils";/*** React access to a workspace-level plan feature flag. Re-renders when@@ -41,7 +46,6 @@ export const useSQLEditorFeature = (feature: PlanFeature): boolean => {// policy limits.type FormattedQueryDataPolicy = {disableCopyData: boolean;- disableExport: boolean;allowAdminDataSource: boolean;maximumResultRows: number;};@@ -52,7 +56,6 @@ const formatQueryDataPolicy = (const max = policy?.maximumResultRows ?? -1;return {disableCopyData: policy?.disableCopyData ?? false,- disableExport: policy?.disableExport ?? false,allowAdminDataSource: policy?.allowAdminDataSource ?? false,maximumResultRows: max <= 0 ? Number.MAX_VALUE : max,};@@ -129,12 +132,15 @@ export const useClampResultRowsLimitToPolicy = (project: string): void => {};/**- * React access to "can the current user run admin SQL against this- * project?". Self-fetches the project + its IAM policy so the SQL editor- * route (which doesn't preload either) gets a correct answer once both- * resolve.+ * React access to a project permission of the current user. Self-fetches the+ * project + its IAM policy so the SQL editor route (which doesn't preload+ * either) gets a correct answer once both resolve. Database-scoped binding+ * conditions are ignored; the server makes the final decision.*/-export const useSQLEditorAllowAdmin = (project: string): boolean => {+const useSQLEditorProjectPermission = (+ project: string,+ permission: Permission+): boolean => {const fetchProject = useAppStore((s) => s.fetchProject);const loadProjectIamPolicy = useAppStore((s) => s.loadProjectIamPolicy);useEffect(() => {@@ -143,7 +149,64 @@ export const useSQLEditorAllowAdmin = (project: string): boolean => {void loadProjectIamPolicy(project);}, [fetchProject, loadProjectIamPolicy, project]);return useAppStore((s) =>- s.hasProjectPermission(s.getProjectByName(project), "bb.sql.admin")+ s.hasProjectPermission(s.getProjectByName(project), permission)+ );+};++/** Whether the current user can run admin SQL against this project. */+export const useSQLEditorAllowAdmin = (project: string): boolean =>+ useSQLEditorProjectPermission(project, "bb.sql.admin");++/**+ * The names of `databases` the current user can export from without an access+ * grant: bb.sql.export from a role, including database-scoped binding+ * conditions. Schema and table conditions are checked only by the server.+ * Self-fetches each project and its IAM policy, which the SQL editor route+ * doesn't preload.+ */+export const useSQLEditorDatabasesWithExport = (+ databases: Database[]+): Set<string> => {+ const fetchProject = useAppStore((s) => s.fetchProject);+ const loadProjectIamPolicy = useAppStore((s) => s.loadProjectIamPolicy);+ const projectsKey = [+ ...new Set(databases.map((database) => database.project)),+ ]+ .filter(isValidProjectName)+ .sort((a, b) => a.localeCompare(b))+ .join(",");+ useEffect(() => {+ for (const project of projectsKey.split(",").filter(Boolean)) {+ void fetchProject(project);+ void loadProjectIamPolicy(project);+ }+ }, [fetchProject, loadProjectIamPolicy, projectsKey]);+ // isDatabaseV1Queryable reads these through the store bridge; subscribing+ // recomputes the answer once they load.+ const currentUser = useAppStore((s) => s.currentUser);+ const roles = useAppStore((s) => s.roles);+ const roleList = useAppStore((s) => s.roleList);+ const workspacePolicy = useAppStore((s) => s.workspacePolicy);+ const projectsByName = useAppStore((s) => s.projectsByName);+ const projectPoliciesByName = useAppStore((s) => s.projectPoliciesByName);+ return useMemo(+ () =>+ new Set(+ databases+ .filter((database) =>+ isDatabaseV1Queryable(database, ["bb.sql.export"])+ )+ .map((database) => database.name)+ ),+ [+ databases,+ currentUser,+ roles,+ roleList,+ workspacePolicy,+ projectsByName,+ projectPoliciesByName,+ ]);};diff --git a/frontend/src/routes/auth/WorkspaceSetupPage.test.tsx b/frontend/src/routes/auth/WorkspaceSetupPage.test.tsxindex 874292a535..a8630221ce 100644--- a/frontend/src/routes/auth/WorkspaceSetupPage.test.tsx+++ b/frontend/src/routes/auth/WorkspaceSetupPage.test.tsx@@ -2077,7 +2077,7 @@ describe("WorkspaceSetupPage", () => {expect(projectBindings()).toEqual([OWNER_BINDING,["roles/projectDeveloper", ["user:[email protected]"]],- ["roles/sqlEditorReadUser", ["user:[email protected]"]],+ ["roles/sqlEditorExporter", ["user:[email protected]"]],]);expect(mocks.patchWorkspaceIamPolicy).toHaveBeenCalledWith([{ member: "user:[email protected]", roles: ["roles/workspaceMember"] }],@@ -2420,7 +2420,7 @@ describe("WorkspaceSetupPage", () => {expect(projectBindings()).toEqual([OWNER_BINDING,["roles/projectDeveloper", ["user:[email protected]"]],- ["roles/sqlEditorReadUser", ["user:[email protected]"]],+ ["roles/sqlEditorExporter", ["user:[email protected]"]],]);});@@ -2479,7 +2479,7 @@ describe("WorkspaceSetupPage", () => {expect(projectBindings()).toEqual([OWNER_BINDING,["roles/projectDeveloper", ["user:[email protected]"]],- ["roles/sqlEditorReadUser", ["user:[email protected]"]],+ ["roles/sqlEditorExporter", ["user:[email protected]"]],]);expect(mocks.patchWorkspaceIamPolicy).toHaveBeenLastCalledWith([{ member: "user:[email protected]", roles: ["roles/workspaceMember"] }],@@ -2545,7 +2545,7 @@ describe("WorkspaceSetupPage", () => {["user:[email protected]", "user:[email protected]"],"",],- ["roles/sqlEditorReadUser", ["user:[email protected]"], ""],+ ["roles/sqlEditorExporter", ["user:[email protected]"], ""],]);});@@ -2581,7 +2581,7 @@ describe("WorkspaceSetupPage", () => {bindings: [...server.projectPolicy.bindings,{ role: "roles/projectDeveloper", members: ["user:[email protected]"] },- { role: "roles/sqlEditorReadUser", members: ["user:[email protected]"] },+ { role: "roles/sqlEditorExporter", members: ["user:[email protected]"] },],} as IamPolicy;mocks.patchWorkspaceIamPolicy.mockRejectedValueOnce(unavailable());@@ -2598,7 +2598,7 @@ describe("WorkspaceSetupPage", () => {expect(serverBindings()).toEqual([OWNER_BINDING,["roles/projectDeveloper", ["user:[email protected]"]],- ["roles/sqlEditorReadUser", ["user:[email protected]"]],+ ["roles/sqlEditorExporter", ["user:[email protected]"]],]);});@@ -2620,7 +2620,7 @@ describe("WorkspaceSetupPage", () => {expect(serverBindings()).toEqual([OWNER_BINDING,["roles/projectDeveloper", ["user:[email protected]"]],- ["roles/sqlEditorReadUser", ["user:[email protected]"]],+ ["roles/sqlEditorExporter", ["user:[email protected]"]],]);});@@ -2648,7 +2648,7 @@ describe("WorkspaceSetupPage", () => {"roles/projectDeveloper",["user:[email protected]", "user:[email protected]"],],- ["roles/sqlEditorReadUser", ["user:[email protected]"]],+ ["roles/sqlEditorExporter", ["user:[email protected]"]],]);});@@ -2662,7 +2662,7 @@ describe("WorkspaceSetupPage", () => {bindings: [...read.bindings,{ role: "roles/projectDeveloper", members: ["user:[email protected]"] },- { role: "roles/sqlEditorReadUser", members: ["user:[email protected]"] },+ { role: "roles/sqlEditorExporter", members: ["user:[email protected]"] },],} as IamPolicy;return read;@@ -2678,7 +2678,7 @@ describe("WorkspaceSetupPage", () => {expect(serverBindings()).toEqual([OWNER_BINDING,["roles/projectDeveloper", ["user:[email protected]"]],- ["roles/sqlEditorReadUser", ["user:[email protected]"]],+ ["roles/sqlEditorExporter", ["user:[email protected]"]],]);});@@ -2715,7 +2715,7 @@ describe("WorkspaceSetupPage", () => {"roles/projectDeveloper",["user:[email protected]", "user:[email protected]"],],- ["roles/sqlEditorReadUser", ["user:[email protected]"]],+ ["roles/sqlEditorExporter", ["user:[email protected]"]],]);});@@ -2760,7 +2760,7 @@ describe("WorkspaceSetupPage", () => {expect(serverBindings()).toEqual([OWNER_BINDING,["roles/projectDeveloper", ["user:[email protected]"]],- ["roles/sqlEditorReadUser", ["user:[email protected]"]],+ ["roles/sqlEditorExporter", ["user:[email protected]"]],]);});@@ -2886,7 +2886,7 @@ describe("WorkspaceSetupPage", () => {expect(serverBindings()).toEqual([OWNER_BINDING,["roles/projectDeveloper", ["user:[email protected]"]],- ["roles/sqlEditorReadUser", ["user:[email protected]"]],+ ["roles/sqlEditorExporter", ["user:[email protected]"]],]);});@@ -3302,7 +3302,7 @@ describe("WorkspaceSetupPage", () => {bindings: [...server.projectPolicy.bindings,{ role: "roles/projectDeveloper", members: ["user:[email protected]"] },- { role: "roles/sqlEditorReadUser", members: ["user:[email protected]"] },+ { role: "roles/sqlEditorExporter", members: ["user:[email protected]"] },],} as IamPolicy;render(<WorkspaceSetupPage />);diff --git a/frontend/src/routes/auth/workspace-setup/finish.ts b/frontend/src/routes/auth/workspace-setup/finish.tsindex 91d84e3ffa..a53dea4fa9 100644--- a/frontend/src/routes/auth/workspace-setup/finish.ts+++ b/frontend/src/routes/auth/workspace-setup/finish.ts@@ -86,10 +86,11 @@ const SUPERSEDED = { ok: false, superseded: true } as const;// would report it a second time.const REPORT = { byCaller: true };-// Together these let an invitee propose changes and run read-only queries.+// Together these let an invitee propose changes, run read-only queries, and+// export their results.const INVITEE_PROJECT_ROLES: string[] = [PresetRoleType.PROJECT_DEVELOPER,- PresetRoleType.SQL_EDITOR_READ_USER,+ PresetRoleType.SQL_EDITOR_EXPORTER,];// Screen 1's two names. The name is optional, and an empty one is not saveddiff --git a/frontend/src/routes/workspace/general/SQLEditorSection.test.tsx b/frontend/src/routes/workspace/general/SQLEditorSection.test.tsxindex ce420941f0..19fad3c756 100644--- a/frontend/src/routes/workspace/general/SQLEditorSection.test.tsx+++ b/frontend/src/routes/workspace/general/SQLEditorSection.test.tsx@@ -22,7 +22,6 @@ const mocks = vi.hoisted(() => {queryTimeout: undefined as undefined | { seconds: bigint },},policy: {- disableExport: false,disableCopyData: false,allowAdminDataSource: false,maximumResultRows: 0n,@@ -186,7 +185,6 @@ beforeEach(() => {mocks.profile.sqlEditorCustomTheme = undefined;mocks.profile.sqlResultSize = 0n;mocks.profile.queryTimeout = undefined;- mocks.policy.disableExport = false;mocks.policy.disableCopyData = false;mocks.policy.allowAdminDataSource = false;mocks.policy.maximumResultRows = 0n;@@ -356,60 +354,48 @@ describe("SQLEditorSection theme", () => {});});-// The data-export policy is stored as `disableExport`, while the control names-// the inverse allowed state. Keep that inversion and its explanatory copy in-// sync.-describe("SQLEditorSection data-export policy toggle", () => {- function renderSection() {- const ref = createRef<SectionHandle>();- render(- <SQLEditorSection ref={ref} title="SQL Editor" onDirtyChange={() => {}} />- );- return ref;- }-- function exportSwitch(): HTMLElement {- // The switch renders inside the FormField title span, as a sibling of- // the label text (SQLEditorSection.tsx) — scope by that span.- const span = Array.from(container.querySelectorAll("span")).find((s) =>- s.textContent?.includes("settings.general.workspace.data-export.self")- );- expect(span).toBeTruthy();- const control = span?.querySelector<HTMLElement>('[role="switch"]');- expect(control).toBeTruthy();- return control as HTMLElement;+// Export is controlled by the bb.sql.export permission, so the query data+// policy toggles cover only copying and the admin data source.+describe("SQLEditorSection query data policy toggles", () => {+ // The theme preview renders switches of its own; keep the settings ones.+ function settingSwitchLabels(): string[] {+ return Array.from(container.querySelectorAll('[role="switch"]'))+ .map((control) => control.parentElement?.textContent ?? "")+ .filter((label) => label.startsWith("settings.general.workspace."));}- test("renders the retitled label with its description", () => {- renderSection();- expect(container.textContent).toContain(- "settings.general.workspace.data-export.self"- );- expect(container.textContent).toContain(- "settings.general.workspace.data-export.description"- );- });-- test("export allowed without approval (disableExport=false) renders checked", () => {- mocks.policy.disableExport = false;- renderSection();- expect(exportSwitch().getAttribute("aria-checked")).toBe("true");- });+ test("offers no workspace export setting", () => {+ render(<SQLEditorSection title="SQL Editor" onDirtyChange={() => {}} />);- test("approval-gated export (disableExport=true) renders unchecked", () => {- mocks.policy.disableExport = true;- renderSection();- expect(exportSwitch().getAttribute("aria-checked")).toBe("false");+ expect(settingSwitchLabels()).toEqual([+ "settings.general.workspace.data-copy",+ "settings.general.workspace.allow-admin-data-source.self",+ ]);});- test("toggling the switch marks the section dirty for the Update bar", () => {- mocks.policy.disableExport = false;- const ref = renderSection();- expect(ref.current?.isDirty()).toBe(false);+ test("saving a toggle change upserts the remaining policy fields", async () => {+ const ref = createRef<SectionHandle>();+ render(+ <SQLEditorSection ref={ref} title="SQL Editor" onDirtyChange={() => {}} />+ );+ const copySwitch = container.querySelector<HTMLElement>('[role="switch"]');act(() => {- exportSwitch().click();+ copySwitch!.click();});expect(ref.current?.isDirty()).toBe(true);- expect(exportSwitch().getAttribute("aria-checked")).toBe("false");++ await act(async () => {+ await ref.current?.update();+ });++ expect(mocks.upsertPolicy).toHaveBeenCalledTimes(1);+ expect(mocks.upsertPolicy.mock.calls[0][0]).toMatchObject({+ policy: {+ policy: {+ case: "queryDataPolicy",+ value: { disableCopyData: true, allowAdminDataSource: false },+ },+ },+ });});});diff --git a/frontend/src/routes/workspace/general/SQLEditorSection.tsx b/frontend/src/routes/workspace/general/SQLEditorSection.tsxindex 63353f02da..8f2f88943e 100644--- a/frontend/src/routes/workspace/general/SQLEditorSection.tsx+++ b/frontend/src/routes/workspace/general/SQLEditorSection.tsx@@ -75,7 +75,6 @@ interface SQLEditorSectionProps {}interface LocalState {- disableExport: boolean;disableCopyData: boolean;allowAdminDataSource: boolean;// `null` represents an empty input while the user is typing; coerced to a@@ -149,7 +148,6 @@ export const SQLEditorSection = forwardRef<rows = 0;}return {- disableExport: policyPayload.disableExport,disableCopyData: policyPayload.disableCopyData,allowAdminDataSource: policyPayload.allowAdminDataSource,maximumResultSize: Math.round(Number(size) / 1024 / 1024),@@ -291,7 +289,6 @@ export const SQLEditorSection = forwardRef<const init = getInitialState();const maximumResultRows = state.maximumResultRows ?? 0;return (- init.disableExport !== state.disableExport ||init.disableCopyData !== state.disableCopyData ||init.allowAdminDataSource !== state.allowAdminDataSource ||init.maximumResultRows !== maximumResultRows@@ -356,7 +353,6 @@ export const SQLEditorSection = forwardRef<case: "queryDataPolicy",value: create(QueryDataPolicySchema, {...policyPayload,- disableExport: state.disableExport,disableCopyData: state.disableCopyData,allowAdminDataSource: state.allowAdminDataSource,maximumResultRows,@@ -406,7 +402,7 @@ export const SQLEditorSection = forwardRef<}, [state, selectedThemeId, customDraft, onDirtyChange]);const handleToggle = (- field: "disableExport" | "disableCopyData" | "allowAdminDataSource",+ field: "disableCopyData" | "allowAdminDataSource",value: boolean) => {setState((prev) => ({ ...prev, [field]: value }));@@ -422,28 +418,6 @@ export const SQLEditorSection = forwardRef<return (<FormSection id="security" title={title}><FormFieldGroup>- {/* Data Export toggle */}- <PermissionGuard permissions={["bb.policies.update"]} display="block">- <FormField- title={- <span className="w-full inline-flex items-center gap-x-2">- <Switch- checked={!state.disableExport}- disabled={!canUpdatePolicy || !hasQueryPolicyFeature}- onCheckedChange={(checked) =>- handleToggle("disableExport", !checked)- }- />- {t("settings.general.workspace.data-export.self")}- <FeatureBadge feature={PlanFeature.FEATURE_QUERY_POLICY} />- </span>- }- description={t(- "settings.general.workspace.data-export.description"- )}- />- </PermissionGuard>-{/* Data Copy toggle */}<PermissionGuard permissions={["bb.policies.update"]} display="block"><FormFielddiff --git a/frontend/src/types/iam/permission-generated.ts b/frontend/src/types/iam/permission-generated.tsindex eeb00940f6..0562219560 100644--- a/frontend/src/types/iam/permission-generated.ts+++ b/frontend/src/types/iam/permission-generated.ts@@ -130,6 +130,7 @@ export type Permission =| "bb.sheets.get"| "bb.subscription.manage"| "bb.sql.select"+ | "bb.sql.export"| "bb.sql.ddl"| "bb.sql.dml"| "bb.sql.explain"diff --git a/frontend/src/types/iam/permission.ts b/frontend/src/types/iam/permission.tsindex 3b51c16085..5cd3f077a5 100644--- a/frontend/src/types/iam/permission.ts+++ b/frontend/src/types/iam/permission.ts@@ -5,6 +5,7 @@ export type { Permission };export type QueryPermission = Extract<Permission,| "bb.sql.select"+ | "bb.sql.export"| "bb.sql.info"| "bb.sql.explain"| "bb.sql.ddl"diff --git a/frontend/src/types/iam/role.ts b/frontend/src/types/iam/role.tsindex 4dc35a9604..96b4f1c99c 100644--- a/frontend/src/types/iam/role.ts+++ b/frontend/src/types/iam/role.ts@@ -8,6 +8,7 @@ export enum PresetRoleType {PROJECT_DEVELOPER = `${roleNamePrefix}projectDeveloper`,SQL_EDITOR_USER = `${roleNamePrefix}sqlEditorUser`,SQL_EDITOR_READ_USER = `${roleNamePrefix}sqlEditorReadUser`,+ SQL_EDITOR_EXPORTER = `${roleNamePrefix}sqlEditorExporter`,PROJECT_RELEASER = `${roleNamePrefix}projectReleaser`,GITOPS_SERVICE_AGENT = `${roleNamePrefix}gitopsServiceAgent`,PROJECT_VIEWER = `${roleNamePrefix}projectViewer`,@@ -27,6 +28,7 @@ export const PRESET_PROJECT_ROLES: string[] = [PresetRoleType.PROJECT_RELEASER,PresetRoleType.SQL_EDITOR_USER,PresetRoleType.SQL_EDITOR_READ_USER,+ PresetRoleType.SQL_EDITOR_EXPORTER,PresetRoleType.PROJECT_VIEWER,PresetRoleType.GITOPS_SERVICE_AGENT,];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 ed8bba3055..b46574870b 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@@ -115,7 +115,8 @@ export declare type AccessGrant = Message<"bytebase.v1.AccessGrant"> & {reason: string;/**- * Whether export the query result.+ * Whether the grant allows exporting the query result.+ * An active grant with export=true grants bb.sql.export for this query until the grant expires.** @generated from field: bool export = 13;*/diff --git a/frontend/src/types/proto-es/v1/iam_policy_pb.d.ts b/frontend/src/types/proto-es/v1/iam_policy_pb.d.tsindex 8c0037c310..64bb13ad68 100644--- a/frontend/src/types/proto-es/v1/iam_policy_pb.d.ts+++ b/frontend/src/types/proto-es/v1/iam_policy_pb.d.ts@@ -132,9 +132,9 @@ export declare type Binding = Message<"bytebase.v1.Binding"> & {* The syntax and semantics of CEL are documented at https://github.com/google/cel-spec** Support variables:- * resource.database: the canonical database full name in "instances/{instance}/databases/{database}" or "projects/{project}/instances/{instance}/databases/{database}" format, used by any role with SQL Editor read (e.g. "roles/sqlEditorUser", "roles/sqlEditorReadUser") or write (bb.sql.ddl / bb.sql.dml) access, support "==" operator.- * resource.schema_name: the schema name, used by any role with SQL Editor read or write (bb.sql.ddl / bb.sql.dml) access; for writes it is evaluated per write-target table, support "==" operator.- * resource.table_name: the table name, used by any role with SQL Editor read or write (bb.sql.ddl / bb.sql.dml) access; for writes it is evaluated per write-target table, support "==" operator.+ * resource.database: the canonical database full name in "instances/{instance}/databases/{database}" or "projects/{project}/instances/{instance}/databases/{database}" format, used by any role with SQL Editor read (e.g. "roles/sqlEditorUser", "roles/sqlEditorReadUser"), export (bb.sql.export, e.g. "roles/sqlEditorExporter") or write (bb.sql.ddl / bb.sql.dml) access, support "==" operator.+ * resource.schema_name: the schema name, used by any role with SQL Editor read, export (bb.sql.export) or write (bb.sql.ddl / bb.sql.dml) access; for writes it is evaluated per write-target table, support "==" operator.+ * resource.table_name: the table name, used by any role with SQL Editor read, export (bb.sql.export) or write (bb.sql.ddl / bb.sql.dml) access; for writes it is evaluated per write-target table, support "==" operator.* resource.environment_id: the environment to allow the DDL/DML operation in the SQL Editor, only works for the role with bb.sql.ddl or bb.sql.dml permissions. Support "in" operator.* request.time: the expiration. Only support "<" operation in `request.time < timestamp("{ISO datetime string format}")`.*diff --git a/frontend/src/types/proto-es/v1/issue_service_pb.d.ts b/frontend/src/types/proto-es/v1/issue_service_pb.d.tsindex e35304fec7..643f04721e 100644--- a/frontend/src/types/proto-es/v1/issue_service_pb.d.ts+++ b/frontend/src/types/proto-es/v1/issue_service_pb.d.ts@@ -705,7 +705,7 @@ export declare const Issue_TypeSchema: GenEnum<Issue_Type>;export declare type RoleGrant = Message<"bytebase.v1.RoleGrant"> & {/*** The requested role.- * Format: roles/EXPORTER.+ * Format: roles/{role}.** @generated from field: string role = 1;*/diff --git a/frontend/src/types/proto-es/v1/org_policy_service_pb.d.ts b/frontend/src/types/proto-es/v1/org_policy_service_pb.d.tsindex 3104746cac..29dd539eb2 100644--- a/frontend/src/types/proto-es/v1/org_policy_service_pb.d.ts+++ b/frontend/src/types/proto-es/v1/org_policy_service_pb.d.ts@@ -370,10 +370,10 @@ export declare type QueryDataPolicy = Message<"bytebase.v1.QueryDataPolicy"> & {maximumResultRows: number;/**- * workspace-level policy- * Disable data export in the SQL editor.+ * Deprecated: export is controlled by the bb.sql.export permission. Always false; setting it to true is rejected.*- * @generated from field: bool disable_export = 2;+ * @generated from field: bool disable_export = 2 [deprecated = true];+ * @deprecated*/disableExport: boolean;diff --git a/frontend/src/types/proto-es/v1/org_policy_service_pb.js b/frontend/src/types/proto-es/v1/org_policy_service_pb.jsindex c909b65b13..941b779b84 100644--- a/frontend/src/types/proto-es/v1/org_policy_service_pb.js+++ b/frontend/src/types/proto-es/v1/org_policy_service_pb.js@@ -16,7 +16,7 @@ import { file_v1_review_rule } from "./review_rule_pb";* Describes the file v1/org_policy_service.proto.*/export const file_v1_org_policy_service = /*@__PURE__*/- fileDesc("Cht2MS9vcmdfcG9saWN5X3NlcnZpY2UucHJvdG8SC2J5dGViYXNlLnYxIpMBChNDcmVhdGVQb2xpY3lSZXF1ZXN0EisKBnBhcmVudBgBIAEoCUIb4EEC+kEVEhNieXRlYmFzZS5jb20vUG9saWN5EigKBnBvbGljeRgCIAEoCzITLmJ5dGViYXNlLnYxLlBvbGljeUID4EECEiUKBHR5cGUYAyABKA4yFy5ieXRlYmFzZS52MS5Qb2xpY3lUeXBlIocBChNVcGRhdGVQb2xpY3lSZXF1ZXN0EigKBnBvbGljeRgBIAEoCzITLmJ5dGViYXNlLnYxLlBvbGljeUID4EECEi8KC3VwZGF0ZV9tYXNrGAIgASgLMhouZ29vZ2xlLnByb3RvYnVmLkZpZWxkTWFzaxIVCg1hbGxvd19taXNzaW5nGAMgASgIIkAKE0RlbGV0ZVBvbGljeVJlcXVlc3QSKQoEbmFtZRgBIAEoCUIb4EEC+kEVChNieXRlYmFzZS5jb20vUG9saWN5Ij0KEEdldFBvbGljeVJlcXVlc3QSKQoEbmFtZRgBIAEoCUIb4EEC+kEVChNieXRlYmFzZS5jb20vUG9saWN5IpsBChNMaXN0UG9saWNpZXNSZXF1ZXN0EisKBnBhcmVudBgBIAEoCUIb4EEC+kEVEhNieXRlYmFzZS5jb20vUG9saWN5EjEKC3BvbGljeV90eXBlGAIgASgOMhcuYnl0ZWJhc2UudjEuUG9saWN5VHlwZUgAiAEBEhQKDHNob3dfZGVsZXRlZBgDIAEoCEIOCgxfcG9saWN5X3R5cGUiPQoUTGlzdFBvbGljaWVzUmVzcG9uc2USJQoIcG9saWNpZXMYASADKAsyEy5ieXRlYmFzZS52MS5Qb2xpY3ki7wUKBlBvbGljeRIMCgRuYW1lGAEgASgJEhsKE2luaGVyaXRfZnJvbV9wYXJlbnQYAiABKAgSJQoEdHlwZRgDIAEoDjIXLmJ5dGViYXNlLnYxLlBvbGljeVR5cGUSNAoOcm9sbG91dF9wb2xpY3kYBCABKAsyGi5ieXRlYmFzZS52MS5Sb2xsb3V0UG9saWN5SAASPQoTbWFza2luZ19ydWxlX3BvbGljeRgFIAEoCzIeLmJ5dGViYXNlLnYxLk1hc2tpbmdSdWxlUG9saWN5SAASRwoYbWFza2luZ19leGVtcHRpb25fcG9saWN5GAYgASgLMiMuYnl0ZWJhc2UudjEuTWFza2luZ0V4ZW1wdGlvblBvbGljeUgAEiwKCnRhZ19wb2xpY3kYByABKAsyFi5ieXRlYmFzZS52MS5UYWdQb2xpY3lIABI5ChFxdWVyeV9kYXRhX3BvbGljeRgJIAEoCzIcLmJ5dGViYXNlLnYxLlF1ZXJ5RGF0YVBvbGljeUgAEjsKEnJldmlld19ydWxlX3BvbGljeRgMIAEoCzIdLmJ5dGViYXNlLnYxLlJldmlld1J1bGVQb2xpY3lIABI3ChByZXZpZXdfYWlfcG9saWN5GA0gASgLMhsuYnl0ZWJhc2UudjEuUmV2aWV3QUlQb2xpY3lIABIPCgdlbmZvcmNlGAogASgIEjsKDXJlc291cmNlX3R5cGUYCyABKA4yHy5ieXRlYmFzZS52MS5Qb2xpY3lSZXNvdXJjZVR5cGVCA+BBAzqXAepBkwEKE2J5dGViYXNlLmNvbS9Qb2xpY3kSKHdvcmtzcGFjZXMve3dvcmtzcGFjZX0vcG9saWNpZXMve3BvbGljeX0SJHByb2plY3RzL3twcm9qZWN0fS9wb2xpY2llcy97cG9saWN5fRIsZW52aXJvbm1lbnRzL3tlbnZpcm9ubWVudH0vcG9saWNpZXMve3BvbGljeX1CCAoGcG9saWN5SgQICBAJIj4KEFJldmlld1J1bGVQb2xpY3kSKgoFcnVsZXMYASADKA4yGy5ieXRlYmFzZS52MS5SZXZpZXdSdWxlVHlwZSIhCg5SZXZpZXdBSVBvbGljeRIPCgdjb250ZW50GAEgASgJIjEKDVJvbGxvdXRQb2xpY3kSEQoJYXV0b21hdGljGAEgASgIEg0KBXJvbGVzGAIgAygJIoIBCg9RdWVyeURhdGFQb2xpY3kSGwoTbWF4aW11bV9yZXN1bHRfcm93cxgBIAEoBRIWCg5kaXNhYmxlX2V4cG9ydBgCIAEoCBIZChFkaXNhYmxlX2NvcHlfZGF0YRgDIAEoCBIfChdhbGxvd19hZG1pbl9kYXRhX3NvdXJjZRgEIAEoCCKfAQoWTWFza2luZ0V4ZW1wdGlvblBvbGljeRJBCgpleGVtcHRpb25zGAEgAygLMi0uYnl0ZWJhc2UudjEuTWFza2luZ0V4ZW1wdGlvblBvbGljeS5FeGVtcHRpb24aQgoJRXhlbXB0aW9uEg8KB21lbWJlcnMYASADKAkSJAoJY29uZGl0aW9uGAIgASgLMhEuZ29vZ2xlLnR5cGUuRXhwciKmAQoRTWFza2luZ1J1bGVQb2xpY3kSOQoFcnVsZXMYASADKAsyKi5ieXRlYmFzZS52MS5NYXNraW5nUnVsZVBvbGljeS5NYXNraW5nUnVsZRpWCgtNYXNraW5nUnVsZRIKCgJpZBgBIAEoCRIkCgljb25kaXRpb24YAiABKAsyES5nb29nbGUudHlwZS5FeHByEhUKDXNlbWFudGljX3R5cGUYAyABKAkiaAoJVGFnUG9saWN5Ei4KBHRhZ3MYASADKAsyIC5ieXRlYmFzZS52MS5UYWdQb2xpY3kuVGFnc0VudHJ5GisKCVRhZ3NFbnRyeRILCgNrZXkYASABKAkSDQoFdmFsdWUYAiABKAk6AjgBKqUBCgpQb2xpY3lUeXBlEhsKF1BPTElDWV9UWVBFX1VOU1BFQ0lGSUVEEAASEAoMTUFTS0lOR19SVUxFEAESFQoRTUFTS0lOR19FWEVNUFRJT04QAhISCg5ST0xMT1VUX1BPTElDWRADEgcKA1RBRxAEEg4KCkRBVEFfUVVFUlkQBhIPCgtSRVZJRVdfUlVMRRAHEg0KCVJFVklFV19BSRAIIgQIBRAFKmAKElBvbGljeVJlc291cmNlVHlwZRIdChlSRVNPVVJDRV9UWVBFX1VOU1BFQ0lGSUVEEAASDQoJV09SS1NQQUNFEAESDwoLRU5WSVJPTk1FTlQQAhILCgdQUk9KRUNUEAMyhAoKEE9yZ1BvbGljeVNlcnZpY2US2gEKCUdldFBvbGljeRIdLmJ5dGViYXNlLnYxLkdldFBvbGljeVJlcXVlc3QaEy5ieXRlYmFzZS52MS5Qb2xpY3kimAHaQQRuYW1liuowD2JiLnBvbGljaWVzLmdldJDqMAKg6jABgtPkkwJwWiISIC92MS97bmFtZT1wcm9qZWN0cy8qL3BvbGljaWVzLyp9WiYSJC92MS97bmFtZT1lbnZpcm9ubWVudHMvKi9wb2xpY2llcy8qfRIiL3YxL3tuYW1lPXdvcmtzcGFjZXMvKi9wb2xpY2llcy8qfRLrAQoMTGlzdFBvbGljaWVzEiAuYnl0ZWJhc2UudjEuTGlzdFBvbGljaWVzUmVxdWVzdBohLmJ5dGViYXNlLnYxLkxpc3RQb2xpY2llc1Jlc3BvbnNlIpUB2kEAiuowEGJiLnBvbGljaWVzLmxpc3SQ6jABoOowAYLT5JMCcFoiEiAvdjEve3BhcmVudD1wcm9qZWN0cy8qfS9wb2xpY2llc1omEiQvdjEve3BhcmVudD1lbnZpcm9ubWVudHMvKn0vcG9saWNpZXMSIi92MS97cGFyZW50PXdvcmtzcGFjZXMvKn0vcG9saWNpZXMSjQIKDENyZWF0ZVBvbGljeRIgLmJ5dGViYXNlLnYxLkNyZWF0ZVBvbGljeVJlcXVlc3QaEy5ieXRlYmFzZS52MS5Qb2xpY3kixQHaQQ1wYXJlbnQscG9saWN5iuowEmJiLnBvbGljaWVzLmNyZWF0ZZDqMAKY6jABoOowBKjqMAmC0+STAogBOgZwb2xpY3laKjoGcG9saWN5IiAvdjEve3BhcmVudD1wcm9qZWN0cy8qfS9wb2xpY2llc1ouOgZwb2xpY3kiJC92MS97cGFyZW50PWVudmlyb25tZW50cy8qfS9wb2xpY2llcyIiL3YxL3twYXJlbnQ9d29ya3NwYWNlcy8qfS9wb2xpY2llcxKjAgoMVXBkYXRlUG9saWN5EiAuYnl0ZWJhc2UudjEuVXBkYXRlUG9saWN5UmVxdWVzdBoTLmJ5dGViYXNlLnYxLlBvbGljeSLbAdpBEnBvbGljeSx1cGRhdGVfbWFza4rqMBJiYi5wb2xpY2llcy51cGRhdGWQ6jACmOowAaDqMAKC0+STAp0BOgZwb2xpY3laMToGcG9saWN5MicvdjEve3BvbGljeS5uYW1lPXByb2plY3RzLyovcG9saWNpZXMvKn1aNToGcG9saWN5MisvdjEve3BvbGljeS5uYW1lPWVudmlyb25tZW50cy8qL3BvbGljaWVzLyp9MikvdjEve3BvbGljeS5uYW1lPXdvcmtzcGFjZXMvKi9wb2xpY2llcy8qfRLuAQoMRGVsZXRlUG9saWN5EiAuYnl0ZWJhc2UudjEuRGVsZXRlUG9saWN5UmVxdWVzdBoWLmdvb2dsZS5wcm90b2J1Zi5FbXB0eSKjAdpBBG5hbWWK6jASYmIucG9saWNpZXMuZGVsZXRlkOowApjqMAGg6jAEqOowCYLT5JMCcFoiKiAvdjEve25hbWU9cHJvamVjdHMvKi9wb2xpY2llcy8qfVomKiQvdjEve25hbWU9ZW52aXJvbm1lbnRzLyovcG9saWNpZXMvKn0qIi92MS97bmFtZT13b3Jrc3BhY2VzLyovcG9saWNpZXMvKn1CqwEKD2NvbS5ieXRlYmFzZS52MUIVT3JnUG9saWN5U2VydmljZVByb3RvUAFaNGdpdGh1Yi5jb20vYnl0ZWJhc2UvYnl0ZWJhc2UvYmFja2VuZC9nZW5lcmF0ZWQtZ28vdjGiAgNCWFiqAgtCeXRlYmFzZS5WMcoCC0J5dGViYXNlXFYx4gIXQnl0ZWJhc2VcVjFcR1BCTWV0YWRhdGHqAgxCeXRlYmFzZTo6VjFiBnByb3RvMw", [file_google_api_annotations, file_google_api_client, file_google_api_field_behavior, file_google_api_resource, file_google_protobuf_empty, file_google_protobuf_field_mask, file_google_type_expr, file_v1_annotation, file_v1_review_rule]);+ fileDesc("Cht2MS9vcmdfcG9saWN5X3NlcnZpY2UucHJvdG8SC2J5dGViYXNlLnYxIpMBChNDcmVhdGVQb2xpY3lSZXF1ZXN0EisKBnBhcmVudBgBIAEoCUIb4EEC+kEVEhNieXRlYmFzZS5jb20vUG9saWN5EigKBnBvbGljeRgCIAEoCzITLmJ5dGViYXNlLnYxLlBvbGljeUID4EECEiUKBHR5cGUYAyABKA4yFy5ieXRlYmFzZS52MS5Qb2xpY3lUeXBlIocBChNVcGRhdGVQb2xpY3lSZXF1ZXN0EigKBnBvbGljeRgBIAEoCzITLmJ5dGViYXNlLnYxLlBvbGljeUID4EECEi8KC3VwZGF0ZV9tYXNrGAIgASgLMhouZ29vZ2xlLnByb3RvYnVmLkZpZWxkTWFzaxIVCg1hbGxvd19taXNzaW5nGAMgASgIIkAKE0RlbGV0ZVBvbGljeVJlcXVlc3QSKQoEbmFtZRgBIAEoCUIb4EEC+kEVChNieXRlYmFzZS5jb20vUG9saWN5Ij0KEEdldFBvbGljeVJlcXVlc3QSKQoEbmFtZRgBIAEoCUIb4EEC+kEVChNieXRlYmFzZS5jb20vUG9saWN5IpsBChNMaXN0UG9saWNpZXNSZXF1ZXN0EisKBnBhcmVudBgBIAEoCUIb4EEC+kEVEhNieXRlYmFzZS5jb20vUG9saWN5EjEKC3BvbGljeV90eXBlGAIgASgOMhcuYnl0ZWJhc2UudjEuUG9saWN5VHlwZUgAiAEBEhQKDHNob3dfZGVsZXRlZBgDIAEoCEIOCgxfcG9saWN5X3R5cGUiPQoUTGlzdFBvbGljaWVzUmVzcG9uc2USJQoIcG9saWNpZXMYASADKAsyEy5ieXRlYmFzZS52MS5Qb2xpY3ki7wUKBlBvbGljeRIMCgRuYW1lGAEgASgJEhsKE2luaGVyaXRfZnJvbV9wYXJlbnQYAiABKAgSJQoEdHlwZRgDIAEoDjIXLmJ5dGViYXNlLnYxLlBvbGljeVR5cGUSNAoOcm9sbG91dF9wb2xpY3kYBCABKAsyGi5ieXRlYmFzZS52MS5Sb2xsb3V0UG9saWN5SAASPQoTbWFza2luZ19ydWxlX3BvbGljeRgFIAEoCzIeLmJ5dGViYXNlLnYxLk1hc2tpbmdSdWxlUG9saWN5SAASRwoYbWFza2luZ19leGVtcHRpb25fcG9saWN5GAYgASgLMiMuYnl0ZWJhc2UudjEuTWFza2luZ0V4ZW1wdGlvblBvbGljeUgAEiwKCnRhZ19wb2xpY3kYByABKAsyFi5ieXRlYmFzZS52MS5UYWdQb2xpY3lIABI5ChFxdWVyeV9kYXRhX3BvbGljeRgJIAEoCzIcLmJ5dGViYXNlLnYxLlF1ZXJ5RGF0YVBvbGljeUgAEjsKEnJldmlld19ydWxlX3BvbGljeRgMIAEoCzIdLmJ5dGViYXNlLnYxLlJldmlld1J1bGVQb2xpY3lIABI3ChByZXZpZXdfYWlfcG9saWN5GA0gASgLMhsuYnl0ZWJhc2UudjEuUmV2aWV3QUlQb2xpY3lIABIPCgdlbmZvcmNlGAogASgIEjsKDXJlc291cmNlX3R5cGUYCyABKA4yHy5ieXRlYmFzZS52MS5Qb2xpY3lSZXNvdXJjZVR5cGVCA+BBAzqXAepBkwEKE2J5dGViYXNlLmNvbS9Qb2xpY3kSKHdvcmtzcGFjZXMve3dvcmtzcGFjZX0vcG9saWNpZXMve3BvbGljeX0SJHByb2plY3RzL3twcm9qZWN0fS9wb2xpY2llcy97cG9saWN5fRIsZW52aXJvbm1lbnRzL3tlbnZpcm9ubWVudH0vcG9saWNpZXMve3BvbGljeX1CCAoGcG9saWN5SgQICBAJIj4KEFJldmlld1J1bGVQb2xpY3kSKgoFcnVsZXMYASADKA4yGy5ieXRlYmFzZS52MS5SZXZpZXdSdWxlVHlwZSIhCg5SZXZpZXdBSVBvbGljeRIPCgdjb250ZW50GAEgASgJIjEKDVJvbGxvdXRQb2xpY3kSEQoJYXV0b21hdGljGAEgASgIEg0KBXJvbGVzGAIgAygJIoYBCg9RdWVyeURhdGFQb2xpY3kSGwoTbWF4aW11bV9yZXN1bHRfcm93cxgBIAEoBRIaCg5kaXNhYmxlX2V4cG9ydBgCIAEoCEICGAESGQoRZGlzYWJsZV9jb3B5X2RhdGEYAyABKAgSHwoXYWxsb3dfYWRtaW5fZGF0YV9zb3VyY2UYBCABKAginwEKFk1hc2tpbmdFeGVtcHRpb25Qb2xpY3kSQQoKZXhlbXB0aW9ucxgBIAMoCzItLmJ5dGViYXNlLnYxLk1hc2tpbmdFeGVtcHRpb25Qb2xpY3kuRXhlbXB0aW9uGkIKCUV4ZW1wdGlvbhIPCgdtZW1iZXJzGAEgAygJEiQKCWNvbmRpdGlvbhgCIAEoCzIRLmdvb2dsZS50eXBlLkV4cHIipgEKEU1hc2tpbmdSdWxlUG9saWN5EjkKBXJ1bGVzGAEgAygLMiouYnl0ZWJhc2UudjEuTWFza2luZ1J1bGVQb2xpY3kuTWFza2luZ1J1bGUaVgoLTWFza2luZ1J1bGUSCgoCaWQYASABKAkSJAoJY29uZGl0aW9uGAIgASgLMhEuZ29vZ2xlLnR5cGUuRXhwchIVCg1zZW1hbnRpY190eXBlGAMgASgJImgKCVRhZ1BvbGljeRIuCgR0YWdzGAEgAygLMiAuYnl0ZWJhc2UudjEuVGFnUG9saWN5LlRhZ3NFbnRyeRorCglUYWdzRW50cnkSCwoDa2V5GAEgASgJEg0KBXZhbHVlGAIgASgJOgI4ASqlAQoKUG9saWN5VHlwZRIbChdQT0xJQ1lfVFlQRV9VTlNQRUNJRklFRBAAEhAKDE1BU0tJTkdfUlVMRRABEhUKEU1BU0tJTkdfRVhFTVBUSU9OEAISEgoOUk9MTE9VVF9QT0xJQ1kQAxIHCgNUQUcQBBIOCgpEQVRBX1FVRVJZEAYSDwoLUkVWSUVXX1JVTEUQBxINCglSRVZJRVdfQUkQCCIECAUQBSpgChJQb2xpY3lSZXNvdXJjZVR5cGUSHQoZUkVTT1VSQ0VfVFlQRV9VTlNQRUNJRklFRBAAEg0KCVdPUktTUEFDRRABEg8KC0VOVklST05NRU5UEAISCwoHUFJPSkVDVBADMoQKChBPcmdQb2xpY3lTZXJ2aWNlEtoBCglHZXRQb2xpY3kSHS5ieXRlYmFzZS52MS5HZXRQb2xpY3lSZXF1ZXN0GhMuYnl0ZWJhc2UudjEuUG9saWN5IpgB2kEEbmFtZYrqMA9iYi5wb2xpY2llcy5nZXSQ6jACoOowAYLT5JMCcFoiEiAvdjEve25hbWU9cHJvamVjdHMvKi9wb2xpY2llcy8qfVomEiQvdjEve25hbWU9ZW52aXJvbm1lbnRzLyovcG9saWNpZXMvKn0SIi92MS97bmFtZT13b3Jrc3BhY2VzLyovcG9saWNpZXMvKn0S6wEKDExpc3RQb2xpY2llcxIgLmJ5dGViYXNlLnYxLkxpc3RQb2xpY2llc1JlcXVlc3QaIS5ieXRlYmFzZS52MS5MaXN0UG9saWNpZXNSZXNwb25zZSKVAdpBAIrqMBBiYi5wb2xpY2llcy5saXN0kOowAaDqMAGC0+STAnBaIhIgL3YxL3twYXJlbnQ9cHJvamVjdHMvKn0vcG9saWNpZXNaJhIkL3YxL3twYXJlbnQ9ZW52aXJvbm1lbnRzLyp9L3BvbGljaWVzEiIvdjEve3BhcmVudD13b3Jrc3BhY2VzLyp9L3BvbGljaWVzEo0CCgxDcmVhdGVQb2xpY3kSIC5ieXRlYmFzZS52MS5DcmVhdGVQb2xpY3lSZXF1ZXN0GhMuYnl0ZWJhc2UudjEuUG9saWN5IsUB2kENcGFyZW50LHBvbGljeYrqMBJiYi5wb2xpY2llcy5jcmVhdGWQ6jACmOowAaDqMASo6jAJgtPkkwKIAToGcG9saWN5Wio6BnBvbGljeSIgL3YxL3twYXJlbnQ9cHJvamVjdHMvKn0vcG9saWNpZXNaLjoGcG9saWN5IiQvdjEve3BhcmVudD1lbnZpcm9ubWVudHMvKn0vcG9saWNpZXMiIi92MS97cGFyZW50PXdvcmtzcGFjZXMvKn0vcG9saWNpZXMSowIKDFVwZGF0ZVBvbGljeRIgLmJ5dGViYXNlLnYxLlVwZGF0ZVBvbGljeVJlcXVlc3QaEy5ieXRlYmFzZS52MS5Qb2xpY3ki2wHaQRJwb2xpY3ksdXBkYXRlX21hc2uK6jASYmIucG9saWNpZXMudXBkYXRlkOowApjqMAGg6jACgtPkkwKdAToGcG9saWN5WjE6BnBvbGljeTInL3YxL3twb2xpY3kubmFtZT1wcm9qZWN0cy8qL3BvbGljaWVzLyp9WjU6BnBvbGljeTIrL3YxL3twb2xpY3kubmFtZT1lbnZpcm9ubWVudHMvKi9wb2xpY2llcy8qfTIpL3YxL3twb2xpY3kubmFtZT13b3Jrc3BhY2VzLyovcG9saWNpZXMvKn0S7gEKDERlbGV0ZVBvbGljeRIgLmJ5dGViYXNlLnYxLkRlbGV0ZVBvbGljeVJlcXVlc3QaFi5nb29nbGUucHJvdG9idWYuRW1wdHkiowHaQQRuYW1liuowEmJiLnBvbGljaWVzLmRlbGV0ZZDqMAKY6jABoOowBKjqMAmC0+STAnBaIiogL3YxL3tuYW1lPXByb2plY3RzLyovcG9saWNpZXMvKn1aJiokL3YxL3tuYW1lPWVudmlyb25tZW50cy8qL3BvbGljaWVzLyp9KiIvdjEve25hbWU9d29ya3NwYWNlcy8qL3BvbGljaWVzLyp9QqsBCg9jb20uYnl0ZWJhc2UudjFCFU9yZ1BvbGljeVNlcnZpY2VQcm90b1ABWjRnaXRodWIuY29tL2J5dGViYXNlL2J5dGViYXNlL2JhY2tlbmQvZ2VuZXJhdGVkLWdvL3YxogIDQlhYqgILQnl0ZWJhc2UuVjHKAgtCeXRlYmFzZVxWMeICF0J5dGViYXNlXFYxXEdQQk1ldGFkYXRh6gIMQnl0ZWJhc2U6OlYxYgZwcm90bzM", [file_google_api_annotations, file_google_api_client, file_google_api_field_behavior, file_google_api_resource, file_google_protobuf_empty, file_google_protobuf_field_mask, file_google_type_expr, file_v1_annotation, file_v1_review_rule]);/*** Describes the message bytebase.v1.CreatePolicyRequest.diff --git a/frontend/src/types/proto-es/v1/sql_service_pb.d.ts b/frontend/src/types/proto-es/v1/sql_service_pb.d.tsindex 520ade3e2e..924e5f7684 100644--- a/frontend/src/types/proto-es/v1/sql_service_pb.d.ts+++ b/frontend/src/types/proto-es/v1/sql_service_pb.d.ts@@ -1250,7 +1250,8 @@ export declare const SQLService: GenService<{},/*** Exports query results to a file format.- * Permissions required: bb.databases.get+ * Permissions required: bb.databases.get, and bb.sql.export on the data the statement reads.+ * An active access grant with export=true for the statement satisfies bb.sql.export on its target databases.** @generated from rpc bytebase.v1.SQLService.Export*/diff --git a/frontend/src/utils/role.ts b/frontend/src/utils/role.tsindex e7dfa835be..1850568c37 100644--- a/frontend/src/utils/role.ts+++ b/frontend/src/utils/role.ts@@ -38,6 +38,8 @@ export const displayRoleTitle = (role: string): string => {return i18n.t("role.sql-editor-user.self");case PresetRoleType.SQL_EDITOR_READ_USER:return i18n.t("role.sql-editor-read-user.self");+ case PresetRoleType.SQL_EDITOR_EXPORTER:+ return i18n.t("role.sql-editor-exporter.self");case PresetRoleType.GITOPS_SERVICE_AGENT:return i18n.t("role.gitops-service-agent.self");case PresetRoleType.PROJECT_VIEWER:@@ -67,6 +69,8 @@ export const displayRoleDescription = (role: string): string => {return i18n.t("role.sql-editor-user.description");case PresetRoleType.SQL_EDITOR_READ_USER:return i18n.t("role.sql-editor-read-user.description");+ case PresetRoleType.SQL_EDITOR_EXPORTER:+ return i18n.t("role.sql-editor-exporter.description");case PresetRoleType.GITOPS_SERVICE_AGENT:return i18n.t("role.gitops-service-agent.description");case PresetRoleType.PROJECT_VIEWER:diff --git a/frontend/tests/e2e/README.md b/frontend/tests/e2e/README.mdindex 2099133b2f..32548ab6c2 100644--- a/frontend/tests/e2e/README.md+++ b/frontend/tests/e2e/README.md@@ -57,7 +57,7 @@ pnpm exec playwright test masking-exemption### Enterprise licenseThe suite exercises enterprise-only features (masking, JIT drawer, approval-rules, query-data-policy gates like `disableExport` / `disableCopyData`,+rules, query-data-policy gates like `disableCopyData`,database groups) and does not run on the free plan. Global setup installs alicense before any spec runs, resolved in this order:diff --git a/frontend/tests/e2e/sql-editor/sql-editor-export.spec.ts b/frontend/tests/e2e/sql-editor/sql-editor-export.spec.tsindex 3620ba2c58..ccc6fabfdf 100644--- a/frontend/tests/e2e/sql-editor/sql-editor-export.spec.ts+++ b/frontend/tests/e2e/sql-editor/sql-editor-export.spec.ts@@ -1,11 +1,11 @@// SQL Editor — result export workflow (PRs #20487 / #20491 / #20501).//-// The export path was rewritten: the client-side `sql-download` formatter-// library was deleted and export now goes through the backend Export RPC. A-// workspace `DATA_QUERY` policy (`disableExport`) gates the toolbar's Export-// button; when export is disabled but the project allows access grants,-// a "Request export" affordance replaces it, and an active export grant-// for the EXACT statement re-enables the real Export button.+// Export goes through the backend Export RPC and requires bb.sql.export. A+// user who holds it through a role (SQL Editor Exporter, Workspace Admin) sees+// the toolbar's Export button. A user without it (SQL Editor Read User) sees a+// "Request export" affordance in projects that allow just-in-time access, and+// an active export grant for the EXACT statement re-enables the real Export+// button.//// One file per sub-area (the repo convention): all export CUJs live here as// describe blocks with describe-scoped setup, and the bug-lock is inlined@@ -15,84 +15,123 @@// the bug's state changes, not on an unrelated setup error).//// Groups (CUJ ids from the QA session):-// - Direct export (export allowed): C1 backend Export RPC, C9 password-// - Gated + JIT on: C2 Request export, C3/C4 drawer pre-fill (export only)-// - Gated + JIT off: C8 no affordance-// - Multi-statement: C10 one affordance above the tabs-// - Active export grant: C7 exact-match re-enable, C5 badge, C6 filter-// - Masking ↔ export security: no-leak without grant, reveal with grant+// - Exporter role: C1 backend Export RPC, C9 password+// - Read user + JIT on: C2 Request export, C3/C4 drawer pre-fill (export only)+// - Read user + JIT off: C8 no affordance+// - Read user, multi-statement: C10 one affordance above the tabs+// - Read user with an active export grant: C7 exact-match re-enable,+// C5 badge, C6 filter+// - Masking ↔ export security (admin): no-leak without grant, reveal with grant// - BUG (BYT-9656): re-request of a revoked grant drops the Export pre-fill//-// Owns its fixtures (API/psql for setup, browser for verification) and-// restores the workspace policy + project JIT in afterAll. Requires `psql` +-// `unzip` on PATH and an enterprise license (installed at bootstrap).--import { test, expect, type BrowserContext, type Page } from "@playwright/test";+// Owns its fixtures (API/psql for setup, browser for verification): it creates+// the two role users, binds them on the sample project, and removes the+// bindings and restores project JIT in afterAll. Each role signs in to its own+// browser context. Requires `psql` + `unzip` on PATH and an enterprise license+// (installed at bootstrap).++import {+ test,+ expect,+ type Browser,+ type BrowserContext,+ type Page,+} from "@playwright/test";import { execFileSync } from "child_process";import { loadTestEnv, type TestEnv } from "../framework/env";-import type { BytebaseApiClient } from "../framework/api-client";+import { BytebaseApiClient } from "../framework/api-client";import { execSql, getInstancePgPort } from "../framework/psql";+import { signInBrowserAs } from "../framework/sign-in";import { SqlEditorPage } from "./sql-editor.page";test.setTimeout(180_000);let env: TestEnv & { api: BytebaseApiClient };let projectId: string;-let workspace = "";let pgPort = "";let sharedContext: BrowserContext;let page: Page;let sqlEditor: SqlEditorPage;-// Snapshot of the original workspace QueryDataPolicy + project JIT flag so the-// file-level afterAll restores the baseline other specs depend on.-let originalDisableExport = false;-let originalDisableCopyData = false;-let originalMaxRows = 0;-let originalAllowAdminDataSource = false;+// Snapshot of the project JIT flag so the file-level afterAll restores the+// baseline other specs depend on.let originalJIT = false;// createActiveGrant + the masking reveal test flip allowSelfApproval; snapshot it// so afterAll restores it (otherwise it leaks into later specs).let originalSelfApproval = false;-async function setWorkspaceExportPolicy(disableExport: boolean): Promise<void> {- await env.api.upsertPolicy(workspace, "data_query", {- name: `${workspace}/policies/data_query`,- type: "DATA_QUERY",- resourceType: "WORKSPACE",- queryDataPolicy: {- disableExport,- disableCopyData: originalDisableCopyData,- allowAdminDataSource: originalAllowAdminDataSource,- maximumResultRows: originalMaxRows,- },+// The shared password of this file's role users.+const TEST_PASSWORD = "e2e-export-pw-1!"; // NOSONAR — e2e fixture only++// Holds bb.sql.export through SQL Editor Exporter.+const EXPORTER = {+ email: "[email protected]",+ title: "E2E Export Exporter",+ authFile: ".auth/export-exporter.json",+ role: "roles/sqlEditorExporter",+};+// Can query but lacks bb.sql.export.+const READER = {+ email: "[email protected]",+ title: "E2E Export Reader",+ authFile: ".auth/export-reader.json",+ role: "roles/sqlEditorReadUser",+};++type RoleContext = {+ context: BrowserContext;+ page: Page;+ sqlEditor: SqlEditorPage;+};++let exporter: RoleContext;+let reader: RoleContext;+// The reader's own API client: access grants belong to their creator.+let readerApi: BytebaseApiClient;++async function openAs(+ browser: Browser,+ user: { authFile: string },+): Promise<RoleContext> {+ // Clipboard permission so the C9 generate-password copy-gate hits its+ // SUCCESS path.+ const context = await browser.newContext({+ storageState: user.authFile,+ permissions: ["clipboard-read", "clipboard-write"],});+ const rolePage = await context.newPage();+ return {+ context,+ page: rolePage,+ sqlEditor: new SqlEditorPage(rolePage, env.baseURL),+ };}-// Apply the export-gate state, then hard-reload the editor so the SQL editor-// store picks up the new workspace policy + project JIT flag (both cached-// per-tab; an in-flight API change doesn't invalidate that cache).-async function applyExportState(opts: {- disableExport: boolean;- jit: boolean;-}): Promise<void> {- await setWorkspaceExportPolicy(opts.disableExport);+// Set the project JIT flag, then hard-reload the editor so the SQL editor+// store picks up the change (the project is cached per-tab; an in-flight API+// change doesn't invalidate that cache).+async function openEditorAs(+ rc: RoleContext,+ opts: { jit: boolean },+): Promise<void> {await env.api.updateProjectSettings(env.project, {allowJustInTimeAccess: opts.jit,});- await sqlEditor.gotoWithDb(projectId, env.instanceId, env.databaseId);- await page.waitForTimeout(1200);+ await rc.sqlEditor.gotoWithDb(projectId, env.instanceId, env.databaseId);+ await rc.page.waitForTimeout(1200);}-// Create a grant for `query` and drive it to ACTIVE. JIT grants open an-// approval issue even with no workspace approval rules; as workspace admin-// (creator + approver) we self-approve. The issue's approval flow can 404 for-// a beat right after creation, so retry approve until the grant activates.+// Create a grant for `query` as `creator` and drive it to ACTIVE. JIT grants+// open an approval issue even with no workspace approval rules; the workspace+// admin approves it, which needs self-approval when the admin is also the+// creator. The issue's approval flow can 404 for a beat right after creation,+// so retry approve until the grant activates.async function createActiveGrant(+ creator: BytebaseApiClient,query: string,caps: { unmask: boolean; export: boolean },): Promise<string> {- const grant = await env.api.createAccessGrant(env.project, {+ const grant = await creator.createAccessGrant(env.project, {targets: [env.database],query,reason: "e2e export grant",@@ -115,7 +154,7 @@ async function createActiveGrant(// many other grants exist (a client-side scan of a status==ACTIVE page// could miss ours past pageSize, and matching by query/caps could pick a// stale grant from a prior CI retry against the same server).- const r = await env.api.searchMyAccessGrants(+ const r = await creator.searchMyAccessGrants(env.project,`name == "${grant.name}"`,);@@ -132,28 +171,30 @@ async function createActiveGrant(// Open the export drawer (after a query is on screen) and return it, ready at// the Confirm step. Centralizes the click-Export + "Export Data" dialog + wait// ritual that C1/C7/C9 and the masking export helper all need.-async function openExportDrawer() {- await page.getByRole("button", { name: /^Export$/ }).first().click();- const drawer = page.getByRole("dialog").filter({ hasText: "Export Data" });+async function openExportDrawer(on: Page = page) {+ await on.getByRole("button", { name: /^Export$/ }).first().click();+ const drawer = on.getByRole("dialog").filter({ hasText: "Export Data" });await expect(drawer.getByText("Export rows")).toBeVisible({ timeout: 10_000 });return drawer;}+// Remove this file's role users from the project IAM policy.+async function removeRoleBindings(): Promise<void> {+ const members = [EXPORTER, READER].map((u) => `user:${u.email}`);+ const policy = await env.api.getProjectIamPolicy(env.project);+ policy.bindings = policy.bindings+ .map((b) => ({ ...b, members: b.members.filter((m) => !members.includes(m)) }))+ .filter((b) => b.members.length > 0);+ await env.api.setProjectIamPolicy(env.project, policy);+}+test.beforeAll(async ({ browser }) => {+ test.setTimeout(180_000);env = loadTestEnv();projectId = env.project.split("/").pop()!;await env.api.login(env.adminEmail, env.adminPassword);- ({ workspace } = await env.api.getActuatorInfo());pgPort = await getInstancePgPort(env);- const existing = await env.api.getPolicy(`${workspace}/policies/data_query`);- const qdp =- (existing as { queryDataPolicy?: Record<string, unknown> } | null)- ?.queryDataPolicy ?? {};- originalDisableExport = Boolean(qdp.disableExport);- originalDisableCopyData = Boolean(qdp.disableCopyData);- originalAllowAdminDataSource = Boolean(qdp.allowAdminDataSource);- originalMaxRows = Number(qdp.maximumResultRows ?? 0);const project = (await env.api.getProject(env.project)) as {allowJustInTimeAccess?: boolean;allowSelfApproval?: boolean;@@ -161,6 +202,27 @@ test.beforeAll(async ({ browser }) => {originalJIT = Boolean(project.allowJustInTimeAccess);originalSelfApproval = Boolean(project.allowSelfApproval);+ // A rerun against the same server finds the users already created.+ for (const u of [EXPORTER, READER]) {+ try {+ await env.api.createUser(u.email, TEST_PASSWORD, u.title);+ } catch (err) {+ const msg = err instanceof Error ? err.message : String(err);+ if (!msg.includes("(409)")) throw err;+ }+ await env.api.appendProjectBinding(env.project, u.role, [+ `user:${u.email}`,+ ]);+ await signInBrowserAs(browser, env.baseURL, u.email, TEST_PASSWORD, u.authFile);+ }+ exporter = await openAs(browser, EXPORTER);+ reader = await openAs(browser, READER);+ readerApi = await BytebaseApiClient.asUser(+ env.baseURL,+ READER.email,+ TEST_PASSWORD,+ );+// Clipboard permission so the C9 generate-password copy-gate hits its// SUCCESS path; acceptDownloads so the masking tests can read the export zip.sharedContext = await browser.newContext({@@ -176,7 +238,7 @@ test.afterAll(async () => {// Restore each piece of mutated state independently so one failing restore// doesn't skip the others (and so a leak in one field is isolated).for (const restore of [- () => setWorkspaceExportPolicy(originalDisableExport),+ removeRoleBindings,() =>env.api.updateProjectSettings(env.project, {allowJustInTimeAccess: originalJIT,@@ -189,20 +251,25 @@ test.afterAll(async () => {/* best-effort restore */}}+ await exporter?.context.close();+ await reader?.context.close();await sharedContext?.close();});-// --- Direct export when the policy allows it (C1, C9) ---------------------+// --- Direct export with bb.sql.export from a role (C1, C9) -----------------test.describe("Direct export when the policy allows it (C1, C9)", () => {+test.describe("Direct export with the SQL Editor Exporter role (C1, C9)", () => {test("running a query then Export opens the backend-export drawer and Confirm fires the Export RPC", async () => {- await applyExportState({ disableExport: false, jit: originalJIT });+ const { page, sqlEditor } = exporter;+ // JIT on, so a missing Request export proves the role, not the project.+ await openEditorAs(exporter, { jit: true });await sqlEditor.runPreparedQuery("SELECT emp_no, first_name FROM employee LIMIT 5;");await expect(page.getByRole("button", { name: /^Export$/ }).first(),).toBeVisible({ timeout: 10_000 });- const drawer = await openExportDrawer();+ await expect(sqlEditor.requestExportButton).toHaveCount(0);+ const drawer = await openExportDrawer(page);await expect(drawer.getByText("Export format")).toBeVisible();// The format is a Select whose list renders in a popup outside the drawer.const formatSelect = drawer.getByRole("combobox");@@ -234,10 +301,11 @@ test.describe("Direct export when the policy allows it (C1, C9)", () => {});test("Generate password fills an 8-character value (copy-gated) (C9)", async () => {- await applyExportState({ disableExport: false, jit: originalJIT });+ const { page, sqlEditor } = exporter;+ await openEditorAs(exporter, { jit: originalJIT });await sqlEditor.runPreparedQuery("SELECT emp_no FROM employee LIMIT 2;");- const drawer = await openExportDrawer();+ const drawer = await openExportDrawer(page);await drawer.getByRole("button", { name: "Generate password" }).click();// The password commits to the field ONLY after the clipboard copy@@ -265,11 +333,12 @@ test.describe("Direct export when the policy allows it (C1, C9)", () => {});});-// --- Gated export, JIT on → Request export (C2, C3, C4) -------------------+// --- Without bb.sql.export, JIT on → Request export (C2, C3, C4) -----------test.describe("Export gated by policy, JIT enabled (C2, C3, C4)", () => {+test.describe("Read user without bb.sql.export, JIT enabled (C2, C3, C4)", () => {test('the toolbar shows "Request export" instead of "Export"', async () => {- await applyExportState({ disableExport: true, jit: true });+ const { page, sqlEditor } = reader;+ await openEditorAs(reader, { jit: true });await sqlEditor.runPreparedQuery("SELECT emp_no, first_name FROM employee LIMIT 5;");await expect(@@ -282,7 +351,8 @@ test.describe("Export gated by policy, JIT enabled (C2, C3, C4)", () => {});test('the export-blocked "Request export" CTA opens the grant drawer pre-filled with the statement, DB, and Export checked (unmask not)', async () => {- await applyExportState({ disableExport: true, jit: true });+ const { page, sqlEditor } = reader;+ await openEditorAs(reader, { jit: true });const statement = "SELECT emp_no, last_name FROM employee LIMIT 4;";await sqlEditor.runPreparedQuery(statement);@@ -314,7 +384,8 @@ test.describe("Export gated by policy, JIT enabled (C2, C3, C4)", () => {// (Export checked, Unmask not). This proves the SUBMITTED grant carries the// same capabilities — an export request must not silently escalate into an// unmask request that approvers would unknowingly grant.- await applyExportState({ disableExport: true, jit: true });+ const { sqlEditor } = reader;+ await openEditorAs(reader, { jit: true });// Unique statement so we can find exactly this grant via the API.const marker = Date.now();const statement = `SELECT emp_no FROM employee WHERE emp_no = ${marker % 100000} LIMIT 1;`;@@ -350,7 +421,7 @@ test.describe("Export gated by policy, JIT enabled (C2, C3, C4)", () => {await expect.poll(async () => {- const r = await env.api.searchMyAccessGrants(env.project);+ const r = await readerApi.searchMyAccessGrants(env.project);const g = r.accessGrants.find((x) => x.query === statement);if (!g) return "not-found";createdName = g.name;@@ -370,11 +441,12 @@ test.describe("Export gated by policy, JIT enabled (C2, C3, C4)", () => {});});-// --- Gated export, JIT off → no export affordance (C8) --------------------+// --- Without bb.sql.export, JIT off → no export affordance (C8) ------------test.describe("Export gated by policy, JIT disabled (C8)", () => {+test.describe("Read user without bb.sql.export, JIT disabled (C8)", () => {test("neither an Export button nor a Request-export button is shown", async () => {- await applyExportState({ disableExport: true, jit: false });+ const { page, sqlEditor } = reader;+ await openEditorAs(reader, { jit: false });await sqlEditor.runPreparedQuery("SELECT emp_no FROM employee LIMIT 3;");await expect(@@ -391,7 +463,8 @@ test.describe("Export gated by policy, JIT disabled (C8)", () => {test.describe("Multi-statement result export affordance (C10)", () => {test("two SELECTs render Query #1 / #2 tabs with a single Request-export control above them", async () => {- await applyExportState({ disableExport: true, jit: true });+ const { page, sqlEditor } = reader;+ await openEditorAs(reader, { jit: true });await sqlEditor.runPreparedQuery("SELECT 1 AS a; SELECT 2 AS b;");await expect(@@ -406,10 +479,10 @@ test.describe("Multi-statement result export affordance (C10)", () => {});});-// --- Active export grant re-enables Export for its exact statement (C7),-// surfaces an Export badge (C5), and is filterable (C6) ----------------+// --- A read user's active export grant re-enables Export for its exact+// statement (C7), surfaces an Export badge (C5), and is filterable (C6) ---test.describe("Active export grant (C5, C6, C7)", () => {+test.describe("Active export grant without bb.sql.export (C5, C6, C7)", () => {const GRANTED_STATEMENT ="SELECT emp_no, first_name, last_name FROM employee LIMIT 6;";const UNGRANTED_STATEMENT = "SELECT emp_no FROM employee LIMIT 6;";@@ -419,8 +492,7 @@ test.describe("Active export grant (C5, C6, C7)", () => {await env.api.updateProjectSettings(env.project, {allowJustInTimeAccess: true,});- await setWorkspaceExportPolicy(true);- grantedAccessName = await createActiveGrant(GRANTED_STATEMENT, {+ grantedAccessName = await createActiveGrant(readerApi, GRANTED_STATEMENT, {unmask: true,export: true,});@@ -437,11 +509,12 @@ test.describe("Active export grant (C5, C6, C7)", () => {});test.beforeEach(async () => {- await sqlEditor.gotoWithDb(projectId, env.instanceId, env.databaseId);- await page.waitForTimeout(1000);+ await reader.sqlEditor.gotoWithDb(projectId, env.instanceId, env.databaseId);+ await reader.page.waitForTimeout(1000);});test("the granted statement re-enables Export AND exporting under the grant succeeds (C7)", async () => {+ const { page, sqlEditor } = reader;await sqlEditor.runPreparedQuery(GRANTED_STATEMENT);const exportButton = page.getByRole("button", { name: /^Export$/ }).first();@@ -459,14 +532,14 @@ test.describe("Active export grant (C5, C6, C7)", () => {page.getByText(/Export (available via issue|enabled by access grant)/),).toBeVisible({ timeout: 5000 });- // Not just "the button shows" — actually export. Under disableExport=true the+ // Not just "the button shows" — actually export. Without bb.sql.export the// backend must honor the export grant, so Confirm fires a successful Export// RPC. (We can't read ExportResponse.applied_access_grant here: the Export RPC// uses the Connect protobuf codec, so the response body is binary protobuf —// the zip-bearing ExportResponse — not JSON. The grant-vs-ACL authorization is// a backend concern covered by backend tests; here we prove the UI exports// end-to-end under the grant.)- const drawer = await openExportDrawer();+ const drawer = await openExportDrawer(page);const exportResponse = page.waitForResponse((r) => r.url().includes("SQLService/Export"),{ timeout: 20_000 },@@ -480,6 +553,7 @@ test.describe("Active export grant (C5, C6, C7)", () => {});test("running a DIFFERENT statement keeps export gated (Request export, no Export) (C7)", async () => {+ const { page, sqlEditor } = reader;await sqlEditor.runPreparedQuery(UNGRANTED_STATEMENT);await expect(@@ -489,6 +563,7 @@ test.describe("Active export grant (C5, C6, C7)", () => {});test("the granted access is listed in the ACCESS pane with an Export badge (C5)", async () => {+ const { page, sqlEditor } = reader;await sqlEditor.gutterAccessTab.click();await page.waitForTimeout(1000);@@ -505,6 +580,7 @@ test.describe("Active export grant (C5, C6, C7)", () => {});test('filtering the ACCESS pane by export "No" hides the export grant (C6)', async () => {+ const { page, sqlEditor } = reader;await sqlEditor.gutterAccessTab.click();await page.waitForTimeout(1000);await expect(page.getByText(GRANTED_STATEMENT).first()).toBeVisible({@@ -586,8 +662,8 @@ test.describe("Masking ↔ export security", () => {}test.beforeAll(async () => {- // Export allowed (so the Export button shows), JIT on for the grant test.- await setWorkspaceExportPolicy(false);+ // The admin holds bb.sql.export, so the Export button shows; JIT on for+ // the grant test.await env.api.updateProjectSettings(env.project, {allowJustInTimeAccess: true,});@@ -710,7 +786,7 @@ test.describe("Masking ↔ export security", () => {await env.api.updateProjectSettings(env.project, {allowSelfApproval: true,});- unmaskGrantName = await createActiveGrant(STATEMENT, {+ unmaskGrantName = await createActiveGrant(env.api, STATEMENT, {unmask: true,export: true,});@@ -754,7 +830,7 @@ test.describe("Re-requesting a revoked grant restores Unmask AND Export (BYT-965// Seed an unmask+export grant, then revoke it so the ACCESS pane offers// a "Re-request" affordance for it. (revokeAccessGrant throws on non-OK,// so a failed revoke surfaces here instead of silently leaving it ACTIVE.)- const name = await createActiveGrant(REVOKED_STATEMENT, {+ const name = await createActiveGrant(env.api, REVOKED_STATEMENT, {unmask: true,export: true,});diff --git a/frontend/tests/e2e/sql-editor/sql-editor-workspace-gates.spec.ts b/frontend/tests/e2e/sql-editor/sql-editor-workspace-gates.spec.tsindex a8145f17fc..1065784323 100644--- a/frontend/tests/e2e/sql-editor/sql-editor-workspace-gates.spec.ts+++ b/frontend/tests/e2e/sql-editor/sql-editor-workspace-gates.spec.ts@@ -1,14 +1,16 @@// SQL Editor — workspace-level QueryDataPolicy gates (Batch 9, M-series).//// Covers:-// - M1 disableExport hides the result toolbar's Export button.// - M2 disableCopyData hides the Copy button on a non-empty result.//-// Both fields live on a `QueryDataPolicy` policy attached to the+// The field lives on a `QueryDataPolicy` policy attached to the// workspace resource (PolicyType.DATA_QUERY). We capture the current// policy in `beforeAll`, mutate per-test, and restore on `afterEach` so// other specs see the original baseline.//+// Export is gated by the bb.sql.export permission; sql-editor-export.spec.ts+// covers it.+//// Deferred from this batch (need separate investigation):// - M3 maximumResultRows enforcement — frontend caps the row-limit// input (QueryContextSettingPopover) but backend enforcement is@@ -40,7 +42,6 @@ let sqlEditor: SqlEditorPage;// Snapshot of the original QueryDataPolicy body so afterEach can restore.// Stored as the raw policy resource so we can re-PATCH with the same shape.let originalQueryDataPolicy: {- disableExport?: boolean;disableCopyData?: boolean;allowAdminDataSource?: boolean;maximumResultRows?: number;@@ -78,7 +79,6 @@ test.afterEach(async () => {type: "DATA_QUERY",resourceType: "WORKSPACE",queryDataPolicy: {- disableExport: originalQueryDataPolicy.disableExport ?? false,disableCopyData: originalQueryDataPolicy.disableCopyData ?? false,allowAdminDataSource:originalQueryDataPolicy.allowAdminDataSource ?? false,@@ -103,8 +103,6 @@ async function applyQueryDataPolicy(queryDataPolicy: {// Preserve all other fields; only mutate the ones the test cares// about.- disableExport:- patch.disableExport ?? originalQueryDataPolicy.disableExport ?? false,disableCopyData:patch.disableCopyData ??originalQueryDataPolicy.disableCopyData ??@@ -121,40 +119,6 @@ async function applyQueryDataPolicy(});}-test.describe("disableExport hides the result toolbar Export button (M1)", () => {- test("setting disableExport=true removes the Export button from a non-empty result", async () => {- // QueryDataPolicy enforcement is enterprise-gated; the license is installed at bootstrap.- await applyQueryDataPolicy({ disableExport: true });-- const projectId = env.project.split("/").pop()!;- await sqlEditor.gotoWithDb(projectId, env.instanceId, env.databaseId);- await sqlEditor.runPreparedQuery("SELECT 1 AS n;");- await expect(page.getByText(/^1\s+rows?$/i).first()).toBeVisible({- timeout: 10_000,- });-- // No Export button in the result toolbar.- await expect(- page.getByRole("button", { name: /^Export/ }),- ).toHaveCount(0);- });-- test("with disableExport=false (baseline) the Export button is present", async () => {- await applyQueryDataPolicy({ disableExport: false }).catch(() => {});-- const projectId = env.project.split("/").pop()!;- await sqlEditor.gotoWithDb(projectId, env.instanceId, env.databaseId);- await sqlEditor.runPreparedQuery("SELECT 1 AS n;");- await expect(page.getByText(/^1\s+rows?$/i).first()).toBeVisible({- timeout: 10_000,- });-- await expect(- page.getByRole("button", { name: /^Export/ }).first(),- ).toBeVisible({ timeout: 5_000 });- });-});-test.describe("disableCopyData hides the Copy button on results (M2)", () => {test("setting disableCopyData=true removes the Copy button", async () => {await applyQueryDataPolicy({ disableCopyData: true });diff --git a/frontend/tests/e2e/workspace/workspace-general-settings.spec.ts b/frontend/tests/e2e/workspace/workspace-general-settings.spec.tsdeleted file mode 100644index 8adadfaa7b..0000000000--- a/frontend/tests/e2e/workspace/workspace-general-settings.spec.ts+++ /dev/null@@ -1,150 +0,0 @@-// Workspace Settings → General → SQL Editor section: the data-export policy-// control. #21081 unified all wording to "access grant" terminology; customers-// then reported they couldn't tell that DISABLING export is how you enable-// approval-gated (access-grant) export — the control was a bare "Enable data-// export" checkbox with no description. The rework retitles it "Allow data-// export without approval" and adds a description naming the "Request export"-// CTA users see in the SQL editor.-//-// Covers:-// - W1 wording + policy→UI: the retitled label and its description render-// in the SQL Editor settings section, and the switch reflects the LIVE-// workspace DATA_QUERY policy in both states (on = export allowed-// without approval = disableExport:false).-// - W2 UI→policy wiring: switching off + Update persists disableExport:true-// (verified via the API, not just the UI), and switching on + Update-// restores it — both directions of the `checked={!disableExport}`-// inversion in SQLEditorSection.tsx.-//-// State safety: the DATA_QUERY policy is snapshotted in beforeAll and-// restored via API in afterAll. The sql-editor specs that flip the same-// policy run earlier (directory order) and restore their own state; this-// file runs before workspace-seat-limit's license drop.--import {- test,- expect,- type BrowserContext,- type Page,-} from "@playwright/test";-import { loadTestEnv, type TestEnv } from "../framework/env";-import { BytebaseApiClient } from "../framework/api-client";--test.setTimeout(120_000);--let env: TestEnv & { api: BytebaseApiClient };-let workspace = "";-let sharedContext: BrowserContext;-let page: Page;-let originalQueryDataPolicy: Record<string, unknown> = {};--const EXPORT_LABEL = "Allow data export without approval";--async function readDisableExport(): Promise<boolean> {- const policy = (await env.api.getPolicy(- `${workspace}/policies/data_query`- )) as { queryDataPolicy?: Record<string, unknown> } | null;- return Boolean(policy?.queryDataPolicy?.disableExport);-}--async function setQueryDataPolicy(- payload: Record<string, unknown>-): Promise<void> {- await env.api.upsertPolicy(workspace, "data_query", {- name: `${workspace}/policies/data_query`,- type: "DATA_QUERY",- queryDataPolicy: payload,- });-}--// The switch lives inside the FormField title span next to the label text-// (SQLEditorSection.tsx renders `<Switch/>{label}<FeatureBadge/>` in one-// inline-flex span), so scope by that span rather than by accessible name —-// the label text is a sibling, not an aria label.-function exportSwitch() {- return page- .locator("span", { hasText: EXPORT_LABEL })- .first()- .getByRole("switch");-}--async function gotoGeneralSettings(): Promise<void> {- await page.goto(`${env.baseURL}/setting/general`);- await page.waitForLoadState("networkidle").catch(() => {});- await expect(page.getByText(EXPORT_LABEL, { exact: true })).toBeVisible({- timeout: 10_000,- });-}--test.beforeAll(async ({ browser }) => {- env = loadTestEnv();- await env.api.login(env.adminEmail, env.adminPassword);- ({ workspace } = await env.api.getActuatorInfo());-- // Snapshot the whole queryDataPolicy so afterAll restores every field we- // may clobber via the UI's Update (it writes the full payload).- const existing = (await env.api.getPolicy(- `${workspace}/policies/data_query`- )) as { queryDataPolicy?: Record<string, unknown> } | null;- originalQueryDataPolicy = existing?.queryDataPolicy ?? {};-- sharedContext = await browser.newContext({ storageState: ".auth/state.json" });- page = await sharedContext.newPage();-});--test.afterAll(async () => {- try {- await setQueryDataPolicy(originalQueryDataPolicy);- } catch {- /* best-effort restore */- }- await sharedContext?.close();-});--test.describe("data-export policy control wording and wiring", () => {- test("the retitled switch and its description render, reflecting the live policy in both states (W1)", async () => {- // Known state first (own your fixtures): export allowed without approval.- await setQueryDataPolicy({ ...originalQueryDataPolicy, disableExport: false });- await gotoGeneralSettings();-- // The description teaches the access-grant path and quotes the exact- // "Request export" button label (coupling enforced by scripts/check-i18n.mjs).- await expect(- page.getByText(- /In projects that allow access grants, users can still click "Request export"/- )- ).toBeVisible();- await expect(exportSwitch()).toBeChecked();-- // Flip the policy via API → a fresh load shows the switch off.- await setQueryDataPolicy({ ...originalQueryDataPolicy, disableExport: true });- await gotoGeneralSettings();- await expect(exportSwitch()).not.toBeChecked();- });-- test("switching off + Update persists disableExport, switching on restores it (W2)", async () => {- // Start from export-allowed so the test owns its precondition.- await setQueryDataPolicy({ ...originalQueryDataPolicy, disableExport: false });- await gotoGeneralSettings();- await expect(exportSwitch()).toBeChecked();-- // Switch off → the dirty bar's Update commits the policy.- await exportSwitch().click();- await expect(exportSwitch()).not.toBeChecked();- await page.getByRole("button", { name: "Update", exact: true }).click();- await expect(- page.getByText("Configuration is updated.").first()- ).toBeVisible({ timeout: 10_000 });- await expect- .poll(readDisableExport, { timeout: 10_000 })- .toBe(true);-- // Switch on → Update → the policy returns to export-without-approval.- await exportSwitch().click();- await expect(exportSwitch()).toBeChecked();- await page.getByRole("button", { name: "Update", exact: true }).click();- await expect- .poll(readDisableExport, { timeout: 10_000 })- .toBe(false);- });-});diff --git a/proto/gen/grpc-doc/openapi.yaml b/proto/gen/grpc-doc/openapi.yamlindex 1aff572b4e..0fb3804b35 100644--- a/proto/gen/grpc-doc/openapi.yaml+++ b/proto/gen/grpc-doc/openapi.yaml@@ -4733,7 +4733,8 @@ paths:summary: Exportdescription: |-Exports query results to a file format.- Permissions required: bb.databases.get+ Permissions required: bb.databases.get, and bb.sql.export on the data the statement reads.+ An active access grant with export=true for the statement satisfies bb.sql.export on its target databases.operationId: SQLService_Exportparameters:- name: instance@@ -10049,7 +10050,8 @@ paths:summary: Exportdescription: |-Exports query results to a file format.- Permissions required: bb.databases.get+ Permissions required: bb.databases.get, and bb.sql.export on the data the statement reads.+ An active access grant with export=true for the statement satisfies bb.sql.export on its target databases.operationId: SQLService_Export2parameters:- name: project@@ -16841,7 +16843,9 @@ components:export:type: booleantitle: export- description: Whether export the query result.+ description: |-+ Whether the grant allows exporting the query result.+ An active grant with export=true grants bb.sql.export for this query until the grant expires.schema:type: stringtitle: schema@@ -18271,9 +18275,9 @@ components:The syntax and semantics of CEL are documented at https://github.com/google/cel-specSupport variables:- resource.database: the canonical database full name in "instances/{instance}/databases/{database}" or "projects/{project}/instances/{instance}/databases/{database}" format, used by any role with SQL Editor read (e.g. "roles/sqlEditorUser", "roles/sqlEditorReadUser") or write (bb.sql.ddl / bb.sql.dml) access, support "==" operator.- resource.schema_name: the schema name, used by any role with SQL Editor read or write (bb.sql.ddl / bb.sql.dml) access; for writes it is evaluated per write-target table, support "==" operator.- resource.table_name: the table name, used by any role with SQL Editor read or write (bb.sql.ddl / bb.sql.dml) access; for writes it is evaluated per write-target table, support "==" operator.+ resource.database: the canonical database full name in "instances/{instance}/databases/{database}" or "projects/{project}/instances/{instance}/databases/{database}" format, used by any role with SQL Editor read (e.g. "roles/sqlEditorUser", "roles/sqlEditorReadUser"), export (bb.sql.export, e.g. "roles/sqlEditorExporter") or write (bb.sql.ddl / bb.sql.dml) access, support "==" operator.+ resource.schema_name: the schema name, used by any role with SQL Editor read, export (bb.sql.export) or write (bb.sql.ddl / bb.sql.dml) access; for writes it is evaluated per write-target table, support "==" operator.+ resource.table_name: the table name, used by any role with SQL Editor read, export (bb.sql.export) or write (bb.sql.ddl / bb.sql.dml) access; for writes it is evaluated per write-target table, support "==" operator.resource.environment_id: the environment to allow the DDL/DML operation in the SQL Editor, only works for the role with bb.sql.ddl or bb.sql.dml permissions. Support "in" operator.request.time: the expiration. Only support "<" operation in `request.time < timestamp("{ISO datetime string format}")`.@@ -26134,9 +26138,8 @@ components:disableExport:type: booleantitle: disable_export- description: |-- workspace-level policy- Disable data export in the SQL editor.+ description: 'Deprecated: export is controlled by the bb.sql.export permission. Always false; setting it to true is rejected.'+ deprecated: truedisableCopyData:type: booleantitle: disable_copy_data@@ -27250,7 +27253,7 @@ components:title: roledescription: |-The requested role.- Format: roles/EXPORTER.+ Format: roles/{role}.user:type: stringtitle: userdiff --git a/proto/gen/grpc-doc/store/README.md b/proto/gen/grpc-doc/store/README.mdindex 99326f17f4..fa5efd7b0a 100644--- a/proto/gen/grpc-doc/store/README.md+++ b/proto/gen/grpc-doc/store/README.md@@ -1955,7 +1955,7 @@ RoleGrant contains details for requesting a project role.| Field | Type | Label | Description || ----- | ---- | ----- | ----------- |-| role | [string](#string) | | The role being requested for the user. Format: roles/EXPORTER. |+| role | [string](#string) | | The role being requested for the user. Format: roles/{role}. || user | [string](#string) | | The user who will receive the role. Format: users/{email}. || condition | [google.type.Expr](#google-type-Expr) | | Optional conditional expression that limits when the grant applies. || expiration | [google.protobuf.Duration](#google-protobuf-Duration) | | Duration after which the grant automatically expires. |@@ -2736,7 +2736,6 @@ QueryDataPolicy is the policy configuration for querying data in the SQL Editor.| Field | Type | Label | Description || ----- | ---- | ----- | ----------- |-| disable_export | [bool](#bool) | | workspace-level policy Disable exporting data in the SQL editor. || maximum_result_rows | [int32](#int32) | | Support both project-level and workspace-level. The maximum number of rows to return in the SQL editor. The default value <= 0, means no limit. || disable_copy_data | [bool](#bool) | | workspace-level policy Disable copying data. || allow_admin_data_source | [bool](#bool) | | workspace-level policy Allow using the admin data source to query in the SQL editor. |diff --git a/proto/gen/grpc-doc/store/index.html b/proto/gen/grpc-doc/store/index.htmlindex 4f8f6aac7a..0381facf8d 100644--- a/proto/gen/grpc-doc/store/index.html+++ b/proto/gen/grpc-doc/store/index.html@@ -5800,7 +5800,7 @@ Missing from persisted payloads means false. </p></td><td><a href="#string">string</a></td><td></td><td><p>The role being requested for the user.-Format: roles/EXPORTER. </p></td>+Format: roles/{role}. </p></td></tr><tr>@@ -7440,14 +7440,6 @@ resource.instance_id == "local" && resource.database_name == </thead><tbody>- <tr>- <td>disable_export</td>- <td><a href="#bool">bool</a></td>- <td></td>- <td><p>workspace-level policy-Disable exporting data in the SQL editor. </p></td>- </tr>-<tr><td>maximum_result_rows</td><td><a href="#int32">int32</a></td>diff --git a/proto/gen/grpc-doc/v1/README.md b/proto/gen/grpc-doc/v1/README.mdindex f5fe53a391..fbabc8420e 100644--- a/proto/gen/grpc-doc/v1/README.md+++ b/proto/gen/grpc-doc/v1/README.md@@ -979,7 +979,7 @@ The line against FORBIDDEN is reversibility. An admin-capable ceiling, if one is| create_time | [google.protobuf.Timestamp](#google-protobuf-Timestamp) | | || update_time | [google.protobuf.Timestamp](#google-protobuf-Timestamp) | | || reason | [string](#string) | | |-| export | [bool](#bool) | | Whether export the query result. |+| export | [bool](#bool) | | Whether the grant allows exporting the query result. An active grant with export=true grants bb.sql.export for this query until the grant expires. || schema | [string](#string) | | The default schema to execute the query. || container | [string](#string) | | The container name to execute the query against, used for CosmosDB only. |@@ -2926,7 +2926,7 @@ SQLService executes SQL queries and manages query operations.| SearchQueryHistories | [SearchQueryHistoriesRequest](#bytebase-v1-SearchQueryHistoriesRequest) | [SearchQueryHistoriesResponse](#bytebase-v1-SearchQueryHistoriesResponse) | Deprecated: use QueryHistoryService.SearchQueryHistories instead. Delegating alias kept for upgrade transition; will be removed in a future release. No HTTP binding: the REST route is served by QueryHistoryService. Permissions required: None (only returns caller's own query histories) || ListQueryHistories | [ListQueryHistoriesRequest](#bytebase-v1-ListQueryHistoriesRequest) | [ListQueryHistoriesResponse](#bytebase-v1-ListQueryHistoriesResponse) | Deprecated: use QueryHistoryService.ListQueryHistories instead. Delegating alias kept for upgrade transition; will be removed in a future release. No HTTP binding: the REST route is served by QueryHistoryService. Permissions required: bb.queryHistories.list || GetQueryHistory | [GetQueryHistoryRequest](#bytebase-v1-GetQueryHistoryRequest) | [QueryHistory](#bytebase-v1-QueryHistory) | Deprecated: use QueryHistoryService.GetQueryHistory instead. Delegating alias kept for upgrade transition; will be removed in a future release. No HTTP binding: the REST route is served by QueryHistoryService. Permissions required: None (only returns the caller's own query history) |-| Export | [ExportRequest](#bytebase-v1-ExportRequest) | [ExportResponse](#bytebase-v1-ExportResponse) | Exports query results to a file format. Permissions required: bb.databases.get |+| Export | [ExportRequest](#bytebase-v1-ExportRequest) | [ExportResponse](#bytebase-v1-ExportResponse) | Exports query results to a file format. Permissions required: bb.databases.get, and bb.sql.export on the data the statement reads. An active access grant with export=true for the statement satisfies bb.sql.export on its target databases. |@@ -3859,7 +3859,7 @@ For example: creator == "users/[email protected]" && status in [&#| Field | Type | Label | Description || ----- | ---- | ----- | ----------- |-| role | [string](#string) | | The requested role. Format: roles/EXPORTER. |+| role | [string](#string) | | The requested role. Format: roles/{role}. || user | [string](#string) | | The user to be granted. Format: users/{email}. || condition | [google.type.Expr](#google-type-Expr) | | The condition for the role. Same as the condition in IAM Binding message. || expiration | [google.protobuf.Duration](#google-protobuf-Duration) | | The duration for which the grant is valid. |@@ -5337,7 +5337,7 @@ Binding associates members with a role and optional conditions.| members | [string](#string) | repeated | Specifies the principals requesting access for a Bytebase resource. For users, the member should be: user:{email} For groups, the member should be: group:{email} For service accounts, the member should be: serviceAccount:{email} For workload identities, the member should be: workloadIdentity:{email} || condition | [google.type.Expr](#google-type-Expr) | | The condition that is associated with this binding, only used in the project IAM policy. If the condition evaluates to true, then this binding applies to the current request. If the condition evaluates to false, then this binding does not apply to the current request. However, a different role binding might grant the same role to one or more of the principals in this binding. The syntax and semantics of CEL are documented at https://github.com/google/cel-spec-Support variables: resource.database: the canonical database full name in "instances/{instance}/databases/{database}" or "projects/{project}/instances/{instance}/databases/{database}" format, used by any role with SQL Editor read (e.g. "roles/sqlEditorUser", "roles/sqlEditorReadUser") or write (bb.sql.ddl / bb.sql.dml) access, support "==" operator. resource.schema_name: the schema name, used by any role with SQL Editor read or write (bb.sql.ddl / bb.sql.dml) access; for writes it is evaluated per write-target table, support "==" operator. resource.table_name: the table name, used by any role with SQL Editor read or write (bb.sql.ddl / bb.sql.dml) access; for writes it is evaluated per write-target table, support "==" operator. resource.environment_id: the environment to allow the DDL/DML operation in the SQL Editor, only works for the role with bb.sql.ddl or bb.sql.dml permissions. Support "in" operator. request.time: the expiration. Only support "<" operation in `request.time < timestamp("{ISO datetime string format}")`.+Support variables: resource.database: the canonical database full name in "instances/{instance}/databases/{database}" or "projects/{project}/instances/{instance}/databases/{database}" format, used by any role with SQL Editor read (e.g. "roles/sqlEditorUser", "roles/sqlEditorReadUser"), export (bb.sql.export, e.g. "roles/sqlEditorExporter") or write (bb.sql.ddl / bb.sql.dml) access, support "==" operator. resource.schema_name: the schema name, used by any role with SQL Editor read, export (bb.sql.export) or write (bb.sql.ddl / bb.sql.dml) access; for writes it is evaluated per write-target table, support "==" operator. resource.table_name: the table name, used by any role with SQL Editor read, export (bb.sql.export) or write (bb.sql.ddl / bb.sql.dml) access; for writes it is evaluated per write-target table, support "==" operator. resource.environment_id: the environment to allow the DDL/DML operation in the SQL Editor, only works for the role with bb.sql.ddl or bb.sql.dml permissions. Support "in" operator. request.time: the expiration. Only support "<" operation in `request.time < timestamp("{ISO datetime string format}")`.Known limitations of table/schema-scoped DDL/DML grants: - The scope only gates the write target, not the read sources of a write: e.g. `INSERT INTO granted_table SELECT * FROM other_table` may read `other_table` without a grant on it, so a table-scoped write grant is not an exfiltration boundary. - It must be paired with a database/project-level read grant: a table-scoped grant alone does not satisfy the SQL Editor query method permission (bb.databases.get). - A resource.schema_name-scoped grant only authorizes a write whose schema is unambiguous — qualify the table (schema.table) or select the schema for the SQL Editor session. An unqualified write whose effective schema cannot be determined ahead of execution is denied (qualify it, or use a table-only grant). - Multi-statement batches are authorized at the database level: an earlier statement can rebind the session's default schema or database mid-batch, so per-table/schema scoping is dropped and a table/schema-scoped grant requires a database-level grant. The database-level check is still per target database — a qualified cross-database write is gated by a grant on its own database, not the request database — but an unqualified write whose session default is rebound mid-batch is evaluated against the database it literally names, so qualify cross-database writes or run them as single statements. - A write target in a different project than the SQL-Editor session's database is denied: the per-target check evaluates the session project's IAM policy, so a cross-project write is failed closed (to write it, open the SQL Editor on a database in the target project). - Enforcement is on the statement's literal write target; writes routed elsewhere by a view/synonym, or into a temporary schema (e.g. pg_temp), are evaluated against what the statement names, not the ultimate base object. - Write-target gating uses an ALLOWLIST of statement types the resolver models. It does NOT cover every syntactically-identifiable cross-database write; statement types off the allowlist are authorized against the request database. The allowlist is: - Modeled table/data writes (per-table/schema-scopable): INSERT/UPDATE/DELETE/TRUNCATE/MERGE, LOAD DATA, IMPORT INTO, CREATE TABLE AS / SELECT INTO, and table-level CREATE/DROP/ALTER/RENAME/index. - Modeled non-table object DDL (gated at the DATABASE level by the object's own explicit database/schema qualifier; an unqualified name keeps the request-database check): CREATE/ALTER/DROP of view, procedure/function/routine, trigger, sequence, synonym, type, and (Oracle) package and cluster; plus Oracle ALTER/DROP MATERIALIZED VIEW (Oracle CREATE MATERIALIZED VIEW is not modeled — see below). NOT modeled (these fall back to the request-database check, so a qualified cross-database one is authorized against the request database): MySQL CREATE TRIGGER and CREATE/ALTER/DROP EVENT (bare-string AST names); MSSQL ALTER of view/procedure/function/trigger (no ALTER node in the grammar); Oracle CREATE MATERIALIZED VIEW and the niche object DDL — dimension, attribute dimension, hierarchy, analytic view, JSON duality view, materialized zonemap, operator, in-memory join group, property graph, vector index, index type, domain; COPY ... FROM; and engine-specific bulk-load / deprecated text writes. A structural "write-target object database" extraction layer to remove this allowlist dependence is tracked as a follow-up. - Out of scope (read sources / indirect effects): the tables a write READS (INSERT … SELECT, MERGE … USING, CREATE TABLE AS … SELECT) and objects reached indirectly via views/synonyms/function bodies/triggers are NOT gated. Invariant: for a statement ON the modeled allowlist that explicitly names a different database as its write target, the ACL uses that target database, not the request database. Statement types OFF the allowlist are authorized against the request database.@@ -10036,7 +10036,7 @@ QueryDataPolicy is the policy configuration for querying data in the SQL Editor.| Field | Type | Label | Description || ----- | ---- | ----- | ----------- || maximum_result_rows | [int32](#int32) | | Support both project-level and workspace-level. The maximum number of rows to return in the SQL editor. The default value <= 0, means no limit. |-| disable_export | [bool](#bool) | | workspace-level policy Disable data export in the SQL editor. |+| disable_export | [bool](#bool) | | **Deprecated.** Deprecated: export is controlled by the bb.sql.export permission. Always false; setting it to true is rejected. || disable_copy_data | [bool](#bool) | | workspace-level policy Disable copying query results in the SQL editor. || allow_admin_data_source | [bool](#bool) | | workspace-level policy Allow using the admin data source to query in the SQL editor. If true, users can select the admin data source or read-only data source If false, 1. when read-only data source is configured, users're force to use the read-only data source 2. otherwise fallback to use the admin data source. |diff --git a/proto/gen/grpc-doc/v1/index.html b/proto/gen/grpc-doc/v1/index.htmlindex 14bed5ecbb..349f77819c 100644--- a/proto/gen/grpc-doc/v1/index.html+++ b/proto/gen/grpc-doc/v1/index.html@@ -3777,7 +3777,8 @@ Format: instances/{instance}/databases/{database} or projects/{project}/instance<td>export</td><td><a href="#bool">bool</a></td><td></td>- <td><p>Whether export the query result. </p></td>+ <td><p>Whether the grant allows exporting the query result.+An active grant with export=true grants bb.sql.export for this query until the grant expires. </p></td></tr><tr>@@ -9134,7 +9135,8 @@ Permissions required: None (only returns the caller's own query history)</p><td><a href="#bytebase.v1.ExportRequest">ExportRequest</a></td><td><a href="#bytebase.v1.ExportResponse">ExportResponse</a></td><td><p>Exports query results to a file format.-Permissions required: bb.databases.get</p></td>+Permissions required: bb.databases.get, and bb.sql.export on the data the statement reads.+An active access grant with export=true for the statement satisfies bb.sql.export on its target databases.</p></td></tr></tbody>@@ -11621,7 +11623,7 @@ creates the rollout automatically. </p></td><td><a href="#string">string</a></td><td></td><td><p>The requested role.-Format: roles/EXPORTER. </p></td>+Format: roles/{role}. </p></td></tr><tr>@@ -15515,9 +15517,9 @@ If the condition evaluates to false, then this binding does not apply to the curThe syntax and semantics of CEL are documented at https://github.com/google/cel-specSupport variables:-resource.database: the canonical database full name in "instances/{instance}/databases/{database}" or "projects/{project}/instances/{instance}/databases/{database}" format, used by any role with SQL Editor read (e.g. "roles/sqlEditorUser", "roles/sqlEditorReadUser") or write (bb.sql.ddl / bb.sql.dml) access, support "==" operator.-resource.schema_name: the schema name, used by any role with SQL Editor read or write (bb.sql.ddl / bb.sql.dml) access; for writes it is evaluated per write-target table, support "==" operator.-resource.table_name: the table name, used by any role with SQL Editor read or write (bb.sql.ddl / bb.sql.dml) access; for writes it is evaluated per write-target table, support "==" operator.+resource.database: the canonical database full name in "instances/{instance}/databases/{database}" or "projects/{project}/instances/{instance}/databases/{database}" format, used by any role with SQL Editor read (e.g. "roles/sqlEditorUser", "roles/sqlEditorReadUser"), export (bb.sql.export, e.g. "roles/sqlEditorExporter") or write (bb.sql.ddl / bb.sql.dml) access, support "==" operator.+resource.schema_name: the schema name, used by any role with SQL Editor read, export (bb.sql.export) or write (bb.sql.ddl / bb.sql.dml) access; for writes it is evaluated per write-target table, support "==" operator.+resource.table_name: the table name, used by any role with SQL Editor read, export (bb.sql.export) or write (bb.sql.ddl / bb.sql.dml) access; for writes it is evaluated per write-target table, support "==" operator.resource.environment_id: the environment to allow the DDL/DML operation in the SQL Editor, only works for the role with bb.sql.ddl or bb.sql.dml permissions. Support "in" operator.request.time: the expiration. Only support "<" operation in `request.time < timestamp("{ISO datetime string format}")`.@@ -28657,8 +28659,7 @@ The default value <= 0, means no limit. </p></td><td>disable_export</td><td><a href="#bool">bool</a></td><td></td>- <td><p>workspace-level policy-Disable data export in the SQL editor. </p></td>+ <td><p><strong>Deprecated.</strong> Deprecated: export is controlled by the bb.sql.export permission. Always false; setting it to true is rejected. </p></td></tr><tr>@@ -28685,6 +28686,27 @@ If false,</table>+++ <h4>Fields with deprecated option</h4>+ <table>+ <thead>+ <tr>+ <td>Name</td>+ <td>Option</td>+ </tr>+ </thead>+ <tbody>++ <tr>+ <td>disable_export</td>+ <td><p>true</p></td>+ </tr>++ </tbody>+ </table>++diff --git a/proto/store/store/issue.proto b/proto/store/store/issue.protoindex a5f4b8f8ce..8d134300dc 100644--- a/proto/store/store/issue.proto+++ b/proto/store/store/issue.proto@@ -53,7 +53,7 @@ message Issue {// RoleGrant contains details for requesting a project role.message RoleGrant {// The role being requested for the user.- // Format: roles/EXPORTER.+ // Format: roles/{role}.string role = 1;// The user who will receive the role.// Format: users/{email}.diff --git a/proto/store/store/policy.proto b/proto/store/store/policy.protoindex 950bfbf3a0..8a3d460814 100644--- a/proto/store/store/policy.proto+++ b/proto/store/store/policy.proto@@ -121,10 +121,8 @@ message IamPolicy {message QueryDataPolicy {reserved 6;reserved 1, 3;-- // workspace-level policy- // Disable exporting data in the SQL editor.- bool disable_export = 2;+ reserved 2;+ reserved "disable_export";// Support both project-level and workspace-level.// The maximum number of rows to return in the SQL editor.diff --git a/proto/v1/v1/access_grant_service.proto b/proto/v1/v1/access_grant_service.protoindex 099b6f6b47..d8f415b4b6 100644--- a/proto/v1/v1/access_grant_service.proto+++ b/proto/v1/v1/access_grant_service.proto@@ -152,7 +152,8 @@ message AccessGrant {string reason = 12;- // Whether export the query result.+ // Whether the grant allows exporting the query result.+ // An active grant with export=true grants bb.sql.export for this query until the grant expires.bool export = 13;// The default schema to execute the query.diff --git a/proto/v1/v1/iam_policy.proto b/proto/v1/v1/iam_policy.protoindex a5b9dae387..21fb430808 100644--- a/proto/v1/v1/iam_policy.proto+++ b/proto/v1/v1/iam_policy.proto@@ -69,9 +69,9 @@ message Binding {// The syntax and semantics of CEL are documented at https://github.com/google/cel-spec//// Support variables:- // resource.database: the canonical database full name in "instances/{instance}/databases/{database}" or "projects/{project}/instances/{instance}/databases/{database}" format, used by any role with SQL Editor read (e.g. "roles/sqlEditorUser", "roles/sqlEditorReadUser") or write (bb.sql.ddl / bb.sql.dml) access, support "==" operator.- // resource.schema_name: the schema name, used by any role with SQL Editor read or write (bb.sql.ddl / bb.sql.dml) access; for writes it is evaluated per write-target table, support "==" operator.- // resource.table_name: the table name, used by any role with SQL Editor read or write (bb.sql.ddl / bb.sql.dml) access; for writes it is evaluated per write-target table, support "==" operator.+ // resource.database: the canonical database full name in "instances/{instance}/databases/{database}" or "projects/{project}/instances/{instance}/databases/{database}" format, used by any role with SQL Editor read (e.g. "roles/sqlEditorUser", "roles/sqlEditorReadUser"), export (bb.sql.export, e.g. "roles/sqlEditorExporter") or write (bb.sql.ddl / bb.sql.dml) access, support "==" operator.+ // resource.schema_name: the schema name, used by any role with SQL Editor read, export (bb.sql.export) or write (bb.sql.ddl / bb.sql.dml) access; for writes it is evaluated per write-target table, support "==" operator.+ // resource.table_name: the table name, used by any role with SQL Editor read, export (bb.sql.export) or write (bb.sql.ddl / bb.sql.dml) access; for writes it is evaluated per write-target table, support "==" operator.// resource.environment_id: the environment to allow the DDL/DML operation in the SQL Editor, only works for the role with bb.sql.ddl or bb.sql.dml permissions. Support "in" operator.// request.time: the expiration. Only support "<" operation in `request.time < timestamp("{ISO datetime string format}")`.//diff --git a/proto/v1/v1/issue_service.proto b/proto/v1/v1/issue_service.protoindex bb0e83e844..892956363c 100644--- a/proto/v1/v1/issue_service.proto+++ b/proto/v1/v1/issue_service.proto@@ -553,7 +553,7 @@ message Issue {message RoleGrant {// The requested role.- // Format: roles/EXPORTER.+ // Format: roles/{role}.string role = 1;// The user to be granted.// Format: users/{email}.diff --git a/proto/v1/v1/org_policy_service.proto b/proto/v1/v1/org_policy_service.protoindex 8db367cc2a..a972ddb100 100644--- a/proto/v1/v1/org_policy_service.proto+++ b/proto/v1/v1/org_policy_service.proto@@ -299,9 +299,8 @@ message QueryDataPolicy {// The default value <= 0, means no limit.int32 maximum_result_rows = 1;- // workspace-level policy- // Disable data export in the SQL editor.- bool disable_export = 2;+ // Deprecated: export is controlled by the bb.sql.export permission. Always false; setting it to true is rejected.+ bool disable_export = 2 [deprecated = true];// workspace-level policy// Disable copying query results in the SQL editor.diff --git a/proto/v1/v1/sql_service.proto b/proto/v1/v1/sql_service.protoindex 226a3c62e3..1ea82669d9 100644--- a/proto/v1/v1/sql_service.proto+++ b/proto/v1/v1/sql_service.proto@@ -85,7 +85,8 @@ service SQLService {}// Exports query results to a file format.- // Permissions required: bb.databases.get+ // Permissions required: bb.databases.get, and bb.sql.export on the data the statement reads.+ // An active access grant with export=true for the statement satisfies bb.sql.export on its target databases.rpc Export(ExportRequest) returns (ExportResponse) {option (google.api.http) = {post: "/v1/{name=instances/*/databases/*}:export"