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(api): route every CEL filter literal through an escaping helper (T17) (#21283)
Danny Xuc83228e0bbaf
diff --git a/backend/api/v1/database_service_test.go b/backend/api/v1/database_service_test.goindex b46b0fb34e..7807b4b59c 100644--- a/backend/api/v1/database_service_test.go+++ b/backend/api/v1/database_service_test.go@@ -131,12 +131,12 @@ func TestListDatabaseFilter(t *testing.T) {},{input: `name.contains("Employee")`,- wantSQL: `(LOWER(db.name) LIKE $1)`,+ wantSQL: `(LOWER(db.name) LIKE $1 ESCAPE '\')`,wantArgs: []any{"%employee%"},},{input: `table.contains("user")`,- wantSQL: "(EXISTS (\n\t\t\t\t\t\tSELECT 1\n\t\t\t\t\t\tFROM json_array_elements(ds.metadata->'schemas') AS s,\n\t\t\t\t\t\t \t json_array_elements(s->'tables') AS t\n\t\t\t\t\t\tWHERE t->>'name' LIKE $1))",+ wantSQL: "(EXISTS (\n\t\t\t\t\t\tSELECT 1\n\t\t\t\t\t\tFROM json_array_elements(ds.metadata->'schemas') AS s,\n\t\t\t\t\t\t \t json_array_elements(s->'tables') AS t\n\t\t\t\t\t\tWHERE t->>'name' LIKE $1 ESCAPE '\\'))",wantArgs: []any{"%user%"},},{@@ -150,18 +150,18 @@ func TestListDatabaseFilter(t *testing.T) {},{input: `labels.region == "asia" && labels.tenant == "bytebase"`,- wantSQL: `((db.metadata->'labels'->>'region' = $1 AND db.metadata->'labels'->>'tenant' = $2))`,- wantArgs: []any{"asia", "bytebase"},+ wantSQL: `((db.metadata->'labels'->>$1::text = $2 AND db.metadata->'labels'->>$3::text = $4))`,+ wantArgs: []any{"region", "asia", "tenant", "bytebase"},},{input: `(labels.region == "asia" || labels.tenant == "bytebase") && exclude_unassigned == true`,- wantSQL: `(((db.metadata->'labels'->>'region' = $1 OR db.metadata->'labels'->>'tenant' = $2) AND db.project != $3 AND db.project != 'default'))`,- wantArgs: []any{"asia", "bytebase", common.DefaultProjectID("test-workspace")},+ wantSQL: `(((db.metadata->'labels'->>$1::text = $2 OR db.metadata->'labels'->>$3::text = $4) AND db.project != $5 AND db.project != 'default'))`,+ wantArgs: []any{"region", "asia", "tenant", "bytebase", common.DefaultProjectID("test-workspace")},},{input: `labels.region in ["asia", "europe"] && labels.tenant == "bytebase"`,- wantSQL: `((db.metadata->'labels'->>'region' = ANY($1) AND db.metadata->'labels'->>'tenant' = $2))`,- wantArgs: []any{[]any{"asia", "europe"}, "bytebase"},+ wantSQL: `((db.metadata->'labels'->>$1::text = ANY($2) AND db.metadata->'labels'->>$3::text = $4))`,+ wantArgs: []any{"region", []any{"asia", "europe"}, "tenant", "bytebase"},},}diff --git a/backend/store/access_grant.go b/backend/store/access_grant.goindex d4a24a6eaf..0cb0a93ff2 100644--- a/backend/store/access_grant.go+++ b/backend/store/access_grant.go@@ -439,7 +439,7 @@ func GetListAccessGrantFilter(filter string) (*qb.Query, error) {}// Normalize whitespace on both sides so "SELECT *" matches "SELECT\n *".normalizedValue := strings.Join(strings.Fields(value), " ")- return qb.Q().Space("regexp_replace(access_grant.payload->>'query', '\\s+', ' ', 'g') ILIKE ?", "%"+normalizedValue+"%"), nil+ return qb.Q().Space("regexp_replace(access_grant.payload->>'query', '\\s+', ' ', 'g') ILIKE ? ESCAPE '\\'", containsPattern(normalizedValue)), nilcase celoperators.In:variable, value := getVariableAndValueFromExpr(expr)if variable != "status" {diff --git a/backend/store/access_grant_filter_test.go b/backend/store/access_grant_filter_test.goindex b11382f795..49f8364814 100644--- a/backend/store/access_grant_filter_test.go+++ b/backend/store/access_grant_filter_test.go@@ -25,14 +25,14 @@ func TestGetListAccessGrantFilter(t *testing.T) {{name: "query contains",filter: `query.contains("SELECT * FROM users")`,- wantSQL: "(regexp_replace(access_grant.payload->>'query', '\\s+', ' ', 'g') ILIKE $1)",+ wantSQL: "(regexp_replace(access_grant.payload->>'query', '\\s+', ' ', 'g') ILIKE $1 ESCAPE '\\')",wantArgs: []any{"%SELECT * FROM users%"},wantErr: false,},{name: "query contains normalizes whitespace",filter: `query.contains("SELECT * FROM users")`,- wantSQL: "(regexp_replace(access_grant.payload->>'query', '\\s+', ' ', 'g') ILIKE $1)",+ wantSQL: "(regexp_replace(access_grant.payload->>'query', '\\s+', ' ', 'g') ILIKE $1 ESCAPE '\\')",wantArgs: []any{"%SELECT * FROM users%"},wantErr: false,},diff --git a/backend/store/account_filter.go b/backend/store/account_filter.goindex aa31cedbb1..da2ca5900d 100644--- a/backend/store/account_filter.go+++ b/backend/store/account_filter.go@@ -115,7 +115,7 @@ func GetAccountListFilter(filter string) (*AccountListFilter, error) {if !ok {return nil, errors.Errorf("expect string, got %T, hint: filter literals should be string", value)}- return qb.Q().Space("LOWER("+variable+") LIKE ?", "%"+strings.ToLower(strValue)+"%"), nil+ return qb.Q().Space("LOWER("+variable+") LIKE ? ESCAPE '\\'", containsPattern(strings.ToLower(strValue))), nildefault:return nil, errors.Errorf("unexpected function %v", functionName)}diff --git a/backend/store/account_filter_test.go b/backend/store/account_filter_test.goindex 2d2434671f..bc2f1f61b0 100644--- a/backend/store/account_filter_test.go+++ b/backend/store/account_filter_test.go@@ -40,14 +40,14 @@ func TestGetAccountListFilter(t *testing.T) {{name: "name contains",filter: `name.contains("ED")`,- wantSQL: "(LOWER(name) LIKE $1)",+ wantSQL: "(LOWER(name) LIKE $1 ESCAPE '\\')",wantArgs: []any{"%ed%"},wantErr: false,},{name: "email contains",filter: `email.contains("test")`,- wantSQL: "(LOWER(email) LIKE $1)",+ wantSQL: "(LOWER(email) LIKE $1 ESCAPE '\\')",wantArgs: []any{"%test%"},wantErr: false,},diff --git a/backend/store/database.go b/backend/store/database.goindex 6f7a807910..f61b5901af 100644--- a/backend/store/database.go+++ b/backend/store/database.go@@ -944,24 +944,6 @@ func GetListDatabaseFilter(workspace, filter string) (*qb.Query, error) {var getFilter func(expr celast.Expr) (*qb.Query, error)- parseToLabelFilterSQL := func(resource, key string, value any) (*qb.Query, error) {- switch v := value.(type) {- case string:- return qb.Q().Space(fmt.Sprintf("%s->'labels'->>'%s' = ?", resource, key), v), nil- case []any:- if len(v) == 0 {- return nil, errors.Errorf("empty label filter")- }- labelValueList := []any{}- for _, raw := range v {- labelValueList = append(labelValueList, raw.(string))- }- return qb.Q().Space(fmt.Sprintf("%s->'labels'->>'%s' = ANY(?)", resource, key), labelValueList), nil- default:- return nil, errors.Errorf("empty value %v for label filter", value)- }- }-parseToEngineSQL := func(expr celast.Expr) (*qb.Query, error) {variable, value := getVariableAndValueFromExpr(expr)if variable != "engine" {@@ -1051,7 +1033,7 @@ func GetListDatabaseFilter(workspace, filter string) (*qb.Query, error) {return nil, errors.Errorf("unsupport variable %q", variable)}if labelKey, ok := strings.CutPrefix(varStr, "labels."); ok {- return parseToLabelFilterSQL("db.metadata", labelKey, value)+ return buildLabelFilterSQL("db.metadata", labelKey, value)}return nil, errors.Errorf("unsupport variable %q", variable)}@@ -1099,13 +1081,13 @@ func GetListDatabaseFilter(workspace, filter string) (*qb.Query, error) {switch variable {case "name":- return qb.Q().Space("LOWER(db.name) LIKE ?", "%"+strValue+"%"), nil+ return qb.Q().Space("LOWER(db.name) LIKE ? ESCAPE '\\'", containsPattern(strValue)), nilcase "table":return qb.Q().Space(`EXISTS (SELECT 1FROM json_array_elements(ds.metadata->'schemas') AS s,json_array_elements(s->'tables') AS t- WHERE t->>'name' LIKE ?)`, "%"+strValue+"%"), nil+ WHERE t->>'name' LIKE ? ESCAPE '\')`, containsPattern(strValue)), nildefault:return nil, errors.Errorf(`only "name" or "table" support %q operator, but found %q`, celoverloads.Contains, variable)}@@ -1114,7 +1096,7 @@ func GetListDatabaseFilter(workspace, filter string) (*qb.Query, error) {if variable == "engine" {return parseToEngineSQL(expr)} else if labelKey, ok := strings.CutPrefix(variable, "labels."); ok {- return parseToLabelFilterSQL("db.metadata", labelKey, value)+ return buildLabelFilterSQL("db.metadata", labelKey, value)}return nil, errors.Errorf("unsupport variable %q", variable)case celoperators.LogicalNot:diff --git a/backend/store/filter.go b/backend/store/filter.goindex 96966a8cac..3a40255a7e 100644--- a/backend/store/filter.go+++ b/backend/store/filter.go@@ -2,8 +2,13 @@ package storeimport ("fmt"+ "strings"celast "github.com/google/cel-go/common/ast"+ celoperators "github.com/google/cel-go/common/operators"+ "github.com/pkg/errors"++ "github.com/bytebase/bytebase/backend/common/qb")func getVariableAndValueFromExpr(expr celast.Expr) (string, any) {@@ -19,6 +24,12 @@ func getVariableAndValueFromExpr(expr celast.Expr) (string, any) {if sel.Operand().Kind() == celast.IdentKind {variable = fmt.Sprintf("%s.%s", sel.Operand().AsIdent(), sel.FieldName())}+ case celast.CallKind:+ // Handle index selection like `labels["cost-center"]`, which is the+ // only form that survives a key CEL cannot parse as an identifier.+ if name, ok := getIndexVariable(arg); ok {+ variable = name+ }case celast.LiteralKind:value = arg.AsLiteral().Value()case celast.ListKind:@@ -34,3 +45,63 @@ func getVariableAndValueFromExpr(expr celast.Expr) (string, any) {}return variable, value}++// getIndexVariable renders `labels["cost-center"]` as `labels.cost-center`, the+// same shape the dotted form produces, so callers keep one prefix to match.+// Label keys allow dashes, which CEL parses as subtraction in the dotted form,+// so index syntax is the only way such a key reaches the filter at all.+func getIndexVariable(expr celast.Expr) (string, bool) {+ call := expr.AsCall()+ if call.FunctionName() != celoperators.Index || len(call.Args()) != 2 {+ return "", false+ }+ operand, key := call.Args()[0], call.Args()[1]+ if operand.Kind() != celast.IdentKind || key.Kind() != celast.LiteralKind {+ return "", false+ }+ keyStr, ok := key.AsLiteral().Value().(string)+ if !ok {+ return "", false+ }+ return fmt.Sprintf("%s.%s", operand.AsIdent(), keyStr), true+}++// buildLabelFilterSQL matches one label key against a value or a value list.+// The key is bound, never interpolated: index syntax lets it hold anything.+func buildLabelFilterSQL(resource, key string, value any) (*qb.Query, error) {+ switch v := value.(type) {+ case string:+ return qb.Q().Space(fmt.Sprintf("%s->'labels'->>?::text = ?", resource), key, v), nil+ case []any:+ if len(v) == 0 {+ return nil, errors.Errorf("empty label filter")+ }+ labelValueList := make([]any, len(v))+ for i, raw := range v {+ str, ok := raw.(string)+ if !ok {+ return nil, errors.Errorf("label value must be string, got %T", raw)+ }+ labelValueList[i] = str+ }+ return qb.Q().Space(fmt.Sprintf("%s->'labels'->>?::text = ANY(?)", resource), key, labelValueList), nil+ default:+ return nil, errors.Errorf("empty value %v for label filter", value)+ }+}++// escapeLikePattern neutralizes the wildcards in a value that is about to be+// wrapped in `%...%`. Without it a search for a statement holding `%` or `_`+// silently matches rows the user never asked for. Pair it with `ESCAPE '\'`.+func escapeLikePattern(pattern string) string {+ return strings.NewReplacer(+ `\`, `\\`,+ `%`, `\%`,+ `_`, `\_`,+ ).Replace(pattern)+}++// containsPattern renders a substring search as an escaped LIKE pattern.+func containsPattern(value string) string {+ return "%" + escapeLikePattern(value) + "%"+}diff --git a/backend/store/filter_test.go b/backend/store/filter_test.gonew file mode 100644index 0000000000..ad7a0a657c--- /dev/null+++ b/backend/store/filter_test.go@@ -0,0 +1,131 @@+package store++import (+ "testing"++ "github.com/stretchr/testify/require"++ "github.com/bytebase/bytebase/backend/common/qb"+)++func TestEscapeLikePattern(t *testing.T) {+ // `%` and `_` are wildcards to LIKE. Left raw, a search for a statement+ // holding either matched rows the user never asked for.+ require.Equal(t, `100\% off`, escapeLikePattern("100% off"))+ require.Equal(t, `a\_b`, escapeLikePattern("a_b"))+ require.Equal(t, `a\\b`, escapeLikePattern(`a\b`))+ require.Equal(t, "select 1", escapeLikePattern("select 1"))+ require.Equal(t, `%100\% off%`, containsPattern("100% off"))+}++func TestContainsEscapesLikeWildcards(t *testing.T) {+ tests := []struct {+ name string+ filter string+ wantArg string+ build func(string) (*qb.Query, error)+ }{+ {+ name: "database name",+ filter: `name.contains("a_b")`,+ wantArg: `%a\_b%`,+ build: func(f string) (*qb.Query, error) { return GetListDatabaseFilter("default", f) },+ },+ {+ name: "instance name",+ filter: `name.contains("a_b")`,+ wantArg: `%a\_b%`,+ build: GetListInstanceFilter,+ },+ {+ name: "project name",+ filter: `name.contains("a_b")`,+ wantArg: `%a\_b%`,+ build: func(f string) (*qb.Query, error) { return GetListProjectFilter("default", f) },+ },+ {+ name: "plan title",+ filter: `title.contains("100% off")`,+ wantArg: `%100\% off%`,+ build: GetListPlanFilter,+ },+ {+ name: "access grant query",+ filter: `query.contains("WHERE x LIKE '%a%'")`,+ wantArg: `%WHERE x LIKE '\%a\%'%`,+ build: GetListAccessGrantFilter,+ },+ }++ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ query, err := tt.build(tt.filter)+ require.NoError(t, err)+ sql, args, err := query.ToSQL()+ require.NoError(t, err)+ require.Contains(t, sql, `ESCAPE '\'`)+ require.Equal(t, []any{tt.wantArg}, args)+ })+ }+}++func TestLabelFilterAcceptsIndexSyntax(t *testing.T) {+ // Label keys allow dashes (`^[a-z][a-z0-9_-]{0,62}$`). CEL parses+ // `labels.cost-center` as subtraction, so the dotted form never reaches the+ // store — index syntax is the only one that carries such a key. The key is+ // bound rather than interpolated, since index syntax admits any string.+ tests := []struct {+ name string+ filter string+ wantSQL string+ wantArgs []any+ build func(string) (*qb.Query, error)+ }{+ {+ name: "database, dashed key",+ filter: `labels["cost-center"] == "eng"`,+ wantSQL: "(db.metadata->'labels'->>$1::text = $2)",+ wantArgs: []any{"cost-center", "eng"},+ build: func(f string) (*qb.Query, error) { return GetListDatabaseFilter("default", f) },+ },+ {+ name: "database, dotted key still works",+ filter: `labels.environment == "prod"`,+ wantSQL: "(db.metadata->'labels'->>$1::text = $2)",+ wantArgs: []any{"environment", "prod"},+ build: func(f string) (*qb.Query, error) { return GetListDatabaseFilter("default", f) },+ },+ {+ name: "database, key is bound not interpolated",+ filter: `labels["a' OR '1'='1"] == "x"`,+ wantSQL: "(db.metadata->'labels'->>$1::text = $2)",+ wantArgs: []any{"a' OR '1'='1", "x"},+ build: func(f string) (*qb.Query, error) { return GetListDatabaseFilter("default", f) },+ },+ {+ name: "instance, dashed key in a list",+ filter: `labels["cost-center"] in ["eng", "ops"]`,+ wantSQL: "(instance.metadata->'labels'->>$1::text = ANY($2))",+ wantArgs: []any{"cost-center", []any{"eng", "ops"}},+ build: GetListInstanceFilter,+ },+ {+ name: "project, dashed key",+ filter: `labels["cost-center"] == "eng"`,+ wantSQL: "(project.setting->'labels'->>$1::text = $2)",+ wantArgs: []any{"cost-center", "eng"},+ build: func(f string) (*qb.Query, error) { return GetListProjectFilter("default", f) },+ },+ }++ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ query, err := tt.build(tt.filter)+ require.NoError(t, err)+ sql, args, err := query.ToSQL()+ require.NoError(t, err)+ require.Equal(t, tt.wantSQL, sql)+ require.Equal(t, tt.wantArgs, args)+ })+ }+}diff --git a/backend/store/group.go b/backend/store/group.goindex c64ca7b4a9..8952b1d762 100644--- a/backend/store/group.go+++ b/backend/store/group.go@@ -549,9 +549,9 @@ func GetListGroupFilter(find *FindGroupMessage, filter string) (*qb.Query, errorswitch variable {case "title":- return qb.Q().Space("LOWER(name) LIKE ?", "%"+strings.ToLower(strValue)+"%"), nil+ return qb.Q().Space("LOWER(name) LIKE ? ESCAPE '\\'", containsPattern(strings.ToLower(strValue))), nilcase "email":- return qb.Q().Space("LOWER(email) LIKE ?", "%"+strings.ToLower(strValue)+"%"), nil+ return qb.Q().Space("LOWER(email) LIKE ? ESCAPE '\\'", containsPattern(strings.ToLower(strValue))), nildefault:return nil, errors.Errorf("unsupport variable %q", variable)}diff --git a/backend/store/group_filter_test.go b/backend/store/group_filter_test.goindex 51b47ee471..2852447cb8 100644--- a/backend/store/group_filter_test.go+++ b/backend/store/group_filter_test.go@@ -41,14 +41,14 @@ func TestGetListGroupFilter(t *testing.T) {{name: "title contains",filter: `title.contains("dev")`,- wantSQL: "(LOWER(name) LIKE $1)",+ wantSQL: "(LOWER(name) LIKE $1 ESCAPE '\\')",wantArgs: []any{"%dev%"},wantErr: false,},{name: "email contains",filter: `email.contains("example")`,- wantSQL: "(LOWER(email) LIKE $1)",+ wantSQL: "(LOWER(email) LIKE $1 ESCAPE '\\')",wantArgs: []any{"%example%"},wantErr: false,},@@ -69,7 +69,7 @@ func TestGetListGroupFilter(t *testing.T) {{name: "complex nested AND/OR",filter: `(title == "Developers" || title == "Admins") && email.contains("example")`,- wantSQL: "(((name = $1 OR name = $2) AND LOWER(email) LIKE $3))",+ wantSQL: "(((name = $1 OR name = $2) AND LOWER(email) LIKE $3 ESCAPE '\\'))",wantArgs: []any{"Developers", "Admins", "%example%"},wantErr: false,},diff --git a/backend/store/instance.go b/backend/store/instance.goindex d6c31a3f06..6ea9dcf155 100644--- a/backend/store/instance.go+++ b/backend/store/instance.go@@ -1100,34 +1100,11 @@ func GetListInstanceFilter(filter string) (*qb.Query, error) {var getFilter func(expr celast.Expr) (*qb.Query, error)- parseToLabelFilterSQL := func(resource, key string, value any) (*qb.Query, error) {- switch v := value.(type) {- case string:- return qb.Q().Space(fmt.Sprintf("%s->'labels'->>'%s' = ?", resource, key), v), nil- case []any:- if len(v) == 0 {- return nil, errors.Errorf("empty label filter")- }-- labelValueList := make([]any, len(v))- for i, raw := range v {- str, ok := raw.(string)- if !ok {- return nil, errors.Errorf("label value must be string, got %T", raw)- }- labelValueList[i] = str- }- return qb.Q().Space(fmt.Sprintf("%s->'labels'->>'%s' = ANY(?)", resource, key), labelValueList), nil- default:- return nil, errors.Errorf("empty value %v for label filter", value)- }- }-parseToSQL := func(variable, value any) (*qb.Query, error) {// Handle label filters like "labels.org_group"if varStr, ok := variable.(string); ok {if labelKey, ok := strings.CutPrefix(varStr, "labels."); ok {- return parseToLabelFilterSQL("instance.metadata", labelKey, value)+ return buildLabelFilterSQL("instance.metadata", labelKey, value)}}@@ -1259,13 +1236,13 @@ func GetListInstanceFilter(filter string) (*qb.Query, error) {switch variable {case "name":- return qb.Q().Space("LOWER(instance.metadata->>'title') LIKE ?", "%"+strings.ToLower(strValue)+"%"), nil+ return qb.Q().Space("LOWER(instance.metadata->>'title') LIKE ? ESCAPE '\\'", containsPattern(strings.ToLower(strValue))), nilcase "resource_id":- return qb.Q().Space("LOWER(instance.resource_id) LIKE ?", "%"+strings.ToLower(strValue)+"%"), nil+ return qb.Q().Space("LOWER(instance.resource_id) LIKE ? ESCAPE '\\'", containsPattern(strings.ToLower(strValue))), nilcase "host", "port":return qb.Q().Space(- fmt.Sprintf(`EXISTS (SELECT 1 FROM jsonb_array_elements(instance.metadata -> 'dataSources') AS ds WHERE ds ->> '%s' LIKE ?)`, variable),- "%"+strValue+"%"), nil+ fmt.Sprintf(`EXISTS (SELECT 1 FROM jsonb_array_elements(instance.metadata -> 'dataSources') AS ds WHERE ds ->> '%s' LIKE ? ESCAPE '\')`, variable),+ containsPattern(strValue)), nildefault:return nil, errors.Errorf("unsupport variable %q", variable)}@@ -1274,7 +1251,7 @@ func GetListInstanceFilter(filter string) (*qb.Query, error) {if variable == "engine" {return parseToEngineSQL(expr)} else if labelKey, ok := strings.CutPrefix(variable, "labels."); ok {- return parseToLabelFilterSQL("instance.metadata", labelKey, value)+ return buildLabelFilterSQL("instance.metadata", labelKey, value)}return nil, errors.Errorf("unsupport variable %q", variable)case celoperators.LogicalNot:diff --git a/backend/store/instance_filter_test.go b/backend/store/instance_filter_test.goindex c91d4a6634..dffae579b4 100644--- a/backend/store/instance_filter_test.go+++ b/backend/store/instance_filter_test.go@@ -18,25 +18,25 @@ func TestGetListInstanceFilter(t *testing.T) {{name: "name contains",filter: `name.contains("sample")`,- wantSQL: "(LOWER(instance.metadata->>'title') LIKE $1)",+ wantSQL: "(LOWER(instance.metadata->>'title') LIKE $1 ESCAPE '\\')",wantArgs: []any{"%sample%"},},{name: "resource_id contains",filter: `resource_id.contains("prod")`,- wantSQL: "(LOWER(instance.resource_id) LIKE $1)",+ wantSQL: "(LOWER(instance.resource_id) LIKE $1 ESCAPE '\\')",wantArgs: []any{"%prod%"},},{name: "host contains",filter: `host.contains("127.0")`,- wantSQL: "(EXISTS (SELECT 1 FROM jsonb_array_elements(instance.metadata -> 'dataSources') AS ds WHERE ds ->> 'host' LIKE $1))",+ wantSQL: "(EXISTS (SELECT 1 FROM jsonb_array_elements(instance.metadata -> 'dataSources') AS ds WHERE ds ->> 'host' LIKE $1 ESCAPE '\\'))",wantArgs: []any{"%127.0%"},},{name: "port contains",filter: `port.contains("543")`,- wantSQL: "(EXISTS (SELECT 1 FROM jsonb_array_elements(instance.metadata -> 'dataSources') AS ds WHERE ds ->> 'port' LIKE $1))",+ wantSQL: "(EXISTS (SELECT 1 FROM jsonb_array_elements(instance.metadata -> 'dataSources') AS ds WHERE ds ->> 'port' LIKE $1 ESCAPE '\\'))",wantArgs: []any{"%543%"},},{diff --git a/backend/store/issue.go b/backend/store/issue.goindex c7a0d6b223..6aaf1cccb4 100644--- a/backend/store/issue.go+++ b/backend/store/issue.go@@ -415,7 +415,7 @@ func (s *Store) ListIssues(ctx context.Context, find *FindIssueMessage) ([]*IssusearchCondition.Or("issue.ts_vector @@ query")rankOrder = "ts_rank(issue.ts_vector, query) DESC"}- searchCondition.Or("issue.name ILIKE ?", "%"+escapeLikePattern(*v)+"%")+ searchCondition.Or("issue.name ILIKE ? ESCAPE '\\'", containsPattern(*v))where.And("(?)", searchCondition)}if len(find.StatusList) != 0 {diff --git a/backend/store/plan.go b/backend/store/plan.goindex 776973ef6b..4fea58fa59 100644--- a/backend/store/plan.go+++ b/backend/store/plan.go@@ -348,7 +348,7 @@ func GetListPlanFilter(filter string) (*qb.Query, error) {switch variable {case "title":- return qb.Q().Space("LOWER(plan.name) LIKE ?", "%"+strValue+"%"), nil+ return qb.Q().Space("LOWER(plan.name) LIKE ? ESCAPE '\\'", containsPattern(strValue)), nildefault:return nil, errors.Errorf(`only "title" supports %q operator, but found %q`, celoverloads.Contains, variable)}diff --git a/backend/store/plan_filter_test.go b/backend/store/plan_filter_test.goindex 9608110505..e561d60d85 100644--- a/backend/store/plan_filter_test.go+++ b/backend/store/plan_filter_test.go@@ -60,7 +60,7 @@ func TestGetListPlanFilter(t *testing.T) {{name: "title contains",filter: `title.contains("test")`,- wantSQL: "(LOWER(plan.name) LIKE $1)",+ wantSQL: "(LOWER(plan.name) LIKE $1 ESCAPE '\\')",wantArgs: []any{"%test%"},wantErr: false,},diff --git a/backend/store/project.go b/backend/store/project.goindex 698f833176..a4e705e67a 100644--- a/backend/store/project.go+++ b/backend/store/project.go@@ -887,29 +887,6 @@ func GetListProjectFilter(workspace, filter string) (*qb.Query, error) {var getFilter func(expr celast.Expr) (*qb.Query, error)- parseToLabelFilterSQL := func(resource, key string, value any) (*qb.Query, error) {- switch v := value.(type) {- case string:- return qb.Q().Space(fmt.Sprintf("%s->'labels'->>'%s' = ?", resource, key), v), nil- case []any:- if len(v) == 0 {- return nil, errors.Errorf("empty label filter")- }-- labelValueList := make([]any, len(v))- for i, raw := range v {- str, ok := raw.(string)- if !ok {- return nil, errors.Errorf("label value must be string, got %T", raw)- }- labelValueList[i] = str- }- return qb.Q().Space(fmt.Sprintf("%s->'labels'->>'%s' = ANY(?)", resource, key), labelValueList), nil- default:- return nil, errors.Errorf("empty value %v for label filter", value)- }- }-parseToSQL := func(variable, value any) (*qb.Query, error) {switch variable {case "name":@@ -945,7 +922,7 @@ func GetListProjectFilter(workspace, filter string) (*qb.Query, error) {return nil, errors.Errorf("unsupport variable %q", variable)}if labelKey, ok := strings.CutPrefix(varStr, "labels."); ok {- return parseToLabelFilterSQL("project.setting", labelKey, value)+ return buildLabelFilterSQL("project.setting", labelKey, value)}return nil, errors.Errorf("unsupport variable %q", variable)}@@ -992,16 +969,16 @@ func GetListProjectFilter(workspace, filter string) (*qb.Query, error) {switch variable {case "name":- return qb.Q().Space("LOWER(project.name) LIKE ?", "%"+strings.ToLower(strValue)+"%"), nil+ return qb.Q().Space("LOWER(project.name) LIKE ? ESCAPE '\\'", containsPattern(strings.ToLower(strValue))), nilcase "resource_id":- return qb.Q().Space("LOWER(project.resource_id) LIKE ?", "%"+strings.ToLower(strValue)+"%"), nil+ return qb.Q().Space("LOWER(project.resource_id) LIKE ? ESCAPE '\\'", containsPattern(strings.ToLower(strValue))), nildefault:return nil, errors.Errorf("unsupport variable %q", variable)}case celoperators.In:variable, value := getVariableAndValueFromExpr(expr)if labelKey, ok := strings.CutPrefix(variable, "labels."); ok {- return parseToLabelFilterSQL("project.setting", labelKey, value)+ return buildLabelFilterSQL("project.setting", labelKey, value)}return nil, errors.Errorf("unexpected %v operator for %v", functionName, variable)default:diff --git a/backend/store/project_filter_test.go b/backend/store/project_filter_test.goindex 9879779b84..e999bf19ec 100644--- a/backend/store/project_filter_test.go+++ b/backend/store/project_filter_test.go@@ -67,29 +67,29 @@ func TestGetListProjectFilter(t *testing.T) {{name: "name contains",filter: `name.contains("test")`,- wantSQL: "(LOWER(project.name) LIKE $1)",+ wantSQL: "(LOWER(project.name) LIKE $1 ESCAPE '\\')",wantArgs: []any{"%test%"},wantErr: false,},{name: "resource_id contains",filter: `resource_id.contains("prod")`,- wantSQL: "(LOWER(project.resource_id) LIKE $1)",+ wantSQL: "(LOWER(project.resource_id) LIKE $1 ESCAPE '\\')",wantArgs: []any{"%prod%"},wantErr: false,},{name: "label filter - string",filter: `labels.environment == "production"`,- wantSQL: "(project.setting->'labels'->>'environment' = $1)",- wantArgs: []any{"production"},+ wantSQL: "(project.setting->'labels'->>$1::text = $2)",+ wantArgs: []any{"environment", "production"},wantErr: false,},{name: "label filter - in operator",filter: `labels.environment in ["production", "staging"]`,- wantSQL: "(project.setting->'labels'->>'environment' = ANY($1))",- wantArgs: []any{[]any{"production", "staging"}},+ wantSQL: "(project.setting->'labels'->>$1::text = ANY($2))",+ wantArgs: []any{"environment", []any{"production", "staging"}},wantErr: false,},{diff --git a/backend/store/query_history.go b/backend/store/query_history.goindex a2497b08f4..364596ed3e 100644--- a/backend/store/query_history.go+++ b/backend/store/query_history.go@@ -312,7 +312,7 @@ func GetListQueryHistoryFilter(filter string) (*qb.Query, error) {// the access-grant `query.contains` search in// GetListAccessGrantFilter.normalizedValue := strings.Join(strings.Fields(strValue), " ")- return qb.Q().Space("regexp_replace(query_history.statement, '\\s+', ' ', 'g') ILIKE ?", "%"+normalizedValue+"%"), nil+ return qb.Q().Space("regexp_replace(query_history.statement, '\\s+', ' ', 'g') ILIKE ? ESCAPE '\\'", containsPattern(normalizedValue)), nildefault:return nil, errors.Errorf("unexpected function %v", functionName)}diff --git a/backend/store/query_history_filter_test.go b/backend/store/query_history_filter_test.goindex c64bb310fe..a41fc91826 100644--- a/backend/store/query_history_filter_test.go+++ b/backend/store/query_history_filter_test.go@@ -60,7 +60,7 @@ func TestGetListQueryHistoryFilter(t *testing.T) {{name: "statement contains operator",filter: `statement.contains("SELECT")`,- wantSQL: "(regexp_replace(query_history.statement, '\\s+', ' ', 'g') ILIKE $1)",+ wantSQL: "(regexp_replace(query_history.statement, '\\s+', ' ', 'g') ILIKE $1 ESCAPE '\\')",wantArgs: []any{"%SELECT%"},wantErr: false,},@@ -102,7 +102,7 @@ func TestGetListQueryHistoryFilter(t *testing.T) {{name: "complex nested with statement contains",filter: `project == "projects/test" && statement.contains("SELECT") && type == "QUERY"`,- wantSQL: "(((query_history.project = $1 AND regexp_replace(query_history.statement, '\\s+', ' ', 'g') ILIKE $2) AND query_history.type = $3))",+ wantSQL: "(((query_history.project = $1 AND regexp_replace(query_history.statement, '\\s+', ' ', 'g') ILIKE $2 ESCAPE '\\') AND query_history.type = $3))",wantArgs: []any{"test", "%SELECT%", QueryHistoryType("QUERY")},wantErr: false,},@@ -195,7 +195,7 @@ func TestGetListQueryHistoryFilter_EdgeCases(t *testing.T) {name: "statement contains punctuation literally",filter: `statement.contains("SELECT.*FROM")`,description: "contains should treat punctuation as plain substring content",- wantSQL: "(regexp_replace(query_history.statement, '\\s+', ' ', 'g') ILIKE $1)",+ wantSQL: "(regexp_replace(query_history.statement, '\\s+', ' ', 'g') ILIKE $1 ESCAPE '\\')",wantArgs: []any{"%SELECT.*FROM%"},wantErr: false,},@@ -227,7 +227,7 @@ func TestGetListQueryHistoryFilter_EdgeCases(t *testing.T) {name: "complex filter with all supported fields",filter: `project == "projects/test" && database == "instances/i1/databases/db1" && type == "EXPORT" && statement.contains("INSERT")`,description: "combination of all supported filter types",- wantSQL: "(((query_history.project = $1 AND query_history.database = $2) AND (query_history.type = $3 AND regexp_replace(query_history.statement, '\\s+', ' ', 'g') ILIKE $4)))",+ wantSQL: "(((query_history.project = $1 AND query_history.database = $2) AND (query_history.type = $3 AND regexp_replace(query_history.statement, '\\s+', ' ', 'g') ILIKE $4 ESCAPE '\\')))",wantArgs: []any{"test", "instances/i1/databases/db1", QueryHistoryType("EXPORT"), "%INSERT%"},wantErr: false,},@@ -282,7 +282,7 @@ func TestGetListQueryHistoryFilter_CompareWithOriginal(t *testing.T) {{name: "statement contains",filter: `statement.contains("SELECT")`,- expectedConditions: []string{"regexp_replace(query_history.statement, '\\s+', ' ', 'g') ILIKE $1"},+ expectedConditions: []string{"regexp_replace(query_history.statement, '\\s+', ' ', 'g') ILIKE $1 ESCAPE '\\'"},},{name: "OR condition",diff --git a/backend/store/saved_query.go b/backend/store/saved_query.goindex 7de1ef31ce..82ba7cc3fa 100644--- a/backend/store/saved_query.go+++ b/backend/store/saved_query.go@@ -856,7 +856,7 @@ func GetSearchSavedQueryFilter(ctx context.Context, s *Store, caller string, accif !allowTitleContains {return nil, errors.Errorf("unsupport variable %q", variable)}- return qb.Q().Space("LOWER(saved_query.name) LIKE ? ESCAPE '\\'", "%"+escapeLikePattern(strings.ToLower(strValue))+"%"), nil+ return qb.Q().Space("LOWER(saved_query.name) LIKE ? ESCAPE '\\'", containsPattern(strings.ToLower(strValue))), nildefault:return nil, errors.Errorf("unsupport variable %q", variable)}@@ -916,14 +916,6 @@ func GetSearchSavedQueryFilter(ctx context.Context, s *Store, caller string, accreturn qb.Q().Space("(?)", q), nil}-func escapeLikePattern(pattern string) string {- return strings.NewReplacer(- `\`, `\\`,- `%`, `\%`,- `_`, `\_`,- ).Replace(pattern)-}-// GetSavedQueryOrders parses an AIP-132 order_by string into OrderByKey// entries for ListSavedQueries. Supported fields: update_time, create_time,// title.diff --git a/docs/design/v1-api-audit-2026-08.md b/docs/design/v1-api-audit-2026-08.mdindex 73ca117a99..ba497f9e35 100644--- a/docs/design/v1-api-audit-2026-08.md+++ b/docs/design/v1-api-audit-2026-08.md@@ -13,7 +13,6 @@ noted. Fixed findings are removed and listed at the end.| T12 | Anonymous callers can enumerate emails, relay mail, and read your LDAP config | MED || T16 | Four `BatchGet` RPCs behave four different ways when an item is missing | MED || T11 | A create-permission check is skipped on `allow_missing` updates | MED |-| T17 | Typing `"` in a search box breaks search | MED || T18c | Three smaller ones: broken filter, unpaginated list, half-finished delete | MED |---@@ -83,16 +82,6 @@ None of this is documented, and the responses are bare repeated lists — so any- **`ListTaskRuns` has no pagination and no limit** — and its documented wildcard parent pulls anentire rollout in one call, on the table that grows fastest. `store/task_run.go:64-130`-### T17 · Typing a quote breaks search — MED--The frontend builds CEL filter strings by interpolating raw user input. There's an escaping helper-that exists precisely for this, used at 6 sites; 11 others still interpolate raw. Type a `"` in-those search boxes and search fails with `InvalidArgument`. It also allows filter-semantics-injection — not a privilege boundary, since the filter only narrows an already-authorized list.--Worst site: `accessGrant.ts:35` interpolates SQL statement text raw, while lines 37-40 right next to-it do it safely.----## What anonymous callers can learn@@ -173,6 +162,7 @@ constraints.| T13 `SearchWorksheets` | [#21160](https://github.com/bytebase/bytebase/pull/21160) + [#21178](https://github.com/bytebase/bytebase/pull/21178) — visibility predicate pushed into SQL before `LIMIT` || T13 issue filters | `approval_status` and `current_approver` are matched in SQL before `LIMIT`, so a filtered page can no longer come back empty under a live page token. The status is a `CASE` over `payload->'approval'` mirroring `computeApprovalStatus`; `current_approver` cannot be resolved in SQL alone (binding conditions and group expansion are evaluated in Go), so the caller passes down the `(project, role)` pairs the named user holds, the same shape as the saved-query `AccessMembers` predicate. Accepted with it: the predicates are not indexable, so a filtered list scans until it has a full page of matches — measured on 50,000 issues across 40 projects, that is ~9 ms against ~14 ms for the same unfiltered query, and ~3.5 ms in the zero-match case, because PostgreSQL drives the join from the small `(project, role)` set, so no expression index is warranted yet. Deliberately unchanged: the filter still ignores rejection and self-approval, so a rejected issue names the holder of the *next* role as its current approver — masked in the default view, and worth its own fix || T18 worksheet write/delete | [#21169](https://github.com/bytebase/bytebase/pull/21169) + [#21181](https://github.com/bytebase/bytebase/pull/21181) — per-verb permissions; SQL Editor Read User can no longer rewrite or delete |+| T17 | Every CEL string literal the frontend emits now comes from `celString`/`celStringList`/`celMapField` in a dependency-free `frontend/src/utils/v1/celLiteral.ts` — the helpers own the quotes, so the escape cannot be forgotten the way it was at 11 of 17 sites. Worst was the access-grant page, whose search box takes SQL: a quoted identifier made `InvalidArgument` routine. All 17 sites converted, the enum and resource-name ones included, because an absolute rule is the only one a machine can check — `src/architecture/cel-filter-literals.test.ts` scans `src/**` for the three raw shapes and fails CI on a new one, in the style of the existing Vue-boundary guards. The helpers are a leaf module because putting them beside the CEL RPC clients dragged `@/api` into `modules/cel/logic/stringify.ts` and broke that subtree's tests. Two adjacent defects the sweep found, neither of which escaping addresses, fixed with it. **A label key with a dash never reached the backend at all**: keys are validated `^[a-z][a-z0-9_-]{0,62}$`, and CEL parses `labels.cost-center` as subtraction, so the store answered `unsupport variable \"\"` — the frontend now emits `labels[\"key\"]` index syntax, `getVariableAndValueFromExpr` canonicalizes both forms, and the key is **bound** rather than interpolated into the JSONB path, since index syntax admits a quote the dotted form could not. **`%` and `_` reached `LIKE` as wildcards**, so a statement search containing either silently over-matched — `escapeLikePattern`, already in-tree for saved queries, plus `ESCAPE '\\'` now covers all 13 `contains` translations. The three copies of the label-filter closure collapsed into one `buildLabelFilterSQL`, which also drops an unchecked `raw.(string)` that panicked on `labels.k in [1]`. Verified against PostgreSQL 16: `->>$1::text` matches, an injected key is inert, and `\_` stops matching what `_` did. Accepted with it: the guard is line-based and skips test files, which should spell out expected filter strings literally; and `query_history`'s `instance ==`/`database ==` LIKE-without-wildcard filters are left alone — those are T18c-ii || T18a | [#21265](https://github.com/bytebase/bytebase/pull/21265) — `BatchCancelTaskRuns` confines its lookup to the plan and environment just authorized; the stage in a task run name is caller-supplied, so cancel rights in one environment reached a RUNNING row in another. An out-of-scope ID is rejected, not dropped — the cancel is driven by the requested IDs || T9 | [#21189](https://github.com/bytebase/bytebase/pull/21189) (self-hosted audit rows) + [#21234](https://github.com/bytebase/bytebase/pull/21234) — one `login_attempt` table bounds password, email-code, and MFA guessing per identity on both deployments, replacing the audit-log counter and the per-code attempt column (which bypassed the resend cooldown). Accepted with it: no per-tenant failed-login record on Cloud, and lockout-as-denial-of-service — see [`login-attempt-lockout.md`](login-attempt-lockout.md) || T15 | `update_mask` now decides what each of the four Update methods writes. **`UpdateDataSource`** dispatches the IAM credential on the mask path instead of the request's `authentication_type`, which was unset on any request that masked only the credential — the AIP-134 shape — so rotating a leaked key returned 200 and wrote nothing. The same branch, given a body type that disagreed with the mask, wrote the *other* credential and moved `authentication_type` with it though the mask named neither; the effective type is now resolved from the mask before the loop and a mismatched path is `InvalidArgument`. **`UpdateSetting(APP_IM)`** splices only the masked providers into the stored value rather than assigning the request wholesale, so saving Slack no longer erases the Feishu, WeCom, Lark, DingTalk and Teams secrets; the mask is now required, and a masked provider the payload omits is removed, which is how the console deletes one (it no longer merges the list client-side). **`UpdateIssue`** rejects paths it does not implement instead of returning 200 and dropping them — `status` belongs to `BatchUpdateIssuesStatus` and approvals to `ApproveIssue`/`RejectIssue`, so the supported set was right and only the silence was wrong. **`UpdateDatabaseCatalog`** keeps full-replace semantics and now says so in the proto; its `allow_missing` is removed and the number reserved, because a catalog is not independently creatable — it exists once its database is synced — so the flag had nothing to create, and the ACL's create-permission check on it denied every caller. Both merges were extracted into pure functions (`applyDataSourceUpdateMask`, `mergeAppIMSetting`), so `instance_service_test.go` and `setting_service_test.go` pin the behavior in milliseconds without a server or a metadata database. Accepted with it: the APP_IM mask paths still name no real proto field (`AppIMSetting` holds one repeated `settings`, and `value.app_im_setting_value.teams` is not a field path at all), so they are matched as a fixed vocabulary — making them true paths means restructuring the message one-field-per-provider, which needs a JSONB migration. Also left open, and the reason `UpdateDatabaseCatalog`'s hazard is documented rather than removed: a mask cannot express "this one table" while `schemas` is repeated, and read-modify-write on the catalog still loses one side of a concurrent edit, which needs an etag (AIP-154); the IAM-policy half of it is fixed, see T18b below |diff --git a/frontend/src/architecture/cel-filter-literals.test.ts b/frontend/src/architecture/cel-filter-literals.test.tsnew file mode 100644index 0000000000..0abd0b3f1a--- /dev/null+++ b/frontend/src/architecture/cel-filter-literals.test.ts@@ -0,0 +1,64 @@+import { readdirSync, readFileSync } from "node:fs";+import { join, relative } from "node:path";+import { describe, expect, test } from "vitest";++const repoRoot = process.cwd();+const srcRoot = join(repoRoot, "src");+// Tests are excluded: they spell out expected filter strings literally, which+// is exactly what an assertion should do.+const sourceFilePattern = /(?<!\.test)\.(?:ts|tsx)$/;+const generatedRoot = join(srcRoot, "types", "proto-es");++// A value interpolated straight into a double-quoted CEL string literal breaks+// the filter the moment it holds a `"` — a SQL identifier, anything typed into+// a search box — and the backend rejects the whole expression with+// InvalidArgument. `celString` / `celStringList` / `celMapField` in+// `src/utils/v1/celLiteral.ts` own the quotes so the escape cannot be forgotten.+const rawInterpolationRules = [+ {+ what: "a CEL string argument — use `name.contains(${celString(x)})`",+ pattern: /\.(?:contains|matches|startsWith|endsWith)\("\$\{/,+ },+ {+ what: "a CEL comparison operand — use `state == ${celString(x)}`",+ // The left operand may be a plain field, a computed one (`${field} ==`,+ // which getLabelFilter builds), or an index (`labels["k"] ==`).+ pattern: /(?:[a-z][a-zA-Z0-9_.]*|\}|\])\s*(?:==|!=|>=|<=|<|>)\s*"\$\{/,+ },+ {+ what: "a CEL list element — use `engine in ${celStringList(xs)}`",+ pattern: /\bin\s*\[\$\{[^\n]*"\$\{/,+ },+];++function listSourceFiles(dir: string): string[] {+ return readdirSync(dir, { withFileTypes: true }).flatMap((entry) => {+ const path = join(dir, entry.name);+ if (path === generatedRoot) {+ return [];+ }+ if (entry.isDirectory()) {+ return listSourceFiles(path);+ }+ return sourceFilePattern.test(entry.name) ? [path] : [];+ });+}++describe("CEL filter string literals", () => {+ test("no filter builder interpolates a raw value into a CEL literal", () => {+ const violations: string[] = [];+ for (const file of listSourceFiles(srcRoot)) {+ const lines = readFileSync(file, "utf-8").split("\n");+ lines.forEach((line, index) => {+ for (const rule of rawInterpolationRules) {+ if (rule.pattern.test(line)) {+ violations.push(+ `${relative(srcRoot, file)}:${index + 1} — ${rule.what}`+ );+ }+ }+ });+ }+ expect(violations).toEqual([]);+ });+});diff --git a/frontend/src/components/AuditLogTable.tsx b/frontend/src/components/AuditLogTable.tsxindex 4cc0fb0466..017717f688 100644--- a/frontend/src/components/AuditLogTable.tsx+++ b/frontend/src/components/AuditLogTable.tsx@@ -72,6 +72,7 @@ import {getDefaultPagination,humanizeDurationV1,} from "@/utils";+import { celString } from "@/utils/v1/celLiteral";dayjs.extend(utc);@@ -89,18 +90,18 @@ interface AuditLogFilter {function buildFilterString(filter: AuditLogFilter): string {const parts: string[] = [];- if (filter.method) parts.push(`method == "${filter.method}"`);+ if (filter.method) parts.push(`method == ${celString(filter.method)}`);if (filter.level !== undefined)- parts.push(`severity == "${AuditLog_Severity[filter.level]}"`);+ parts.push(`severity == ${celString(AuditLog_Severity[filter.level])}`);if (filter.userEmail)- parts.push(`user == "${userNamePrefix}${filter.userEmail}"`);+ parts.push(`user == ${celString(`${userNamePrefix}${filter.userEmail}`)}`);if (filter.createdTsAfter)parts.push(- `create_time >= "${dayjs(filter.createdTsAfter).utc().format()}"`+ `create_time >= ${celString(dayjs(filter.createdTsAfter).utc().format())}`);if (filter.createdTsBefore)parts.push(- `create_time <= "${dayjs(filter.createdTsBefore).utc().format()}"`+ `create_time <= ${celString(dayjs(filter.createdTsBefore).utc().format())}`);return parts.join(" && ");}diff --git a/frontend/src/lib/sensitive-data/exemptionDataUtils.ts b/frontend/src/lib/sensitive-data/exemptionDataUtils.tsindex f76b762c2a..24180b9154 100644--- a/frontend/src/lib/sensitive-data/exemptionDataUtils.ts+++ b/frontend/src/lib/sensitive-data/exemptionDataUtils.ts@@ -1,4 +1,5 @@import i18n from "@/lib/i18n";+import { celString } from "@/utils/v1/celLiteral";import type {AccessUser,ClassificationLevel,@@ -174,14 +175,14 @@ export function generateGrantTitle(grant: ExemptionGrant): string {// `resource.instance_id == "X" && resource.database_name == "Y"`.// The expression editor uses resource.database as a combined selector,// but the backend masking exemption evaluator only knows individual attributes.-export function rewriteResourceDatabase(celString: string): string {- return celString.replaceAll(+export function rewriteResourceDatabase(expression: string): string {+ return expression.replaceAll(/resource\.database\s*==\s*"([^"]+)"/g,(_match, fullPath: string) => {const matches = fullPath.match(databaseResourcePattern);const instanceName = matches?.groups?.instanceName ?? "";const databaseName = matches?.groups?.databaseName ?? "";- return `resource.instance_id == "${instanceName}" && resource.database_name == "${databaseName}"`;+ return `resource.instance_id == ${celString(instanceName)} && resource.database_name == ${celString(databaseName)}`;});}diff --git a/frontend/src/lib/sensitive-data/utils.ts b/frontend/src/lib/sensitive-data/utils.tsindex 3b330b4250..1ba4a1ca44 100644--- a/frontend/src/lib/sensitive-data/utils.ts+++ b/frontend/src/lib/sensitive-data/utils.ts@@ -10,6 +10,7 @@ import {CEL_ATTRIBUTE_RESOURCE_SCHEMA_NAME,CEL_ATTRIBUTE_RESOURCE_TABLE_NAME,} from "@/utils/cel-attributes";+import { celString, celStringList } from "@/utils/v1/celLiteral";import type { MaskData, SensitiveColumn } from "./types";export const getMaskDataIdentifier = (maskData: MaskData): string => {@@ -71,27 +72,27 @@ export const getExpressionsForDatabaseResource = (databaseResource.databaseFullName);const expressions = [- `${CEL_ATTRIBUTE_RESOURCE_INSTANCE_ID} == "${instanceName}"`,- `${CEL_ATTRIBUTE_RESOURCE_DATABASE_NAME} == "${databaseName}"`,+ `${CEL_ATTRIBUTE_RESOURCE_INSTANCE_ID} == ${celString(instanceName)}`,+ `${CEL_ATTRIBUTE_RESOURCE_DATABASE_NAME} == ${celString(databaseName)}`,];if (databaseResource.schema) {expressions.push(- `${CEL_ATTRIBUTE_RESOURCE_SCHEMA_NAME} == "${databaseResource.schema}"`+ `${CEL_ATTRIBUTE_RESOURCE_SCHEMA_NAME} == ${celString(databaseResource.schema)}`);}if (databaseResource.table) {expressions.push(- `${CEL_ATTRIBUTE_RESOURCE_TABLE_NAME} == "${databaseResource.table}"`+ `${CEL_ATTRIBUTE_RESOURCE_TABLE_NAME} == ${celString(databaseResource.table)}`);}if (databaseResource.columns && databaseResource.columns.length > 0) {if (databaseResource.columns.length === 1) {expressions.push(- `${CEL_ATTRIBUTE_RESOURCE_COLUMN_NAME} == "${databaseResource.columns[0]}"`+ `${CEL_ATTRIBUTE_RESOURCE_COLUMN_NAME} == ${celString(databaseResource.columns[0])}`);} else {expressions.push(- `${CEL_ATTRIBUTE_RESOURCE_COLUMN_NAME} in [${databaseResource.columns.map((c) => `"${c}"`)}]`+ `${CEL_ATTRIBUTE_RESOURCE_COLUMN_NAME} in ${celStringList(databaseResource.columns)}`);}}diff --git a/frontend/src/modules/cel/logic/stringify.ts b/frontend/src/modules/cel/logic/stringify.tsindex 980ac217d3..662078a3e1 100644--- a/frontend/src/modules/cel/logic/stringify.ts+++ b/frontend/src/modules/cel/logic/stringify.ts@@ -2,6 +2,7 @@ import type {Constant,Expr,} from "@/types/proto-es/google/api/expr/v1alpha1/syntax_pb";+import { celString } from "@/utils/v1/celLiteral";function stringifyExpr(expr: Expr): string {if (expr.exprKind?.case === "constExpr") {@@ -79,7 +80,7 @@ function stringifyConstant(constant: Constant): string {} else if (constant.constantKind?.case === "doubleValue") {return constant.constantKind.value.toString();} else if (constant.constantKind?.case === "stringValue") {- return `"${constant.constantKind.value}"`;+ return celString(constant.constantKind.value);} else if (constant.constantKind?.case === "bytesValue") {return `b'${constant.constantKind.value.toString()}'`;} else if (constant.constantKind?.case === "durationValue") {diff --git a/frontend/src/modules/sql-editor/model/Sheet/context.ts b/frontend/src/modules/sql-editor/model/Sheet/context.tsindex cec6fbd6b8..f354087eeb 100644--- a/frontend/src/modules/sql-editor/model/Sheet/context.ts+++ b/frontend/src/modules/sql-editor/model/Sheet/context.ts@@ -30,7 +30,7 @@ import {storageKeySqlEditorSavedQueryTree,workspaceCacheScope,} from "@/utils";-import { escapeCELStringLiteral } from "@/utils/v1/cel";+import { celString } from "@/utils/v1/celLiteral";import { isSubFolder } from "./folder";import { type SheetViewMode, SheetViewModeList } from "./types";@@ -1007,7 +1007,7 @@ const folderFilterForKey = (view: SheetViewMode, folderKey: string): string => {return `folder == ""`;}const folder = getFoldersForSavedQuery(view, key).join("/");- return `folder == "${escapeCELStringLiteral(folder)}"`;+ return `folder == ${celString(folder)}`;};const savedQuerySearchFilters = (): string[] => {@@ -1015,7 +1015,7 @@ const savedQuerySearchFilters = (): string[] => {const filters: string[] = [];const keyword = filter.keyword.trim().toLowerCase();if (keyword) {- filters.push(`title.contains("${escapeCELStringLiteral(keyword)}")`);+ filters.push(`title.contains(${celString(keyword)})`);}if (filter.onlyShowStarred) {filters.push("starred == true");@@ -1034,7 +1034,7 @@ const sheetFilterForView = (// and those must not appear here.const baseFilters =view === "my"- ? [`creator == "users/${escapeCELStringLiteral(email)}"`]+ ? [`creator == ${celString(`users/${email}`)}`]: [`shared == true`];return [...baseFilters,@@ -1115,7 +1115,7 @@ const fetchSavedQueriesByFolder = async (const { savedQueries, nextPageToken } = await fetchSavedQueriesPage(view,"",- [`folder == "${escapeCELStringLiteral(folder)}"`]+ [`folder == ${celString(folder)}`]);const names = new Set(useSheetContextStore.getState().viewStates[view].savedQueryNamesdiff --git a/frontend/src/modules/sql-editor/store/queryHistory.ts b/frontend/src/modules/sql-editor/store/queryHistory.tsindex a44d998eca..702ade2e5b 100644--- a/frontend/src/modules/sql-editor/store/queryHistory.ts+++ b/frontend/src/modules/sql-editor/store/queryHistory.ts@@ -8,7 +8,7 @@ import {} from "@/types/proto-es/v1/query_history_service_pb";import { isValidDatabaseName } from "@/types/v1/database";import { isValidProjectName } from "@/types/v1/project";-import { escapeCELStringLiteral } from "@/utils/v1/cel";+import { celString } from "@/utils/v1/celLiteral";import type {QueryHistoryEntry,QueryHistoryFilter,@@ -28,12 +28,10 @@ const EMPTY_RESPONSE = create(SearchQueryHistoriesResponseSchema, {});const getListQueryHistoryFilter = (filter: QueryHistoryFilter) => {const params = [`type == "QUERY"`];if (isValidDatabaseName(filter.database)) {- params.push(`database == "${filter.database}"`);+ params.push(`database == ${celString(filter.database)}`);}if (filter.statement) {- params.push(- `statement.contains("${escapeCELStringLiteral(filter.statement)}")`- );+ params.push(`statement.contains(${celString(filter.statement)})`);}return params.join(" && ");};diff --git a/frontend/src/routes/project/ProjectSyncSchemaPage.tsx b/frontend/src/routes/project/ProjectSyncSchemaPage.tsxindex fa277c4a5a..4058019cc1 100644--- a/frontend/src/routes/project/ProjectSyncSchemaPage.tsx+++ b/frontend/src/routes/project/ProjectSyncSchemaPage.tsx@@ -80,6 +80,7 @@ import {getDefaultPagination,getInstanceResource,} from "@/utils";+import { celString } from "@/utils/v1/celLiteral";import {extractDatabaseNameAndChangelogUID,isValidChangelogName,@@ -751,7 +752,7 @@ function ChangelogSelector({await listChangelogs({parent: database,pageSize: getDefaultPagination(),- filter: `status == "${Changelog_Status[Changelog_Status.DONE]}"`,+ filter: `status == ${celString(Changelog_Status[Changelog_Status.DONE])}`,});if (cancelled) return;@@ -785,7 +786,7 @@ function ChangelogSelector({parent: database,pageToken: nextPageToken,pageSize: getDefaultPagination(),- filter: `status == "${Changelog_Status[Changelog_Status.DONE]}"`,+ filter: `status == ${celString(Changelog_Status[Changelog_Status.DONE])}`,});setEntries((prev) => [...prev, ...more.map(toEntry)]);setNextPageToken(token);diff --git a/frontend/src/stores/app/accessGrant.ts b/frontend/src/stores/app/accessGrant.tsindex 2ffc288344..70da48e52a 100644--- a/frontend/src/stores/app/accessGrant.ts+++ b/frontend/src/stores/app/accessGrant.ts@@ -9,6 +9,7 @@ import {RevokeAccessGrantRequestSchema,SearchMyAccessGrantsRequestSchema,} from "@/types/proto-es/v1/access_grant_service_pb";+import { celString } from "@/utils/v1/celLiteral";import type {AccessGrantFilter,AccessGrantSlice,@@ -22,40 +23,38 @@ export const buildAccessGrantFilter = (const parts: string[] = [];if (filter.name) {- parts.push(`name == "${filter.name}"`);+ parts.push(`name == ${celString(filter.name)}`);}if (filter.status !== undefined && filter.status.length > 0) {const statusFilter: string[] = [];for (const status of filter.status) {- statusFilter.push(`status == "${status}"`);+ statusFilter.push(`status == ${celString(status)}`);}parts.push(`(${statusFilter.join(" || ")})`);}if (filter.statement) {- parts.push(`query.contains("${filter.statement.trim()}")`);+ parts.push(`query.contains(${celString(filter.statement.trim())})`);}if (filter.statementExact !== undefined) {- // Use JSON.stringify so internal quotes / backslashes / newlines in- // the SQL are escaped safely into the CEL string literal.- parts.push(`query == ${JSON.stringify(filter.statementExact.trim())}`);+ parts.push(`query == ${celString(filter.statementExact.trim())}`);}if (filter.creator) {- parts.push(`creator == "${filter.creator}"`);+ parts.push(`creator == ${celString(filter.creator)}`);}if (filter.issue) {- parts.push(`issue == "${filter.issue}"`);+ parts.push(`issue == ${celString(filter.issue)}`);}if (filter.target) {- parts.push(`target == "${filter.target}"`);+ parts.push(`target == ${celString(filter.target)}`);}if (filter.createdTsAfter !== undefined) {parts.push(- `create_time >= "${new Date(filter.createdTsAfter).toISOString()}"`+ `create_time >= ${celString(new Date(filter.createdTsAfter).toISOString())}`);}if (filter.createdTsBefore !== undefined) {parts.push(- `create_time <= "${new Date(filter.createdTsBefore).toISOString()}"`+ `create_time <= ${celString(new Date(filter.createdTsBefore).toISOString())}`);}if (filter.unmask !== undefined) {diff --git a/frontend/src/stores/app/changelog.ts b/frontend/src/stores/app/changelog.tsindex 0e2fda2e36..e2699f5b6b 100644--- a/frontend/src/stores/app/changelog.ts+++ b/frontend/src/stores/app/changelog.ts@@ -7,6 +7,7 @@ import {GetChangelogRequestSchema,ListChangelogsRequestSchema,} from "@/types/proto-es/v1/changelog_service_pb";+import { celString } from "@/utils/v1/celLiteral";import { extractChangelogUID } from "@/utils/v1/changelog";import type { AppSliceCreator, ChangelogSlice } from "./types";@@ -202,7 +203,7 @@ export const createChangelogSlice: AppSliceCreator<ChangelogSlice> = (parent: database,pageSize: 1,view: ChangelogView.FULL,- filter: `has_schema_snapshot == true && create_time < "${createTime}"`,+ filter: `has_schema_snapshot == true && create_time < ${celString(createTime)}`,});return changelogs[0];},diff --git a/frontend/src/stores/app/filterEscaping.test.ts b/frontend/src/stores/app/filterEscaping.test.tsnew file mode 100644index 0000000000..14f573005e--- /dev/null+++ b/frontend/src/stores/app/filterEscaping.test.ts@@ -0,0 +1,76 @@+import { describe, expect, test } from "vitest";+import { buildAccessGrantFilter } from "./accessGrant";+import { buildGroupFilter } from "./group";+import { getListInstanceFilter } from "./instance";+import { buildPlanFilter } from "./plan";+import { getListProjectFilter } from "./project";+import { buildAccountListFilter } from "./serviceAccount";+import { buildUserFilter } from "./user";+import {+ buildDatabaseFilter,+ buildProjectFilter,+ getLabelFilter,+} from "./utils";++const QUOTED = 'SELECT * FROM "users"';+const ESCAPED = 'SELECT * FROM \\"users\\"';++// A `"` typed into any of these search boxes used to close the CEL string+// literal early, and the backend rejected the whole filter with+// InvalidArgument. SQL identifiers make this routine on the access-grant page.+describe("free-text search filters escape the quote", () => {+ const cases: [string, () => string][] = [+ [+ "access grant statement",+ () => buildAccessGrantFilter({ statement: QUOTED }),+ ],+ ["group", () => buildGroupFilter({ query: QUOTED })],+ ["instance", () => getListInstanceFilter({ query: QUOTED })],+ ["plan", () => buildPlanFilter({ project: "projects/p", query: QUOTED })],+ ["project list", () => getListProjectFilter({ query: QUOTED })],+ ["project picker", () => buildProjectFilter(QUOTED)],+ ["service account", () => buildAccountListFilter({ query: QUOTED })],+ ["user", () => buildUserFilter({ query: QUOTED })],+ ["database", () => buildDatabaseFilter({ query: QUOTED })],+ ];++ test.each(cases)("%s", (_name, build) => {+ const filter = build().toLowerCase();+ expect(filter).not.toContain(QUOTED.toLowerCase());+ expect(filter).toContain(ESCAPED.toLowerCase());+ });++ test("access grant keeps the statement readable", () => {+ expect(buildAccessGrantFilter({ statement: QUOTED })).toBe(+ `query.contains("${ESCAPED}")`+ );+ });++ test("instance host and port are escaped too", () => {+ expect(getListInstanceFilter({ host: 'h"1', port: 'p"2' })).toBe(+ 'host.contains("h\\"1") && port.contains("p\\"2")'+ );+ });++ test("database table filter is escaped", () => {+ expect(buildDatabaseFilter({ table: 't"1' })).toBe(+ 'table.contains("t\\"1")'+ );+ });+});++describe("getLabelFilter", () => {+ // Label keys allow dashes. `labels.cost-center` parses as subtraction, so+ // the backend never saw the key and rejected the whole filter.+ test("uses index syntax so a dashed key survives CEL parsing", () => {+ expect(getLabelFilter(["cost-center:eng"])).toEqual([+ 'labels["cost-center"] == "eng"',+ ]);+ });++ test("uses index syntax for multi-value keys", () => {+ expect(getLabelFilter(["cost-center:eng,ops"])).toEqual([+ 'labels["cost-center"] in ["eng", "ops"]',+ ]);+ });+});diff --git a/frontend/src/stores/app/group.ts b/frontend/src/stores/app/group.tsindex fffc087e36..21428d33ae 100644--- a/frontend/src/stores/app/group.ts+++ b/frontend/src/stores/app/group.ts@@ -13,6 +13,7 @@ import {ListGroupsRequestSchema,UpdateGroupRequestSchema,} from "@/types/proto-es/v1/group_service_pb";+import { celString } from "@/utils/v1/celLiteral";import type { AppSliceCreator, GroupFilter, GroupSlice } from "./types";import { toError } from "./utils";@@ -32,10 +33,11 @@ export const buildGroupFilter = (params: GroupFilter) => {const filter = [];const search = params.query?.trim()?.toLowerCase();if (search) {- filter.push(`(title.contains("${search}") || email.contains("${search}"))`);+ const value = celString(search);+ filter.push(`(title.contains(${value}) || email.contains(${value}))`);}if (isValidProjectName(params.project)) {- filter.push(`project == "${params.project}"`);+ filter.push(`project == ${celString(params.project)}`);}return filter.join(" && ");};diff --git a/frontend/src/stores/app/instance.ts b/frontend/src/stores/app/instance.tsindex bee46f72b3..72693f3a96 100644--- a/frontend/src/stores/app/instance.ts+++ b/frontend/src/stores/app/instance.ts@@ -37,38 +37,38 @@ import {hasProjectPermissionV2,hasWorkspacePermissionV2,} from "@/utils";+import { celString, celStringList } from "@/utils/v1/celLiteral";import type { AppSliceCreator, InstanceFilter, InstanceSlice } from "./types";import { getLabelFilter, toError } from "./utils";-const getListInstanceFilter = (params: InstanceFilter): string => {+export const getListInstanceFilter = (params: InstanceFilter): string => {const list: string[] = [];const search = params.query?.trim().toLowerCase();if (search) {- list.push(- `(name.contains("${search}") || resource_id.contains("${search}"))`- );+ const value = celString(search);+ list.push(`(name.contains(${value}) || resource_id.contains(${value}))`);}if (isValidProjectName(params.project)) {- list.push(`project == "${params.project}"`);+ list.push(`project == ${celString(params.project)}`);}if (params.environment === unknownEnvironment().name) {list.push(`environment == ""`);} else if (isValidEnvironmentName(params.environment)) {- list.push(`environment == "${params.environment}"`);+ list.push(`environment == ${celString(params.environment)}`);}if (params.host) {- list.push(`host.contains("${params.host}")`);+ list.push(`host.contains(${celString(params.host)})`);}if (params.port) {- list.push(`port.contains("${params.port}")`);+ list.push(`port.contains(${celString(params.port)})`);}if (params.engines && params.engines.length > 0) {list.push(- `engine in [${params.engines.map((e) => `"${Engine[e]}"`).join(", ")}]`+ `engine in ${celStringList(params.engines.map((e) => Engine[e]))}`);}if (params.state === State.DELETED) {- list.push(`state == "${State[params.state]}"`);+ list.push(`state == ${celString(State[params.state])}`);}if (params.labels) {list.push(...getLabelFilter(params.labels));diff --git a/frontend/src/stores/app/issue.ts b/frontend/src/stores/app/issue.tsindex 7fe6b7d95d..52bec30066 100644--- a/frontend/src/stores/app/issue.ts+++ b/frontend/src/stores/app/issue.ts@@ -27,6 +27,7 @@ import {} from "@/types/proto-es/v1/plan_service_pb";import type { Project } from "@/types/proto-es/v1/project_service_pb";import { CreateRolloutRequestSchema } from "@/types/proto-es/v1/rollout_service_pb";+import { celString, celStringList } from "@/utils/v1/celLiteral";import type { AppSliceCreator, IssueSlice } from "./types";// Resource names are `projects/{project}/issues/{issue}` — yank the project@@ -40,41 +41,43 @@ function projectResourceFromIssueName(issueName: string): string {export const buildIssueFilter = (find: IssueFilter): string => {const filter: string[] = [];if (find.creator) {- filter.push(`creator == "${find.creator}"`);+ filter.push(`creator == ${celString(find.creator)}`);}if (find.currentApprover) {- filter.push(`current_approver == "${find.currentApprover}"`);+ filter.push(`current_approver == ${celString(find.currentApprover)}`);}if (find.approvalStatus) {- filter.push(`approval_status == "${ApprovalStatus[find.approvalStatus]}"`);+ filter.push(+ `approval_status == ${celString(ApprovalStatus[find.approvalStatus])}`+ );}if (find.statusList && find.statusList.length > 0) {filter.push(- `status in [${find.statusList.map((s) => `"${IssueStatus[s]}"`).join(",")}]`+ `status in ${celStringList(find.statusList.map((s) => IssueStatus[s]))}`);}if (find.riskLevelList && find.riskLevelList.length > 0) {filter.push(- `risk_level in [${find.riskLevelList.map((r) => `"${RiskLevel[r]}"`).join(",")}]`+ `risk_level in ${celStringList(find.riskLevelList.map((r) => RiskLevel[r]))}`);}if (find.createdTsAfter) {filter.push(- `create_time >= "${dayjs(find.createdTsAfter).utc().format()}"`+ `create_time >= ${celString(dayjs(find.createdTsAfter).utc().format())}`);}if (find.createdTsBefore) {filter.push(- `create_time <= "${dayjs(find.createdTsBefore).utc().format()}"`+ `create_time <= ${celString(dayjs(find.createdTsBefore).utc().format())}`);}if (find.typeList && find.typeList.length > 0) {filter.push(- `type in [${find.typeList.map((t) => `"${Issue_Type[t]}"`).join(",")}]`+ `type in ${celStringList(find.typeList.map((t) => Issue_Type[t]))}`);}if (find.labels && find.labels.length > 0) {- filter.push(`labels in [${find.labels.map((l) => `"${l}"`).join(",")}]`);+ filter.push(`labels in ${celStringList(find.labels)}`);}return filter.join(" && ");};diff --git a/frontend/src/stores/app/plan.ts b/frontend/src/stores/app/plan.tsindex 379d835614..e428b193d4 100644--- a/frontend/src/stores/app/plan.ts+++ b/frontend/src/stores/app/plan.ts@@ -11,34 +11,37 @@ import {getValueFromSearchParams,type SearchParams,} from "@/utils";+import { celString } from "@/utils/v1/celLiteral";import type { AppSliceCreator, PlanFind, PlanSlice } from "./types";export const buildPlanFilter = (find: PlanFind): string => {const filter: string[] = [];if (find.query) {- filter.push(`title.contains("${find.query.trim().toLowerCase()}")`);+ filter.push(+ `title.contains(${celString(find.query.trim().toLowerCase())})`+ );}if (find.creator) {- filter.push(`creator == "${find.creator}"`);+ filter.push(`creator == ${celString(find.creator)}`);}if (find.createdTsAfter) {filter.push(- `create_time >= "${dayjs(find.createdTsAfter).utc().format()}"`+ `create_time >= ${celString(dayjs(find.createdTsAfter).utc().format())}`);}if (find.createdTsBefore) {filter.push(- `create_time <= "${dayjs(find.createdTsBefore).utc().format()}"`+ `create_time <= ${celString(dayjs(find.createdTsBefore).utc().format())}`);}if (find.hasRollout !== undefined) {filter.push(`has_rollout == ${find.hasRollout}`);}if (find.specType) {- filter.push(`spec_type == "${find.specType}"`);+ filter.push(`spec_type == ${celString(find.specType)}`);}if (find.state) {- filter.push(`state == "${find.state}"`);+ filter.push(`state == ${celString(find.state)}`);}return filter.join(" && ");};diff --git a/frontend/src/stores/app/project.ts b/frontend/src/stores/app/project.tsindex f0e4232daf..49c53b8d1a 100644--- a/frontend/src/stores/app/project.ts+++ b/frontend/src/stores/app/project.ts@@ -19,6 +19,7 @@ import {UpdateProjectRequestSchema,} from "@/types/proto-es/v1/project_service_pb";import { hasWorkspacePermissionV2 } from "@/utils";+import { celString } from "@/utils/v1/celLiteral";import { setProjectAccess } from "./projectAccess";import type { AppSliceCreator, ProjectFilter, ProjectSlice } from "./types";import {@@ -28,13 +29,12 @@ import {toError,} from "./utils";-const getListProjectFilter = (params: ProjectFilter): string => {+export const getListProjectFilter = (params: ProjectFilter): string => {const list: string[] = [];const search = params.query?.trim().toLowerCase();if (search) {- list.push(- `(name.contains("${search}") || resource_id.contains("${search}"))`- );+ const value = celString(search);+ list.push(`(name.contains(${value}) || resource_id.contains(${value}))`);}if (params.labels) {list.push(...getLabelFilter(params.labels));@@ -43,7 +43,7 @@ const getListProjectFilter = (params: ProjectFilter): string => {list.push("exclude_default == true");}if (params.state === State.DELETED) {- list.push(`state == "${State[params.state]}"`);+ list.push(`state == ${celString(State[params.state])}`);}return list.join(" && ");};diff --git a/frontend/src/stores/app/serviceAccount.ts b/frontend/src/stores/app/serviceAccount.tsindex 47e3831683..88d448713f 100644--- a/frontend/src/stores/app/serviceAccount.ts+++ b/frontend/src/stores/app/serviceAccount.ts@@ -13,6 +13,7 @@ import {UndeleteServiceAccountRequestSchema,UpdateServiceAccountRequestSchema,} from "@/types/proto-es/v1/service_account_service_pb";+import { celString } from "@/utils/v1/celLiteral";import type {AccountFilter,AppSliceCreator,@@ -37,10 +38,11 @@ export const buildAccountListFilter = (params: AccountFilter) => {const filter = [];const search = params.query?.trim()?.toLowerCase();if (search) {- filter.push(`(name.contains("${search}") || email.contains("${search}"))`);+ const value = celString(search);+ filter.push(`(name.contains(${value}) || email.contains(${value}))`);}if (params.state === State.DELETED) {- filter.push(`state == "${State[params.state]}"`);+ filter.push(`state == ${celString(State[params.state])}`);}return filter.join(" && ");};diff --git a/frontend/src/stores/app/user.ts b/frontend/src/stores/app/user.tsindex 63aa792088..9f7cc485f4 100644--- a/frontend/src/stores/app/user.ts+++ b/frontend/src/stores/app/user.ts@@ -23,6 +23,7 @@ import {UpdateEmailRequestSchema,UpdateUserRequestSchema,} from "@/types/proto-es/v1/user_service_pb";+import { celString } from "@/utils/v1/celLiteral";import { ensureUserFullName } from "@/utils/v1/user";import type { AppSliceCreator, UserFilter, UserSlice } from "./types";@@ -32,16 +33,17 @@ export const buildUserFilter = (params: UserFilter) => {const filter = [];const search = params.query?.trim()?.toLowerCase();if (search) {- filter.push(`(name.contains("${search}") || email.contains("${search}"))`);+ const value = celString(search);+ filter.push(`(name.contains(${value}) || email.contains(${value}))`);}if (isValidProjectName(params.project) &¶ms.project !== UNKNOWN_PROJECT_NAME_LEGACY) {- filter.push(`project == "${params.project}"`);+ filter.push(`project == ${celString(params.project)}`);}if (params.state === State.DELETED) {- filter.push(`state == "${State[params.state]}"`);+ filter.push(`state == ${celString(State[params.state])}`);}return filter.join(" && ");};diff --git a/frontend/src/stores/app/utils.ts b/frontend/src/stores/app/utils.tsindex 8783b28f3d..b10ecfdffd 100644--- a/frontend/src/stores/app/utils.ts+++ b/frontend/src/stores/app/utils.ts@@ -17,7 +17,7 @@ import {} from "@/types/v1/environment";import { isValidInstanceName } from "@/types/v1/instance";import { workspaceCacheScope } from "@/utils/storage-keys";-import { escapeCELStringLiteral } from "@/utils/v1/cel";+import { celMapField, celString, celStringList } from "@/utils/v1/celLiteral";import { bindingScopesResources } from "@/utils/v1/iam";import type { AppStoreState } from "./types";@@ -71,16 +71,15 @@ export function buildProjectFilter(query: string | undefined) {const filters = ["exclude_default == true"];const search = query?.trim().toLowerCase();if (search) {- filters.push(- `(name.contains("${search}") || resource_id.contains("${search}"))`- );+ const value = celString(search);+ filters.push(`(name.contains(${value}) || resource_id.contains(${value}))`);}return filters.join(" && ");}// Converts label selectors like "{key}:{v1},{v2}" into API filter clauses-// (`labels.{key} == "v"` or `labels.{key} in [...]`). Ported verbatim from-// the legacy Pinia database store.+// (`labels["{key}"] == "v"` or `labels["{key}"] in [...]`). Index syntax, not+// `labels.{key}` — label keys allow dashes, which CEL parses as subtraction.export function getLabelFilter(labels: string[]): string[] {const labelMap = new Map<string, string[]>();for (const label of labels) {@@ -96,16 +95,15 @@ export function getLabelFilter(labels: string[]): string[] {labelMap.get(key)?.push(...values);}return [...labelMap.entries()].reduce((result, [key, values]) => {+ const field = celMapField("labels", key);switch (values.length) {case 0:return result;case 1:- result.push(`labels.${key} == "${values[0]}"`);+ result.push(`${field} == ${celString(values[0])}`);return result;default:- result.push(- `labels.${key} in [${values.map((v) => `"${v}"`).join(", ")}]`- );+ result.push(`${field} in ${celStringList(values)}`);return result;}}, [] as string[]);@@ -117,39 +115,37 @@ export function getLabelFilter(labels: string[]): string[] {export function buildDatabaseFilter(filter: DatabaseFilter): string {const params: string[] = [];if (isValidProjectName(filter.project)) {- params.push(`project == "${filter.project}"`);+ params.push(`project == ${celString(filter.project)}`);}if (isValidInstanceName(filter.instance)) {- params.push(`instance == "${filter.instance}"`);+ params.push(`instance == ${celString(filter.instance)}`);}if (filter.environment === unknownEnvironment().name) {params.push(`environment == ""`);} else if (isValidEnvironmentName(filter.environment)) {- params.push(`environment == "${filter.environment}"`);+ params.push(`environment == ${celString(filter.environment)}`);}if (filter.excludeUnassigned) {params.push(`exclude_unassigned == true`);}if (filter.engines && filter.engines.length > 0) {params.push(- `engine in [${filter.engines.map((e) => `"${Engine[e]}"`).join(", ")}]`+ `engine in ${celStringList(filter.engines.map((e) => Engine[e]))}`);} else if (filter.excludeEngines && filter.excludeEngines.length > 0) {params.push(- `!(engine in [${filter.excludeEngines- .map((e) => `"${Engine[e]}"`)- .join(", ")}])`+ `!(engine in ${celStringList(filter.excludeEngines.map((e) => Engine[e]))})`);}const keyword = filter.query?.trim()?.toLowerCase();if (keyword) {- params.push(`name.contains("${escapeCELStringLiteral(keyword)}")`);+ params.push(`name.contains(${celString(keyword)})`);}if (filter.labels) {params.push(...getLabelFilter(filter.labels));}if (filter.table) {- params.push(`table.contains("${filter.table}")`);+ params.push(`table.contains(${celString(filter.table)})`);}return params.join(" && ");}diff --git a/frontend/src/types/v1/project.ts b/frontend/src/types/v1/project.tsindex 8ede7feede..4510f9cfd8 100644--- a/frontend/src/types/v1/project.ts+++ b/frontend/src/types/v1/project.ts@@ -34,7 +34,9 @@ export const defaultProject = (name: string): Project => {};};-export const isValidProjectName = (name: string | undefined) => {+export const isValidProjectName = (+ name: string | undefined+): name is string => {const projectID = name?.slice("projects/".length);return (!!name &&diff --git a/frontend/src/utils/issue/cel.ts b/frontend/src/utils/issue/cel.tsindex fee64cfffb..45d5574f8e 100644--- a/frontend/src/utils/issue/cel.ts+++ b/frontend/src/utils/issue/cel.ts@@ -28,6 +28,7 @@ import {CEL_ATTRIBUTE_RESOURCE_SCHEMA_NAME,CEL_ATTRIBUTE_RESOURCE_TABLE_NAME,} from "@/utils/cel-attributes";+import { celString, celStringList } from "@/utils/v1/celLiteral";interface DatabaseLevelCondition {database: string[];@@ -239,12 +240,12 @@ export const stringifyConditionExpression = ({}if (expirationTimestampInMS) {expression.push(- `${CEL_ATTRIBUTE_REQUEST_TIME} < timestamp("${dayjs(expirationTimestampInMS).toISOString()}")`+ `${CEL_ATTRIBUTE_REQUEST_TIME} < timestamp(${celString(dayjs(expirationTimestampInMS).toISOString())})`);}if (environments !== undefined) {expression.push(- `${CEL_ATTRIBUTE_RESOURCE_ENVIRONMENT_ID} in [${environments.map((env) => `"${getEnvironmentId(env)}"`)}]`+ `${CEL_ATTRIBUTE_RESOURCE_ENVIRONMENT_ID} in ${celStringList(environments.map((env) => getEnvironmentId(env)))}`);}return expression.join(" && ");@@ -266,14 +267,14 @@ const convertToCELString = (if (arr.length === 0) {return "";}- return `${resource} in ${JSON.stringify(arr)}`;+ return `${resource} in ${celStringList(arr)}`;};const getStringExpressionString = (resource: string, value: string) => {if (!value) {return "";}- return `${resource} == "${value}"`;+ return `${resource} == ${celString(value)}`;};function buildCondition(@@ -283,10 +284,11 @@ const convertToCELString = (| TableLevelCondition| ColumnLevelCondition): string {- const databaseExpression = `${CEL_ATTRIBUTE_RESOURCE_DATABASE} == "${condition.database}"`;+ const databaseExpression = (database: string) =>+ `${CEL_ATTRIBUTE_RESOURCE_DATABASE} == ${celString(database)}`;if ("column" in condition) {return [- databaseExpression,+ databaseExpression(condition.database),getStringExpressionString(CEL_ATTRIBUTE_RESOURCE_SCHEMA_NAME,condition.schema@@ -304,7 +306,7 @@ const convertToCELString = (.join(" && ");} else if ("table" in condition) {return [- databaseExpression,+ databaseExpression(condition.database),getStringExpressionString(CEL_ATTRIBUTE_RESOURCE_SCHEMA_NAME,condition.schema@@ -318,7 +320,7 @@ const convertToCELString = (.join(" && ");} else if ("schema" in condition) {return [- databaseExpression,+ databaseExpression(condition.database),getArrayExpressionString(CEL_ATTRIBUTE_RESOURCE_TABLE_NAME,condition.schema@@ -327,7 +329,7 @@ const convertToCELString = (.filter((str) => str).join(" && ");} else {- return `${CEL_ATTRIBUTE_RESOURCE_DATABASE} in ${JSON.stringify(condition.database)}`;+ return `${CEL_ATTRIBUTE_RESOURCE_DATABASE} in ${celStringList(condition.database)}`;}}diff --git a/frontend/src/utils/releaseFilter.ts b/frontend/src/utils/releaseFilter.tsindex 3c4d57cc47..c01cacb243 100644--- a/frontend/src/utils/releaseFilter.ts+++ b/frontend/src/utils/releaseFilter.ts@@ -1,5 +1,7 @@+import { celString } from "@/utils/v1/celLiteral";+// Convert category value to CEL filter expressionexport const buildCategoryFilter = (category: string | undefined): string => {if (!category) return "";- return `category == "${category}"`;+ return `category == ${celString(category)}`;};diff --git a/frontend/src/utils/v1/cel.test.ts b/frontend/src/utils/v1/cel.test.tsdeleted file mode 100644index 60d469f004..0000000000--- a/frontend/src/utils/v1/cel.test.ts+++ /dev/null@@ -1,24 +0,0 @@-import { describe, expect, test } from "vitest";-import { escapeCELStringLiteral } from "./cel";--describe("escapeCELStringLiteral", () => {- test("escapes double quotes — regression for SQL identifiers", () => {- // `statement.contains("...")` must stay valid CEL when the statement- // contains double quotes (e.g. a quoted identifier).- expect(escapeCELStringLiteral('SELECT * FROM "public".db LIMIT 1;')).toBe(- 'SELECT * FROM \\"public\\".db LIMIT 1;'- );- });-- test("escapes backslashes before quotes", () => {- expect(escapeCELStringLiteral('a\\b"c')).toBe('a\\\\b\\"c');- });-- test("escapes newlines, carriage returns, and tabs", () => {- expect(escapeCELStringLiteral("a\nb\rc\td")).toBe("a\\nb\\rc\\td");- });-- test("leaves plain text unchanged", () => {- expect(escapeCELStringLiteral("select 1")).toBe("select 1");- });-});diff --git a/frontend/src/utils/v1/cel.ts b/frontend/src/utils/v1/cel.tsindex ec8bd484b3..4e1a3856c6 100644--- a/frontend/src/utils/v1/cel.ts+++ b/frontend/src/utils/v1/cel.ts@@ -9,18 +9,6 @@ import {BatchParseRequestSchema,} from "@/types/proto-es/v1/cel_service_pb";-// Escapes a value for embedding inside a double-quoted CEL string literal,-// e.g. `statement.contains("<escaped>")`. Without this, free text containing a-// double quote (such as a SQL identifier like `"public"`) breaks the filter-// the backend parses. Backslash must be escaped first.-export const escapeCELStringLiteral = (value: string): string =>- value- .replace(/\\/g, "\\\\")- .replace(/"/g, '\\"')- .replace(/\n/g, "\\n")- .replace(/\r/g, "\\r")- .replace(/\t/g, "\\t");-export const batchConvertCELStringToParsedExpr = async (celList: string[]): Promise<Expr[]> => {diff --git a/frontend/src/utils/v1/celLiteral.test.ts b/frontend/src/utils/v1/celLiteral.test.tsnew file mode 100644index 0000000000..936dc1fefe--- /dev/null+++ b/frontend/src/utils/v1/celLiteral.test.ts@@ -0,0 +1,56 @@+import { describe, expect, test } from "vitest";+import { celMapField, celString, celStringList } from "./celLiteral";++describe("celString", () => {+ test("escapes double quotes — regression for SQL identifiers", () => {+ // `statement.contains(...)` must stay valid CEL when the statement+ // contains double quotes (e.g. a quoted identifier).+ expect(celString('SELECT * FROM "public".db LIMIT 1;')).toBe(+ '"SELECT * FROM \\"public\\".db LIMIT 1;"'+ );+ });++ test("escapes backslashes before quotes", () => {+ expect(celString('a\\b"c')).toBe('"a\\\\b\\"c"');+ });++ test("escapes newlines, carriage returns, and tabs", () => {+ expect(celString("a\nb\rc\td")).toBe('"a\\nb\\rc\\td"');+ });++ test("quotes plain text", () => {+ expect(celString("select 1")).toBe('"select 1"');+ });++ test("closes the literal it opens", () => {+ // The escape is only worth anything if the quotes come from the same+ // place — a caller writing its own quotes is the bug this prevents.+ expect(celString('a"b')).toMatch(/^".*"$/);+ });+});++describe("celStringList", () => {+ test("renders a CEL list literal", () => {+ expect(celStringList(["a", "b"])).toBe('["a", "b"]');+ });++ test("escapes each element", () => {+ expect(celStringList(['a"b'])).toBe('["a\\"b"]');+ });++ test("renders an empty list", () => {+ expect(celStringList([])).toBe("[]");+ });+});++describe("celMapField", () => {+ test("uses index syntax so non-identifier keys survive", () => {+ // Label keys allow dashes; `labels.cost-center` parses as subtraction and+ // the backend rejects it with `unsupport variable ""`.+ expect(celMapField("labels", "cost-center")).toBe('labels["cost-center"]');+ });++ test("escapes the key", () => {+ expect(celMapField("labels", 'a"b')).toBe('labels["a\\"b"]');+ });+});diff --git a/frontend/src/utils/v1/celLiteral.ts b/frontend/src/utils/v1/celLiteral.tsnew file mode 100644index 0000000000..6f939d3c16--- /dev/null+++ b/frontend/src/utils/v1/celLiteral.ts@@ -0,0 +1,33 @@+// Pure CEL string-literal helpers. Deliberately dependency-free: every filter+// builder needs them, and importing this must not pull the RPC clients in+// `./cel` into a caller's module graph.++// Escapes a value for embedding inside a double-quoted CEL string literal.+// Backslash must be escaped first. Prefer `celString`, which also writes the+// surrounding quotes — a call site that forgets them looks identical to one+// that never escaped at all.+const escapeCELStringLiteral = (value: string): string =>+ value+ .replace(/\\/g, "\\\\")+ .replace(/"/g, '\\"')+ .replace(/\n/g, "\\n")+ .replace(/\r/g, "\\r")+ .replace(/\t/g, "\\t");++// Renders a value as a complete CEL string literal, quotes included:+// `statement.contains(${celString(keyword)})`. Never interpolate a value into+// `"..."` by hand — free text holding a double quote (a SQL identifier like+// `"public"`, anything typed into a search box) closes the literal early, and+// the backend rejects the whole filter with InvalidArgument.+export const celString = (value: string): string =>+ `"${escapeCELStringLiteral(value)}"`;++// Renders values as a CEL list literal, e.g. `["a", "b"]`, for `in` operands.+export const celStringList = (values: readonly string[]): string =>+ `[${values.map(celString).join(", ")}]`;++// Renders a map field selector. CEL only parses `labels.foo` when the key is+// an identifier, so a key holding anything else — a dash, which label keys+// allow — must go through index syntax to reach the backend at all.+export const celMapField = (field: string, key: string): string =>+ `${field}[${celString(key)}]`;diff --git a/frontend/src/utils/v1/index.ts b/frontend/src/utils/v1/index.tsindex f17822126a..db302875e0 100644--- a/frontend/src/utils/v1/index.ts+++ b/frontend/src/utils/v1/index.ts@@ -15,6 +15,7 @@ export * from "./issue";export * from "./changelog";export * from "./revision";export * from "./cel";+export * from "./celLiteral";export * from "./advanced-search";export * from "./iam";export * from "./dbSchema";