Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
fix(sql): authorize table/schema-scoped DML/DDL grants in SQL Editor (#20587)
Vincent Huang9a5cc8584595
diff --git a/backend/api/mcp/gen/openapi.yaml b/backend/api/mcp/gen/openapi.yamlindex 87c4c62fe4..9f3f552c30 100644--- a/backend/api/mcp/gen/openapi.yaml+++ b/backend/api/mcp/gen/openapi.yaml@@ -9157,12 +9157,26 @@ components:The syntax and semantics of CEL are documented at https://github.com/google/cel-specSupport variables:- resource.database: the database full name in "instances/{instance}/databases/{database}" format, used by the "roles/sqlEditorUser" and "roles/sqlEditorReadUser" roles, support "==" operator.- resource.schema_name: the schema name, used by the "roles/sqlEditorUser" and "roles/sqlEditorReadUser" roles, support "==" operator.- resource.table_name: the table name, used by the "roles/sqlEditorUser" and "roles/sqlEditorReadUser" roles, support "==" operator.+ resource.database: the database full name in "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}")`.+ 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.+For example:resource.database == "instances/local-pg/databases/postgres" && resource.schema_name in ["public","another_schema"]resource.database == "instances/local-pg/databases/bytebase" && resource.schema_name == "public" && resource.table_name in ["audit_log"]diff --git a/backend/api/v1/sql_service.go b/backend/api/v1/sql_service.goindex 7ad34a9ce2..387375552c 100644--- a/backend/api/v1/sql_service.go+++ b/backend/api/v1/sql_service.go@@ -495,7 +495,24 @@ func getEffectiveQueryDataPolicy(return value}-type accessCheckFunc func(context.Context, *store.InstanceMessage, *store.DatabaseMessage, *store.UserMessage, []*parserbase.QuerySpan, bool /* isExplain */) error+type accessCheckFunc func(context.Context, *store.InstanceMessage, *store.DatabaseMessage, *store.UserMessage, []*parserbase.QuerySpan, bool /* isExplain */, []parserbase.Statement, string /* requestSchema */, bool /* multiStatement */) error++// hasMultipleStatements reports whether a batch has more than one non-empty statement.+// Multi-statement batches can change the session's default schema mid-batch (e.g. Postgres+// `SET search_path`), so DML/DDL in them falls back to the database-level check. SUP-222.+func hasMultipleStatements(statements []parserbase.Statement) bool {+ n := 0+ for _, st := range statements {+ if st.Empty {+ continue+ }+ n+++ if n > 1 {+ return true+ }+ }+ return false+}func extractSourceTable(comment string) (string, string, string, error) {pattern := `\((\w+),\s*(\w+)(?:,\s*(\w+))?\)`@@ -634,6 +651,7 @@ func queryRetry(licenseService *enterprise.LicenseService,optionalAccessCheck accessCheckFunc,schemaSyncer *schemasync.Syncer,+ multiStatement bool,) ([]*v1pb.QueryResult, []*parserbase.QuerySpan, time.Duration, error) {var spans []*parserbase.QuerySpanvar sensitivePredicateColumns [][]parserbase.ColumnResource@@ -663,7 +681,7 @@ func queryRetry(}if optionalAccessCheck != nil {// Check query access- if err := optionalAccessCheck(ctx, instance, database, user, spans, queryContext.Explain); err != nil {+ if err := optionalAccessCheck(ctx, instance, database, user, spans, queryContext.Explain, statements, queryContext.Schema, multiStatement); err != nil {return nil, nil, time.Duration(0), err}slog.Debug("optional access check", slog.String("instance", instance.ResourceID), slog.String("database", database.DatabaseName))@@ -853,7 +871,7 @@ func queryRetryStopOnError(if err != nil {return nil, nil, 0, err}- return queryRetry(ctx, stores, user, instance, database, driver, conn, statements, statement, queryContext, licenseService, optionalAccessCheck, schemaSyncer)+ return queryRetry(ctx, stores, user, instance, database, driver, conn, statements, statement, queryContext, licenseService, optionalAccessCheck, schemaSyncer, hasMultipleStatements(statements))}// Split the statement into individual SQLs@@ -862,9 +880,14 @@ func queryRetryStopOnError(// Engines without splitter support (MongoDB, Redis, Elasticsearch) fall back to// treating the entire statement as a single unit. These engines also don't have// GetQuerySpan support, so queryRetry will return nil spans (old behavior).- return queryRetry(ctx, stores, user, instance, database, driver, conn, []parserbase.Statement{{Text: statement}}, statement, queryContext, licenseService, optionalAccessCheck, schemaSyncer)+ return queryRetry(ctx, stores, user, instance, database, driver, conn, []parserbase.Statement{{Text: statement}}, statement, queryContext, licenseService, optionalAccessCheck, schemaSyncer, false)}+ // A multi-statement batch can change the session schema mid-batch (e.g. SET search_path),+ // which the per-statement access check below cannot track; flag it so DML/DDL falls back+ // to the database-level check. SUP-222.+ multiStatement := hasMultipleStatements(statements)+var allResults []*v1pb.QueryResultvar allSpans []*parserbase.QuerySpanvar totalDuration time.Duration@@ -875,7 +898,7 @@ func queryRetryStopOnError(continue}- results, spans, duration, err := queryRetry(ctx, stores, user, instance, database, driver, conn, []parserbase.Statement{stmt}, stmt.Text, queryContext, licenseService, optionalAccessCheck, schemaSyncer)+ results, spans, duration, err := queryRetry(ctx, stores, user, instance, database, driver, conn, []parserbase.Statement{stmt}, stmt.Text, queryContext, licenseService, optionalAccessCheck, schemaSyncer, multiStatement)totalDuration += durationif err != nil {@@ -1187,6 +1210,7 @@ func doExport(licenseService,optionalAccessCheck,schemaSyncer,+ hasMultipleStatements(statements),)if queryErr != nil {return nil, duration, queryErr@@ -1483,8 +1507,11 @@ func (s *SQLService) accessCheck(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, nil)+ return s.accessCheckWithGrantedTargets(ctx, instance, database, user, spans, isExplain, statements, nil, requestSchema, multiStatement)}// accessCheckWithGrant returns an accessCheckFunc that exempts the access@@ -1504,8 +1531,8 @@ func (s *SQLService) accessCheckWithGrant(accessGrant *store.AccessGrantMessage)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) error {- return s.accessCheckWithGrantedTargets(ctx, instance, database, user, spans, isExplain, grantedTargets)+ 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)}}@@ -1516,7 +1543,10 @@ func (s *SQLService) accessCheckWithGrantedTargets(user *store.UserMessage,spans []*parserbase.QuerySpan,isExplain bool,+ statements []parserbase.Statement,grantedTargets map[string]struct{},+ requestSchema string,+ multiStatement bool,) error {project, err := s.store.GetProject(ctx, &store.FindProjectMessage{Workspace: common.GetWorkspaceIDFromContext(ctx), ResourceID: &database.ProjectID})if err != nil {@@ -1585,7 +1615,15 @@ func (s *SQLService) accessCheckWithGrantedTargets(return checkDatabaseAccess(perm)}- for _, span := range spans {+ // Spans align with non-empty statements (GetQuerySpan skips Empty statements).+ nonEmptyStatements := make([]parserbase.Statement, 0, len(statements))+ for _, st := range statements {+ if !st.Empty {+ nonEmptyStatements = append(nonEmptyStatements, st)+ }+ }++ for i, span := range spans {var perm permission.Permission// New query ACL experience.if common.EngineSupportQueryNewACL(instance.Metadata.GetEngine()) {@@ -1613,6 +1651,52 @@ func (s *SQLService) accessCheckWithGrantedTargets(perm = permission.SQLSelect}+ // DML/DDL: authorize per write-target so table/schema-scoped grants work. Resolve the+ // write targets of the statement aligned with this span (spans skip Empty statements, so+ // nonEmptyStatements is indexed in lockstep).+ //+ // A single statement is authorized at full per-(schema,table) precision. A multi-statement+ // batch can rebind the session's default schema (SET search_path) or database (USE) mid-+ // batch, so an unqualified write's schema/table identity is unreliable; such a batch is+ // authorized at the DATABASE level only. Crucially that database-level check still runs+ // against each TARGET database, not the request database: a qualified cross-database write+ // (e.g. MySQL `INSERT INTO other_db.t`) is not rebindable, so a grant on the request+ // database must not authorize it. SUP-222 / BYT-9698.+ if perm == permission.SQLDml || perm == permission.SQLDdl {+ stmtText := ""+ if i < len(nonEmptyStatements) {+ stmtText = nonEmptyStatements[i].Text+ }+ targets, err := s.resolveWriteTargets(ctx, instance, database, stmtText, requestSchema)+ if err != nil {+ return connect.NewError(connect.CodeInternal, errors.Errorf("failed to resolve write targets: %v", err))+ }+ if len(targets) == 0 {+ // No resolvable table target (non-table DDL, unsupported engine, parse failure) →+ // database-level check on the request database.+ if err := checkDatabaseAccess(perm); err != nil {+ return err+ }+ continue+ }+ databaseLevelOnly := multiStatement || len(nonEmptyStatements) != 1+ deniedResources, err := s.authorizeWriteTargets(ctx, user, instance, database, perm, targets, grantedTargets, databaseLevelOnly, workspacePolicy.Policy, projectPolicy.Policy)+ if err != nil {+ return err+ }+ if len(deniedResources) > 0 {+ return &queryError{+ err: connect.NewError(+ connect.CodePermissionDenied,+ errors.Errorf("permission denied to access resources: %v", deniedResources),+ ),+ resources: deniedResources,+ permission: perm,+ }+ }+ continue+ }+// For non-SELECT queries or SELECT queries with no source columns (e.g., SELECT 1),// check at database level and skip column-level checksif span.Type != parserbase.Select || len(span.SourceColumns) == 0 {@@ -1674,6 +1758,281 @@ func (s *SQLService) accessCheckWithGrantedTargets(return nil}+// authorizeWriteTargets evaluates perm for each resolved DML/DDL write target and returns the+// resources that were denied (empty = all authorized). A target whose database is already+// JIT-granted is skipped.+//+// databaseLevelOnly selects the precision of the check. For a single statement it is false and+// each target is authorized at full per-(schema,table) precision. For a multi-statement batch it+// is true: an earlier statement can rebind the session's default schema (SET search_path) or+// database (USE), so per-(schema,table) identity is unreliable and only the TARGET database is+// authorized (each distinct database once) — schema/table attributes are omitted so a+// schema/table-scoped grant fails closed, and a denial names the bare database.+//+// resource.schema_name (full-precision mode only) is asserted ONLY when the target schema is+// known: an empty schema (the sentinel mapped to "") omits the attribute, so a schema-scoped+// grant fails closed (CEL errors on the missing attribute → the binding is skipped) while a+// table-only grant still matches. A present-but-empty value would instead let a negated condition+// (schema_name != "x") wrongly match.+//+// resource.environment_id is always set, and is resolved PER TARGET database: a cross-database+// write (e.g. MySQL/MSSQL `INSERT INTO other_db.t`) targets a database that may live in a+// different environment than the one the editor opened, and resource.database already names that+// target — copying the request database's environment (or authorizing against the request+// database at all) would let a grant on the request database authorize a write into another+// database/environment. The request database needs no lookup (the common same-database case);+// other targets are fetched once and cached, and an unknown target fails closed. The attribute is+// always present because hasDatabaseAccessRights keeps the environment clause for SQLDml/SQLDdl,+// so omitting it would reintroduce a "no such attribute" error. SUP-222 / BYT-9698.+func (s *SQLService) authorizeWriteTargets(+ ctx context.Context,+ user *store.UserMessage,+ instance *store.InstanceMessage,+ database *store.DatabaseMessage,+ perm permission.Permission,+ targets []writeTargetResource,+ grantedTargets map[string]struct{},+ databaseLevelOnly bool,+ iamPolicies ...*storepb.IamPolicy,+) ([]string, error) {+ // One timestamp per request so every target evaluates request.time consistently.+ requestTime := time.Now()++ // environment_id of the request database, reused without a lookup for same-database targets.+ envByDatabase := map[string]string{database.DatabaseName: ""}+ if database.EffectiveEnvironmentID != nil {+ envByDatabase[database.DatabaseName] = *database.EffectiveEnvironmentID+ }+ checkedDatabase := map[string]bool{} // databaseLevelOnly: authorize each target database once++ var deniedResources []string+ for _, t := range targets {+ databaseFullName := common.FormatDatabase(instance.ResourceID, t.database)+ if _, granted := grantedTargets[databaseFullName]; granted {+ continue+ }+ // A target with no table name is a database-only target: DDL on a non-table object+ // (view/procedure/function/trigger/…) whose only auth-relevant identity is its database.+ // Authorize it at the database level — like a multi-statement batch — so a qualified+ // cross-database object DDL is gated by its own database, not the request database, with+ // no spurious table-name match. SUP-222 / BYT-9698.+ useDatabaseLevel := databaseLevelOnly || t.table == ""+ if useDatabaseLevel {+ if checkedDatabase[t.database] {+ continue+ }+ checkedDatabase[t.database] = true+ }++ // A denial names the bare database for a database-level check, else the schema/table target.+ deniedResource := databaseFullName+ if !useDatabaseLevel {+ deniedResource = formatWriteTargetResource(databaseFullName, t.schema, t.table)+ }++ env, known := envByDatabase[t.database]+ if !known {+ targetName := t.database+ targetDB, err := s.store.GetDatabase(ctx, &store.FindDatabaseMessage{+ Workspace: common.GetWorkspaceIDFromContext(ctx),+ InstanceID: &instance.ResourceID,+ DatabaseName: &targetName,+ })+ if err != nil {+ return nil, connect.NewError(connect.CodeInternal, errors.Errorf("failed to resolve target database %q: %v", t.database, err))+ }+ if targetDB == nil {+ // Unknown target database → its environment can't be established → fail closed.+ deniedResources = append(deniedResources, deniedResource)+ continue+ }+ if targetDB.ProjectID != database.ProjectID {+ // A write target in a DIFFERENT project than the SQL-Editor session must be gated+ // by that target project's IAM policy, which this check (evaluating the request+ // project's policy) does not consult. Fail closed to preserve the project+ // boundary — a cross-project write is denied. SUP-222 / BYT-9698.+ deniedResources = append(deniedResources, deniedResource)+ continue+ }+ if targetDB.EffectiveEnvironmentID != nil {+ env = *targetDB.EffectiveEnvironmentID+ }+ envByDatabase[t.database] = env+ }++ attributes := map[string]any{+ common.CELAttributeRequestTime: requestTime,+ common.CELAttributeResourceDatabase: databaseFullName,+ common.CELAttributeResourceEnvironmentID: env,+ }+ if !useDatabaseLevel {+ attributes[common.CELAttributeResourceTableName] = t.table+ if t.schema != "" {+ attributes[common.CELAttributeResourceSchemaName] = t.schema+ }+ }+ allowed, err := s.hasDatabaseAccessRights(ctx, user, perm, attributes, iamPolicies...)+ if err != nil {+ return nil, connect.NewError(connect.CodeInternal, errors.Errorf("failed to check access control for target %q: %v", deniedResource, err))+ }+ if !allowed {+ deniedResources = append(deniedResources, deniedResource)+ }+ }+ return deniedResources, nil+}++// formatWriteTargetResource renders a denied write target as+// instances/i/databases/d[/schemas/s]/tables/t; the schema segment is omitted when unknown.+func formatWriteTargetResource(databaseFullName, schema, table string) string {+ resource := databaseFullName+ if schema != "" {+ resource = fmt.Sprintf("%s/schemas/%s", resource, schema)+ }+ return fmt.Sprintf("%s/tables/%s", resource, table)+}++// writeTargetResource is a (database, schema, table) write target of a DML/DDL statement.+type writeTargetResource struct {+ database string+ schema string+ table string+}++// resolveWriteTargets returns the tables a DML/DDL statement writes/changes, using+// the same extractor plan-check trusts. Returns (nil, nil) when the engine has no+// extractor, the statement can't be parsed, or no targets are found — callers must+// then fall back to the database-level check (never fail open). See SUP-222.+//+// Some engines' extractors report auxiliary tables referenced by the change (e.g.+// the joined/using tables of an UPDATE … JOIN … / DELETE … USING …) alongside the+// mutated table, others only the primary target; either way this can only ever+// over-restrict (fail-closed), never under-restrict.+//+// DDL on a non-table object (view/procedure/function/trigger/…) has no table to scope. When+// such DDL names an EXPLICIT target database (e.g. CREATE VIEW other_db.v), the extractor+// records a database-only target so the write is gated by that database; an UNqualified one+// records nothing and falls back to the request-database check. Object DDL the extractor does+// not model still resolves to zero targets → request-database fallback.+func (s *SQLService) resolveWriteTargets(+ ctx context.Context,+ instance *store.InstanceMessage,+ database *store.DatabaseMessage,+ statement string,+ requestSchema string,+) ([]writeTargetResource, error) {+ engine := instance.Metadata.GetEngine()++ stmts, err := parserbase.ParseStatements(engine, statement)+ if err != nil {+ //nolint:nilerr // unparseable here → fall back to database-level check (already parsed once for the span)+ return nil, nil+ }+ asts := parserbase.ExtractASTs(stmts)+ if len(asts) == 0 {+ return nil, nil+ }++ // Cache-first: GetQuerySpan already fetched and cached this database's metadata earlier in+ // the same request, so reuse it instead of issuing a second store query on the write path.+ dbMeta, err := s.store.GetDBSchemaSnapshot(ctx, common.GetWorkspaceIDFromContext(ctx), database.InstanceID, database.DatabaseName)+ if err != nil {+ return nil, err+ }+ if dbMeta == nil {+ return nil, nil+ }++ changeSummary, err := parserbase.ExtractChangedResources(+ engine, database.DatabaseName, schemaForWriteTargetResolution(engine, database.DatabaseName, requestSchema), dbMeta, asts, statement,+ )+ if err != nil || changeSummary == nil || changeSummary.ChangedResources == nil {+ //nolint:nilerr // unsupported engine / no result → fall back to database-level check+ return nil, nil+ }++ var targets []writeTargetResource+ databasesWithTableTarget := map[string]bool{}+ for _, db := range changeSummary.ChangedResources.Build().GetDatabases() {+ for _, sc := range db.GetSchemas() {+ schema := sc.GetName()+ // An unqualified target whose executed schema can't be determined here resolves+ // to the sentinel; treat it as unknown ("") so the schema_name attribute is+ // omitted (fail-closed for schema-scoped grants, still matches table-only ones).+ if schema == unresolvedSchemaSentinel {+ schema = ""+ }+ for _, tbl := range sc.GetTables() {+ databasesWithTableTarget[db.GetName()] = true+ targets = append(targets, writeTargetResource{+ database: db.GetName(),+ schema: schema,+ table: tbl.GetName(),+ })+ }+ }+ }+ // Database-only targets (Tier 2): a qualified non-table object DDL (e.g. CREATE VIEW+ // other_db.v) records only its target database, with no table. It is authorized at the+ // database level against that database (a table-less target → useDatabaseLevel in+ // authorizeWriteTargets), so a qualified cross-database object DDL is gated by its own+ // database, not the request database. Skip any database already covered by a (more precise)+ // table target. See SUP-222 / BYT-9698.+ for _, db := range changeSummary.ChangedResources.GetDatabaseOnlyTargets() {+ if databasesWithTableTarget[db] {+ continue+ }+ targets = append(targets, writeTargetResource{database: db})+ }+ return targets, nil+}++// unresolvedSchemaSentinel is an impossible schema name (it contains NUL, which no real+// PostgreSQL/MSSQL identifier can) used as the default schema for UNqualified write targets+// when the schema the engine will actually resolve cannot be known ahead of execution+// (Postgres's connection-user `$user` search_path, MSSQL's login default_schema). It+// propagates only to unqualified targets — qualified ones keep their explicit schema — and+// is mapped to "" so the resource.schema_name attribute is omitted before the grant check.+const unresolvedSchemaSentinel = "\x00bb_unresolved_schema\x00"++// schemaForWriteTargetResolution returns the default schema to resolve UNqualified write+// targets against, per engine — the schema the engine will actually write to, or the+// sentinel when that can't be determined here (so the schema_name attribute is omitted and+// schema-scoped grants fail closed). Qualified targets ignore this and keep their qualifier.+func schemaForWriteTargetResolution(engine storepb.Engine, databaseName, requestSchema string) string {+ switch engine {+ case storepb.Engine_POSTGRES:+ // Execution pins search_path to QueryRequest.schema when set; otherwise the+ // connection user's default ($user, public) is not knowable here.+ if requestSchema != "" {+ return requestSchema+ }+ return unresolvedSchemaSentinel+ case storepb.Engine_MSSQL:+ // No per-request schema pin; execution uses the login's default_schema, which is not+ // in synced metadata. Never trust a request schema for MSSQL.+ return unresolvedSchemaSentinel+ case storepb.Engine_ORACLE:+ // Execution pins CURRENT_SCHEMA to the connection database (= schema) once at pool Open+ // (oracle.go), and the SQL Editor opens a fresh pool per request, so an unqualified write+ // resolves to databaseName — knowable and execution-accurate. (A mid-batch ALTER SESSION+ // is covered by the multi-statement fallback.) This pin is the reason the schema is+ // auth-grade here; if the driver ever stops pinning per-connection, switch to the sentinel.+ return databaseName+ case storepb.Engine_MYSQL, storepb.Engine_TIDB:+ // No schema layer; the extractor emits an empty schema and resource.schema_name is omitted.+ return ""+ default:+ // Fail closed for any other engine. An engine that reaches here without an explicit,+ // execution-verified schema mapping must NOT have its unqualified writes resolved against+ // a guessed default — e.g. a pg-family extractor (COCKROACHDB, REDSHIFT) would fill in the+ // metadata search_path, a REAL schema name, which we'd then assert as resource.schema_name+ // and over-allow a schema-scoped grant. The sentinel maps to an omitted attribute, so+ // schema-scoped grants fail closed while table-only grants still match. SUP-222 / BYT-9698.+ return unresolvedSchemaSentinel+ }+}+// sanitizeResults sanitizes the strings in the results by replacing all the invalid UTF-8 characters with its hexadecimal representation.func sanitizeResults(results []*v1pb.QueryResult) {for _, result := range results {diff --git a/backend/api/v1/sql_service_schema_resolution_test.go b/backend/api/v1/sql_service_schema_resolution_test.gonew file mode 100644index 0000000000..d790e24a01--- /dev/null+++ b/backend/api/v1/sql_service_schema_resolution_test.go@@ -0,0 +1,48 @@+package v1++import (+ "testing"++ "github.com/stretchr/testify/require"++ storepb "github.com/bytebase/bytebase/backend/generated-go/store"+)++// TestSchemaForWriteTargetResolution pins the per-engine default schema used to resolve+// UNqualified DML/DDL write targets — the schema the engine will actually write to, or the+// sentinel when that can't be determined ahead of execution (so resource.schema_name is+// omitted and schema-scoped grants fail closed). See SUP-222 / BYT-9698.+func TestSchemaForWriteTargetResolution(t *testing.T) {+ const dbName = "ORADB"+ tests := []struct {+ name string+ engine storepb.Engine+ requestSchema string+ want string+ }{+ {"postgres with request schema resolves to it", storepb.Engine_POSTGRES, "other_schema", "other_schema"},+ {"postgres without request schema is unknowable ($user/public) → sentinel", storepb.Engine_POSTGRES, "", unresolvedSchemaSentinel},+ {"mssql is always sentinel (login default_schema; never trust a request schema)", storepb.Engine_MSSQL, "ignored", unresolvedSchemaSentinel},+ {"oracle pins CURRENT_SCHEMA to the database name", storepb.Engine_ORACLE, "", dbName},+ {"mysql has no schema layer → omit", storepb.Engine_MYSQL, "", ""},+ {"tidb has no schema layer → omit", storepb.Engine_TIDB, "", ""},+ // Any engine without an explicit, execution-verified mapping must fail closed via the+ // sentinel — never "" (which a pg-family extractor would fill from the metadata search+ // path, a real schema name we'd then wrongly assert). Guards a future newACL flip for+ // COCKROACHDB/REDSHIFT (both pg-family extractors). SUP-222 / BYT-9698.+ {"unlisted engine fails closed via sentinel", storepb.Engine_SNOWFLAKE, "ignored", unresolvedSchemaSentinel},+ {"cockroachdb (pg-family extractor) fails closed via sentinel", storepb.Engine_COCKROACHDB, "", unresolvedSchemaSentinel},+ {"redshift (pg-family extractor) fails closed via sentinel", storepb.Engine_REDSHIFT, "", unresolvedSchemaSentinel},+ }+ for _, tc := range tests {+ t.Run(tc.name, func(t *testing.T) {+ require.Equal(t, tc.want, schemaForWriteTargetResolution(tc.engine, dbName, tc.requestSchema))+ })+ }+}++// TestUnresolvedSchemaSentinelIsImpossible guards that the sentinel can never collide with a+// real schema: a NUL byte is not representable in a PostgreSQL/MSSQL identifier.+func TestUnresolvedSchemaSentinelIsImpossible(t *testing.T) {+ require.Contains(t, unresolvedSchemaSentinel, "\x00")+}diff --git a/backend/generated-go/v1/iam_policy.pb.go b/backend/generated-go/v1/iam_policy.pb.goindex 408b4f28b4..bbd79c81d3 100644--- a/backend/generated-go/v1/iam_policy.pb.go+++ b/backend/generated-go/v1/iam_policy.pb.go@@ -266,12 +266,26 @@ type Binding struct {// The syntax and semantics of CEL are documented at https://github.com/google/cel-spec//// Support variables:- // resource.database: the database full name in "instances/{instance}/databases/{database}" format, used by the "roles/sqlEditorUser" and "roles/sqlEditorReadUser" roles, support "==" operator.- // resource.schema_name: the schema name, used by the "roles/sqlEditorUser" and "roles/sqlEditorReadUser" roles, support "==" operator.- // resource.table_name: the table name, used by the "roles/sqlEditorUser" and "roles/sqlEditorReadUser" roles, support "==" operator.+ // resource.database: the database full name in "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}")`.//+ // 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.+ //// For example:// resource.database == "instances/local-pg/databases/postgres" && resource.schema_name in ["public","another_schema"]// resource.database == "instances/local-pg/databases/bytebase" && resource.schema_name == "public" && resource.table_name in ["audit_log"]diff --git a/backend/plugin/parser/mysql/resource_change.go b/backend/plugin/parser/mysql/resource_change.goindex 71dad113fb..940b6eee3a 100644--- a/backend/plugin/parser/mysql/resource_change.go+++ b/backend/plugin/parser/mysql/resource_change.go@@ -26,6 +26,16 @@ func extractChangedResources(currentDatabase string, _ string, dbMetadata *modelvar dmlCount, insertCount intvar sampleDMLs []string+ // addObjectDatabase records a database-only write target for a non-table object DDL+ // (view/function/routine/trigger) ONLY when the object's own name carries an explicit+ // database qualifier (TableRef.Schema). Unqualified names record nothing (request-database+ // fallback). The object's own qualifier is used — never an ON-table reference. SUP-222.+ addObjectDatabase := func(ref *ast.TableRef) {+ if ref != nil && ref.Schema != "" {+ changedResources.AddDatabase(ref.Schema)+ }+ }+for _, unifiedAST := range asts {omniAST, ok := unifiedAST.(*OmniAST)if !ok {@@ -48,6 +58,18 @@ func extractChangedResources(currentDatabase string, _ string, dbMetadata *modelchangedResources.AddTable(db, "", &storepb.ChangedResourceTable{Name: table}, true)}+ case *ast.TruncateStmt:+ for _, ref := range n.Tables {+ db, table := omniTableRef(ref, currentDatabase)+ changedResources.AddTable(db, "", &storepb.ChangedResourceTable{Name: table}, true)+ }++ case *ast.LoadDataStmt:+ if n.Table != nil {+ db, table := omniTableRef(n.Table, currentDatabase)+ changedResources.AddTable(db, "", &storepb.ChangedResourceTable{Name: table}, false)+ }+case *ast.AlterTableStmt:if n.Table != nil {db, table := omniTableRef(n.Table, currentDatabase)@@ -113,6 +135,26 @@ func extractChangedResources(currentDatabase string, _ string, dbMetadata *modelsampleDMLs = append(sampleDMLs, omniStatementText(omniAST))}+ // Non-table object DDL: gate by the object's own explicit database qualifier only.+ // CREATE TRIGGER is intentionally skipped — its AST name is unqualified (a bare string);+ // inferring the database from the ON table is out of scope. SUP-222 / BYT-9698.+ case *ast.CreateViewStmt:+ addObjectDatabase(n.Name)+ case *ast.AlterViewStmt:+ addObjectDatabase(n.Name)+ case *ast.DropViewStmt:+ for _, ref := range n.Views {+ addObjectDatabase(ref)+ }+ case *ast.CreateFunctionStmt:+ addObjectDatabase(n.Name)+ case *ast.AlterRoutineStmt:+ addObjectDatabase(n.Name)+ case *ast.DropRoutineStmt:+ addObjectDatabase(n.Name)+ case *ast.DropTriggerStmt:+ addObjectDatabase(n.Name)+default:}}diff --git a/backend/plugin/parser/mysql/resource_change_test.go b/backend/plugin/parser/mysql/resource_change_test.goindex a2a4590890..a983e521a1 100644--- a/backend/plugin/parser/mysql/resource_change_test.go+++ b/backend/plugin/parser/mysql/resource_change_test.go@@ -52,3 +52,55 @@ func TestExtractChangedResources(t *testing.T) {require.NoError(t, err)require.Equal(t, want, got)}++func TestExtractChangedResourcesTruncate(t *testing.T) {+ const statement = `TRUNCATE TABLE t;`++ want := model.NewChangedResources(nil /* dbMetadata */)+ want.AddTable("db", "", &storepb.ChangedResourceTable{Name: "t"}, true)++ stmts, err := base.ParseStatements(storepb.Engine_MYSQL, statement)+ require.NoError(t, err)+ asts := base.ExtractASTs(stmts)+ got, err := extractChangedResources("db", "", nil /* dbMetadata */, asts, statement)+ require.NoError(t, err)+ require.Equal(t, want, got.ChangedResources)+}++func TestExtractChangedResourcesLoadData(t *testing.T) {+ const statement = `LOAD DATA INFILE '/tmp/f.csv' INTO TABLE other_db.t (a, b);`++ want := model.NewChangedResources(nil /* dbMetadata */)+ want.AddTable("other_db", "", &storepb.ChangedResourceTable{Name: "t"}, false)++ stmts, err := base.ParseStatements(storepb.Engine_MYSQL, statement)+ require.NoError(t, err)+ asts := base.ExtractASTs(stmts)+ got, err := extractChangedResources("db", "", nil /* dbMetadata */, asts, statement)+ require.NoError(t, err)+ require.Equal(t, want, got.ChangedResources)+}++func TestExtractChangedResourcesObjectDDLDatabaseOnly(t *testing.T) {+ // Qualified non-table object DDL → a database-only target on the qualifier.+ for _, statement := range []string{+ `CREATE VIEW other_db.v AS SELECT 1;`,+ `DROP VIEW other_db.v;`,+ `ALTER PROCEDURE other_db.p COMMENT 'c';`,+ } {+ stmts, err := base.ParseStatements(storepb.Engine_MYSQL, statement)+ require.NoError(t, err, statement)+ asts := base.ExtractASTs(stmts)+ got, err := extractChangedResources("db", "", nil /* dbMetadata */, asts, statement)+ require.NoError(t, err, statement)+ require.Equal(t, []string{"other_db"}, got.ChangedResources.GetDatabaseOnlyTargets(), statement)+ }+ // Unqualified → no database-only target (request-database fallback).+ const unqualified = `CREATE VIEW v AS SELECT 1;`+ stmts, err := base.ParseStatements(storepb.Engine_MYSQL, unqualified)+ require.NoError(t, err)+ asts := base.ExtractASTs(stmts)+ got, err := extractChangedResources("db", "", nil /* dbMetadata */, asts, unqualified)+ require.NoError(t, err)+ require.Empty(t, got.ChangedResources.GetDatabaseOnlyTargets())+}diff --git a/backend/plugin/parser/pg/query_type.go b/backend/plugin/parser/pg/query_type.goindex 83e70a963d..5983d96211 100644--- a/backend/plugin/parser/pg/query_type.go+++ b/backend/plugin/parser/pg/query_type.go@@ -102,20 +102,22 @@ func classifyQueryType(node ast.Node, allSystems bool) (queryType base.QueryType// hasOmniIntoClause checks if a SelectStmt has an INTO clause (SELECT INTO).func hasOmniIntoClause(n *ast.SelectStmt) bool {+ return omniIntoClause(n) != nil+}++// omniIntoClause returns the INTO clause of n, searching set-operation arms+// (UNION/INTERSECT/EXCEPT) — the parser attaches INTO to the first arm, not the root.+func omniIntoClause(n *ast.SelectStmt) *ast.IntoClause {if n == nil {- return false+ return nil}if n.IntoClause != nil {- return true+ return n.IntoClause}- // Check set operations (UNION/INTERSECT/EXCEPT)- if n.Larg != nil && hasOmniIntoClause(n.Larg) {- return true+ if c := omniIntoClause(n.Larg); c != nil {+ return c}- if n.Rarg != nil && hasOmniIntoClause(n.Rarg) {- return true- }- return false+ return omniIntoClause(n.Rarg)}// isExplainAnalyzeOmni checks if an ExplainStmt has the ANALYZE option.diff --git a/backend/plugin/parser/pg/resource_change.go b/backend/plugin/parser/pg/resource_change.goindex 93eb101195..899ccb04a7 100644--- a/backend/plugin/parser/pg/resource_change.go+++ b/backend/plugin/parser/pg/resource_change.go@@ -17,9 +17,12 @@ func init() {base.RegisterExtractChangedResourcesFunc(storepb.Engine_COCKROACHDB, extractChangedResources)}-func extractChangedResources(database string, _ string, dbMetadata *model.DatabaseMetadata, asts []base.AST, _ string) (*base.ChangeSummary, error) {+func extractChangedResources(database string, currentSchema string, dbMetadata *model.DatabaseMetadata, asts []base.AST, _ string) (*base.ChangeSummary, error) {changedResources := model.NewChangedResources(dbMetadata)searchPath := dbMetadata.GetSearchPath()+ if currentSchema != "" {+ searchPath = []string{currentSchema}+ }if len(searchPath) == 0 {searchPath = []string{"public"}}@@ -166,6 +169,38 @@ func extractChangedResources(database string, _ string, dbMetadata *model.Databaif len(sampleDMLs) < common.MaximumLintExplainSize {sampleDMLs = append(sampleDMLs, getOmniStatementText(omniAST))}+ case *ast.TruncateStmt:+ if n.Relations != nil {+ for _, item := range n.Relations.Items {+ rv, ok := item.(*ast.RangeVar)+ if !ok {+ continue+ }+ db, schema, table := extractRangeVarNames(rv, database, searchPath)+ changedResources.AddTable(db, schema, &storepb.ChangedResourceTable{Name: table}, true)+ }+ }++ case *ast.MergeStmt:+ if n.Relation != nil {+ db, schema, table := extractRangeVarNames(n.Relation, database, searchPath)+ changedResources.AddTable(db, schema, &storepb.ChangedResourceTable{Name: table}, false)+ }++ case *ast.CreateTableAsStmt:+ if n.Into != nil && n.Into.Rel != nil {+ db, schema, table := extractRangeVarNames(n.Into.Rel, database, searchPath)+ changedResources.AddTable(db, schema, &storepb.ChangedResourceTable{Name: table}, false)+ }++ case *ast.SelectStmt:+ // SELECT ... INTO target_table is a write (classified DDL via the INTO clause,+ // which may sit on the first arm of a set operation).+ if into := omniIntoClause(n); into != nil && into.Rel != nil {+ db, schema, table := extractRangeVarNames(into.Rel, database, searchPath)+ changedResources.AddTable(db, schema, &storepb.ChangedResourceTable{Name: table}, false)+ }+default:}}diff --git a/backend/plugin/parser/pg/resource_change_test.go b/backend/plugin/parser/pg/resource_change_test.goindex bcbe78480e..967bcb43f1 100644--- a/backend/plugin/parser/pg/resource_change_test.go+++ b/backend/plugin/parser/pg/resource_change_test.go@@ -61,3 +61,56 @@ func TestExtractChangedResources(t *testing.T) {require.NoError(t, err)require.Equal(t, want, got)}++func TestExtractChangedResourcesTruncate(t *testing.T) {+ dbMetadata := model.NewDatabaseMetadata(&storepb.DatabaseSchemaMetadata{}, []byte{}, &storepb.DatabaseConfig{}, storepb.Engine_POSTGRES, true /* caseSensitive */)+ const statement = `TRUNCATE TABLE public.t1, myschema.t2;`++ want := model.NewChangedResources(dbMetadata)+ want.AddTable("db", "public", &storepb.ChangedResourceTable{Name: "t1"}, true)+ want.AddTable("db", "myschema", &storepb.ChangedResourceTable{Name: "t2"}, true)++ stmts, err := base.ParseStatements(storepb.Engine_POSTGRES, statement)+ require.NoError(t, err)+ asts := base.ExtractASTs(stmts)+ got, err := extractChangedResources("db", "public", dbMetadata, asts, statement)+ require.NoError(t, err)+ require.Equal(t, want, got.ChangedResources)+}++func TestExtractChangedResourcesMerge(t *testing.T) {+ dbMetadata := model.NewDatabaseMetadata(&storepb.DatabaseSchemaMetadata{}, []byte{}, &storepb.DatabaseConfig{}, storepb.Engine_POSTGRES, true /* caseSensitive */)+ const statement = `MERGE INTO myschema.tgt t USING src s ON t.id = s.id WHEN MATCHED THEN UPDATE SET a = s.a;`++ want := model.NewChangedResources(dbMetadata)+ want.AddTable("db", "myschema", &storepb.ChangedResourceTable{Name: "tgt"}, false)++ stmts, err := base.ParseStatements(storepb.Engine_POSTGRES, statement)+ require.NoError(t, err)+ asts := base.ExtractASTs(stmts)+ got, err := extractChangedResources("db", "public", dbMetadata, asts, statement)+ require.NoError(t, err)+ require.Equal(t, want, got.ChangedResources)+}++func TestExtractChangedResourcesCTAS(t *testing.T) {+ dbMetadata := model.NewDatabaseMetadata(&storepb.DatabaseSchemaMetadata{}, []byte{}, &storepb.DatabaseConfig{}, storepb.Engine_POSTGRES, true /* caseSensitive */)+ for _, tc := range []struct {+ statement, schema, table string+ }{+ {`CREATE TABLE myschema.t1 AS SELECT * FROM src;`, "myschema", "t1"},+ {`SELECT * INTO myschema.t2 FROM src;`, "myschema", "t2"},+ // INTO sits on the first arm of a set operation, not the root.+ {`SELECT a INTO myschema.t3 FROM src UNION SELECT a FROM src2;`, "myschema", "t3"},+ } {+ want := model.NewChangedResources(dbMetadata)+ want.AddTable("db", tc.schema, &storepb.ChangedResourceTable{Name: tc.table}, false)++ stmts, err := base.ParseStatements(storepb.Engine_POSTGRES, tc.statement)+ require.NoError(t, err, tc.statement)+ asts := base.ExtractASTs(stmts)+ got, err := extractChangedResources("db", "public", dbMetadata, asts, tc.statement)+ require.NoError(t, err, tc.statement)+ require.Equal(t, want, got.ChangedResources, tc.statement)+ }+}diff --git a/backend/plugin/parser/plsql/resource_change.go b/backend/plugin/parser/plsql/resource_change.goindex 3b1b842abd..ed0efc40c0 100644--- a/backend/plugin/parser/plsql/resource_change.go+++ b/backend/plugin/parser/plsql/resource_change.go@@ -70,6 +70,16 @@ func (e *omniChangedResourceExtractor) extract(a *OmniAST) {e.addIndexTable(name)}}+ switch n.ObjectType {+ case oracleast.OBJECT_VIEW, oracleast.OBJECT_SEQUENCE, oracleast.OBJECT_SYNONYM,+ oracleast.OBJECT_PROCEDURE, oracleast.OBJECT_FUNCTION, oracleast.OBJECT_TRIGGER,+ oracleast.OBJECT_PACKAGE, oracleast.OBJECT_PACKAGE_BODY, oracleast.OBJECT_TYPE,+ oracleast.OBJECT_TYPE_BODY, oracleast.OBJECT_MATERIALIZED_VIEW, oracleast.OBJECT_CLUSTER:+ for _, name := range omniObjectNameList(n.Names) {+ e.addObjectDatabase(name)+ }+ default:+ }case *oracleast.AlterTableStmt:affected := truefor _, cmd := range omniAlterTableCmdList(n.Actions) {@@ -89,6 +99,47 @@ func (e *omniChangedResourceExtractor) extract(a *OmniAST) {case *oracleast.DeleteStmt:e.addTable(n.Table, false)e.trackDML(a.Text)+ case *oracleast.MergeStmt:+ e.addTable(n.Target, false)+ e.trackDML(a.Text)+ case *oracleast.TruncateStmt:+ e.addTable(n.Table, true)+ case *oracleast.CreateViewStmt:+ e.addObjectDatabase(n.Name)+ case *oracleast.CreateProcedureStmt:+ e.addObjectDatabase(n.Name)+ case *oracleast.CreateFunctionStmt:+ e.addObjectDatabase(n.Name)+ case *oracleast.CreateTriggerStmt:+ e.addObjectDatabase(n.Name)+ case *oracleast.CreateSequenceStmt:+ e.addObjectDatabase(n.Name)+ case *oracleast.CreateSynonymStmt:+ e.addObjectDatabase(n.Name)+ case *oracleast.AlterViewStmt:+ e.addObjectDatabase(n.Name)+ case *oracleast.AlterSequenceStmt:+ e.addObjectDatabase(n.Name)+ case *oracleast.AlterProcedureStmt:+ e.addObjectDatabase(n.Name)+ case *oracleast.AlterFunctionStmt:+ e.addObjectDatabase(n.Name)+ case *oracleast.AlterTriggerStmt:+ e.addObjectDatabase(n.Name)+ case *oracleast.AlterSynonymStmt:+ e.addObjectDatabase(n.Name)+ case *oracleast.CreatePackageStmt:+ e.addObjectDatabase(n.Name)+ case *oracleast.AlterPackageStmt:+ e.addObjectDatabase(n.Name)+ case *oracleast.CreateTypeStmt:+ e.addObjectDatabase(n.Name)+ case *oracleast.AlterTypeStmt:+ e.addObjectDatabase(n.Name)+ case *oracleast.CreateClusterStmt:+ e.addObjectDatabase(n.Name)+ case *oracleast.AlterMaterializedViewStmt:+ e.addObjectDatabase(n.Name)default:}}@@ -108,6 +159,16 @@ func (e *omniChangedResourceExtractor) extractInsert(stmt *oracleast.InsertStmt,e.trackDML(text)}+// addObjectDatabase records a database-only write target for a non-table object DDL (view,+// procedure, function, trigger, sequence, synonym) ONLY when its name carries an explicit schema+// qualifier (Oracle's schema maps to a database). An unqualified name records nothing, keeping+// the request-database fallback. See SUP-222 / BYT-9698.+func (e *omniChangedResourceExtractor) addObjectDatabase(name *oracleast.ObjectName) {+ if name != nil && name.Schema != "" {+ e.changedResources.AddDatabase(name.Schema)+ }+}+func (e *omniChangedResourceExtractor) addTable(name *oracleast.ObjectName, affected bool) {if name == nil || name.Name == "" {returndiff --git a/backend/plugin/parser/plsql/resource_change_test.go b/backend/plugin/parser/plsql/resource_change_test.goindex dcfc20a726..828670633a 100644--- a/backend/plugin/parser/plsql/resource_change_test.go+++ b/backend/plugin/parser/plsql/resource_change_test.go@@ -177,3 +177,59 @@ type testAST struct{}func (testAST) ASTStartPosition() *storepb.Position {return nil}++func TestExtractChangedResourcesTruncate(t *testing.T) {+ const statement = `TRUNCATE TABLE t;`++ want := model.NewChangedResources(nil /* dbMetadata */)+ want.AddTable("DB", "", &storepb.ChangedResourceTable{Name: "T"}, true)++ stmts, err := base.ParseStatements(storepb.Engine_ORACLE, statement)+ require.NoError(t, err)+ asts := base.ExtractASTs(stmts)+ got, err := extractChangedResources("DB", "", nil /* dbMetadata */, asts, statement)+ require.NoError(t, err)+ require.Equal(t, want, got.ChangedResources)+}++func TestExtractChangedResourcesMerge(t *testing.T) {+ const statement = `MERGE INTO OTHER.TGT t USING SRC s ON (t.id = s.id) WHEN MATCHED THEN UPDATE SET t.a = s.a;`++ want := model.NewChangedResources(nil /* dbMetadata */)+ want.AddTable("OTHER", "", &storepb.ChangedResourceTable{Name: "TGT"}, false)++ stmts, err := base.ParseStatements(storepb.Engine_ORACLE, statement)+ require.NoError(t, err)+ asts := base.ExtractASTs(stmts)+ got, err := extractChangedResources("DB", "", nil /* dbMetadata */, asts, statement)+ require.NoError(t, err)+ require.Equal(t, want, got.ChangedResources)+}++func TestExtractChangedResourcesObjectDDLDatabaseOnly(t *testing.T) {+ // Qualified non-table object DDL → a database-only target on the qualified schema.+ for _, statement := range []string{+ `CREATE VIEW OTHER.V AS SELECT * FROM T;`,+ `CREATE SEQUENCE OTHER.S;`,+ `CREATE SYNONYM OTHER.SYN FOR T;`,+ `DROP PACKAGE OTHER.PKG;`,+ `DROP TYPE OTHER.TY;`,+ `ALTER PACKAGE OTHER.PKG COMPILE;`,+ } {+ stmts, err := base.ParseStatements(storepb.Engine_ORACLE, statement)+ require.NoError(t, err, statement)+ asts := base.ExtractASTs(stmts)+ got, err := extractChangedResources("DB", "", nil /* dbMetadata */, asts, statement)+ require.NoError(t, err, statement)+ require.Equal(t, []string{"OTHER"}, got.ChangedResources.GetDatabaseOnlyTargets(), statement)+ }++ // Unqualified object DDL → no database-only target (keeps the request-database fallback).+ const unqualified = `CREATE VIEW V AS SELECT * FROM T;`+ stmts, err := base.ParseStatements(storepb.Engine_ORACLE, unqualified)+ require.NoError(t, err)+ asts := base.ExtractASTs(stmts)+ got, err := extractChangedResources("DB", "", nil /* dbMetadata */, asts, unqualified)+ require.NoError(t, err)+ require.Empty(t, got.ChangedResources.GetDatabaseOnlyTargets())+}diff --git a/backend/plugin/parser/tidb/resource_change.go b/backend/plugin/parser/tidb/resource_change.goindex 91ed37c293..d5f3d3ec38 100644--- a/backend/plugin/parser/tidb/resource_change.go+++ b/backend/plugin/parser/tidb/resource_change.go@@ -62,6 +62,15 @@ func extractChangedResources(database string, _ string, dbMetadata *model.Databa}, nil}+// addTiDBObjectDatabase records a database-only write target for a non-table object DDL+// (view/sequence) ONLY when its name carries an explicit database qualifier. An unqualified+// name records nothing (request-database fallback). SUP-222 / BYT-9698.+func addTiDBObjectDatabase(changedResources *model.ChangedResources, name *tidbast.TableName) {+ if name != nil && name.Schema.O != "" {+ changedResources.AddDatabase(name.Schema.O)+ }+}+func getResourceChanges(database string, node tidbast.StmtNode, _ string, changedResources *model.ChangedResources) error {switch node := node.(type) {case *tidbast.CreateTableStmt:@@ -79,7 +88,11 @@ func getResourceChanges(database string, node tidbast.StmtNode, _ string, change)case *tidbast.DropTableStmt:if node.IsView {- // View tracking removed - not used in risk/approval calculations+ // Views aren't tracked as changed tables (risk/approval doesn't use them), but a+ // qualified cross-database DROP VIEW is gated by its target database. SUP-222.+ for _, name := range node.Tables {+ addTiDBObjectDatabase(changedResources, name)+ }return nil}for _, name := range node.Tables {@@ -109,6 +122,35 @@ func getResourceChanges(database string, node tidbast.StmtNode, _ string, change},true,)+ case *tidbast.TruncateTableStmt:+ d, table := node.Table.Schema.O, node.Table.Name.O+ if d == "" {+ d = database+ }+ changedResources.AddTable(+ d,+ "",+ &storepb.ChangedResourceTable{+ Name: table,+ },+ true,+ )+ case *tidbast.LoadDataStmt:+ if node.Table != nil {+ d, table := node.Table.Schema.O, node.Table.Name.O+ if d == "" {+ d = database+ }+ changedResources.AddTable(d, "", &storepb.ChangedResourceTable{Name: table}, false)+ }+ case *tidbast.ImportIntoStmt:+ if node.Table != nil {+ d, table := node.Table.Schema.O, node.Table.Name.O+ if d == "" {+ d = database+ }+ changedResources.AddTable(d, "", &storepb.ChangedResourceTable{Name: table}, false)+ }case *tidbast.RenameTableStmt:for _, tableToTable := range node.TableToTables {{@@ -167,7 +209,17 @@ func getResourceChanges(database string, node tidbast.StmtNode, _ string, changefalse,)case *tidbast.CreateViewStmt:- // View tracking removed - not used in risk/approval calculations+ // Not tracked as a changed table (risk/approval doesn't use views), but a qualified+ // cross-database view is gated by its target database. SUP-222 / BYT-9698.+ addTiDBObjectDatabase(changedResources, node.ViewName)+ case *tidbast.CreateSequenceStmt:+ addTiDBObjectDatabase(changedResources, node.Name)+ case *tidbast.AlterSequenceStmt:+ addTiDBObjectDatabase(changedResources, node.Name)+ case *tidbast.DropSequenceStmt:+ for _, seq := range node.Sequences {+ addTiDBObjectDatabase(changedResources, seq)+ }case *tidbast.InsertStmt:tables, err := extractTableRefs(node.Table)if err != nil {diff --git a/backend/plugin/parser/tidb/resource_change_test.go b/backend/plugin/parser/tidb/resource_change_test.goindex ac5515e9c3..056eb88ae8 100644--- a/backend/plugin/parser/tidb/resource_change_test.go+++ b/backend/plugin/parser/tidb/resource_change_test.go@@ -51,3 +51,58 @@ func TestExtractChangedResources(t *testing.T) {require.NoError(t, err)require.Equal(t, want, got)}++func TestExtractChangedResourcesTruncate(t *testing.T) {+ const statement = `TRUNCATE TABLE t;`++ want := model.NewChangedResources(nil /* dbMetadata */)+ want.AddTable("db", "", &storepb.ChangedResourceTable{Name: "t"}, true)++ stmts, err := base.ParseStatements(storepb.Engine_TIDB, statement)+ require.NoError(t, err)+ asts := base.ExtractASTs(stmts)+ got, err := extractChangedResources("db", "", nil /* dbMetadata */, asts, statement)+ require.NoError(t, err)+ require.Equal(t, want, got.ChangedResources)+}++func TestExtractChangedResourcesLoadDataImport(t *testing.T) {+ for _, statement := range []string{+ `LOAD DATA INFILE '/tmp/f.csv' INTO TABLE other_db.t;`,+ `IMPORT INTO other_db.t FROM '/tmp/f.csv';`,+ } {+ want := model.NewChangedResources(nil /* dbMetadata */)+ want.AddTable("other_db", "", &storepb.ChangedResourceTable{Name: "t"}, false)++ stmts, err := base.ParseStatements(storepb.Engine_TIDB, statement)+ require.NoError(t, err, statement)+ asts := base.ExtractASTs(stmts)+ got, err := extractChangedResources("db", "", nil /* dbMetadata */, asts, statement)+ require.NoError(t, err, statement)+ require.Equal(t, want, got.ChangedResources, statement)+ }+}++func TestExtractChangedResourcesObjectDDLDatabaseOnly(t *testing.T) {+ // Qualified non-table object DDL (view/sequence) → a database-only target on the qualifier.+ for _, statement := range []string{+ `CREATE VIEW other_db.v AS SELECT 1;`,+ `DROP VIEW other_db.v;`,+ `CREATE SEQUENCE other_db.s;`,+ } {+ stmts, err := base.ParseStatements(storepb.Engine_TIDB, statement)+ require.NoError(t, err, statement)+ asts := base.ExtractASTs(stmts)+ got, err := extractChangedResources("db", "", nil /* dbMetadata */, asts, statement)+ require.NoError(t, err, statement)+ require.Equal(t, []string{"other_db"}, got.ChangedResources.GetDatabaseOnlyTargets(), statement)+ }+ // Unqualified → no database-only target (request-database fallback).+ const unqualified = `CREATE VIEW v AS SELECT 1;`+ stmts, err := base.ParseStatements(storepb.Engine_TIDB, unqualified)+ require.NoError(t, err)+ asts := base.ExtractASTs(stmts)+ got, err := extractChangedResources("db", "", nil /* dbMetadata */, asts, unqualified)+ require.NoError(t, err)+ require.Empty(t, got.ChangedResources.GetDatabaseOnlyTargets())+}diff --git a/backend/plugin/parser/tsql/query.go b/backend/plugin/parser/tsql/query.goindex 8317481936..69009a63c7 100644--- a/backend/plugin/parser/tsql/query.go+++ b/backend/plugin/parser/tsql/query.go@@ -48,17 +48,20 @@ func isReadOnlySelect(node ast.Node) bool {// HasSelectInto reports whether sel (or any branch of its set operations)// carries an INTO clause.func HasSelectInto(sel *ast.SelectStmt) bool {+ return selectIntoTarget(sel) != nil+}++// selectIntoTarget returns the INTO target of sel, searching set-operation+// arms — T-SQL attaches INTO to the first arm of a UNION, not the root.+func selectIntoTarget(sel *ast.SelectStmt) *ast.TableRef {if sel == nil {- return false+ return nil}if sel.IntoTable != nil {- return true- }- if sel.Larg != nil && HasSelectInto(sel.Larg) {- return true+ return sel.IntoTable}- if sel.Rarg != nil && HasSelectInto(sel.Rarg) {- return true+ if target := selectIntoTarget(sel.Larg); target != nil {+ return target}- return false+ return selectIntoTarget(sel.Rarg)}diff --git a/backend/plugin/parser/tsql/query_type.go b/backend/plugin/parser/tsql/query_type.goindex c6670ec8c8..07cf71a8f8 100644--- a/backend/plugin/parser/tsql/query_type.go+++ b/backend/plugin/parser/tsql/query_type.go@@ -1,6 +1,8 @@package tsqlimport (+ "strings"+"github.com/bytebase/omni/mssql/ast""github.com/bytebase/bytebase/backend/plugin/parser/base"@@ -13,8 +15,16 @@ func classifyQueryType(node ast.Node, allSystems bool) base.QueryType {return base.QueryTypeUnknown}- switch node.(type) {+ switch n := node.(type) {case *ast.SelectStmt:+ // SELECT ... INTO new_table creates a table — it is a write (DDL), not a read.+ // Without this the write would take the SELECT path and execute under read access.+ // INTO may sit on the first arm of a set operation, not the root. An INTO #temp+ // (or ##temp) target stays a read: it materialises a session-scoped tempdb table+ // that the extractor registers in TempTables for follow-up statements.+ if target := selectIntoTarget(n); target != nil && !strings.HasPrefix(target.Object, "#") {+ return base.DDL+ }if allSystems {return base.SelectInfoSchema}diff --git a/backend/plugin/parser/tsql/resource_change.go b/backend/plugin/parser/tsql/resource_change.goindex c46b05be5f..08ebd6af4c 100644--- a/backend/plugin/parser/tsql/resource_change.go+++ b/backend/plugin/parser/tsql/resource_change.go@@ -39,6 +39,16 @@ func extractChangedResources(currentDatabase string, currentSchema string, dbMetchangedResources.AddTable(d, s, &storepb.ChangedResourceTable{Name: t}, affectData)}+ // addObjectDatabase records a database-only write target for a non-table object DDL+ // (view/procedure/function/trigger) ONLY when the object's own name carries an explicit+ // database qualifier. Unqualified names record nothing (request-database fallback). The+ // object's own qualifier is used — never an ON-table or body reference. SUP-222 / BYT-9698.+ addObjectDatabase := func(ref *ast.TableRef) {+ if ref != nil && ref.Database != "" {+ changedResources.AddDatabase(ref.Database)+ }+ }+for _, unifiedAST := range asts {omniAST, ok := unifiedAST.(*OmniAST)if !ok {@@ -75,12 +85,25 @@ func extractChangedResources(currentDatabase string, currentSchema string, dbMetaddTable(ref, false)}}+ case ast.DropView, ast.DropProcedure, ast.DropFunction, ast.DropTrigger,+ ast.DropSequence, ast.DropSynonym, ast.DropType:+ if n.Names == nil {+ continue+ }+ for _, item := range n.Names.Items {+ if ref, ok := item.(*ast.TableRef); ok {+ addObjectDatabase(ref)+ }+ }default:}case *ast.CreateIndexStmt:addTable(n.Table, false)+ case *ast.TruncateStmt:+ addTable(n.Table, true)+case *ast.InsertStmt:if ref, ok := n.Relation.(*ast.TableRef); ok {addTable(ref, false)@@ -107,6 +130,40 @@ func extractChangedResources(currentDatabase string, currentSchema string, dbMet}addDML(omniAST.Text)+ case *ast.MergeStmt:+ if ref, ok := n.Target.(*ast.TableRef); ok {+ addTable(ref, false)+ }+ addDML(omniAST.Text)++ case *ast.CreateTableAsSelectStmt:+ addTable(n.Name, false)++ case *ast.SelectStmt:+ // SELECT ... INTO new_table creates a table; the INTO target is the write+ // target (possibly on the first arm of a set operation). INTO #temp is a+ // session-scoped tempdb table, not a database change.+ if target := selectIntoTarget(n); target != nil && !strings.HasPrefix(target.Object, "#") {+ addTable(target, false)+ }++ case *ast.CreateViewStmt:+ addObjectDatabase(n.Name)+ case *ast.CreateProcedureStmt:+ addObjectDatabase(n.Name)+ case *ast.CreateFunctionStmt:+ addObjectDatabase(n.Name)+ case *ast.CreateTriggerStmt:+ addObjectDatabase(n.Name)+ case *ast.CreateSequenceStmt:+ addObjectDatabase(n.Name)+ case *ast.AlterSequenceStmt:+ addObjectDatabase(n.Name)+ case *ast.CreateSynonymStmt:+ addObjectDatabase(n.Name)+ case *ast.CreateTypeStmt:+ addObjectDatabase(n.Name)+default:}}diff --git a/backend/plugin/parser/tsql/resource_change_test.go b/backend/plugin/parser/tsql/resource_change_test.goindex 54effedb15..9a7ddab9e8 100644--- a/backend/plugin/parser/tsql/resource_change_test.go+++ b/backend/plugin/parser/tsql/resource_change_test.go@@ -70,3 +70,102 @@ func TestExtractChangedResources_InsertDefaultValues(t *testing.T) {require.Equal(t, 0, got.DMLCount)require.Empty(t, got.SampleDMLS)}++func TestExtractChangedResources_Truncate(t *testing.T) {+ const statement = `TRUNCATE TABLE dbo.t;`++ want := model.NewChangedResources(nil)+ want.AddTable("DB", "dbo", &storepb.ChangedResourceTable{Name: "t"}, true)++ stmts, err := base.ParseStatements(storepb.Engine_MSSQL, statement)+ require.NoError(t, err)+ asts := base.ExtractASTs(stmts)+ got, err := extractChangedResources("DB", "dbo", nil, asts, statement)+ require.NoError(t, err)+ require.Equal(t, want, got.ChangedResources)+}++func TestExtractChangedResources_Merge(t *testing.T) {+ const statement = `MERGE INTO other_db.dbo.tgt AS t USING dbo.src AS s ON (t.id = s.id) WHEN MATCHED THEN UPDATE SET t.a = s.a;`++ want := model.NewChangedResources(nil)+ want.AddTable("other_db", "dbo", &storepb.ChangedResourceTable{Name: "tgt"}, false)++ stmts, err := base.ParseStatements(storepb.Engine_MSSQL, statement)+ require.NoError(t, err)+ asts := base.ExtractASTs(stmts)+ got, err := extractChangedResources("DB", "dbo", nil, asts, statement)+ require.NoError(t, err)+ require.Equal(t, want, got.ChangedResources)+}++func TestExtractChangedResources_ObjectDDLDatabaseOnly(t *testing.T) {+ // Qualified non-table object DDL → a database-only target on the qualifier.+ for _, statement := range []string{+ `CREATE VIEW other_db.dbo.v AS SELECT 1 AS x;`,+ `DROP VIEW other_db.dbo.v;`,+ `CREATE SEQUENCE other_db.dbo.s;`,+ `CREATE SYNONYM other_db.dbo.syn FOR t;`,+ `DROP TYPE other_db.dbo.ty;`,+ } {+ stmts, err := base.ParseStatements(storepb.Engine_MSSQL, statement)+ require.NoError(t, err, statement)+ asts := base.ExtractASTs(stmts)+ got, err := extractChangedResources("DB", "dbo", nil, asts, statement)+ require.NoError(t, err, statement)+ require.Equal(t, []string{"other_db"}, got.ChangedResources.GetDatabaseOnlyTargets(), statement)+ }+ // Unqualified → no database-only target (request-database fallback).+ const unqualified = `CREATE VIEW v AS SELECT 1 AS x;`+ stmts, err := base.ParseStatements(storepb.Engine_MSSQL, unqualified)+ require.NoError(t, err)+ asts := base.ExtractASTs(stmts)+ got, err := extractChangedResources("DB", "dbo", nil, asts, unqualified)+ require.NoError(t, err)+ require.Empty(t, got.ChangedResources.GetDatabaseOnlyTargets())+}++func TestClassifyQueryType_SelectInto(t *testing.T) {+ classify := func(statement string) base.QueryType {+ stmts, err := base.ParseStatements(storepb.Engine_MSSQL, statement)+ require.NoError(t, err, statement)+ asts := base.ExtractASTs(stmts)+ require.Len(t, asts, 1, statement)+ omniAST, ok := asts[0].(*OmniAST)+ require.True(t, ok, statement)+ return classifyQueryType(omniAST.Node, false)+ }+ // SELECT ... INTO creates a table — a write — so it must classify as DDL and take the+ // write-authorization path, not be authorized as a read. INTO may sit on the first+ // arm of a set operation, not the root.+ require.Equal(t, base.DDL, classify(`SELECT a INTO dbo.new_t FROM dbo.src;`))+ require.Equal(t, base.DDL, classify(`SELECT a INTO new_t FROM x UNION SELECT b FROM y;`))+ // INTO a session-scoped temp table stays a read: the extractor registers it in+ // TempTables so follow-up SELECTs in the same session resolve its columns.+ require.Equal(t, base.Select, classify(`SELECT a INTO #t FROM dbo.src;`))+ require.Equal(t, base.Select, classify(`SELECT a INTO ##g FROM dbo.src;`))+ // A plain SELECT stays a read.+ require.Equal(t, base.Select, classify(`SELECT a FROM dbo.src;`))+}++func TestExtractChangedResources_SelectInto(t *testing.T) {+ extract := func(statement string) *model.ChangedResources {+ stmts, err := base.ParseStatements(storepb.Engine_MSSQL, statement)+ require.NoError(t, err, statement)+ asts := base.ExtractASTs(stmts)+ got, err := extractChangedResources("DB", "dbo", nil, asts, statement)+ require.NoError(t, err, statement)+ return got.ChangedResources+ }++ // The INTO target is the write target, including when it sits on the first+ // arm of a set operation.+ want := model.NewChangedResources(nil)+ want.AddTable("DB", "dbo", &storepb.ChangedResourceTable{Name: "new_t"}, false)+ require.Equal(t, want, extract(`SELECT a INTO new_t FROM x;`))+ require.Equal(t, want, extract(`SELECT a INTO new_t FROM x UNION SELECT b FROM y;`))++ // INTO #temp is session-scoped tempdb — not a database change.+ empty := model.NewChangedResources(nil)+ require.Equal(t, empty, extract(`SELECT a INTO #t FROM x;`))+}diff --git a/backend/runner/plancheck/statement_report_executor.go b/backend/runner/plancheck/statement_report_executor.goindex f9e3b427d0..2a02953698 100644--- a/backend/runner/plancheck/statement_report_executor.go+++ b/backend/runner/plancheck/statement_report_executor.go@@ -196,7 +196,9 @@ func GetSQLSummaryReport(ctx context.Context, stores *store.Store, sheetManagerfor i, stmt := range stmtsWithPos {sqlTypes[i] = stmt.Type}- defaultSchema = "public"+ // Empty so pg's extractChangedResources falls back to the database's actual+ // default search_path (Change-1 makes a non-empty value force [currentSchema]).+ defaultSchema = ""case storepb.Engine_REDSHIFT:rd, ok := driver.(*redshiftdriver.Driver)if !ok {diff --git a/backend/store/model/changed_resources.go b/backend/store/model/changed_resources.goindex 6e5d5abdd5..c61c7ef2f0 100644--- a/backend/store/model/changed_resources.go+++ b/backend/store/model/changed_resources.go@@ -9,6 +9,13 @@ import (type ChangedResources struct {databases map[string]*ChangedDatabase+ // databaseOnly holds databases changed by a statement whose write target is a non-table+ // object (e.g. a qualified CREATE VIEW/PROCEDURE/... in another database) — there is no+ // table to scope, only the target database. It is auth-only: it is NOT included in Build()+ // (the changed-resource report stays table-shaped), and is consumed by the SQL-editor+ // write-authorization path to gate a qualified cross-database object DDL by its own database.+ databaseOnly map[string]bool+dbMetadata *DatabaseMetadata}@@ -27,8 +34,9 @@ type ChangedTable struct {func NewChangedResources(dbMetadata *DatabaseMetadata) *ChangedResources {return &ChangedResources{- databases: make(map[string]*ChangedDatabase),- dbMetadata: dbMetadata,+ databases: make(map[string]*ChangedDatabase),+ databaseOnly: make(map[string]bool),+ dbMetadata: dbMetadata,}}@@ -119,6 +127,27 @@ func (r *ChangedResources) AddTable(database string, schema string, change *stor}}+// AddDatabase records a database changed by a non-table-object write (Tier 2): a qualified+// object DDL (CREATE/ALTER/DROP VIEW/PROCEDURE/FUNCTION/TRIGGER/...) whose only auth-relevant+// identity is its target database. Auth-only; not surfaced in Build().+func (r *ChangedResources) AddDatabase(database string) {+ if r.databaseOnly == nil {+ r.databaseOnly = make(map[string]bool)+ }+ r.databaseOnly[database] = true+}++// GetDatabaseOnlyTargets returns the databases recorded via AddDatabase (non-table-object+// write targets). Used by the SQL-editor write-authorization path.+func (r *ChangedResources) GetDatabaseOnlyTargets() []string {+ result := make([]string, 0, len(r.databaseOnly))+ for database := range r.databaseOnly {+ result = append(result, database)+ }+ slices.Sort(result)+ return result+}+func (r *ChangedResources) CountAffectedTableRows() int64 {if r.dbMetadata == nil {return 0diff --git a/backend/tests/sql_dml_table_scope_test.go b/backend/tests/sql_dml_table_scope_test.gonew file mode 100644index 0000000000..8701e8b236--- /dev/null+++ b/backend/tests/sql_dml_table_scope_test.go@@ -0,0 +1,995 @@+package tests++import (+ "context"+ "fmt"+ "strings"+ "testing"++ "connectrpc.com/connect"+ "github.com/google/uuid"+ "github.com/stretchr/testify/require"+ "google.golang.org/genproto/googleapis/type/expr"++ "github.com/bytebase/bytebase/backend/common"+ v1pb "github.com/bytebase/bytebase/backend/generated-go/v1"+)++// TestSQLEditorTableScopedDML reproduces SUP-222: a project IAM grant that gives+// bb.sql.dml scoped to a specific table must authorize an INSERT to that table in+// the SQL Editor.+//+// Postgres is required: it is a "newACL" engine, so validateQueryRequest /+// ValidateSQLForEditor is skipped (backend/api/v1/sql_service.go:322). That skip+// is the only reason a DML statement reaches the ACL at all; on a non-newACL+// engine the INSERT would be rejected at validation for the wrong reason.+//+// The bug: the DML access check evaluates the grant's CEL condition at database+// granularity and never supplies resource.table_name (see checkDatabaseAccess in+// backend/api/v1/sql_service.go), so a resource.table_name-scoped condition can't+// match. A SELECT on the same table works because the SELECT path supplies+// per-column resource.table_name. Until the fix lands, the assertion below FAILS+// with "permission denied to access resources: <db>" — the expected RED outcome.+func TestSQLEditorTableScopedDML(t *testing.T) {+ t.Parallel()+ a := require.New(t)+ ctx := context.Background()+ ctl := &controller{}+ ctx, err := ctl.StartServerWithExternalPg(ctx)+ a.NoError(err)+ defer ctl.Close(ctx)++ // Save the owner token so we can swap identities and swap back.+ ownerToken := ctl.authInterceptor.token++ pgContainer, err := getPgContainer(ctx)+ defer func() {+ pgContainer.Close(ctx)+ }()+ a.NoError(err)++ // 1. Create a Postgres instance + database as the owner.+ instanceResp, err := ctl.instanceServiceClient.CreateInstance(ctx, connect.NewRequest(&v1pb.CreateInstanceRequest{+ InstanceId: generateRandomString("instance"),+ Instance: &v1pb.Instance{+ Title: "pgInstance",+ Engine: v1pb.Engine_POSTGRES,+ Environment: new("environments/prod"),+ Activation: true,+ DataSources: []*v1pb.DataSource{{Type: v1pb.DataSourceType_ADMIN, Host: pgContainer.host, Port: pgContainer.port, Username: "postgres", Password: "root-password", Id: "admin"}},+ },+ }))+ a.NoError(err)+ instance := instanceResp.Msg++ const databaseName = "sup222"+ err = ctl.createDatabase(ctx, ctl.project, instance, nil, databaseName, "postgres")+ a.NoError(err)++ databaseResp, err := ctl.databaseServiceClient.GetDatabase(ctx, connect.NewRequest(&v1pb.GetDatabaseRequest{+ Name: fmt.Sprintf("%s/databases/%s", instance.Name, databaseName),+ }))+ a.NoError(err)+ database := databaseResp.Msg++ // 2. Create the table public.locked_accounts via the change-database flow.+ setupSheetResp, err := ctl.sheetServiceClient.CreateSheet(ctx, connect.NewRequest(&v1pb.CreateSheetRequest{+ Parent: ctl.project.Name,+ Sheet: &v1pb.Sheet{Content: []byte(`CREATE TABLE public.locked_accounts (account_id bigint);`)},+ }))+ a.NoError(err)+ err = ctl.changeDatabase(ctx, ctl.project, database, setupSheetResp.Msg, false)+ a.NoError(err)++ // 3. Create a custom role with only bb.sql.dml.+ _, err = ctl.roleServiceClient.CreateRole(ctx, connect.NewRequest(&v1pb.CreateRoleRequest{+ Role: &v1pb.Role{+ Title: "repro-write",+ Permissions: []string{"bb.sql.dml"},+ },+ RoleId: "repro-write",+ }))+ a.NoError(err)++ // 4. Create a limited, non-owner user.+ limitedEmail := fmt.Sprintf("limited-%[email protected]", generateRandomString("u"))+ limitedPassword := "1024bytebase"+ limitedUser, err := ctl.userServiceClient.CreateUser(ctx, connect.NewRequest(&v1pb.CreateUserRequest{+ User: &v1pb.User{+ Email: limitedEmail,+ Password: limitedPassword,+ Title: "Limited User",+ },+ }))+ a.NoError(err)++ // Add to workspace IAM so the user can login.+ _, err = ctl.addMemberToWorkspaceIAM(ctx, limitedUser.Msg.Workspace, fmt.Sprintf("user:%s", limitedEmail), "roles/workspaceMember")+ a.NoError(err)++ // 5. Set the project IAM policy: the limited user gets an unconditional+ // sqlEditorReadUser binding (method-gate + bb.sql.select, NO bb.sql.dml) plus+ // a table-scoped repro-write binding.+ envID, err := common.GetEnvironmentID(database.GetEffectiveEnvironment()) // bare id, e.g. "prod"+ a.NoError(err)+ condition := fmt.Sprintf(+ `resource.database == "%s/databases/%s" && resource.table_name in ["locked_accounts"] && resource.environment_id in ["%s"]`,+ instance.Name, databaseName, envID,+ )++ policyResp, err := ctl.projectServiceClient.GetIamPolicy(ctx, connect.NewRequest(&v1pb.GetIamPolicyRequest{+ Resource: ctl.project.Name,+ }))+ a.NoError(err)+ policy := policyResp.Msg+ policy.Bindings = append(policy.Bindings,+ &v1pb.Binding{+ Role: "roles/sqlEditorReadUser",+ Members: []string{fmt.Sprintf("user:%s", limitedEmail)},+ },+ &v1pb.Binding{+ Role: "roles/repro-write",+ Members: []string{fmt.Sprintf("user:%s", limitedEmail)},+ Condition: &expr.Expr{+ Expression: condition,+ },+ },+ )+ _, err = ctl.projectServiceClient.SetIamPolicy(ctx, connect.NewRequest(&v1pb.SetIamPolicyRequest{+ Resource: ctl.project.Name,+ Policy: policy,+ }))+ a.NoError(err)++ // 6. Swap identity to the limited user and run the INSERT.+ // Non-web login so the bearer token is returned in the response body+ // (Web:true delivers the token only as a Set-Cookie, which the test's+ // bearer-token interceptor does not read).+ loginResp, err := ctl.authServiceClient.Login(ctx, connect.NewRequest(&v1pb.LoginRequest{+ Email: limitedEmail,+ Password: limitedPassword,+ }))+ a.NoError(err)+ ctl.authInterceptor.token = loginResp.Msg.Token++ queryResp, queryErr := ctl.sqlServiceClient.Query(ctx, connect.NewRequest(&v1pb.QueryRequest{+ Name: database.Name,+ Statement: "INSERT INTO public.locked_accounts (account_id) VALUES (1);",+ Limit: 1000,+ }))++ // 7. Assert the write was authorized and executed. The table-scoped bb.sql.dml+ // grant SHOULD authorize this INSERT. Until SUP-222 is fixed, the DML access+ // check denies it and surfaces "permission denied to access resources: <db>".+ a.NoError(queryErr, "INSERT should be authorized by the table-scoped bb.sql.dml grant")+ a.NotNil(queryResp)+ a.Len(queryResp.Msg.Results, 1)+ a.Empty(queryResp.Msg.Results[0].Error, "result should carry no error")+ a.Nil(queryResp.Msg.Results[0].GetPermissionDenied(), "result should carry no permission_denied detail")++ // Swap back to the owner and confirm the row actually landed.+ ctl.authInterceptor.token = ownerToken+ countResp, err := ctl.sqlServiceClient.Query(ctx, connect.NewRequest(&v1pb.QueryRequest{+ Name: database.Name,+ Statement: "SELECT count(*) FROM public.locked_accounts;",+ Limit: 1,+ }))+ a.NoError(err)+ a.Len(countResp.Msg.Results, 1)+ a.Empty(countResp.Msg.Results[0].Error)+ a.Len(countResp.Msg.Results[0].Rows, 1)+ a.Equal(int64(1), countResp.Msg.Results[0].Rows[0].Values[0].GetInt64Value(), "the inserted row should be present")+}++// TestSQLEditorTableScopedDMLEdgeCases exercises the regression + edge cases for+// the SUP-222 fix: DML/DDL grants are authorized per write-target table (via+// ExtractChangedResources), fall back to a database-level check when targets+// can't be resolved (never fail open), and are authorized per statement in+// multi-statement batches.+//+// All cases below MUST pass: they assert the fix's correctness and its edges.+// One server/instance/database is shared across cases via subtests; each subtest+// uses a fresh limited user + a per-case project IAM policy so grants don't leak.+//+// Postgres is required for the same reason the base test documents: it is a+// "newACL" engine, so DML/DDL statements reach the ACL at all.+func TestSQLEditorTableScopedDMLEdgeCases(t *testing.T) {+ // Not t.Parallel(): the subtests share one server/instance/database and each+ // rewrites the project IAM policy, so they must run serially (not in parallel+ // with each other). The whole test still runs alongside other test binaries.+ a := require.New(t)+ ctx := context.Background()+ ctl := &controller{}+ ctx, err := ctl.StartServerWithExternalPg(ctx)+ a.NoError(err)+ defer ctl.Close(ctx)++ ownerToken := ctl.authInterceptor.token++ pgContainer, err := getPgContainer(ctx)+ defer func() {+ pgContainer.Close(ctx)+ }()+ a.NoError(err)++ // Single Postgres instance + database shared by every subtest.+ instanceResp, err := ctl.instanceServiceClient.CreateInstance(ctx, connect.NewRequest(&v1pb.CreateInstanceRequest{+ InstanceId: generateRandomString("instance"),+ Instance: &v1pb.Instance{+ Title: "pgInstance",+ Engine: v1pb.Engine_POSTGRES,+ Environment: new("environments/prod"),+ Activation: true,+ DataSources: []*v1pb.DataSource{{Type: v1pb.DataSourceType_ADMIN, Host: pgContainer.host, Port: pgContainer.port, Username: "postgres", Password: "root-password", Id: "admin"}},+ },+ }))+ a.NoError(err)+ instance := instanceResp.Msg++ const databaseName = "sup222edge"+ a.NoError(ctl.createDatabase(ctx, ctl.project, instance, nil, databaseName, "postgres"))++ databaseResp, err := ctl.databaseServiceClient.GetDatabase(ctx, connect.NewRequest(&v1pb.GetDatabaseRequest{+ Name: fmt.Sprintf("%s/databases/%s", instance.Name, databaseName),+ }))+ a.NoError(err)+ database := databaseResp.Msg++ envID, err := common.GetEnvironmentID(database.GetEffectiveEnvironment()) // bare id, e.g. "prod"+ a.NoError(err)++ // Create every table the subtests reference, plus a non-public schema, via the+ // change-database flow. Doing it once keeps the (slow) rollout flow off the hot path.+ setupSQL := strings.Join([]string{+ `CREATE TABLE public.t_granted (id bigint);`,+ `CREATE TABLE public.t_other (id bigint);`,+ `CREATE TABLE public.t_dst (id bigint);`,+ `CREATE TABLE public.t_src (id bigint);`,+ `CREATE TABLE public.a (id bigint);`,+ `CREATE TABLE public.b (id bigint);`,+ `CREATE SCHEMA other_schema;`,+ `CREATE TABLE other_schema.t_in_other (id bigint);`,+ `INSERT INTO public.t_src (id) VALUES (7), (8), (9);`,+ }, "\n")+ setupSheetResp, err := ctl.sheetServiceClient.CreateSheet(ctx, connect.NewRequest(&v1pb.CreateSheetRequest{+ Parent: ctl.project.Name,+ Sheet: &v1pb.Sheet{Content: []byte(setupSQL)},+ }))+ a.NoError(err)+ a.NoError(ctl.changeDatabase(ctx, ctl.project, database, setupSheetResp.Msg, false))++ // Custom roles used across cases. bb.sql.dml for writes, bb.sql.ddl for schema+ // changes — each table-scopable via the binding's CEL condition.+ _, err = ctl.roleServiceClient.CreateRole(ctx, connect.NewRequest(&v1pb.CreateRoleRequest{+ Role: &v1pb.Role{Title: "repro-write", Permissions: []string{"bb.sql.dml"}},+ RoleId: "repro-write",+ }))+ a.NoError(err)+ _, err = ctl.roleServiceClient.CreateRole(ctx, connect.NewRequest(&v1pb.CreateRoleRequest{+ Role: &v1pb.Role{Title: "repro-ddl", Permissions: []string{"bb.sql.ddl"}},+ RoleId: "repro-ddl",+ }))+ a.NoError(err)++ // Capture the baseline project IAM policy so each subtest can reset to it+ // before layering on its own bindings (no cross-subtest grant leakage).+ baselineResp, err := ctl.projectServiceClient.GetIamPolicy(ctx, connect.NewRequest(&v1pb.GetIamPolicyRequest{+ Resource: ctl.project.Name,+ }))+ a.NoError(err)+ baselineBindings := baselineResp.Msg.Bindings++ dbFullName := fmt.Sprintf("%s/databases/%s", instance.Name, databaseName)++ // newLimitedUser creates a fresh non-owner user that can log in, and returns its+ // email + a bearer token. Run as the owner before calling.+ newLimitedUser := func(t *testing.T) (string, string) {+ t.Helper()+ ra := require.New(t)+ ctl.authInterceptor.token = ownerToken+ email := fmt.Sprintf("limited-%[email protected]", generateRandomString("u"))+ password := "1024bytebase"+ u, err := ctl.userServiceClient.CreateUser(ctx, connect.NewRequest(&v1pb.CreateUserRequest{+ User: &v1pb.User{Email: email, Password: password, Title: "Limited User"},+ }))+ ra.NoError(err)+ _, err = ctl.addMemberToWorkspaceIAM(ctx, u.Msg.Workspace, fmt.Sprintf("user:%s", email), "roles/workspaceMember")+ ra.NoError(err)+ loginResp, err := ctl.authServiceClient.Login(ctx, connect.NewRequest(&v1pb.LoginRequest{Email: email, Password: password}))+ ra.NoError(err)+ return email, loginResp.Msg.Token+ }++ // setProjectBindings resets the project IAM policy to baseline + the given+ // extra bindings. Run as the owner.+ setProjectBindings := func(t *testing.T, extra ...*v1pb.Binding) {+ t.Helper()+ ra := require.New(t)+ ctl.authInterceptor.token = ownerToken+ policyResp, err := ctl.projectServiceClient.GetIamPolicy(ctx, connect.NewRequest(&v1pb.GetIamPolicyRequest{+ Resource: ctl.project.Name,+ }))+ ra.NoError(err)+ policy := policyResp.Msg+ policy.Bindings = append(append([]*v1pb.Binding{}, baselineBindings...), extra...)+ _, err = ctl.projectServiceClient.SetIamPolicy(ctx, connect.NewRequest(&v1pb.SetIamPolicyRequest{+ Resource: ctl.project.Name,+ Policy: policy,+ }))+ ra.NoError(err)+ }++ // readBinding is the unconditional sqlEditorReadUser binding every write case+ // pairs with (method-gate + bb.sql.select, no bb.sql.dml/ddl).+ readBinding := func(email string) *v1pb.Binding {+ return &v1pb.Binding{+ Role: "roles/sqlEditorReadUser",+ Members: []string{fmt.Sprintf("user:%s", email)},+ }+ }+ // scopedBinding builds a conditional binding for the given role/condition.+ scopedBinding := func(role, email, condition string) *v1pb.Binding {+ return &v1pb.Binding{+ Role: role,+ Members: []string{fmt.Sprintf("user:%s", email)},+ Condition: &expr.Expr{Expression: condition},+ }+ }++ // runAs swaps to the user token, runs a Query, then restores the owner token.+ runAs := func(token, statement string) (*v1pb.QueryResponse, error) {+ ctl.authInterceptor.token = token+ resp, qErr := ctl.sqlServiceClient.Query(ctx, connect.NewRequest(&v1pb.QueryRequest{+ Name: database.Name,+ Statement: statement,+ Limit: 1000,+ }))+ ctl.authInterceptor.token = ownerToken+ if resp != nil {+ return resp.Msg, qErr+ }+ return nil, qErr+ }++ // assertAllowed asserts the Query was authorized: no error and no+ // permission_denied detail on any result.+ assertAllowed := func(t *testing.T, resp *v1pb.QueryResponse, qErr error) {+ t.Helper()+ ra := require.New(t)+ ra.NoError(qErr, "statement should be authorized")+ ra.NotNil(resp)+ ra.NotEmpty(resp.Results, "expected at least one result")+ for _, r := range resp.Results {+ ra.Empty(r.Error, "result should carry no error")+ ra.Nil(r.GetPermissionDenied(), "result should carry no permission_denied detail")+ }+ }++ // assertDeniedOn asserts the Query was denied on a specific resource. The denial+ // is surfaced on the last result's permission_denied detail (not as a top-level+ // error): queryRetryStopOnError attaches the access-check failure to the result's+ // Error field and returns a nil top-level error. The result detail must name a+ // resource containing wantResourceSubstr (e.g. ".../tables/t_other"), and no row+ // must have been written (rows == 0).+ assertDeniedOn := func(t *testing.T, resp *v1pb.QueryResponse, _ error, wantResourceSubstr string) {+ t.Helper()+ ra := require.New(t)+ ra.NotNil(resp)+ ra.NotEmpty(resp.Results)+ last := resp.Results[len(resp.Results)-1]+ pd := last.GetPermissionDenied()+ ra.NotNil(pd, "last result should carry a permission_denied detail; got error=%q", last.Error)+ ra.Empty(last.Rows, "a denied statement must not return/execute rows")+ joined := strings.Join(pd.Resources, ",")+ ra.Contains(joined, wantResourceSubstr, "denied resources %v should name %q", pd.Resources, wantResourceSubstr)+ }++ // countRows returns the row count of a table, queried as the owner.+ countRows := func(t *testing.T, table string) int64 {+ t.Helper()+ ra := require.New(t)+ ctl.authInterceptor.token = ownerToken+ resp, err := ctl.sqlServiceClient.Query(ctx, connect.NewRequest(&v1pb.QueryRequest{+ Name: database.Name,+ Statement: fmt.Sprintf("SELECT count(*) FROM %s;", table),+ Limit: 1,+ }))+ ra.NoError(err)+ ra.Len(resp.Msg.Results, 1)+ ra.Empty(resp.Msg.Results[0].Error)+ ra.Len(resp.Msg.Results[0].Rows, 1)+ return resp.Msg.Results[0].Rows[0].Values[0].GetInt64Value()+ }++ tableScopedDML := func(email, table string) *v1pb.Binding {+ cond := fmt.Sprintf(+ `resource.database == "%s" && resource.table_name in ["%s"] && resource.environment_id in ["%s"]`,+ dbFullName, table, envID,+ )+ return scopedBinding("roles/repro-write", email, cond)+ }++ // 1. Denied on a non-granted table: grant is table-scoped to t_granted; an+ // INSERT into t_other must be denied and name t_other.+ t.Run("DeniedOnNonGrantedTable", func(t *testing.T) {+ email, token := newLimitedUser(t)+ setProjectBindings(t, readBinding(email), tableScopedDML(email, "t_granted"))++ resp, qErr := runAs(token, "INSERT INTO public.t_other (id) VALUES (1);")+ assertDeniedOn(t, resp, qErr, "/tables/t_other")+ })++ // 2. Schema-scoped grant: condition scopes by schema_name only (no table_name).+ // An INSERT into a public table is allowed AND executed; an INSERT into a+ // table in a different schema is denied.+ t.Run("SchemaScopedGrant", func(t *testing.T) {+ ra := require.New(t)+ email, token := newLimitedUser(t)+ cond := fmt.Sprintf(+ `resource.database == "%s" && resource.schema_name == "public" && resource.environment_id in ["%s"]`,+ dbFullName, envID,+ )+ setProjectBindings(t, readBinding(email), scopedBinding("roles/repro-write", email, cond))++ before := countRows(t, "public.t_dst")+ resp, qErr := runAs(token, "INSERT INTO public.t_dst (id) VALUES (101);")+ assertAllowed(t, resp, qErr)+ ra.Equal(before+1, countRows(t, "public.t_dst"), "the row should have been inserted")++ // A table outside the granted schema is denied.+ resp, qErr = runAs(token, "INSERT INTO other_schema.t_in_other (id) VALUES (1);")+ assertDeniedOn(t, resp, qErr, "other_schema/tables/t_in_other")+ })++ // 3. INSERT ... SELECT requires DML only on the target. The grant is table-scoped+ // to t_dst; there is NO grant of any kind referencing t_src. The statement+ // reads from t_src and writes to t_dst → allowed AND executed, proving+ // read-source tables are not gated.+ t.Run("InsertSelectGatesTargetOnly", func(t *testing.T) {+ ra := require.New(t)+ email, token := newLimitedUser(t)+ setProjectBindings(t, readBinding(email), tableScopedDML(email, "t_dst"))++ before := countRows(t, "public.t_dst")+ srcCount := countRows(t, "public.t_src")+ resp, qErr := runAs(token, "INSERT INTO public.t_dst SELECT id FROM public.t_src;")+ assertAllowed(t, resp, qErr)+ ra.Equal(before+srcCount, countRows(t, "public.t_dst"), "all source rows should have been copied")+ })++ // 4. Database-scoped DML still works (no regression). The condition scopes by+ // database + environment only (no table/schema clause).+ t.Run("DatabaseScopedDMLNoRegression", func(t *testing.T) {+ ra := require.New(t)+ email, token := newLimitedUser(t)+ cond := fmt.Sprintf(+ `resource.database == "%s" && resource.environment_id in ["%s"]`,+ dbFullName, envID,+ )+ setProjectBindings(t, readBinding(email), scopedBinding("roles/repro-write", email, cond))++ before := countRows(t, "public.t_other")+ resp, qErr := runAs(token, "INSERT INTO public.t_other (id) VALUES (202);")+ assertAllowed(t, resp, qErr)+ ra.Equal(before+1, countRows(t, "public.t_other"), "the row should have been inserted")+ })++ // 5. UPDATE and DELETE on the granted table are allowed; the same statements+ // against a non-granted table are denied.+ t.Run("UpdateDeleteScoped", func(t *testing.T) {+ ra := require.New(t)+ email, token := newLimitedUser(t)+ setProjectBindings(t, readBinding(email), tableScopedDML(email, "t_granted"))++ // Seed a row to mutate (as the owner).+ ctl.authInterceptor.token = ownerToken+ _, err := ctl.sqlServiceClient.Query(ctx, connect.NewRequest(&v1pb.QueryRequest{+ Name: database.Name,+ Statement: "INSERT INTO public.t_granted (id) VALUES (1);",+ Limit: 1,+ }))+ ra.NoError(err)++ resp, qErr := runAs(token, "UPDATE public.t_granted SET id = 2 WHERE id = 1;")+ assertAllowed(t, resp, qErr)+ resp, qErr = runAs(token, "DELETE FROM public.t_granted WHERE id = 2;")+ assertAllowed(t, resp, qErr)++ // The same statements against t_other are denied.+ resp, qErr = runAs(token, "UPDATE public.t_other SET id = 2 WHERE id = 1;")+ assertDeniedOn(t, resp, qErr, "/tables/t_other")+ resp, qErr = runAs(token, "DELETE FROM public.t_other WHERE id = 1;")+ assertDeniedOn(t, resp, qErr, "/tables/t_other")+ })++ // 6. Fail-safe is closed: a user with ONLY the unconditional read pairing and no+ // write grant must be denied (the no-matching-grant fallback denies, not grants).+ t.Run("FailSafeClosed", func(t *testing.T) {+ email, token := newLimitedUser(t)+ setProjectBindings(t, readBinding(email))++ resp, qErr := runAs(token, "INSERT INTO public.t_granted (id) VALUES (1);")+ assertDeniedOn(t, resp, qErr, "/tables/t_granted")+ })++ // 7. Multi-statement batches fall back to the database-level check (fail-closed). A+ // batch can change the session's default schema mid-batch (Postgres SET search_path,+ // Oracle ALTER SESSION SET CURRENT_SCHEMA), redirecting a later unqualified write to+ // a schema the per-statement resolver can't reliably track. Rather than risk+ // authorizing the wrong schema, multi-statement DML/DDL falls back to the+ // database-level check — table/schema-scoped grants then require a database-level+ // grant. Single statements stay per-write-target. SUP-222 / BYT-9698.+ t.Run("MultiStatementBatchFallsBackToDatabaseLevel", func(t *testing.T) {+ ra := require.New(t)+ email, token := newLimitedUser(t)+ ddlCond := fmt.Sprintf(+ `resource.database == "%s" && resource.table_name in ["a"] && resource.environment_id in ["%s"]`,+ dbFullName, envID,+ )+ dmlCond := fmt.Sprintf(+ `resource.database == "%s" && resource.table_name in ["b"] && resource.environment_id in ["%s"]`,+ dbFullName, envID,+ )+ setProjectBindings(t,+ readBinding(email),+ scopedBinding("roles/repro-ddl", email, ddlCond),+ scopedBinding("roles/repro-write", email, dmlCond),+ )++ // A 2-statement batch (DDL on a + DML on b), even though each table is individually+ // granted, is DENIED at the database level — table-scoped grants don't satisfy the+ // fallback. The denial names the bare database, NOT a /tables/ resource.+ col := "c" + strings.ReplaceAll(uuid.NewString(), "-", "")[:12]+ stmt := fmt.Sprintf("ALTER TABLE public.a ADD COLUMN %s int; INSERT INTO public.b (id) VALUES (1);", col)+ resp, qErr := runAs(token, stmt)+ assertDeniedOn(t, resp, qErr, dbFullName)+ last := resp.Results[len(resp.Results)-1]+ ra.NotContains(strings.Join(last.GetPermissionDenied().GetResources(), ","), "/tables/",+ "a multi-statement batch must deny via the database-level fallback, not a per-target check")++ // Sharpness: SINGLE statements are still authorized per write-target table — the DDL+ // grant on a does not authorize a DML on a, and the DML grant on b does not authorize+ // DDL on b.+ resp, qErr = runAs(token, "INSERT INTO public.a (id) VALUES (1);")+ assertDeniedOn(t, resp, qErr, "public/tables/a")+ col2 := "c" + strings.ReplaceAll(uuid.NewString(), "-", "")[:12]+ resp, qErr = runAs(token, fmt.Sprintf("ALTER TABLE public.b ADD COLUMN %s int;", col2))+ assertDeniedOn(t, resp, qErr, "public/tables/b")++ // Positive: with a DATABASE-scoped DML grant the same kind of multi-statement DML+ // batch is allowed (the fallback passes) — confirming the fallback is not a blanket+ // deny.+ dbDmlCond := fmt.Sprintf(`resource.database == "%s" && resource.environment_id in ["%s"]`, dbFullName, envID)+ setProjectBindings(t, readBinding(email), scopedBinding("roles/repro-write", email, dbDmlCond))+ before := countRows(t, "public.b")+ resp, qErr = runAs(token, "INSERT INTO public.b (id) VALUES (1); INSERT INTO public.b (id) VALUES (2);")+ assertAllowed(t, resp, qErr)+ ra.Equal(before+2, countRows(t, "public.b"), "both INSERTs should execute under the database-level grant")+ })++ // 8. Empty-target fail-safe fallback (SUP-222). The DML/DDL access check resolves+ // this statement's write targets via ExtractChangedResources; when that yields+ // ZERO table targets it falls back to checkDatabaseAccess, which must stay+ // fail-CLOSED. resolveWriteTargets returns zero targets in two converging cases:+ // (a) a newACL engine WITHOUT a ChangedResources extractor — BigQuery,+ // Snowflake, Spanner, MongoDB, Elasticsearch; and+ // (b) DDL on a non-table object — ExtractChangedResources tracks tables only.+ // Both hit the SAME engine-agnostic `len(targets)==0 → checkDatabaseAccess(perm)`+ // guard in accessCheckWithGrantedTargets. Standing up BigQuery/Snowflake in the+ // harness is expensive, so we exercise the IDENTICAL guard on Postgres with a+ // non-table DDL — CREATE SEQUENCE — which parses to *ast.CreateSeqStmt: it+ // classifies as DDL (perm = bb.sql.ddl) but is NOT handled by the pg+ // ExtractChangedResources switch (which only adds tables for CREATE TABLE / DROP /+ // ALTER TABLE / RENAME / CREATE INDEX / INSERT / UPDATE / DELETE), so it resolves+ // to zero targets. This Postgres case therefore stands in for the+ // unsupported-engine (no-extractor) case: same guard, same fail-closed contract.+ t.Run("EmptyTargetFailSafeFallback", func(t *testing.T) {+ // Unique sequence name so re-runs (and the two sub-cases) never collide.+ seqName := "s_" + strings.ReplaceAll(uuid.NewString(), "-", "")[:12]+ createSeq := fmt.Sprintf("CREATE SEQUENCE public.%s;", seqName)+ ddlCond := func(extra string) string {+ return fmt.Sprintf(+ `resource.database == "%s"%s && resource.environment_id in ["%s"]`,+ dbFullName, extra, envID,+ )+ }++ // 8a. Db-scoped DDL grant → the empty-target fallback ALLOWS. The condition+ // scopes by database + environment only (no table/schema clause), exactly+ // the attributes checkDatabaseAccess supplies, so the fallback matches and+ // the CREATE SEQUENCE executes.+ t.Run("DbScopedAllows", func(t *testing.T) {+ ra := require.New(t)+ email, token := newLimitedUser(t)+ setProjectBindings(t, readBinding(email), scopedBinding("roles/repro-ddl", email, ddlCond("")))++ resp, qErr := runAs(token, createSeq)+ assertAllowed(t, resp, qErr)+ // Confirm the sequence actually landed (the fallback authorized execution).+ ra.Equal(int64(1), countRows(t,+ fmt.Sprintf("pg_sequences WHERE schemaname = 'public' AND sequencename = '%s'", seqName)),+ "the sequence should have been created")+ })++ // 8b. Table-scoped DDL grant → the empty-target fallback DENIES (never fail+ // open). Same CREATE SEQUENCE, but the grant adds a resource.table_name+ // clause. Because the statement has ZERO table targets, the code falls back+ // to checkDatabaseAccess, whose attributes carry NO resource.table_name, so+ // the table-scoped condition cannot match → denied at the database level.+ // The db-level denial (resource = the bare database, not a /tables/… path)+ // is itself the proof that targets were empty: had a non-empty target been+ // resolved and matched the granted table, the statement would be ALLOWED.+ t.Run("TableScopedDenies", func(t *testing.T) {+ email, token := newLimitedUser(t)+ tableClause := ` && resource.table_name in ["any_table"]`+ setProjectBindings(t, readBinding(email), scopedBinding("roles/repro-ddl", email, ddlCond(tableClause)))++ resp, qErr := runAs(token, createSeq)+ // Denied on the bare database (the fallback's checkDatabaseAccess resource),+ // NOT on a /tables/… path — confirming the empty-target path was taken.+ assertDeniedOn(t, resp, qErr, dbFullName)+ // assertDeniedOn does a substring Contains on dbFullName, which is a PREFIX of+ // any per-target resource name (instances/…/databases/…/schemas/…/tables/…), so+ // it alone cannot distinguish the bare-db fallback from a per-target denial.+ // Assert the denied resources carry NO /tables/ segment to PROVE the empty-target+ // fallback (checkDatabaseAccess) ran — guarding against a future regression where+ // resolveWriteTargets returns a spurious target.+ last := resp.Results[len(resp.Results)-1]+ require.New(t).NotContains(+ strings.Join(last.GetPermissionDenied().GetResources(), ","),+ "/tables/",+ "CREATE SEQUENCE must be denied via the bare-database fallback (empty write targets), not a per-target /tables/ check",+ )+ })+ })++ // 9. Codex P1 search_path-override bypass guard (SUP-222 / BYT-9698). Postgres+ // honors QueryRequest.schema by running `SET search_path TO "<schema>"` before+ // execution, so an UNQUALIFIED `INSERT INTO t_sbx` writes to <request_schema>.t_sbx.+ // The grant is table-scoped to public.t_sbx. The user sends Schema="other_schema"+ // + an unqualified INSERT: Postgres would write other_schema.t_sbx (NOT granted).+ // The fix resolves the write target against the request schema (other_schema), so+ // the public-scoped grant doesn't cover it → DENIED on other_schema/tables/t_sbx.+ // Before the fix, resolution ignored the request schema and used public, wrongly+ // ALLOWING the write to other_schema.t_sbx — the fail-open authorization bypass.+ // The target schema/table need not exist: authorization precedes execution.+ t.Run("RequestSchemaOverrideNotBypassed", func(t *testing.T) {+ ra := require.New(t)+ email, token := newLimitedUser(t)+ // Table-scoped DML grant on public.t_sbx only.+ cond := fmt.Sprintf(+ `resource.database == "%s" && resource.schema_name == "public" && resource.table_name in ["t_sbx"] && resource.environment_id in ["%s"]`,+ dbFullName, envID,+ )+ setProjectBindings(t, readBinding(email), scopedBinding("roles/repro-write", email, cond))++ // Ensure public.t_sbx exists (the granted target) via the change-database flow.+ setupSheetResp, err := ctl.sheetServiceClient.CreateSheet(ctx, connect.NewRequest(&v1pb.CreateSheetRequest{+ Parent: ctl.project.Name,+ Sheet: &v1pb.Sheet{Content: []byte(`CREATE TABLE IF NOT EXISTS public.t_sbx (id int);`)},+ }))+ ra.NoError(err)+ ra.NoError(ctl.changeDatabase(ctx, ctl.project, database, setupSheetResp.Msg, false))++ // Unqualified INSERT + Schema="other_schema": Postgres SET search_path would route+ // the write to other_schema.t_sbx, which the public-scoped grant does not cover.+ ctl.authInterceptor.token = token+ resp, qErr := ctl.sqlServiceClient.Query(ctx, connect.NewRequest(&v1pb.QueryRequest{+ Name: database.Name,+ Statement: "INSERT INTO t_sbx VALUES (1)",+ Schema: new("other_schema"),+ Limit: 1000,+ }))+ ctl.authInterceptor.token = ownerToken++ var msg *v1pb.QueryResponse+ if resp != nil {+ msg = resp.Msg+ }+ // DENIED, naming other_schema (the real write target), NOT public.+ assertDeniedOn(t, msg, qErr, "schemas/other_schema/tables/t_sbx")+ last := msg.Results[len(msg.Results)-1]+ ra.NotContains(+ strings.Join(last.GetPermissionDenied().GetResources(), ","),+ "schemas/public/tables/t_sbx",+ "the request schema (other_schema), not public, must be the resolved write target",+ )+ })++ // 10. Codex P1 (round 2): an EARLIER statement in the same batch changes search_path.+ // `SET search_path = other_schema; INSERT INTO t_sbx2` — SET is a safe Select (passes+ // with the read grant), and Postgres runs both on the same session, so the unqualified+ // INSERT writes other_schema.t_sbx2, which the public-scoped grant does not cover.+ // Because a batch can redirect the schema mid-stream in forms the resolver can't+ // reliably track, multi-statement DML/DDL falls back to the database-level check →+ // DENIED at the bare database, so the redirected write is never authorized.+ // SUP-222 / BYT-9698.+ t.Run("EarlierSetSearchPathNotBypassed", func(t *testing.T) {+ ra := require.New(t)+ email, token := newLimitedUser(t)+ cond := fmt.Sprintf(+ `resource.database == "%s" && resource.schema_name == "public" && resource.table_name in ["t_sbx2"] && resource.environment_id in ["%s"]`,+ dbFullName, envID,+ )+ setProjectBindings(t, readBinding(email), scopedBinding("roles/repro-write", email, cond))++ setupSheetResp, err := ctl.sheetServiceClient.CreateSheet(ctx, connect.NewRequest(&v1pb.CreateSheetRequest{+ Parent: ctl.project.Name,+ Sheet: &v1pb.Sheet{Content: []byte(`CREATE TABLE IF NOT EXISTS public.t_sbx2 (id int);`)},+ }))+ ra.NoError(err)+ ra.NoError(ctl.changeDatabase(ctx, ctl.project, database, setupSheetResp.Msg, false))++ // An earlier SET search_path would redirect the later unqualified INSERT to+ // other_schema; the multi-statement batch must not authorize that write.+ ctl.authInterceptor.token = token+ resp, qErr := ctl.sqlServiceClient.Query(ctx, connect.NewRequest(&v1pb.QueryRequest{+ Name: database.Name,+ Statement: "SET search_path = other_schema; INSERT INTO t_sbx2 VALUES (1)",+ Limit: 1000,+ }))+ ctl.authInterceptor.token = ownerToken++ var msg *v1pb.QueryResponse+ if resp != nil {+ msg = resp.Msg+ }+ // Denied via the database-level fallback (multi-statement) — the bare database, not a+ // per-target /tables/ resource. The public-scoped grant cannot satisfy it.+ assertDeniedOn(t, msg, qErr, dbFullName)+ last := msg.Results[len(msg.Results)-1]+ ra.NotContains(+ strings.Join(last.GetPermissionDenied().GetResources(), ","),+ "/tables/",+ "a SET search_path batch must deny via the database-level fallback, never authorizing the redirected write",+ )+ })++ // 11. Sentinel/omit: for an UNqualified write with no request schema, the schema Postgres+ // will resolve (connection user's $user/public) can't be known here, so the write+ // target resolves to an internal sentinel and resource.schema_name is OMITTED+ // (key-absent). Effects: schema-scoped grants fail closed (must qualify); table-only+ // grants still match; and a negated schema condition must NOT over-allow (the+ // empty-string trap). SUP-222 / BYT-9698.+ t.Run("UnqualifiedSchemaUnknown", func(t *testing.T) {+ ra := require.New(t)+ setupSheetResp, err := ctl.sheetServiceClient.CreateSheet(ctx, connect.NewRequest(&v1pb.CreateSheetRequest{+ Parent: ctl.project.Name,+ Sheet: &v1pb.Sheet{Content: []byte(`CREATE TABLE IF NOT EXISTS public.t_uq (id int);`)},+ }))+ ra.NoError(err)+ ra.NoError(ctl.changeDatabase(ctx, ctl.project, database, setupSheetResp.Msg, false))++ // (a) schema-scoped grant + UNqualified write → denied; schema can't be confirmed, so+ // the schema_name attribute is omitted and the `== "public"` clause errors. The+ // denial names the table with NO /schemas/ segment.+ email, token := newLimitedUser(t)+ schemaCond := fmt.Sprintf(`resource.database == "%s" && resource.schema_name == "public" && resource.table_name in ["t_uq"] && resource.environment_id in ["%s"]`, dbFullName, envID)+ setProjectBindings(t, readBinding(email), scopedBinding("roles/repro-write", email, schemaCond))+ resp, qErr := runAs(token, "INSERT INTO t_uq VALUES (1)")+ assertDeniedOn(t, resp, qErr, "/tables/t_uq")+ ra.NotContains(strings.Join(resp.Results[len(resp.Results)-1].GetPermissionDenied().GetResources(), ","),+ "/schemas/", "unknown schema must omit the /schemas/ segment")++ // (b) Same grant, but a QUALIFIED write → schema is explicit (public) → allowed + executed.+ before := countRows(t, "public.t_uq")+ resp, qErr = runAs(token, "INSERT INTO public.t_uq VALUES (1)")+ assertAllowed(t, resp, qErr)+ ra.Equal(before+1, countRows(t, "public.t_uq"), "qualified write to the granted schema executes")++ // (c) TABLE-only grant (no schema clause) + UNqualified write → allowed (schema-agnostic).+ email2, token2 := newLimitedUser(t)+ tableCond := fmt.Sprintf(`resource.database == "%s" && resource.table_name in ["t_uq"] && resource.environment_id in ["%s"]`, dbFullName, envID)+ setProjectBindings(t, readBinding(email2), scopedBinding("roles/repro-write", email2, tableCond))+ before = countRows(t, "public.t_uq")+ resp, qErr = runAs(token2, "INSERT INTO t_uq VALUES (1)")+ assertAllowed(t, resp, qErr)+ ra.Equal(before+1, countRows(t, "public.t_uq"), "table-only grant allows the unqualified write")++ // (d) THE EMPTY-STRING TRAP: a NEGATED schema condition + UNqualified write must DENY.+ // If schema_name were set to "" rather than omitted, `schema_name != "secret"`+ // would evaluate true → over-allow. Omission (key-absent) makes CEL error → deny.+ email3, token3 := newLimitedUser(t)+ negCond := fmt.Sprintf(`resource.database == "%s" && resource.table_name in ["t_uq"] && resource.schema_name != "secret" && resource.environment_id in ["%s"]`, dbFullName, envID)+ setProjectBindings(t, readBinding(email3), scopedBinding("roles/repro-write", email3, negCond))+ resp, qErr = runAs(token3, "INSERT INTO t_uq VALUES (1)")+ assertDeniedOn(t, resp, qErr, "/tables/t_uq")+ })++ // 12. Case-folding: an unquoted uppercase `PUBLIC.t` folds to `public` and matches a+ // public-scoped grant (the resolved schema is normalized, not the literal text).+ t.Run("CaseFoldedQualifiedSchema", func(t *testing.T) {+ ra := require.New(t)+ setupSheetResp, err := ctl.sheetServiceClient.CreateSheet(ctx, connect.NewRequest(&v1pb.CreateSheetRequest{+ Parent: ctl.project.Name,+ Sheet: &v1pb.Sheet{Content: []byte(`CREATE TABLE IF NOT EXISTS public.t_cf (id int);`)},+ }))+ ra.NoError(err)+ ra.NoError(ctl.changeDatabase(ctx, ctl.project, database, setupSheetResp.Msg, false))++ email, token := newLimitedUser(t)+ cond := fmt.Sprintf(`resource.database == "%s" && resource.schema_name == "public" && resource.table_name in ["t_cf"] && resource.environment_id in ["%s"]`, dbFullName, envID)+ setProjectBindings(t, readBinding(email), scopedBinding("roles/repro-write", email, cond))+ before := countRows(t, "public.t_cf")+ resp, qErr := runAs(token, "INSERT INTO PUBLIC.t_cf VALUES (1)")+ assertAllowed(t, resp, qErr)+ ra.Equal(before+1, countRows(t, "public.t_cf"), "case-folded PUBLIC matches the public-scoped grant")+ })++ // 13. TRUNCATE is table-scopable DDL (SUP-222 / BYT-9698, Codex follow-up). TRUNCATE+ // classifies as DDL and names an explicit base-table target, so the changed-resource+ // extractor resolves that target and a table-scoped bb.sql.ddl grant authorizes a+ // TRUNCATE on the granted table and denies it per-target on any other — it does NOT+ // fall back to the database-level check the way non-table DDL (CREATE SEQUENCE) does.+ t.Run("TruncateScopedDDL", func(t *testing.T) {+ ra := require.New(t)+ // Dedicated, seeded table so the allow case can prove execution (rows → 0).+ setupSheetResp, err := ctl.sheetServiceClient.CreateSheet(ctx, connect.NewRequest(&v1pb.CreateSheetRequest{+ Parent: ctl.project.Name,+ Sheet: &v1pb.Sheet{Content: []byte("CREATE TABLE IF NOT EXISTS public.t_trunc (id int);\nINSERT INTO public.t_trunc VALUES (1), (2), (3);")},+ }))+ ra.NoError(err)+ ra.NoError(ctl.changeDatabase(ctx, ctl.project, database, setupSheetResp.Msg, false))++ email, token := newLimitedUser(t)+ ddlCond := fmt.Sprintf(+ `resource.database == "%s" && resource.table_name in ["t_trunc"] && resource.environment_id in ["%s"]`,+ dbFullName, envID,+ )+ setProjectBindings(t, readBinding(email), scopedBinding("roles/repro-ddl", email, ddlCond))++ // TRUNCATE on the granted table is authorized AND executes (all rows removed).+ ra.Greater(countRows(t, "public.t_trunc"), int64(0), "precondition: t_trunc must be seeded")+ resp, qErr := runAs(token, "TRUNCATE TABLE public.t_trunc;")+ assertAllowed(t, resp, qErr)+ ra.Equal(int64(0), countRows(t, "public.t_trunc"), "TRUNCATE should have removed all rows")++ // TRUNCATE on a non-granted table is denied per-target (names the table, not the bare db).+ resp, qErr = runAs(token, "TRUNCATE TABLE public.t_other;")+ assertDeniedOn(t, resp, qErr, "/tables/t_other")+ })++ // 14. resource.environment_id is resolved per TARGET database, not copied from the request+ // database (SUP-222 / BYT-9698, Codex follow-up). A cross-database write names a database+ // that may sit in a different environment; an environment-scoped grant must be evaluated+ // against the TARGET's environment, or it could authorize a write into another+ // environment. Postgres can't execute cross-database writes, but authorization precedes+ // execution and the resolver keys on the statement's catalog name, so the access decision+ // is observable: a second database on the same instance is placed in the `test`+ // environment, and a grant scoped to the request database's `prod` environment must NOT+ // authorize a write whose catalog names that test-environment database.+ t.Run("CrossDatabaseEnvironmentResolvedPerTarget", func(t *testing.T) {+ ra := require.New(t)+ testEnv, err := ctl.getEnvironment(ctx, "test")+ ra.NoError(err)+ // A second database on the SAME instance, in a DIFFERENT (test) environment.+ const otherDBName = "sup222edge_other_env"+ ra.NoError(ctl.createDatabase(ctx, ctl.project, instance, testEnv, otherDBName, "postgres"))++ // Seed the granted table in the request (prod) database for the positive control.+ setupSheetResp, err := ctl.sheetServiceClient.CreateSheet(ctx, connect.NewRequest(&v1pb.CreateSheetRequest{+ Parent: ctl.project.Name,+ Sheet: &v1pb.Sheet{Content: []byte("CREATE TABLE IF NOT EXISTS public.t_xenv (id int);")},+ }))+ ra.NoError(err)+ ra.NoError(ctl.changeDatabase(ctx, ctl.project, database, setupSheetResp.Msg, false))++ // Grant: environment-scoped to the request database's environment (prod) + table t_xenv,+ // with NO database clause — so only the environment distinguishes the two targets.+ email, token := newLimitedUser(t)+ cond := fmt.Sprintf(+ `resource.environment_id in ["%s"] && resource.table_name in ["t_xenv"]`,+ envID, // the request database's environment (prod)+ )+ setProjectBindings(t, readBinding(email), scopedBinding("roles/repro-write", email, cond))++ // Positive control: a write to the request (prod) database matches the prod-scoped grant.+ before := countRows(t, "public.t_xenv")+ resp, qErr := runAs(token, "INSERT INTO public.t_xenv VALUES (1);")+ assertAllowed(t, resp, qErr)+ ra.Equal(before+1, countRows(t, "public.t_xenv"), "same-environment write executes")++ // The fix: a cross-database write whose catalog names the TEST-environment database is+ // DENIED — its environment is resolved from the target, not copied from the request. The+ // denial names the target database. (Pre-fix the request's prod environment was used, so+ // the prod-scoped grant wrongly authorized this write.)+ resp, qErr = runAs(token, fmt.Sprintf("INSERT INTO %s.public.t_xenv VALUES (1);", otherDBName))+ assertDeniedOn(t, resp, qErr, fmt.Sprintf("databases/%s", otherDBName))+ })++ // 15. A QUALIFIED cross-database write in a MULTI-statement batch must be authorized against+ // its TARGET database, not the request database (SUP-222 / BYT-9698, Codex follow-up).+ // Multi-statement batches drop to a database-level check (an earlier statement can rebind+ // the session schema/database, so per-table/schema scoping is unreliable), but that check+ // must still key on each target database: a grant on the request database must not+ // authorize a write whose catalog names another database — otherwise wrapping the write in+ // a batch would bypass the per-target check the single-statement path applies. (Postgres+ // can't execute cross-database writes, but authorization precedes execution and keys on the+ // catalog name, so the decision is observable.)+ t.Run("MultiStatementCrossDatabaseNotBypassed", func(t *testing.T) {+ ra := require.New(t)+ const otherDBName = "sup222edge_mstmt_other"+ ra.NoError(ctl.createDatabase(ctx, ctl.project, instance, nil /* environment */, otherDBName, "postgres"))++ // Seed the granted table in the request database for the positive control.+ setupSheetResp, err := ctl.sheetServiceClient.CreateSheet(ctx, connect.NewRequest(&v1pb.CreateSheetRequest{+ Parent: ctl.project.Name,+ Sheet: &v1pb.Sheet{Content: []byte("CREATE TABLE IF NOT EXISTS public.t_mxdb (id int);")},+ }))+ ra.NoError(err)+ ra.NoError(ctl.changeDatabase(ctx, ctl.project, database, setupSheetResp.Msg, false))++ // DATABASE-scoped DML grant on the REQUEST database only (no table/schema clause).+ email, token := newLimitedUser(t)+ cond := fmt.Sprintf(+ `resource.database == "%s" && resource.environment_id in ["%s"]`,+ dbFullName, envID,+ )+ setProjectBindings(t, readBinding(email), scopedBinding("roles/repro-write", email, cond))++ // Positive control: a SAME-database multi-statement batch is authorized at the database+ // level by the request-database grant, and executes.+ before := countRows(t, "public.t_mxdb")+ resp, qErr := runAs(token, "SELECT 1; INSERT INTO public.t_mxdb VALUES (1);")+ assertAllowed(t, resp, qErr)+ ra.Equal(before+1, countRows(t, "public.t_mxdb"), "same-database multi-statement write executes")++ // The fix: the same request-database grant must NOT authorize a multi-statement batch+ // whose qualified write targets ANOTHER database — the database-level fallback checks the+ // TARGET database, not the request database. Denied on the other database.+ resp, qErr = runAs(token, fmt.Sprintf("SELECT 1; INSERT INTO %s.public.t_mxdb VALUES (1);", otherDBName))+ assertDeniedOn(t, resp, qErr, fmt.Sprintf("databases/%s", otherDBName))+ })++ // 16. MERGE resolves its write target (the INTO table) and is authorized per-target like+ // INSERT/UPDATE/DELETE — not via the database-level fallback (SUP-222 / BYT-9698, Codex+ // P1: an unmodeled MERGE would resolve to zero targets and authorize the qualified write+ // against the request database). A table-scoped DML grant on the MERGE target authorizes+ // it; MERGE into a non-granted table is denied per-target. (MERGE's USING read source is+ // ungated — the documented read-source limitation.)+ t.Run("MergeAuthorizedPerTarget", func(t *testing.T) {+ email, token := newLimitedUser(t)+ setProjectBindings(t, readBinding(email), tableScopedDML(email, "t_dst"))++ mergeInto := func(target string) string {+ return fmt.Sprintf("MERGE INTO public.%s d USING public.t_src s ON d.id = s.id "++ "WHEN NOT MATCHED THEN INSERT (id) VALUES (s.id);", target)+ }+ // MERGE into the granted table is authorized per-target (not a bare-database denial).+ resp, qErr := runAs(token, mergeInto("t_dst"))+ assertAllowed(t, resp, qErr)+ // MERGE into a non-granted table is denied, naming that table.+ resp, qErr = runAs(token, mergeInto("t_other"))+ assertDeniedOn(t, resp, qErr, "/tables/t_other")+ })++ // 17. A write target in a DIFFERENT project than the SQL-Editor session is denied. The+ // per-target check evaluates the REQUEST project's IAM policy, so a cross-project target+ // must fail closed to preserve the project boundary — otherwise a binding in the session's+ // project could authorize a write to a database owned by another project. SUP-222.+ t.Run("CrossProjectWriteDenied", func(t *testing.T) {+ ra := require.New(t)+ ctl.authInterceptor.token = ownerToken+ projectID := generateRandomString("sup222other")+ _, err := ctl.projectServiceClient.CreateProject(ctx, connect.NewRequest(&v1pb.CreateProjectRequest{+ Project: &v1pb.Project{Name: fmt.Sprintf("projects/%s", projectID), Title: projectID, AllowSelfApproval: true},+ ProjectId: projectID,+ }))+ ra.NoError(err)+ otherProject, err := ctl.projectServiceClient.GetProject(ctx, connect.NewRequest(&v1pb.GetProjectRequest{Name: fmt.Sprintf("projects/%s", projectID)}))+ ra.NoError(err)+ // A database in the OTHER project, on the SAME instance.+ const otherProjDB = "sup222edge_other_proj"+ ra.NoError(ctl.createDatabase(ctx, otherProject.Msg, instance, nil /* environment */, otherProjDB, "postgres"))++ // An ENVIRONMENT-scoped DML grant in the session's project (no database clause), so it+ // WOULD match the cross-project target's environment — proving the denial comes from the+ // cross-project guard, not a non-matching condition.+ email, token := newLimitedUser(t)+ cond := fmt.Sprintf(`resource.environment_id in ["%s"]`, envID)+ setProjectBindings(t, readBinding(email), scopedBinding("roles/repro-write", email, cond))++ resp, qErr := runAs(token, fmt.Sprintf("INSERT INTO %s.public.t VALUES (1);", otherProjDB))+ assertDeniedOn(t, resp, qErr, fmt.Sprintf("databases/%s", otherProjDB))+ })+}diff --git a/backend/tests/tests.go b/backend/tests/tests.goindex 7814570d98..cb86218ff9 100644--- a/backend/tests/tests.go+++ b/backend/tests/tests.go@@ -95,6 +95,7 @@ type controller struct {issueServiceClient v1connect.IssueServiceClientrolloutServiceClient v1connect.RolloutServiceClientplanServiceClient v1connect.PlanServiceClient+ roleServiceClient v1connect.RoleServiceClientorgPolicyServiceClient v1connect.OrgPolicyServiceClientreviewConfigServiceClient v1connect.ReviewConfigServiceClientprojectServiceClient v1connect.ProjectServiceClient@@ -284,6 +285,7 @@ func (ctl *controller) start(ctx context.Context, port int) (context.Context, erctl.issueServiceClient = v1connect.NewIssueServiceClient(ctl.client, baseURL, interceptors)ctl.rolloutServiceClient = v1connect.NewRolloutServiceClient(ctl.client, baseURL, interceptors)ctl.planServiceClient = v1connect.NewPlanServiceClient(ctl.client, baseURL, interceptors)+ ctl.roleServiceClient = v1connect.NewRoleServiceClient(ctl.client, baseURL, interceptors)ctl.orgPolicyServiceClient = v1connect.NewOrgPolicyServiceClient(ctl.client, baseURL, interceptors)ctl.reviewConfigServiceClient = v1connect.NewReviewConfigServiceClient(ctl.client, baseURL, interceptors)ctl.projectServiceClient = v1connect.NewProjectServiceClient(ctl.client, baseURL, interceptors)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 9fd04f0009..64bdc84237 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@@ -130,12 +130,26 @@ 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 database full name in "instances/{instance}/databases/{database}" format, used by the "roles/sqlEditorUser" and "roles/sqlEditorReadUser" roles, support "==" operator.- * resource.schema_name: the schema name, used by the "roles/sqlEditorUser" and "roles/sqlEditorReadUser" roles, support "==" operator.- * resource.table_name: the table name, used by the "roles/sqlEditorUser" and "roles/sqlEditorReadUser" roles, support "==" operator.+ * resource.database: the database full name in "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}")`.*+ * 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.+ ** For example:* resource.database == "instances/local-pg/databases/postgres" && resource.schema_name in ["public","another_schema"]* resource.database == "instances/local-pg/databases/bytebase" && resource.schema_name == "public" && resource.table_name in ["audit_log"]diff --git a/proto/gen/grpc-doc/openapi.yaml b/proto/gen/grpc-doc/openapi.yamlindex acf0a635d7..dc04cf3444 100644--- a/proto/gen/grpc-doc/openapi.yaml+++ b/proto/gen/grpc-doc/openapi.yaml@@ -18145,12 +18145,26 @@ components:The syntax and semantics of CEL are documented at https://github.com/google/cel-specSupport variables:- resource.database: the database full name in "instances/{instance}/databases/{database}" format, used by the "roles/sqlEditorUser" and "roles/sqlEditorReadUser" roles, support "==" operator.- resource.schema_name: the schema name, used by the "roles/sqlEditorUser" and "roles/sqlEditorReadUser" roles, support "==" operator.- resource.table_name: the table name, used by the "roles/sqlEditorUser" and "roles/sqlEditorReadUser" roles, support "==" operator.+ resource.database: the database full name in "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}")`.+ 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.+For example:resource.database == "instances/local-pg/databases/postgres" && resource.schema_name in ["public","another_schema"]resource.database == "instances/local-pg/databases/bytebase" && resource.schema_name == "public" && resource.table_name in ["audit_log"]diff --git a/proto/gen/grpc-doc/v1/README.md b/proto/gen/grpc-doc/v1/README.mdindex 00bf3bac63..3d4eef2f69 100644--- a/proto/gen/grpc-doc/v1/README.md+++ b/proto/gen/grpc-doc/v1/README.md@@ -7101,7 +7101,9 @@ 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 database full name in "instances/{instance}/databases/{database}" format, used by the "roles/sqlEditorUser" and "roles/sqlEditorReadUser" roles, support "==" operator. resource.schema_name: the schema name, used by the "roles/sqlEditorUser" and "roles/sqlEditorReadUser" roles, support "==" operator. resource.table_name: the table name, used by the "roles/sqlEditorUser" and "roles/sqlEditorReadUser" roles, 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 database full name in "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}")`.++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.For example: resource.database == "instances/local-pg/databases/postgres" && resource.schema_name in ["public","another_schema"] resource.database == "instances/local-pg/databases/bytebase" && resource.schema_name == "public" && resource.table_name in ["audit_log"] resource.database == "instances/local-pg/databases/postgres" && resource.environment_id in ["test"] request.time < timestamp("2025-04-26T11:24:48.655Z") || parsed_expr | [google.api.expr.v1alpha1.Expr](#google-api-expr-v1alpha1-Expr) | | The parsed expression of the condition. |diff --git a/proto/gen/grpc-doc/v1/index.html b/proto/gen/grpc-doc/v1/index.htmlindex a9f0767520..17735bb06c 100644--- a/proto/gen/grpc-doc/v1/index.html+++ b/proto/gen/grpc-doc/v1/index.html@@ -20597,12 +20597,26 @@ 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 database full name in "instances/{instance}/databases/{database}" format, used by the "roles/sqlEditorUser" and "roles/sqlEditorReadUser" roles, support "==" operator.-resource.schema_name: the schema name, used by the "roles/sqlEditorUser" and "roles/sqlEditorReadUser" roles, support "==" operator.-resource.table_name: the table name, used by the "roles/sqlEditorUser" and "roles/sqlEditorReadUser" roles, support "==" operator.+resource.database: the database full name in "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}")`.+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.+For example:resource.database == "instances/local-pg/databases/postgres" && resource.schema_name in ["public","another_schema"]resource.database == "instances/local-pg/databases/bytebase" && resource.schema_name == "public" && resource.table_name in ["audit_log"]diff --git a/proto/v1/v1/iam_policy.proto b/proto/v1/v1/iam_policy.protoindex fd7d2fa5fb..e41b297515 100644--- a/proto/v1/v1/iam_policy.proto+++ b/proto/v1/v1/iam_policy.proto@@ -67,12 +67,26 @@ message Binding {// The syntax and semantics of CEL are documented at https://github.com/google/cel-spec//// Support variables:- // resource.database: the database full name in "instances/{instance}/databases/{database}" format, used by the "roles/sqlEditorUser" and "roles/sqlEditorReadUser" roles, support "==" operator.- // resource.schema_name: the schema name, used by the "roles/sqlEditorUser" and "roles/sqlEditorReadUser" roles, support "==" operator.- // resource.table_name: the table name, used by the "roles/sqlEditorUser" and "roles/sqlEditorReadUser" roles, support "==" operator.+ // resource.database: the database full name in "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}")`.//+ // 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.+ //// For example:// resource.database == "instances/local-pg/databases/postgres" && resource.schema_name in ["public","another_schema"]// resource.database == "instances/local-pg/databases/bytebase" && resource.schema_name == "public" && resource.table_name in ["audit_log"]