Skip to content

Database governance built for humans and agents — controlling changes and access across every major database.

fix: handle oversized access grant statements (#21330)

ecmadaodec9d6bbe80b
diff --git a/backend/api/v1/access_grant_service.go b/backend/api/v1/access_grant_service.go
index e1d32a50b0..3a6ec90165 100644
--- a/backend/api/v1/access_grant_service.go
+++ b/backend/api/v1/access_grant_service.go
@@ -90,7 +90,7 @@ func (s *AccessGrantService) ListAccessGrants(ctx context.Context, request *conn
if req.Filter != "" {
filterQ, err := store.GetListAccessGrantFilter(req.Filter)
if err != nil {
- return nil, connect.NewError(connect.CodeInvalidArgument, errors.Wrapf(err, "failed to parse filter"))
+ return nil, connect.NewError(connect.CodeInvalidArgument, err)
}
find.FilterQ = filterQ
}
@@ -444,7 +444,7 @@ func (s *AccessGrantService) SearchMyAccessGrants(ctx context.Context, request *
if req.Filter != "" {
filterQ, err := store.GetListAccessGrantFilter(req.Filter)
if err != nil {
- return nil, connect.NewError(connect.CodeInvalidArgument, errors.Wrapf(err, "failed to parse filter"))
+ return nil, connect.NewError(connect.CodeInvalidArgument, err)
}
find.FilterQ = filterQ
}
diff --git a/backend/api/v1/access_grant_service_test.go b/backend/api/v1/access_grant_service_test.go
index 4f70c121c1..a3f128a068 100644
--- a/backend/api/v1/access_grant_service_test.go
+++ b/backend/api/v1/access_grant_service_test.go
@@ -137,66 +137,3 @@ func TestConvertToAccessGrantNilPayloadIsSafe(t *testing.T) {
require.Empty(t, ag.Schema)
require.Empty(t, ag.Container)
}
-
-func TestAccessGrantMatchesExecutionContext(t *testing.T) {
- schema := "APP"
- tests := []struct {
- name string
- payload *storepb.AccessGrantPayload
- schema *string
- container string
- want bool
- }{
- {
- name: "matching schema and container",
- payload: &storepb.AccessGrantPayload{
- Schema: "APP",
- Container: "orders",
- },
- schema: &schema,
- container: "orders",
- want: true,
- },
- {
- name: "different schema",
- payload: &storepb.AccessGrantPayload{
- Schema: "APP",
- Container: "orders",
- },
- schema: func() *string { v := "OTHER"; return &v }(),
- container: "orders",
- want: false,
- },
- {
- name: "different container",
- payload: &storepb.AccessGrantPayload{
- Schema: "APP",
- Container: "orders",
- },
- schema: &schema,
- container: "customers",
- want: false,
- },
- {
- name: "nil payload",
- payload: nil,
- schema: &schema,
- container: "orders",
- want: false,
- },
- {
- name: "empty context matches omitted values",
- payload: &storepb.AccessGrantPayload{},
- schema: nil,
- container: "",
- want: true,
- },
- }
-
- for _, tc := range tests {
- t.Run(tc.name, func(t *testing.T) {
- grant := &store.AccessGrantMessage{Payload: tc.payload}
- require.Equal(t, tc.want, accessGrantMatchesExecutionContext(grant, tc.schema, tc.container))
- })
- }
-}
diff --git a/backend/api/v1/changelog_service.go b/backend/api/v1/changelog_service.go
index e55937ab4a..1bae57e455 100644
--- a/backend/api/v1/changelog_service.go
+++ b/backend/api/v1/changelog_service.go
@@ -7,7 +7,6 @@ import (
"connectrpc.com/connect"
"google.golang.org/protobuf/types/known/timestamppb"
- "github.com/google/cel-go/cel"
celast "github.com/google/cel-go/common/ast"
celoperators "github.com/google/cel-go/common/operators"
"github.com/pkg/errors"
@@ -36,13 +35,9 @@ func parseChangelogFilter(filter string, find *store.FindChangelogMessage) error
return nil
}
- e, err := cel.NewEnv()
+ ast, err := common.ParseCELFilter(filter)
if err != nil {
- return connect.NewError(connect.CodeInternal, errors.Errorf("failed to create cel env"))
- }
- ast, iss := e.Parse(filter)
- if iss != nil {
- return connect.NewError(connect.CodeInvalidArgument, errors.Errorf("failed to parse filter %v, error: %v", filter, iss.String()))
+ return connect.NewError(connect.CodeInvalidArgument, err)
}
var parseFilter func(expr celast.Expr) error
diff --git a/backend/api/v1/database_service.go b/backend/api/v1/database_service.go
index 8579e4badb..4c5fad730d 100644
--- a/backend/api/v1/database_service.go
+++ b/backend/api/v1/database_service.go
@@ -8,7 +8,6 @@ import (
"strings"
"connectrpc.com/connect"
- "github.com/google/cel-go/cel"
celast "github.com/google/cel-go/common/ast"
celoperators "github.com/google/cel-go/common/operators"
celoverloads "github.com/google/cel-go/common/overloads"
@@ -555,13 +554,9 @@ func getDatabaseMetadataFilter(filter string) (*metadataFilter, error) {
return nil, nil
}
- e, err := cel.NewEnv()
+ ast, err := common.ParseCELFilter(filter)
if err != nil {
- return nil, connect.NewError(connect.CodeInternal, errors.Errorf("failed to create cel env"))
- }
- ast, iss := e.Parse(filter)
- if iss != nil {
- return nil, connect.NewError(connect.CodeInvalidArgument, errors.Errorf("failed to parse filter %v, error: %v", filter, iss.String()))
+ return nil, connect.NewError(connect.CodeInvalidArgument, err)
}
var getFilter func(expr celast.Expr) error
diff --git a/backend/api/v1/database_service_test.go b/backend/api/v1/database_service_test.go
index 7807b4b59c..23bd82644e 100644
--- a/backend/api/v1/database_service_test.go
+++ b/backend/api/v1/database_service_test.go
@@ -232,6 +232,13 @@ func TestGetDatabaseMetadataFilter(t *testing.T) {
}
}
+func TestGetDatabaseMetadataFilterRedactsSyntaxError(t *testing.T) {
+ _, err := getDatabaseMetadataFilter(`table == "sensitive SQL" &&`)
+ require.Equal(t, connect.CodeInvalidArgument, connect.CodeOf(err))
+ require.ErrorContains(t, err, "invalid filter expression")
+ require.NotContains(t, err.Error(), "sensitive SQL")
+}
+
func ptrValue[T any](v T) *T {
return &v
}
diff --git a/backend/api/v1/instance_service.go b/backend/api/v1/instance_service.go
index b7c8325d4a..e0ff71e6af 100644
--- a/backend/api/v1/instance_service.go
+++ b/backend/api/v1/instance_service.go
@@ -15,7 +15,6 @@ import (
"time"
"connectrpc.com/connect"
- "github.com/google/cel-go/cel"
celast "github.com/google/cel-go/common/ast"
celoperators "github.com/google/cel-go/common/operators"
"github.com/pkg/errors"
@@ -279,13 +278,9 @@ func validateProjectInstanceListFilter(parentProjectID *string, filter string) e
if parentProjectID == nil || filter == "" {
return nil
}
- env, err := cel.NewEnv()
+ ast, err := common.ParseCELFilter(filter)
if err != nil {
- return errors.Wrap(err, "failed to create CEL environment")
- }
- ast, issues := env.Parse(filter)
- if issues != nil {
- return errors.Errorf("failed to parse filter %q", filter)
+ return err
}
var validate func(celast.Expr) error
diff --git a/backend/api/v1/issue_service.go b/backend/api/v1/issue_service.go
index c07dbbdaca..ef45a8bcfb 100644
--- a/backend/api/v1/issue_service.go
+++ b/backend/api/v1/issue_service.go
@@ -94,13 +94,9 @@ func (s *IssueService) getIssueFind(
return issueFind, nil, nil
}
- e, err := cel.NewEnv()
+ ast, err := common.ParseCELFilter(filter)
if err != nil {
- return nil, nil, connect.NewError(connect.CodeInternal, errors.Errorf("failed to create cel env"))
- }
- ast, iss := e.Parse(filter)
- if iss != nil {
- return nil, nil, connect.NewError(connect.CodeInvalidArgument, errors.Errorf("failed to parse filter %v, error: %v", filter, iss.String()))
+ return nil, nil, connect.NewError(connect.CodeInvalidArgument, err)
}
var approver *store.UserMessage
diff --git a/backend/api/v1/release_service.go b/backend/api/v1/release_service.go
index 58540ed82f..79349a710c 100644
--- a/backend/api/v1/release_service.go
+++ b/backend/api/v1/release_service.go
@@ -9,7 +9,6 @@ import (
"time"
"connectrpc.com/connect"
- "github.com/google/cel-go/cel"
celast "github.com/google/cel-go/common/ast"
celoperators "github.com/google/cel-go/common/operators"
"github.com/pkg/errors"
@@ -466,14 +465,9 @@ func parseCategoryFilter(filter string) (string, error) {
return "", nil
}
- e, err := cel.NewEnv()
+ ast, err := common.ParseCELFilter(filter)
if err != nil {
- return "", errors.Wrap(err, "failed to create CEL environment")
- }
-
- ast, iss := e.Parse(filter)
- if iss != nil {
- return "", errors.Errorf("failed to parse filter: %v", iss.String())
+ return "", err
}
category, err := extractCategoryFromExpr(ast.NativeRep().Expr())
diff --git a/backend/api/v1/sql_service.go b/backend/api/v1/sql_service.go
index 3705c102c4..c6701cadfe 100644
--- a/backend/api/v1/sql_service.go
+++ b/backend/api/v1/sql_service.go
@@ -191,7 +191,7 @@ func buildExportQueryContext(restriction *store.EffectiveQueryDataPolicy, userEm
}
// preCheckAccess returns the user's most capable active access grant matching
-// the given query, or nil if none. When `requireExport` is true the CEL
+// the given query, or nil if none. When `requireExport` is true the SQL
// filter is narrowed to grants with `export == true`, so an unmask-only
// grant on the same statement can't shadow a separately-active export
// grant via slice-order ties (see PR #20491 review).
@@ -221,36 +221,27 @@ func (s *SQLService) preCheckAccess(ctx context.Context, statement string, insta
return nil
}
- databaseFullName := formatDatabaseResourceName(instance, database)
- now := time.Now().UTC().Format(time.RFC3339)
-
- filter := fmt.Sprintf(
- `status == "ACTIVE" && target == %q && expire_time > %q && query == %q`,
- databaseFullName,
- now,
- strings.TrimSpace(statement),
- )
- if requireExport {
- filter += ` && export == true`
- }
- filterQ, err := store.GetListAccessGrantFilter(filter)
- if err != nil {
- slog.Warn("failed to build access grant filter", log.BBError(err))
- return nil
+ requestSchema := ""
+ if schema != nil {
+ requestSchema = *schema
}
-
- grants, err := s.store.ListAccessGrants(ctx, &store.FindAccessGrantMessage{
- Workspace: common.GetWorkspaceIDFromContext(ctx),
- ProjectID: &database.ProjectID,
- Creator: &user.Email,
- FilterQ: filterQ,
+ grants, err := s.store.ListActiveAccessGrants(ctx, &store.FindActiveAccessGrantMessage{
+ Workspace: common.GetWorkspaceIDFromContext(ctx),
+ ProjectID: database.ProjectID,
+ Creator: user.Email,
+ Target: formatDatabaseResourceName(instance, database),
+ Statement: strings.Trim(statement, " \t\n\r\v\f"),
+ Schema: requestSchema,
+ Container: container,
+ RequireExport: requireExport,
+ ExpireTime: time.Now().UTC(),
})
if err != nil {
- slog.Warn("failed to list access grants", log.BBError(err))
+ slog.Warn("failed to find active access grant", log.BBError(err))
return nil
}
-
- if len(grants) == 0 {
+ grant := selectBestAccessGrant(grants)
+ if grant == nil {
return nil
}
readOnly, err := isReadOnlyStatementForAccessGrant(ctx, instance.Metadata.GetEngine(), statement)
@@ -262,13 +253,7 @@ func (s *SQLService) preCheckAccess(ctx context.Context, statement string, insta
slog.Warn("skip access grant for non-read-only query", slog.String("instance", instance.ResourceID), slog.String("database", database.DatabaseName))
return nil
}
- matchingGrants := make([]*store.AccessGrantMessage, 0, len(grants))
- for _, grant := range grants {
- if accessGrantMatchesExecutionContext(grant, schema, container) {
- matchingGrants = append(matchingGrants, grant)
- }
- }
- return selectBestAccessGrant(matchingGrants)
+ return grant
}
// selectBestAccessGrant picks the highest-ranked grant by capability count
@@ -289,8 +274,8 @@ func selectBestAccessGrant(grants []*store.AccessGrantMessage) *store.AccessGran
}
// Rank by Unmask only — Export plays no role in selection:
//
- // - Export callers pass `requireExport=true`, which pushes
- // `&& export == true` into the CEL filter, so every grant in
+ // - Export callers pass `requireExport=true`, which adds
+ // `export == true` to the SQL filter, so every grant in
// this slice already has `Export=true` and a per-grant Export
// bump would just be a uniform constant.
// - Query callers don't read `Payload.Export` from the returned
@@ -312,17 +297,6 @@ func selectBestAccessGrant(grants []*store.AccessGrantMessage) *store.AccessGran
return best
}
-func accessGrantMatchesExecutionContext(grant *store.AccessGrantMessage, schema *string, container string) bool {
- if grant.Payload == nil {
- return false
- }
- requestSchema := ""
- if schema != nil {
- requestSchema = *schema
- }
- return grant.Payload.Schema == requestSchema && grant.Payload.Container == container
-}
-
func (s *SQLService) Query(ctx context.Context, req *connect.Request[v1pb.QueryRequest]) (*connect.Response[v1pb.QueryResponse], error) {
request := req.Msg
// Prepare related message.
diff --git a/backend/common/cel_filter.go b/backend/common/cel_filter.go
new file mode 100644
index 0000000000..5b566ce568
--- /dev/null
+++ b/backend/common/cel_filter.go
@@ -0,0 +1,27 @@
+package common
+
+import (
+ "unicode/utf8"
+
+ "github.com/google/cel-go/cel"
+ "github.com/pkg/errors"
+)
+
+const MaxCELFilterCodePoints = 100_000
+
+// ParseCELFilter parses a bounded CEL list filter without exposing its content in errors.
+func ParseCELFilter(filter string) (*cel.Ast, error) {
+ if utf8.RuneCountInString(filter) > MaxCELFilterCodePoints {
+ return nil, errors.New("filter exceeds the maximum supported size of 100000 code points")
+ }
+
+ env, err := cel.NewEnv(cel.ParserExpressionSizeLimit(MaxCELFilterCodePoints))
+ if err != nil {
+ return nil, errors.Wrap(err, "failed to create CEL environment")
+ }
+ ast, issues := env.Parse(filter)
+ if issues != nil && issues.Err() != nil {
+ return nil, errors.New("invalid filter expression")
+ }
+ return ast, nil
+}
diff --git a/backend/common/cel_filter_test.go b/backend/common/cel_filter_test.go
new file mode 100644
index 0000000000..5c3bc17702
--- /dev/null
+++ b/backend/common/cel_filter_test.go
@@ -0,0 +1,20 @@
+package common
+
+import (
+ "strings"
+ "testing"
+
+ "github.com/stretchr/testify/require"
+)
+
+func TestParseCELFilterRejectsOversizedInputWithoutEchoingIt(t *testing.T) {
+ filter := `query == "` + strings.Repeat("sensitive", MaxCELFilterCodePoints) + `"`
+ _, err := ParseCELFilter(filter)
+ require.EqualError(t, err, "filter exceeds the maximum supported size of 100000 code points")
+ require.NotContains(t, err.Error(), "sensitive")
+}
+
+func TestParseCELFilterRedactsSyntaxError(t *testing.T) {
+ _, err := ParseCELFilter(`query == "sensitive SQL" &&`)
+ require.EqualError(t, err, "invalid filter expression")
+}
diff --git a/backend/store/access_grant.go b/backend/store/access_grant.go
index 0cb0a93ff2..052bf33da5 100644
--- a/backend/store/access_grant.go
+++ b/backend/store/access_grant.go
@@ -6,7 +6,6 @@ import (
"strings"
"time"
- "github.com/google/cel-go/cel"
celast "github.com/google/cel-go/common/ast"
celoperators "github.com/google/cel-go/common/operators"
celoverloads "github.com/google/cel-go/common/overloads"
@@ -50,6 +49,21 @@ type FindAccessGrantMessage struct {
OrderByKeys []*OrderByKey
}
+// FindActiveAccessGrantMessage scopes a statement-bound JIT grant lookup.
+// It deliberately uses structured fields rather than a CEL filter so a large
+// statement can be passed directly to PostgreSQL as a parameter.
+type FindActiveAccessGrantMessage struct {
+ Workspace string
+ ProjectID string
+ Creator string
+ Target string
+ Statement string
+ Schema string
+ Container string
+ ExpireTime time.Time
+ RequireExport bool
+}
+
// UpdateAccessGrantMessage is the message for updating an access grant.
type UpdateAccessGrantMessage struct {
Status *storepb.AccessGrant_Status
@@ -202,6 +216,33 @@ func (s *Store) ListAccessGrants(ctx context.Context, find *FindAccessGrantMessa
return grants, nil
}
+func getActiveAccessGrantFilter(find *FindActiveAccessGrantMessage) *qb.Query {
+ q := qb.Q().
+ And("access_grant.status = ?", storepb.AccessGrant_ACTIVE.String()).
+ And("access_grant.expire_time > ?", find.ExpireTime).
+ And("access_grant.payload->'targets' @> jsonb_build_array(to_jsonb(?::text))", find.Target).
+ And("btrim(access_grant.payload->>'query', E' \\t\\n\\r\\v\\f') = ?", find.Statement).
+ And("COALESCE(access_grant.payload->>'schema', '') = ?", find.Schema).
+ And("COALESCE(access_grant.payload->>'container', '') = ?", find.Container)
+ if find.RequireExport {
+ q.And("COALESCE((access_grant.payload->>'export')::boolean, false) = true")
+ }
+ return q
+}
+
+// ListActiveAccessGrants returns active, unexpired grants matching one caller,
+// target, statement, and execution context.
+func (s *Store) ListActiveAccessGrants(ctx context.Context, find *FindActiveAccessGrantMessage) ([]*AccessGrantMessage, error) {
+ filterQ := getActiveAccessGrantFilter(find)
+
+ return s.ListAccessGrants(ctx, &FindAccessGrantMessage{
+ Workspace: find.Workspace,
+ ProjectID: &find.ProjectID,
+ Creator: &find.Creator,
+ FilterQ: filterQ,
+ })
+}
+
// UpdateAccessGrant updates an existing access grant.
func (s *Store) UpdateAccessGrant(ctx context.Context, id string, update *UpdateAccessGrantMessage) (*AccessGrantMessage, error) {
set := qb.Q()
@@ -299,13 +340,9 @@ func GetListAccessGrantFilter(filter string) (*qb.Query, error) {
return nil, nil
}
- e, err := cel.NewEnv()
+ ast, err := common.ParseCELFilter(filter)
if err != nil {
- return nil, errors.Errorf("failed to create cel env")
- }
- ast, iss := e.Parse(filter)
- if iss != nil {
- return nil, errors.Errorf("failed to parse filter %v, error: %v", filter, iss.String())
+ return nil, err
}
var getFilter func(expr celast.Expr) (*qb.Query, error)
diff --git a/backend/store/access_grant_filter_test.go b/backend/store/access_grant_filter_test.go
index 49f8364814..87881f0b81 100644
--- a/backend/store/access_grant_filter_test.go
+++ b/backend/store/access_grant_filter_test.go
@@ -2,10 +2,30 @@ package store
import (
"testing"
+ "time"
"github.com/stretchr/testify/require"
)
+func TestGetActiveAccessGrantFilter(t *testing.T) {
+ expireTime := time.Date(2026, time.September, 3, 0, 0, 0, 0, time.UTC)
+ q := getActiveAccessGrantFilter(&FindActiveAccessGrantMessage{
+ Target: "instances/prod/databases/app",
+ Statement: "SELECT 1",
+ Schema: "public",
+ Container: "orders",
+ ExpireTime: expireTime,
+ })
+
+ sql, args, err := q.ToSQL()
+ require.NoError(t, err)
+ require.Contains(t, sql, "access_grant.payload->'targets' @> jsonb_build_array(to_jsonb($3::text))")
+ require.Contains(t, sql, "btrim(access_grant.payload->>'query', E' \\t\\n\\r\\v\\f') = $4")
+ require.Contains(t, sql, "COALESCE(access_grant.payload->>'schema', '') = $5")
+ require.Contains(t, sql, "COALESCE(access_grant.payload->>'container', '') = $6")
+ require.Equal(t, []any{"ACTIVE", expireTime, "instances/prod/databases/app", "SELECT 1", "public", "orders"}, args)
+}
+
func TestGetListAccessGrantFilter(t *testing.T) {
tests := []struct {
name string
diff --git a/backend/store/account_filter.go b/backend/store/account_filter.go
index da2ca5900d..f5617c7c73 100644
--- a/backend/store/account_filter.go
+++ b/backend/store/account_filter.go
@@ -3,7 +3,6 @@ package store
import (
"strings"
- "github.com/google/cel-go/cel"
celast "github.com/google/cel-go/common/ast"
celoperators "github.com/google/cel-go/common/operators"
celoverloads "github.com/google/cel-go/common/overloads"
@@ -26,13 +25,9 @@ func GetAccountListFilter(filter string) (*AccountListFilter, error) {
return &AccountListFilter{}, nil
}
- e, err := cel.NewEnv()
+ ast, err := common.ParseCELFilter(filter)
if err != nil {
- return nil, errors.Errorf("failed to create cel env")
- }
- ast, iss := e.Parse(filter)
- if iss != nil {
- return nil, errors.Errorf("failed to parse filter %v, error: %v", filter, iss.String())
+ return nil, err
}
var getFilter func(expr celast.Expr) (*qb.Query, error)
diff --git a/backend/store/account_filter_test.go b/backend/store/account_filter_test.go
index bc2f1f61b0..65fd8d2ced 100644
--- a/backend/store/account_filter_test.go
+++ b/backend/store/account_filter_test.go
@@ -104,7 +104,7 @@ func TestGetAccountListFilter(t *testing.T) {
name: "invalid filter syntax",
filter: `invalid syntax {{`,
wantErr: true,
- errContains: "failed to parse filter",
+ errContains: "invalid filter expression",
},
{
name: "invalid state",
diff --git a/backend/store/audit_log.go b/backend/store/audit_log.go
index da396dc712..0afb2f0c32 100644
--- a/backend/store/audit_log.go
+++ b/backend/store/audit_log.go
@@ -6,7 +6,6 @@ import (
"strings"
"time"
- "github.com/google/cel-go/cel"
celast "github.com/google/cel-go/common/ast"
celoperators "github.com/google/cel-go/common/operators"
"github.com/pkg/errors"
@@ -184,13 +183,9 @@ func GetSearchAuditLogsFilter(filter string) (*qb.Query, error) {
return nil, nil
}
- e, err := cel.NewEnv()
+ ast, err := common.ParseCELFilter(filter)
if err != nil {
- return nil, errors.New("failed to create cel env")
- }
- ast, iss := e.Parse(filter)
- if iss != nil {
- return nil, errors.Errorf("failed to parse filter %v, error: %v", filter, iss.String())
+ return nil, err
}
var getFilter func(expr celast.Expr) (*qb.Query, error)
diff --git a/backend/store/audit_log_filter_test.go b/backend/store/audit_log_filter_test.go
index fdcccc1629..1f767de7e1 100644
--- a/backend/store/audit_log_filter_test.go
+++ b/backend/store/audit_log_filter_test.go
@@ -114,7 +114,7 @@ func TestGetSearchAuditLogsFilter_WithoutUserLookup(t *testing.T) {
name: "invalid filter syntax",
filter: `invalid syntax {{`,
wantErr: true,
- errContains: "failed to parse filter",
+ errContains: "invalid filter expression",
},
{
name: "unsupported variable",
diff --git a/backend/store/database.go b/backend/store/database.go
index c1567d449c..c6d0c8b309 100644
--- a/backend/store/database.go
+++ b/backend/store/database.go
@@ -7,7 +7,6 @@ import (
"slices"
"strings"
- "github.com/google/cel-go/cel"
celast "github.com/google/cel-go/common/ast"
celoperators "github.com/google/cel-go/common/operators"
celoverloads "github.com/google/cel-go/common/overloads"
@@ -711,13 +710,9 @@ func GetListDatabaseFilter(workspace, filter string) (*qb.Query, error) {
return nil, nil
}
- e, err := cel.NewEnv()
+ ast, err := common.ParseCELFilter(filter)
if err != nil {
- return nil, errors.Errorf("failed to create cel env")
- }
- ast, iss := e.Parse(filter)
- if iss != nil {
- return nil, errors.Errorf("failed to parse filter %v, error: %v", filter, iss.String())
+ return nil, err
}
var getFilter func(expr celast.Expr) (*qb.Query, error)
diff --git a/backend/store/group.go b/backend/store/group.go
index 8952b1d762..c0a0db5b19 100644
--- a/backend/store/group.go
+++ b/backend/store/group.go
@@ -6,7 +6,6 @@ import (
"fmt"
"strings"
- "github.com/google/cel-go/cel"
celast "github.com/google/cel-go/common/ast"
celoperators "github.com/google/cel-go/common/operators"
celoverloads "github.com/google/cel-go/common/overloads"
@@ -476,13 +475,9 @@ func GetListGroupFilter(find *FindGroupMessage, filter string) (*qb.Query, error
return nil, nil
}
- e, err := cel.NewEnv()
+ ast, err := common.ParseCELFilter(filter)
if err != nil {
- return nil, errors.New("failed to create cel env")
- }
- ast, iss := e.Parse(filter)
- if iss != nil {
- return nil, errors.Errorf("failed to parse filter %v, error: %v", filter, iss.String())
+ return nil, err
}
var getFilter func(expr celast.Expr) (*qb.Query, error)
diff --git a/backend/store/group_filter_test.go b/backend/store/group_filter_test.go
index 2852447cb8..748a10094b 100644
--- a/backend/store/group_filter_test.go
+++ b/backend/store/group_filter_test.go
@@ -77,7 +77,7 @@ func TestGetListGroupFilter(t *testing.T) {
name: "invalid filter syntax",
filter: `invalid syntax {{`,
wantErr: true,
- errContains: "failed to parse filter",
+ errContains: "invalid filter expression",
},
{
name: "unsupported variable",
diff --git a/backend/store/instance.go b/backend/store/instance.go
index 70895645ae..8e769d0e36 100644
--- a/backend/store/instance.go
+++ b/backend/store/instance.go
@@ -7,7 +7,6 @@ import (
"slices"
"strings"
- "github.com/google/cel-go/cel"
celast "github.com/google/cel-go/common/ast"
celoperators "github.com/google/cel-go/common/operators"
celoverloads "github.com/google/cel-go/common/overloads"
@@ -993,13 +992,9 @@ func GetListInstanceFilter(filter string) (*qb.Query, error) {
return nil, nil
}
- e, err := cel.NewEnv()
+ ast, err := common.ParseCELFilter(filter)
if err != nil {
- return nil, errors.Errorf("failed to create cel env")
- }
- ast, iss := e.Parse(filter)
- if iss != nil {
- return nil, errors.Errorf("failed to parse filter %v, error: %v", filter, iss.String())
+ return nil, err
}
var getFilter func(expr celast.Expr) (*qb.Query, error)
diff --git a/backend/store/plan.go b/backend/store/plan.go
index d0507021f3..8071190a99 100644
--- a/backend/store/plan.go
+++ b/backend/store/plan.go
@@ -6,7 +6,6 @@ import (
"strings"
"time"
- "github.com/google/cel-go/cel"
celast "github.com/google/cel-go/common/ast"
celoperators "github.com/google/cel-go/common/operators"
celoverloads "github.com/google/cel-go/common/overloads"
@@ -249,13 +248,9 @@ func GetListPlanFilter(filter string) (*qb.Query, error) {
return nil, nil
}
- e, err := cel.NewEnv()
+ ast, err := common.ParseCELFilter(filter)
if err != nil {
- return nil, errors.Errorf("failed to create cel env")
- }
- ast, iss := e.Parse(filter)
- if iss != nil {
- return nil, errors.Errorf("failed to parse filter %v, error: %v", filter, iss.String())
+ return nil, err
}
var getFilter func(expr celast.Expr) (*qb.Query, error)
diff --git a/backend/store/plan_filter_test.go b/backend/store/plan_filter_test.go
index e561d60d85..3fdebc0edd 100644
--- a/backend/store/plan_filter_test.go
+++ b/backend/store/plan_filter_test.go
@@ -136,7 +136,7 @@ func TestGetListPlanFilter(t *testing.T) {
name: "invalid filter syntax",
filter: `invalid syntax {{`,
wantErr: true,
- errContains: "failed to parse filter",
+ errContains: "invalid filter expression",
},
{
name: "unsupported variable",
diff --git a/backend/store/project.go b/backend/store/project.go
index cc7378cca9..925a40b286 100644
--- a/backend/store/project.go
+++ b/backend/store/project.go
@@ -7,7 +7,6 @@ import (
"slices"
"strings"
- "github.com/google/cel-go/cel"
celast "github.com/google/cel-go/common/ast"
celoperators "github.com/google/cel-go/common/operators"
celoverloads "github.com/google/cel-go/common/overloads"
@@ -745,13 +744,9 @@ func GetListProjectFilter(workspace, filter string) (*qb.Query, error) {
return nil, nil
}
- e, err := cel.NewEnv()
+ ast, err := common.ParseCELFilter(filter)
if err != nil {
- return nil, errors.Errorf("failed to create cel env")
- }
- ast, iss := e.Parse(filter)
- if iss != nil {
- return nil, errors.Errorf("failed to parse filter %v, error: %v", filter, iss.String())
+ return nil, err
}
var getFilter func(expr celast.Expr) (*qb.Query, error)
diff --git a/backend/store/project_filter_test.go b/backend/store/project_filter_test.go
index e999bf19ec..bc18296908 100644
--- a/backend/store/project_filter_test.go
+++ b/backend/store/project_filter_test.go
@@ -117,7 +117,7 @@ func TestGetListProjectFilter(t *testing.T) {
name: "invalid filter syntax",
filter: `invalid syntax {{`,
wantErr: true,
- errContains: "failed to parse filter",
+ errContains: "invalid filter expression",
},
{
name: "unsupported variable",
diff --git a/backend/store/query_history.go b/backend/store/query_history.go
index fa210bd150..4731add5de 100644
--- a/backend/store/query_history.go
+++ b/backend/store/query_history.go
@@ -6,7 +6,6 @@ import (
"strings"
"time"
- "github.com/google/cel-go/cel"
celast "github.com/google/cel-go/common/ast"
celoperators "github.com/google/cel-go/common/operators"
celoverloads "github.com/google/cel-go/common/overloads"
@@ -228,13 +227,9 @@ func GetListQueryHistoryFilter(filter string) (*qb.Query, error) {
return nil, nil
}
- e, err := cel.NewEnv()
+ ast, err := common.ParseCELFilter(filter)
if err != nil {
- return nil, errors.Errorf("failed to create cel env")
- }
- ast, iss := e.Parse(filter)
- if iss != nil {
- return nil, errors.Errorf("failed to parse filter %v, error: %v", filter, iss.String())
+ return nil, err
}
var getFilter func(expr celast.Expr) (*qb.Query, error)
@@ -347,13 +342,9 @@ func GetListQueryHistoriesCreatorFilter(filter string) (*string, error) {
return nil, nil
}
- e, err := cel.NewEnv()
+ ast, err := common.ParseCELFilter(filter)
if err != nil {
- return nil, errors.Errorf("failed to create cel env")
- }
- ast, iss := e.Parse(filter)
- if iss != nil {
- return nil, errors.Errorf("failed to parse filter %v, error: %v", filter, iss.String())
+ return nil, err
}
expr := ast.NativeRep().Expr()
diff --git a/backend/store/query_history_filter_test.go b/backend/store/query_history_filter_test.go
index 886811a941..90f61d3078 100644
--- a/backend/store/query_history_filter_test.go
+++ b/backend/store/query_history_filter_test.go
@@ -124,7 +124,7 @@ func TestGetListQueryHistoryFilter(t *testing.T) {
name: "invalid filter syntax",
filter: `invalid syntax {{`,
wantErr: true,
- errContains: "failed to parse filter",
+ errContains: "invalid filter expression",
},
{
name: "unsupported variable",
@@ -385,7 +385,7 @@ func TestGetListQueryHistoriesCreatorFilter(t *testing.T) {
{
name: "invalid CEL",
filter: `creator ==`,
- errContains: "failed to parse filter",
+ errContains: "invalid filter expression",
},
}
diff --git a/backend/store/rollout_filter.go b/backend/store/rollout_filter.go
index 152ec30a35..7bd11c83c0 100644
--- a/backend/store/rollout_filter.go
+++ b/backend/store/rollout_filter.go
@@ -3,11 +3,11 @@ package store
import (
"time"
- "github.com/google/cel-go/cel"
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"
"github.com/bytebase/bytebase/backend/common/qb"
storepb "github.com/bytebase/bytebase/backend/generated-go/store"
v1pb "github.com/bytebase/bytebase/backend/generated-go/v1"
@@ -19,13 +19,9 @@ func GetListRolloutFilter(filter string) (*qb.Query, error) {
return nil, nil
}
- e, err := cel.NewEnv()
+ ast, err := common.ParseCELFilter(filter)
if err != nil {
- return nil, errors.Errorf("failed to create cel env")
- }
- ast, iss := e.Parse(filter)
- if iss != nil {
- return nil, errors.Errorf("failed to parse filter %v, error: %v", filter, iss.String())
+ return nil, err
}
var getFilter func(expr celast.Expr) (*qb.Query, error)
diff --git a/backend/store/rollout_filter_test.go b/backend/store/rollout_filter_test.go
index 5cc5c8e753..7fbce0e100 100644
--- a/backend/store/rollout_filter_test.go
+++ b/backend/store/rollout_filter_test.go
@@ -83,7 +83,7 @@ func TestGetListRolloutFilter(t *testing.T) {
name: "invalid filter syntax",
filter: `invalid syntax {{`,
wantErr: true,
- errContains: "failed to parse filter",
+ errContains: "invalid filter expression",
},
{
name: "unsupported variable",
diff --git a/backend/store/saved_query.go b/backend/store/saved_query.go
index 78c93ff5ee..1fb6823c2d 100644
--- a/backend/store/saved_query.go
+++ b/backend/store/saved_query.go
@@ -10,7 +10,6 @@ import (
"strings"
"time"
- "github.com/google/cel-go/cel"
celast "github.com/google/cel-go/common/ast"
celoperators "github.com/google/cel-go/common/operators"
celoverloads "github.com/google/cel-go/common/overloads"
@@ -689,13 +688,9 @@ func GetSearchSavedQueryFilter(ctx context.Context, s *Store, caller string, acc
return nil, nil
}
- e, err := cel.NewEnv()
+ ast, err := common.ParseCELFilter(filter)
if err != nil {
- return nil, errors.New("failed to create cel env")
- }
- ast, iss := e.Parse(filter)
- if iss != nil {
- return nil, errors.Errorf("failed to parse filter %v, error: %v", filter, iss.String())
+ return nil, err
}
var getFilter func(expr celast.Expr) (*qb.Query, error)
@@ -914,13 +909,9 @@ func GetListSavedQueryFilter(filter string) (*qb.Query, error) {
return nil, nil
}
- e, err := cel.NewEnv()
+ ast, err := common.ParseCELFilter(filter)
if err != nil {
- return nil, errors.New("failed to create cel env")
- }
- ast, iss := e.Parse(filter)
- if iss != nil {
- return nil, errors.Errorf("failed to parse filter %v, error: %v", filter, iss.String())
+ return nil, err
}
var getFilter func(expr celast.Expr) (*qb.Query, error)
diff --git a/frontend/src/modules/sql-editor/components/AccessGrantItem.test.tsx b/frontend/src/modules/sql-editor/components/AccessGrantItem.test.tsx
index fec2122719..6346bfd7ed 100644
--- a/frontend/src/modules/sql-editor/components/AccessGrantItem.test.tsx
+++ b/frontend/src/modules/sql-editor/components/AccessGrantItem.test.tsx
@@ -217,6 +217,25 @@ describe("AccessGrantItem", () => {
unmount();
});
+ test("constrains an unbroken long query within the panel", () => {
+ const { container, render, unmount } = renderIntoContainer(
+ <AccessGrantItem
+ grant={makeGrant({ query: "x".repeat(100_000) }) as never}
+ onRun={vi.fn()}
+ onRequest={vi.fn()}
+ />
+ );
+ render();
+
+ expect(container.firstElementChild?.className).toContain("min-w-0");
+ const query = container.querySelector("p");
+ expect(query?.className).toContain("w-full");
+ expect(query?.className).toContain("min-w-0");
+ expect(query?.className).toContain("wrap-anywhere");
+ expect(query?.className).toContain("line-clamp-2");
+ unmount();
+ });
+
test("Run button shows only for ACTIVE status", () => {
mocks.getAccessGrantDisplayStatus.mockReturnValue("ACTIVE");
const grant = makeGrant();
diff --git a/frontend/src/modules/sql-editor/components/AccessGrantItem.tsx b/frontend/src/modules/sql-editor/components/AccessGrantItem.tsx
index 7fb5e36a94..613fbbf32c 100644
--- a/frontend/src/modules/sql-editor/components/AccessGrantItem.tsx
+++ b/frontend/src/modules/sql-editor/components/AccessGrantItem.tsx
@@ -100,7 +100,7 @@ export function AccessGrantItem({
return (
<div
className={cn(
- "w-full p-2 gap-y-2 border-b flex flex-col justify-start items-start hover:bg-control-bg",
+ "w-full min-w-0 p-2 gap-y-2 border-b flex flex-col justify-start items-start hover:bg-control-bg",
highlight
? "bb-access-grant-highlight"
: "transition-colors duration-1000"
@@ -159,7 +159,7 @@ export function AccessGrantItem({
>
<p
className={cn(
- "max-w-full text-xs wrap-break-word whitespace-pre-wrap font-mono line-clamp-2",
+ "w-full min-w-0 text-xs wrap-anywhere whitespace-pre-wrap font-mono line-clamp-2",
(isExpired || isRejectedOrCanceled) &&
"line-through text-control-placeholder"
)}
diff --git a/frontend/src/modules/sql-editor/components/useExportGrantBypass.tsx b/frontend/src/modules/sql-editor/components/useExportGrantBypass.tsx
index 8e7c041852..f621132dc5 100644
--- a/frontend/src/modules/sql-editor/components/useExportGrantBypass.tsx
+++ b/frontend/src/modules/sql-editor/components/useExportGrantBypass.tsx
@@ -2,6 +2,8 @@ import { type ReactNode, useEffect, useMemo, useState } from "react";
import { useTranslation } from "react-i18next";
import { RouterLink } from "@/components/RouterLink";
import { useAppStore } from "@/stores/app";
+import { isAccessGrantFilterWithinCELLimit } from "@/stores/app/accessGrant";
+import type { AccessGrantFilter } from "@/stores/app/types";
import type { AccessGrant } from "@/types/proto-es/v1/access_grant_service_pb";
interface UseExportGrantBypassArgs {
@@ -16,7 +18,7 @@ interface UseExportGrantBypassArgs {
* The hook is a no-op when this is empty / undefined.
*/
project: string | undefined;
- /** Exact statement to match against grant.payload.query. */
+ /** Statement to match against grant.payload.query. */
statement: string;
/**
* Queried target database resource names. Single-element OK —
@@ -25,6 +27,7 @@ interface UseExportGrantBypassArgs {
*
* Internally the hook fires one `searchMyAccessGrants` call per
* target in parallel (each with `target == "x"` and `pageSize: 1`).
+ * Oversized CEL filters are not sent.
* The fan-out shape is correct by construction: a single multi-
* target `target in [...]` query with a row-limit could cluster all
* results on one target and silently hide coverage for the others.
@@ -145,14 +148,18 @@ export function useExportGrantBypass({
const chunkResults = await Promise.all(
chunk.map(async (target) => {
try {
+ const filter: AccessGrantFilter = {
+ statementExact: statement,
+ status: ["ACTIVE"],
+ export: true,
+ target,
+ };
+ if (!isAccessGrantFilterWithinCELLimit(filter)) {
+ return { target, grant: undefined as AccessGrant | undefined };
+ }
const res = await searchMyAccessGrants({
parent: project,
- filter: {
- statementExact: statement,
- status: ["ACTIVE"],
- export: true,
- target,
- },
+ filter,
pageSize: 1,
});
return { target, grant: res.accessGrants[0] };
diff --git a/frontend/src/routes/project/issue-detail/components/IssueDetailAccessGrantDetails.test.tsx b/frontend/src/routes/project/issue-detail/components/IssueDetailAccessGrantDetails.test.tsx
index 6a43dc849d..7853fb4943 100644
--- a/frontend/src/routes/project/issue-detail/components/IssueDetailAccessGrantDetails.test.tsx
+++ b/frontend/src/routes/project/issue-detail/components/IssueDetailAccessGrantDetails.test.tsx
@@ -100,4 +100,16 @@ describe("IssueDetailAccessGrantDetails", () => {
expect(screen.getByText("common.schema")).toBeInTheDocument();
expect(screen.getByText("issue.access-grant.container")).toBeInTheDocument();
});
+
+ test("wraps an unbroken long statement", async () => {
+ const statement = "x".repeat(100_000);
+ mocks.accessGrant = { ...mocks.accessGrant!, query: statement };
+
+ render(<IssueDetailAccessGrantDetails />);
+
+ const preview = await screen.findByText(statement);
+ expect(preview.tagName).toBe("PRE");
+ expect(preview.className).toContain("whitespace-pre-wrap");
+ expect(preview.className).toContain("wrap-anywhere");
+ });
});
diff --git a/frontend/src/routes/project/issue-detail/components/IssueDetailAccessGrantDetails.tsx b/frontend/src/routes/project/issue-detail/components/IssueDetailAccessGrantDetails.tsx
index dda5a616b0..661dbd4104 100644
--- a/frontend/src/routes/project/issue-detail/components/IssueDetailAccessGrantDetails.tsx
+++ b/frontend/src/routes/project/issue-detail/components/IssueDetailAccessGrantDetails.tsx
@@ -137,7 +137,7 @@ export function IssueDetailAccessGrantDetails() {
{t("common.statement")}
</span>
<div className="max-h-[30em] overflow-auto rounded-xs bg-gray-50 p-4">
- <pre className="whitespace-pre-wrap font-mono text-sm">
+ <pre className="wrap-anywhere whitespace-pre-wrap font-mono text-sm">
{accessGrant.query}
</pre>
</div>
diff --git a/frontend/src/stores/app/accessGrant.test.ts b/frontend/src/stores/app/accessGrant.test.ts
index 87f5c9aebf..2d9c1ff79d 100644
--- a/frontend/src/stores/app/accessGrant.test.ts
+++ b/frontend/src/stores/app/accessGrant.test.ts
@@ -1,5 +1,9 @@
import { describe, expect, test } from "vitest";
-import { buildAccessGrantFilter } from "./accessGrant";
+import {
+ buildAccessGrantFilter,
+ isAccessGrantFilterWithinCELLimit,
+ MAX_CEL_FILTER_CODE_POINTS,
+} from "./accessGrant";
describe("buildAccessGrantFilter", () => {
test("empty filter returns empty string", () => {
@@ -66,12 +70,6 @@ describe("buildAccessGrantFilter", () => {
);
});
- // statementExact pins the distinction from `statement` (substring search)
- // and mirrors the backend JIT authorization predicate `query == "..."`.
- // PR #20491 bot review #3349385091: a substring match like running
- // `SELECT * FROM t` against a grant for `SELECT * FROM t WHERE id = 1`
- // must NOT enable the Export button because the backend exact-match
- // would still deny.
test("statementExact emits exact CEL equality", () => {
expect(buildAccessGrantFilter({ statementExact: "SELECT * FROM t" })).toBe(
`query == "SELECT * FROM t"`
@@ -93,9 +91,6 @@ describe("buildAccessGrantFilter", () => {
});
test("statement and statementExact emit different predicates", () => {
- // Same input: `statement` → substring; `statementExact` → exact.
- // Both must coexist for different UX cases (search box vs.
- // authorization-eligibility check).
expect(buildAccessGrantFilter({ statement: "SELECT 1" })).toBe(
`query.contains("SELECT 1")`
);
@@ -105,9 +100,14 @@ describe("buildAccessGrantFilter", () => {
});
test("empty-string statementExact still emits exact predicate", () => {
- // `statementExact === ""` is a meaningful filter (match grants whose
- // stored query is empty), distinct from `statementExact === undefined`
- // which means "no constraint". Don't conflate them.
expect(buildAccessGrantFilter({ statementExact: "" })).toBe(`query == ""`);
});
+
+ test("does not submit a filter exceeding the CEL code point limit", () => {
+ expect(
+ isAccessGrantFilterWithinCELLimit({
+ statementExact: "x".repeat(MAX_CEL_FILTER_CODE_POINTS),
+ })
+ ).toBe(false);
+ });
});
diff --git a/frontend/src/stores/app/accessGrant.ts b/frontend/src/stores/app/accessGrant.ts
index 70da48e52a..0575dc7ea4 100644
--- a/frontend/src/stores/app/accessGrant.ts
+++ b/frontend/src/stores/app/accessGrant.ts
@@ -16,6 +16,8 @@ import type {
AppSliceCreator,
} from "./types";
+export const MAX_CEL_FILTER_CODE_POINTS = 100_000;
+
export const buildAccessGrantFilter = (
filter: AccessGrantFilter | undefined
): string => {
@@ -66,6 +68,12 @@ export const buildAccessGrantFilter = (
return parts.join(" && ");
};
+export const isAccessGrantFilterWithinCELLimit = (
+ filter: AccessGrantFilter
+): boolean =>
+ Array.from(buildAccessGrantFilter(filter)).length <=
+ MAX_CEL_FILTER_CODE_POINTS;
+
const upsertAccessGrants = (
set: Parameters<AppSliceCreator<AccessGrantSlice>>[0],
accessGrants: AccessGrant[]