Skip to content

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

feat!: split bb.savedQueries.manage into per-verb permissions (#21181)

Danny Xu3813df4890a5
diff --git a/backend/api/mcp/gen/openapi.yaml b/backend/api/mcp/gen/openapi.yaml
index c87d339a09..2f9d8ce261 100644
--- a/backend/api/mcp/gen/openapi.yaml
+++ b/backend/api/mcp/gen/openapi.yaml
@@ -5775,9 +5775,9 @@ paths:
- bytebase.v1.SavedQueryService
summary: CreateSavedQuery
description: |-
- Create a saved query. The creator becomes its fixed owner, and the saved
- query starts private.
- Permissions required: bb.savedQueries.create on the parent project
+ Create a saved query. The creator becomes the owner and the saved query
+ starts private.
+ Permissions required: bb.savedQueries.create on the project
operationId: bytebase.v1.SavedQueryService.CreateSavedQuery
parameters:
- name: Connect-Protocol-Version
@@ -5814,10 +5814,10 @@ paths:
- bytebase.v1.SavedQueryService
summary: DeleteSavedQuery
description: |-
- Delete a saved query and every user's stars on it. An EDITOR binding never
- carries deletion. An unreadable saved query returns NotFound; a grantee
- who can read but not delete gets PermissionDenied.
- Permissions required: creator, or bb.savedQueries.manage
+ Delete a saved query and every user's stars on it. An EDITOR binding
+ cannot delete.
+ Permissions required: bb.savedQueries.delete (creator or project-level
+ grant)
operationId: bytebase.v1.SavedQueryService.DeleteSavedQuery
parameters:
- name: Connect-Protocol-Version
@@ -5854,9 +5854,9 @@ paths:
- bytebase.v1.SavedQueryService
summary: GetSavedQuery
description: |-
- Get a saved query with its full content. An unreadable saved query returns
- NotFound rather than PermissionDenied, so it stays unprobeable by name.
- Permissions required: creator, a VIEWER or EDITOR binding, or bb.savedQueries.manage
+ Get a saved query with its full content.
+ Permissions required: bb.savedQueries.get (creator, VIEWER/EDITOR
+ binding, or project-level grant)
operationId: bytebase.v1.SavedQueryService.GetSavedQuery
parameters:
- name: Connect-Protocol-Version
@@ -5891,12 +5891,11 @@ paths:
post:
tags:
- bytebase.v1.SavedQueryService
- summary: 'Get a saved query''s sharing policy: who it is shared with, at what level.'
+ summary: GetSavedQueryPolicy
description: |-
- Anyone who can read the saved query can read its policy, which is how a
- grantee learns whether they may edit it. Callers who cannot read the
- saved query get NotFound.
- Permissions required: creator, a VIEWER or EDITOR binding, or bb.savedQueries.manage
+ Get a saved query's sharing policy: who it is shared with, at what level.
+ Permissions required: bb.savedQueries.getIamPolicy (creator, VIEWER/EDITOR
+ binding, or project-level grant)
operationId: bytebase.v1.SavedQueryService.GetSavedQueryPolicy
parameters:
- name: Connect-Protocol-Version
@@ -5933,12 +5932,11 @@ paths:
- bytebase.v1.SavedQueryService
summary: ListSavedQueries
description: |-
- List saved queries for auditing. Bindings are ignored: the permission
- alone reads every matched saved query's content, private ones included.
- Returns whole statements rather than Search's previews, and accepts
- "projects/-" to span every project.
- Permissions required: bb.savedQueries.list on the parent project, or
- workspace-wide when the parent is "projects/-"
+ List saved queries for auditing. The permission alone grants reading
+ every matched saved query with full content, private ones included;
+ bindings are ignored. Use parent "projects/-" for all projects.
+ Permissions required: bb.savedQueries.list on the project, or on the
+ workspace when the parent is "projects/-"
operationId: bytebase.v1.SavedQueryService.ListSavedQueries
parameters:
- name: Connect-Protocol-Version
@@ -5973,14 +5971,13 @@ paths:
post:
tags:
- bytebase.v1.SavedQueryService
- summary: |-
- Move the caller's own saved queries into a folder, named individually or a
- whole folder at a time. Moving a folder carries its descendants, so renaming "a/b" to
- "a/c" also moves "a/b/deep" -- one call, not one per path.
+ summary: MoveMySavedQueries
description: |-
- Filing is personal organization, so only the creator's own move: a folder
- is that person's tree, and neither a binding nor the admin backstop
- reaches into it. The response counts what moved.
+ Move the caller's saved queries filed under `source_folder`, descendants
+ included, into `target_folder`: renaming "a/b" to "a/c" also moves
+ "a/b/deep". Only the caller's own saved queries move; the response counts
+ how many did. Re-filing a single saved query is UpdateSavedQuery's
+ `folder` field.
Permissions required: creator
operationId: bytebase.v1.SavedQueryService.MoveMySavedQueries
parameters:
@@ -6016,15 +6013,10 @@ paths:
post:
tags:
- bytebase.v1.SavedQueryService
- summary: |-
- Search saved queries in one project: the SQL Editor's list path, returning
- content previews.
+ summary: SearchSavedQueries
description: |-
- Caller-scoped, always: the caller's own saved queries plus those a binding
- shares with them. bb.savedQueries.manage does not widen it — an admin
- reading everyone's saved queries uses ListSavedQueries, which is built for
- that. The permission here gates discovery only and grants access to
- nothing by itself.
+ Search saved queries in one project. Returns content previews of the
+ saved queries the caller can read, the same access rule as GetSavedQuery.
Permissions required: bb.savedQueries.search on the project
operationId: bytebase.v1.SavedQueryService.SearchSavedQueries
parameters:
@@ -6060,17 +6052,10 @@ paths:
post:
tags:
- bytebase.v1.SavedQueryService
- summary: |-
- Search the folder paths holding saved queries the caller can read. Folders
- are a derived view over the `folder` field rather than a resource
- collection, so this is a custom method, caller-scoped like
- SearchSavedQueries.
+ summary: SearchSavedQueryFolders
description: |-
- A path is returned when at least one readable saved query sits in it —
- including one somebody else filed and shared, since a client seeds its
- folder tree from here and cannot expand into a folder it never learns
- about. Use the filter to split your own folders (`creator == "users/me"`)
- from the ones reaching you through a grant (`shared == true`).
+ Search folder paths. A path is returned when it holds at least one saved
+ query the caller can read, the same access rule as SearchSavedQueries.
Permissions required: bb.savedQueries.search on the project
operationId: bytebase.v1.SavedQueryService.SearchSavedQueryFolders
parameters:
@@ -6109,9 +6094,9 @@ paths:
summary: SetSavedQueryPolicy
description: |-
Replace a saved query's sharing policy in full. `policy.etag` must match
- the stored policy or the call fails with ABORTED, so a stale write cannot
- reinstate a grant somebody just revoked.
- Permissions required: creator, or bb.savedQueries.manage
+ the stored policy; a mismatch fails with ABORTED.
+ Permissions required: bb.savedQueries.setIamPolicy (creator or
+ project-level grant; no predefined role carries it)
operationId: bytebase.v1.SavedQueryService.SetSavedQueryPolicy
parameters:
- name: Connect-Protocol-Version
@@ -6148,12 +6133,9 @@ paths:
- bytebase.v1.SavedQueryService
summary: UpdateSavedQuery
description: |-
- Update a saved query. `title`, `content`, and `database` need write access;
- `folder` is creator/admin only, because filing is organization rather than
- editing. `database` must belong to the saved query's own project. An
- unreadable saved query returns NotFound; a VIEWER who cannot write gets
- PermissionDenied.
- Permissions required: creator, an EDITOR binding, or bb.savedQueries.manage
+ Update a saved query. `database` must belong to the saved query's project.
+ Permissions required: bb.savedQueries.update (creator, EDITOR binding, or
+ project-level grant)
operationId: bytebase.v1.SavedQueryService.UpdateSavedQuery
parameters:
- name: Connect-Protocol-Version
@@ -6190,11 +6172,12 @@ paths:
- bytebase.v1.SavedQueryService
summary: UpdateSavedQueryStar
description: |-
- Star or unstar a saved query for the caller. Stars are personal: yours are
- invisible to everyone else and grant nothing. You can star any saved query
- you created or have been granted access to; anything else answers
- NotFound, so names stay unprobeable.
- Permissions required: creator, or a VIEWER or EDITOR binding
+ Star or unstar a saved query for the caller. Stars are personal: nobody
+ else sees them and they grant nothing. The caller can star any saved
+ query they can read. When access is lost the star is hidden, not
+ deleted; it comes back if access returns.
+ Permissions required: bb.savedQueries.get (creator, VIEWER/EDITOR
+ binding, or project-level grant)
operationId: bytebase.v1.SavedQueryService.UpdateSavedQueryStar
parameters:
- name: Connect-Protocol-Version
@@ -14550,10 +14533,8 @@ components:
type: string
title: page_token
description: |-
- A page token from a previous ListSavedQueries call. Every other parameter
- must match the call that returned it: the token carries the offset reached
- so far, so changing `filter` or `page_size` mid-pagination reinterprets
- that offset against a different result set.
+ A page token from a previous ListSavedQueries call. Keep every other
+ parameter the same as the call that returned it.
title: ListSavedQueriesRequest
additionalProperties: false
bytebase.v1.ListSavedQueriesResponse:
@@ -15177,26 +15158,19 @@ components:
type: string
title: parent
description: 'Format: projects/{project}'
- names:
- type: array
- items:
- type: string
- title: names
- description: |-
- The saved queries to move. Set this or `source_folder`, not both.
- Format: projects/{project}/savedQueries/{savedQuery}
sourceFolder:
type: string
title: source_folder
maxLength: 256
- description: |-
- Move everything filed under this path, descendants included, e.g. "a/b".
- Set this or `names`, not both.
+ minLength: 1
+ description: The folder to move, descendants included, e.g. "a/b".
targetFolder:
type: string
title: target_folder
maxLength: 256
- description: Where they land. A path like "a/b/c"; empty unfiles them.
+ description: |-
+ Where it lands. A path like "a/b/c"; empty drops the `source_folder`
+ prefix, promoting the folder's contents toward the root.
title: MoveMySavedQueriesRequest
additionalProperties: false
bytebase.v1.MoveMySavedQueriesResponse:
@@ -15206,7 +15180,7 @@ components:
type: integer
title: moved_count
format: int32
- description: How many moved. Fewer than were named when some are not the caller's.
+ description: How many moved.
title: MoveMySavedQueriesResponse
additionalProperties: false
bytebase.v1.OAuth2AuthStyle:
@@ -17796,7 +17770,7 @@ components:
type: string
title: creator
description: |-
- The fixed owner. Ownership does not transfer.
+ The owner. Ownership does not transfer.
Format: users/{email}
createTime:
title: create_time
@@ -17809,8 +17783,8 @@ components:
title: content
format: byte
description: |-
- The SQL text. SearchSavedQueries truncates it; when it is shorter than
- `content_size`, GetSavedQuery returns the whole thing.
+ The SQL text. SearchSavedQueries returns a truncated preview;
+ GetSavedQuery returns the full text.
contentSize:
type:
- integer
@@ -17827,8 +17801,8 @@ components:
title: folder
maxLength: 256
description: |-
- The folder holding this saved query, set by its creator or an admin. A
- path like "a/b/c"; empty means unfiled.
+ The folder holding this saved query. A path like "a/b/c"; empty means
+ unfiled.
title: SavedQuery
additionalProperties: false
bytebase.v1.SavedQueryBinding:
@@ -17844,23 +17818,14 @@ components:
title: members
minItems: 1
description: |-
- The principals granted `level`, in bytebase.v1.Binding.members format,
- restricted to "user:{email}" and "group:{email}" -- prefix-checked, as
- project and workspace IAM check their own members.
+ The members granted `level`: "user:{email}" or "group:{email}" only.
- Service accounts and workload identities are not grantees: they own and
- run their own saved queries and reach them as the creator. Naming one
- under a "user:" prefix grants nothing rather than being rejected, because
- a caller's member is derived from their principal type, so such a binding
- matches nobody.
-
- A group is stored as a reference and never expanded, so its membership
- stays live and a large group costs no more than a small one.
+ Service accounts cannot be grantees — they reach their own saved queries
+ as the creator. Naming one under "user:" grants nothing rather than
+ failing. Groups are stored as references, so membership stays live.
title: SavedQueryBinding
additionalProperties: false
- description: |-
- Binds members to one access level on one saved query. Not bytebase.v1.Binding
- because per-object access here is a capability, not a role.
+ description: Binds members to one access level on one saved query.
bytebase.v1.SavedQueryBinding.Level:
type: string
title: Level
@@ -17869,8 +17834,8 @@ components:
- VIEWER
- EDITOR
description: |-
- Nested because bytebase.v1 already defines a package-scoped EDITOR
- (DatabaseChangeMode), and enum values live in the enclosing scope.
+ Nested to avoid colliding with the package-scoped EDITOR in
+ DatabaseChangeMode.
bytebase.v1.SavedQueryPolicy:
type: object
properties:
@@ -17891,9 +17856,8 @@ components:
title: SavedQueryPolicy
additionalProperties: false
description: |-
- Who a saved query is shared with, and at what level. A saved query with no
- bindings is private. The creator is never a binding member: ownership comes
- from creating the saved query and cannot be granted away.
+ Who a saved query is shared with, and at what level. No bindings means
+ private. The creator is never a binding member; ownership cannot be granted.
bytebase.v1.SchemaCatalog:
type: object
properties:
@@ -18374,16 +18338,16 @@ components:
- name: the saved query name. Supports "==" and "in [...]".
- title: the title. Supports "contains".
- creator: the creator in "users/{email}" format. Supports "==" and "!=".
- - shared: true selects only saved queries the caller reaches through a
- binding, excluding their own and any seen through
- bb.savedQueries.manage; false selects the rest. Supports "==".
+ - shared: whether a binding shares the saved query with the caller. Their
+ own saved queries, and ones visible only through a project-level
+ bb.savedQueries.get, are not "shared". Supports "==".
- starred: whether the caller starred it. Supports "==".
- folder: the exact folder path. Supports "==".
- The SQL Editor's views are `creator == "users/{me}"` for My and
- `shared == true` for Shared. Prefer `shared` over `creator !=` for the
- latter: for an admin, `creator !=` also matches saved queries nobody
- shared with them.
+ Use `creator == "users/{me}"` for a My view and `shared == true` for a
+ Shared view. Prefer `shared` over `creator !=`: with a project-level
+ bb.savedQueries.get, `creator !=` also matches saved queries nobody
+ shared with the caller.
For example:
creator == "users/[email protected]"
@@ -18402,11 +18366,8 @@ components:
type: string
title: page_token
description: |-
- A page token from a previous SearchSavedQueries call. Every other
- parameter must match the call that returned it: the token carries the
- offset reached so far, so changing `filter` or `page_size` mid-pagination
- reinterprets that offset against a different result set and can skip or
- repeat rows.
+ A page token from a previous SearchSavedQueries call. Keep every other
+ parameter the same as the call that returned it.
title: SearchSavedQueriesRequest
additionalProperties: false
bytebase.v1.SearchSavedQueriesResponse:
@@ -18630,8 +18591,8 @@ components:
policy:
title: policy
description: |-
- Replaces the stored policy in full: a member absent from it loses their
- grant, and a policy with no bindings makes the saved query private again.
+ The new policy, replacing the stored one in full. Empty `bindings` makes
+ the saved query private again.
$ref: '#/components/schemas/bytebase.v1.SavedQueryPolicy'
title: SetSavedQueryPolicyRequest
additionalProperties: false
@@ -20794,6 +20755,7 @@ components:
description: |-
Fields to update, relative to the saved query (`title`, not
`saved_query.title`). Supported: `title`, `content`, `database`, `folder`.
+ At least one path is required.
$ref: '#/components/schemas/google.protobuf.FieldMask'
title: UpdateSavedQueryRequest
additionalProperties: false
@@ -22845,16 +22807,18 @@ tags:
description: RoleService manages workspace roles and permissions.
- name: bytebase.v1.SavedQueryService
description: |-
- SavedQueryService manages saved queries for SQL Editor query development.
-
- A saved query is private to its creator until shared. Three things grant
- access to one: being its creator (the fixed owner), holding a VIEWER or
- EDITOR binding on it, and holding bb.savedQueries.manage, the admin backstop
- that reaches private saved queries too. Bindings are managed through the
- GetSavedQueryPolicy/SetSavedQueryPolicy pair.
+ SavedQueryService manages saved queries in the SQL Editor.
- Two gates sit on top of that: bb.savedQueries.search gates discovery, and
- running a saved query needs the SQL Editor's own database permissions.
+ A saved query is private to its creator until shared. Permissions come from
+ three places:
+ - The creator owns the saved query and holds every permission on it.
+ - A VIEWER binding grants bb.savedQueries.get and getIamPolicy; an EDITOR
+ binding adds update.
+ - Permissions granted on the project or workspace apply to every saved
+ query in the project, private ones included.
+ A caller without a method's permission gets NotFound, not
+ PermissionDenied, so private names stay unprobeable. Running a saved query
+ is governed by the SQL Editor's database permissions, not by this service.
- name: bytebase.v1.ServiceAccountService
description: ServiceAccountService manages service accounts for API integrations.
- name: bytebase.v1.SheetService
diff --git a/backend/api/v1/saved_query_service.go b/backend/api/v1/saved_query_service.go
index 721262558f..73324cefef 100644
--- a/backend/api/v1/saved_query_service.go
+++ b/backend/api/v1/saved_query_service.go
@@ -100,7 +100,8 @@ func (s *SavedQueryService) CreateSavedQuery(
return connect.NewResponse(convertToAPISavedQuery(savedQuery)), nil
}
-// GetSavedQuery returns the requested saved query, cutoff the content if the content is too long and the `raw` flag in request is false.
+// GetSavedQuery returns the requested saved query with its full content —
+// only Search truncates.
func (s *SavedQueryService) GetSavedQuery(
ctx context.Context,
req *connect.Request[v1pb.GetSavedQueryRequest],
@@ -110,16 +111,29 @@ func (s *SavedQueryService) GetSavedQuery(
return nil, connect.NewError(connect.CodeInvalidArgument, err)
}
- savedQuery, err := s.findSavedQuery(ctx, projectID, savedQueryID, true /* loadFull */)
+ user, ok := GetUserFromContext(ctx)
+ if !ok {
+ return nil, connect.NewError(connect.CodeInternal, errors.Errorf("user not found"))
+ }
+ savedQuery, err := s.store.GetSavedQuery(ctx, &store.FindSavedQueryMessage{
+ ProjectIDs: []string{projectID},
+ Workspace: common.GetWorkspaceIDFromContext(ctx),
+ ResourceID: &savedQueryID,
+ LoadFull: true,
+ PrincipalEmail: user.Email,
+ })
if err != nil {
- return nil, err
+ return nil, connect.NewError(connect.CodeInternal, errors.Errorf("failed to get saved query: %v", err))
+ }
+ if savedQuery == nil {
+ return nil, connect.NewError(connect.CodeNotFound, errors.Errorf("cannot find the saved query"))
}
- access, err := s.savedQueryAccess(ctx, savedQuery)
+ canGet, err := s.hasSavedQueryPermission(ctx, user, savedQuery, permission.SavedQueriesGet)
if err != nil {
return nil, err
}
- if !access.canRead() {
+ if !canGet {
// Same answer as a name that does not exist: a saved query the caller
// cannot read must not be probeable, by existence or by title.
return nil, connect.NewError(connect.CodeNotFound, errors.Errorf("cannot find the saved query"))
@@ -230,28 +244,23 @@ func (s *SavedQueryService) SearchSavedQueryFolders(
if !ok {
return nil, connect.NewError(connect.CodeInternal, errors.Errorf("user not found"))
}
- if err := s.checkDiscoverSavedQueries(ctx, user, projectID); err != nil {
- return nil, err
- }
-
- accessMembers, err := s.iamManager.PrincipalMembers(ctx, common.GetWorkspaceIDFromContext(ctx), user)
+ // Folders inherit the rows' read rule, exactly as SearchSavedQueries does.
+ members, access, err := s.searchScope(ctx, user, projectID)
if err != nil {
- return nil, connect.NewError(connect.CodeInternal, errors.Errorf("failed to resolve principals: %v", err))
+ return nil, err
}
- filterQ, err := store.GetSearchSavedQueryFilter(ctx, s.store, user.Email, accessMembers, request.Filter, false /* allowTitleContains */)
+ filterQ, err := store.GetSearchSavedQueryFilter(ctx, s.store, user.Email, members, request.Filter, false /* allowTitleContains */)
if err != nil {
return nil, connect.NewError(connect.CodeInvalidArgument, err)
}
- // Folders inherit the rows' read rule, exactly as SearchSavedQueries does:
- // the caller's own saved queries plus those a binding shares with them, and
- // no admin widening. The filter is what splits My (creator == me) from
- // Shared (shared == true) — scoping to the caller's own rows here instead
- // would hide a shared saved query its creator filed, since the client seeds
- // its folder tree from this call and cannot expand into a folder it never
- // learns about.
- paths, err := s.store.ListSavedQueryFolderPaths(ctx, projectID, user.Email, accessMembers, filterQ)
+ // The filter is what splits My (creator == me) from Shared (shared ==
+ // true) — scoping to the caller's own rows here instead would hide a
+ // shared saved query its creator filed, since the client seeds its folder
+ // tree from this call and cannot expand into a folder it never learns
+ // about.
+ paths, err := s.store.ListSavedQueryFolderPaths(ctx, common.GetWorkspaceIDFromContext(ctx), projectID, user.Email, access, filterQ)
if err != nil {
return nil, connect.NewError(connect.CodeInternal, errors.Errorf("failed to search saved query folders: %v", err))
}
@@ -294,7 +303,10 @@ func (s *SavedQueryService) SearchSavedQueries(
if projectID == "-" {
return nil, connect.NewError(connect.CodeInvalidArgument, errors.New(`SearchSavedQueries does not support parent "projects/-"`))
}
- if err := s.checkDiscoverSavedQueries(ctx, user, projectID); err != nil {
+ // Search returns the saved queries the caller can read, the same rule as
+ // GetSavedQuery.
+ members, access, err := s.searchScope(ctx, user, projectID)
+ if err != nil {
return nil, err
}
if request.PageSize < 0 {
@@ -312,29 +324,21 @@ func (s *SavedQueryService) SearchSavedQueries(
limitPlusOne := offset.limit + 1
savedQueryFind := &store.FindSavedQueryMessage{
- ProjectIDs: []string{projectID},
+ ProjectIDs: []string{projectID},
+ // The workspace fence: a project outside the caller's workspace, or
+ // a deleted one, yields nothing — required now that a project-level
+ // bb.savedQueries.get drops the access clause entirely.
+ Workspace: common.GetWorkspaceIDFromContext(ctx),
PrincipalEmail: user.Email,
Limit: &limitPlusOne,
Offset: &offset.offset,
+ // Access pushed into the query rather than filtered off the page
+ // afterwards, which would return short pages: nine of ten rows
+ // dropped still consumes the whole page.
+ AccessMembers: access,
}
- // Search is caller-scoped: the caller's own saved queries plus those a
- // binding shares with them, and nothing else — the admin backstop does not
- // widen it. An admin wanting everyone's rows uses ListSavedQueries, the
- // surface built for that, which is gated on bb.savedQueries.list and
- // returns whole statements.
- //
- // The predicate goes into the query rather than filtering the page
- // afterwards, which would return short pages: nine of ten rows dropped
- // still consumes the whole page.
- workspaceID := common.GetWorkspaceIDFromContext(ctx)
- accessMembers, err := s.iamManager.PrincipalMembers(ctx, workspaceID, user)
- if err != nil {
- return nil, connect.NewError(connect.CodeInternal, errors.Errorf("failed to resolve principals: %v", err))
- }
- savedQueryFind.AccessMembers = accessMembers
-
- filterQ, err := store.GetSearchSavedQueryFilter(ctx, s.store, user.Email, accessMembers, request.Filter, true /* allowTitleContains */)
+ filterQ, err := store.GetSearchSavedQueryFilter(ctx, s.store, user.Email, members, request.Filter, true /* allowTitleContains */)
if err != nil {
return nil, connect.NewError(connect.CodeInvalidArgument, err)
}
@@ -371,8 +375,10 @@ func (s *SavedQueryService) UpdateSavedQuery(
if request.SavedQuery == nil {
return nil, connect.NewError(connect.CodeInvalidArgument, errors.Errorf("saved query cannot be empty"))
}
- if request.UpdateMask == nil {
- return nil, connect.NewError(connect.CodeInvalidArgument, errors.Errorf("update mask cannot be empty"))
+ // An empty mask would touch nothing yet still return the full saved query
+ // — a read in update's clothing, which an update-only role must not get.
+ if request.UpdateMask == nil || len(request.UpdateMask.Paths) == 0 {
+ return nil, connect.NewError(connect.CodeInvalidArgument, errors.Errorf("update mask must name at least one field"))
}
if request.SavedQuery.Name == "" {
return nil, connect.NewError(connect.CodeInvalidArgument, errors.Errorf("saved query name cannot be empty"))
@@ -387,26 +393,29 @@ func (s *SavedQueryService) UpdateSavedQuery(
if !ok {
return nil, connect.NewError(connect.CodeInternal, errors.Errorf("user not found"))
}
- savedQuery, err := s.findSavedQuery(ctx, projectID, savedQueryID, false /* loadFull */)
+ savedQuery, err := s.store.GetSavedQuery(ctx, &store.FindSavedQueryMessage{
+ ProjectIDs: []string{projectID},
+ Workspace: common.GetWorkspaceIDFromContext(ctx),
+ ResourceID: &savedQueryID,
+ PrincipalEmail: user.Email,
+ })
if err != nil {
- return nil, err
+ return nil, connect.NewError(connect.CodeInternal, errors.Errorf("failed to get saved query: %v", err))
}
- access, err := s.savedQueryAccess(ctx, savedQuery)
+ if savedQuery == nil {
+ return nil, connect.NewError(connect.CodeNotFound, errors.Errorf("cannot find the saved query"))
+ }
+ canUpdate, err := s.hasSavedQueryPermission(ctx, user, savedQuery, permission.SavedQueriesUpdate)
if err != nil {
return nil, err
}
- if !access.canRead() {
- // Invisible to this caller, so answer as if it were missing rather
- // than confirming the name exists.
+ if !canUpdate {
return nil, connect.NewError(connect.CodeNotFound, errors.Errorf("cannot find the saved query"))
}
- if !access.canWrite() {
- // A VIEWER can already see the row, so there is nothing left to hide.
- return nil, connect.NewError(connect.CodePermissionDenied, errors.Errorf("permission denied to update the saved query"))
- }
savedQueryPatch := &store.PatchSavedQueryMessage{
ResourceID: savedQuery.ResourceID,
+ ProjectID: savedQuery.ProjectID,
}
for _, path := range request.UpdateMask.Paths {
switch path {
@@ -416,11 +425,6 @@ func (s *SavedQueryService) UpdateSavedQuery(
statement := string(request.SavedQuery.Content)
savedQueryPatch.Statement = &statement
case "folder":
- // Filing is organization rather than editing: you never re-file
- // someone else's saved query, whatever your binding says.
- if !access.canManage() {
- return nil, connect.NewError(connect.CodePermissionDenied, errors.Errorf("only the creator or an admin can re-file a saved query"))
- }
folder, err := store.NormalizeSavedQueryFolder(request.SavedQuery.Folder)
if err != nil {
return nil, connect.NewError(connect.CodeInvalidArgument, err)
@@ -454,6 +458,7 @@ func (s *SavedQueryService) UpdateSavedQuery(
savedQuery, err = s.store.GetSavedQuery(ctx, &store.FindSavedQueryMessage{
ProjectIDs: []string{savedQuery.ProjectID},
+ Workspace: common.GetWorkspaceIDFromContext(ctx),
ResourceID: &savedQueryID,
PrincipalEmail: user.Email,
// Only Search truncates. The client caches this response as its FULL
@@ -481,33 +486,48 @@ func (s *SavedQueryService) DeleteSavedQuery(
return nil, connect.NewError(connect.CodeInvalidArgument, err)
}
- savedQuery, err := s.findSavedQuery(ctx, projectID, savedQueryID, false /* loadFull */)
+ user, ok := GetUserFromContext(ctx)
+ if !ok {
+ return nil, connect.NewError(connect.CodeInternal, errors.Errorf("user not found"))
+ }
+ savedQuery, err := s.store.GetSavedQuery(ctx, &store.FindSavedQueryMessage{
+ ProjectIDs: []string{projectID},
+ Workspace: common.GetWorkspaceIDFromContext(ctx),
+ ResourceID: &savedQueryID,
+ PrincipalEmail: user.Email,
+ })
if err != nil {
- return nil, err
+ return nil, connect.NewError(connect.CodeInternal, errors.Errorf("failed to get saved query: %v", err))
}
- access, err := s.savedQueryAccess(ctx, savedQuery)
+ if savedQuery == nil {
+ return nil, connect.NewError(connect.CodeNotFound, errors.Errorf("cannot find the saved query"))
+ }
+ // Bindings never carry deletion, so sharing a saved query for editing
+ // cannot cost its owner the saved query.
+ canDelete, err := s.hasSavedQueryPermission(ctx, user, savedQuery, permission.SavedQueriesDelete)
if err != nil {
return nil, err
}
- if !access.canRead() {
+ if !canDelete {
return nil, connect.NewError(connect.CodeNotFound, errors.Errorf("cannot find the saved query"))
}
- // An EDITOR binding carries content writes, never deletion, so sharing a
- // saved query for editing cannot cost its owner the saved query.
- if !access.canManage() {
- return nil, connect.NewError(connect.CodePermissionDenied, errors.Errorf("only the creator or an admin can delete a saved query"))
- }
- if err := s.store.DeleteSavedQuery(ctx, savedQuery.ResourceID); err != nil {
+ deleted, err := s.store.DeleteSavedQuery(ctx, savedQuery.ProjectID, savedQuery.ResourceID)
+ if err != nil {
return nil, connect.NewError(connect.CodeInternal, errors.Errorf("failed to delete saved query: %v", err))
}
+ if !deleted {
+ // Gone — or reassigned by a purge — between the read above and the
+ // delete.
+ return nil, connect.NewError(connect.CodeNotFound, errors.Errorf("cannot find the saved query"))
+ }
return connect.NewResponse(&emptypb.Empty{}), nil
}
// UpdateSavedQueryStar stars or unstars a saved query for the caller. Stars
-// are personal: you can star anything you created or were granted, and your
-// stars are invisible to everyone else.
+// are personal: you can star anything you can read, and your stars are
+// invisible to everyone else.
func (s *SavedQueryService) UpdateSavedQueryStar(
ctx context.Context,
req *connect.Request[v1pb.UpdateSavedQueryStarRequest],
@@ -518,26 +538,36 @@ func (s *SavedQueryService) UpdateSavedQueryStar(
return nil, connect.NewError(connect.CodeInvalidArgument, err)
}
- savedQuery, err := s.findSavedQuery(ctx, projectID, savedQueryID, true /* loadFull */)
+ user, ok := GetUserFromContext(ctx)
+ if !ok {
+ return nil, connect.NewError(connect.CodeInternal, errors.Errorf("user not found"))
+ }
+ // Truncated read: the permission check needs only creator and bindings,
+ // and no consumer reads the star response's content.
+ savedQuery, err := s.store.GetSavedQuery(ctx, &store.FindSavedQueryMessage{
+ ProjectIDs: []string{projectID},
+ Workspace: common.GetWorkspaceIDFromContext(ctx),
+ ResourceID: &savedQueryID,
+ PrincipalEmail: user.Email,
+ })
if err != nil {
- return nil, err
+ return nil, connect.NewError(connect.CodeInternal, errors.Errorf("failed to get saved query: %v", err))
+ }
+ if savedQuery == nil {
+ return nil, connect.NewError(connect.CodeNotFound, errors.Errorf("cannot find the saved query"))
}
- access, err := s.savedQueryAccess(ctx, savedQuery)
+ // Starring takes read access. NotFound rather than PermissionDenied: the
+ // star surface only concerns saved queries you can use, and answering
+ // "exists, but not yours" would make names probeable.
+ canGet, err := s.hasSavedQueryPermission(ctx, user, savedQuery, permission.SavedQueriesGet)
if err != nil {
return nil, err
}
- // NotFound rather than PermissionDenied: the star surface only concerns
- // saved queries you can use, and answering "exists, but not yours" would
- // make names probeable.
- if !access.canStar() {
+ if !canGet {
return nil, connect.NewError(connect.CodeNotFound, errors.Errorf("cannot find the saved query"))
}
- user, ok := GetUserFromContext(ctx)
- if !ok {
- return nil, connect.NewError(connect.CodeInternal, errors.Errorf("user not found"))
- }
- applied, err := s.store.SetSavedQueryStar(ctx, savedQuery.ResourceID, user.Email, request.Starred)
+ applied, err := s.store.SetSavedQueryStar(ctx, savedQuery.ProjectID, savedQuery.ResourceID, user.Email, request.Starred)
if err != nil {
return nil, connect.NewError(connect.CodeInternal, errors.Errorf("failed to update star: %v", err))
}
@@ -550,10 +580,9 @@ func (s *SavedQueryService) UpdateSavedQueryStar(
return connect.NewResponse(convertToAPISavedQuery(savedQuery)), nil
}
-// MoveMySavedQueries files saved queries, named individually or a folder at a
-// time. Creator-only: filing is personal organization, so the store scopes
-// every move to the caller's own rows and anything else is simply not
-// selected.
+// MoveMySavedQueries moves the caller's saved queries filed under one folder.
+// Creator-only: filing is personal organization, so the store scopes the move
+// to the caller's own rows and anything else is simply not selected.
func (s *SavedQueryService) MoveMySavedQueries(
ctx context.Context,
req *connect.Request[v1pb.MoveMySavedQueriesRequest],
@@ -566,9 +595,6 @@ func (s *SavedQueryService) MoveMySavedQueries(
if projectID == "-" {
return nil, connect.NewError(connect.CodeInvalidArgument, errors.Errorf(`projects/- is not supported`))
}
- if (len(request.Names) == 0) == (request.SourceFolder == "") {
- return nil, connect.NewError(connect.CodeInvalidArgument, errors.Errorf("set either names or source_folder, not both"))
- }
user, ok := GetUserFromContext(ctx)
if !ok {
@@ -579,43 +605,23 @@ func (s *SavedQueryService) MoveMySavedQueries(
if err != nil {
return nil, connect.NewError(connect.CodeInvalidArgument, err)
}
-
- var moved int
- if request.SourceFolder != "" {
- source, err := store.NormalizeSavedQueryFolder(request.SourceFolder)
- if err != nil {
- return nil, connect.NewError(connect.CodeInvalidArgument, err)
- }
- if source == "" {
- return nil, connect.NewError(connect.CodeInvalidArgument, errors.Errorf("source_folder cannot be empty"))
- }
- if source == target {
- return connect.NewResponse(&v1pb.MoveMySavedQueriesResponse{}), nil
- }
- if strings.HasPrefix(target, source+"/") {
- // "a/b" into "a/b/c" would rewrite the rows it just moved.
- return nil, connect.NewError(connect.CodeInvalidArgument, errors.Errorf("cannot move a folder into itself"))
- }
- moved, err = s.store.MoveSavedQueryFolder(ctx, projectID, user.Email, source, target)
- if err != nil {
- return nil, connect.NewError(connect.CodeInternal, errors.Errorf("failed to move folder: %v", err))
- }
- } else {
- resourceIDs := make([]string, 0, len(request.Names))
- for _, name := range request.Names {
- nameProject, savedQueryID, err := common.GetProjectIDSavedQueryID(name)
- if err != nil {
- return nil, connect.NewError(connect.CodeInvalidArgument, err)
- }
- if nameProject != projectID {
- return nil, connect.NewError(connect.CodeInvalidArgument, errors.Errorf("saved query %q is not in %q", name, request.Parent))
- }
- resourceIDs = append(resourceIDs, savedQueryID)
- }
- moved, err = s.store.MoveSavedQueries(ctx, projectID, user.Email, resourceIDs, target)
- if err != nil {
- return nil, connect.NewError(connect.CodeInternal, errors.Errorf("failed to move saved queries: %v", err))
- }
+ source, err := store.NormalizeSavedQueryFolder(request.SourceFolder)
+ if err != nil {
+ return nil, connect.NewError(connect.CodeInvalidArgument, err)
+ }
+ if source == "" {
+ return nil, connect.NewError(connect.CodeInvalidArgument, errors.Errorf("source_folder cannot be empty"))
+ }
+ if source == target {
+ return connect.NewResponse(&v1pb.MoveMySavedQueriesResponse{}), nil
+ }
+ if strings.HasPrefix(target, source+"/") {
+ // "a/b" into "a/b/c" would rewrite the rows it just moved.
+ return nil, connect.NewError(connect.CodeInvalidArgument, errors.Errorf("cannot move a folder into itself"))
+ }
+ moved, err := s.store.MoveSavedQueryFolder(ctx, projectID, user.Email, source, target)
+ if err != nil {
+ return nil, connect.NewError(connect.CodeInternal, errors.Errorf("failed to move folder: %v", err))
}
return connect.NewResponse(&v1pb.MoveMySavedQueriesResponse{MovedCount: int32(moved)}), nil
@@ -632,40 +638,30 @@ func (s *SavedQueryService) checkProjectWide(ctx context.Context, user *store.Us
return nil
}
-func (s *SavedQueryService) checkDiscoverSavedQueries(ctx context.Context, user *store.UserMessage, projectID string) error {
- // bb.savedQueries.search alone, not "search or manage". The search family
- // is caller-scoped, so manage would let a role through the gate to see
- // only its own rows — no use to it, and one more thing to explain. Admins
- // reach everyone's saved queries through ListSavedQueries instead, and
- // every predefined role holding manage holds search too.
- ok, err := s.iamManager.CheckProjectWidePermission(ctx, permission.SavedQueriesSearch, user, common.GetWorkspaceIDFromContext(ctx), projectID)
+// searchScope gates the search family on bb.savedQueries.search, denying the
+// call outright without it, whatever the caller could read. It then returns
+// the caller's members — them plus their groups, which the shared filter
+// probes either way — and the access clause: nil, no restriction, when a
+// project-level bb.savedQueries.get reads every row; the same members
+// otherwise, scoping results to the caller's own rows plus those a binding
+// shares with them.
+func (s *SavedQueryService) searchScope(ctx context.Context, user *store.UserMessage, projectID string) (members, access []string, err error) {
+ if err := s.checkProjectWide(ctx, user, permission.SavedQueriesSearch, projectID); err != nil {
+ return nil, nil, err
+ }
+ groups, err := s.callerGroups(ctx, user)
if err != nil {
- return connect.NewError(connect.CodeInternal, errors.Errorf("failed to check permission with error: %v", err))
+ return nil, nil, err
}
- if !ok {
- return connect.NewError(connect.CodePermissionDenied, errors.Errorf("permission denied: %s", permission.SavedQueriesSearch))
- }
- return nil
-}
-
-func (s *SavedQueryService) findSavedQuery(ctx context.Context, projectID string, savedQueryID string, loadFull bool) (*store.SavedQueryMessage, error) {
- user, ok := GetUserFromContext(ctx)
- if !ok {
- return nil, connect.NewError(connect.CodeInternal, errors.Errorf("user not found"))
- }
- savedQuery, err := s.store.GetSavedQuery(ctx, &store.FindSavedQueryMessage{
- ProjectIDs: []string{projectID},
- ResourceID: &savedQueryID,
- LoadFull: loadFull,
- PrincipalEmail: user.Email,
- })
+ members = append([]string{callerMember(user)}, groups...)
+ canGet, err := s.iamManager.CheckProjectWidePermission(ctx, permission.SavedQueriesGet, user, common.GetWorkspaceIDFromContext(ctx), projectID)
if err != nil {
- return nil, connect.NewError(connect.CodeInternal, errors.Errorf("failed to get saved query: %v", err))
+ return nil, nil, connect.NewError(connect.CodeInternal, errors.Errorf("failed to check permission with error: %v", err))
}
- if savedQuery == nil {
- return nil, connect.NewError(connect.CodeNotFound, errors.Errorf("cannot find the saved query"))
+ if canGet {
+ return members, nil, nil
}
- return savedQuery, nil
+ return members, members, nil
}
// validateSavedQueryDatabase checks that `name` refers to an existing
@@ -710,9 +706,8 @@ func (s *SavedQueryService) validateSavedQueryDatabase(ctx context.Context, proj
return name, nil
}
-// GetSavedQueryPolicy returns a saved query's grants. Anyone who can read the
-// saved query can read its policy — that is how a grantee learns whether they
-// may edit it, now that nothing caller-relative rides on the resource.
+// GetSavedQueryPolicy returns a saved query's grants. Bindings carry
+// getIamPolicy, so a grantee can always learn their own level.
func (s *SavedQueryService) GetSavedQueryPolicy(
ctx context.Context,
req *connect.Request[v1pb.GetSavedQueryPolicyRequest],
@@ -722,15 +717,27 @@ func (s *SavedQueryService) GetSavedQueryPolicy(
return nil, connect.NewError(connect.CodeInvalidArgument, err)
}
- savedQuery, err := s.findSavedQuery(ctx, projectID, savedQueryID, false /* loadFull */)
+ user, ok := GetUserFromContext(ctx)
+ if !ok {
+ return nil, connect.NewError(connect.CodeInternal, errors.Errorf("user not found"))
+ }
+ savedQuery, err := s.store.GetSavedQuery(ctx, &store.FindSavedQueryMessage{
+ ProjectIDs: []string{projectID},
+ Workspace: common.GetWorkspaceIDFromContext(ctx),
+ ResourceID: &savedQueryID,
+ PrincipalEmail: user.Email,
+ })
if err != nil {
- return nil, err
+ return nil, connect.NewError(connect.CodeInternal, errors.Errorf("failed to get saved query: %v", err))
}
- access, err := s.savedQueryAccess(ctx, savedQuery)
+ if savedQuery == nil {
+ return nil, connect.NewError(connect.CodeNotFound, errors.Errorf("cannot find the saved query"))
+ }
+ canGetIamPolicy, err := s.hasSavedQueryPermission(ctx, user, savedQuery, permission.SavedQueriesGetIamPolicy)
if err != nil {
return nil, err
}
- if !access.canRead() {
+ if !canGetIamPolicy {
return nil, connect.NewError(connect.CodeNotFound, errors.Errorf("cannot find the saved query"))
}
@@ -755,20 +762,31 @@ func (s *SavedQueryService) SetSavedQueryPolicy(
return nil, connect.NewError(connect.CodeInvalidArgument, err)
}
- savedQuery, err := s.findSavedQuery(ctx, projectID, savedQueryID, false /* loadFull */)
+ user, ok := GetUserFromContext(ctx)
+ if !ok {
+ return nil, connect.NewError(connect.CodeInternal, errors.Errorf("user not found"))
+ }
+ savedQuery, err := s.store.GetSavedQuery(ctx, &store.FindSavedQueryMessage{
+ ProjectIDs: []string{projectID},
+ Workspace: common.GetWorkspaceIDFromContext(ctx),
+ ResourceID: &savedQueryID,
+ PrincipalEmail: user.Email,
+ })
if err != nil {
- return nil, err
+ return nil, connect.NewError(connect.CodeInternal, errors.Errorf("failed to get saved query: %v", err))
+ }
+ if savedQuery == nil {
+ return nil, connect.NewError(connect.CodeNotFound, errors.Errorf("cannot find the saved query"))
}
- access, err := s.savedQueryAccess(ctx, savedQuery)
+ // No binding and no predefined role carries setIamPolicy, so sharing is
+ // the creator's unless a custom role grants it deliberately.
+ canSetIamPolicy, err := s.hasSavedQueryPermission(ctx, user, savedQuery, permission.SavedQueriesSetIamPolicy)
if err != nil {
return nil, err
}
- if !access.canRead() {
+ if !canSetIamPolicy {
return nil, connect.NewError(connect.CodeNotFound, errors.Errorf("cannot find the saved query"))
}
- if !access.canManage() {
- return nil, connect.NewError(connect.CodePermissionDenied, errors.Errorf("only the creator or an admin can share a saved query"))
- }
bindings, err := convertToStoreSavedQueryBindings(request.Policy.Bindings)
if err != nil {
@@ -843,8 +861,8 @@ func convertToV1SavedQueryMember(member string) string {
// for storage, converting each member from the API's binding form to the
// resource name the store holds -- "user:[email protected]" becomes "users/[email protected]"
// -- exactly as convertToStoreIamPolicyMember does for an IAM policy. Doing it
-// once here rather than at every read is what lets the access queries compare
-// stored members against iam.PrincipalMembers with no conversion at all.
+// once here rather than at every read is what lets the access checks compare
+// stored members against callerMember and the caller's groups directly.
//
// A member may appear at one binding only, so the stored policy never needs a
// tie-break rule. Members are prefix-checked, not resolved, the same shape
@@ -891,81 +909,95 @@ func convertToStoreSavedQueryBindings(bindings []*v1pb.SavedQueryBinding) ([]*st
return converted, nil
}
-// savedQueryAccess is how one caller stands relative to one saved query. The
-// three sources of access are resolved once and the predicates derived from
-// them, so read, write, share, and delete cannot drift apart.
-type savedQueryAccess struct {
- isCreator bool
- // Holds bb.savedQueries.manage in scope.
- isAdmin bool
- // The highest level this caller's bindings grant, directly or through one
- // of their groups. LEVEL_UNSPECIFIED when no binding names them.
- level storepb.SavedQueryBinding_Level
-}
-
-// EDITOR > VIEWER in the enum, so the comparisons below read as the levels do.
-func (a savedQueryAccess) canRead() bool {
- return a.isCreator || a.isAdmin || a.level >= storepb.SavedQueryBinding_VIEWER
-}
-
-func (a savedQueryAccess) canWrite() bool {
- return a.isCreator || a.isAdmin || a.level >= storepb.SavedQueryBinding_EDITOR
-}
-
-// canStar covers starring, which is personal: you can star any saved query you
-// created or were granted access to, and your stars are yours alone.
-func (a savedQueryAccess) canStar() bool {
- return a.isCreator || a.level >= storepb.SavedQueryBinding_VIEWER
+// bindingGrants: a VIEWER binding grants get and getIamPolicy — a grantee
+// can always see their own grant; an EDITOR binding adds update. No binding
+// grants anything else.
+//
+// Must stay in lockstep with the store's level-blind access probe
+// (bindingProbe in store/saved_query.go), which assumes every level grants
+// get; a future level that does not grant get needs a level term there, or
+// Search would leak previews GetSavedQuery denies.
+func bindingGrants(level storepb.SavedQueryBinding_Level, p permission.Permission) bool {
+ switch level {
+ case storepb.SavedQueryBinding_VIEWER:
+ return p == permission.SavedQueriesGet || p == permission.SavedQueriesGetIamPolicy
+ case storepb.SavedQueryBinding_EDITOR:
+ return p == permission.SavedQueriesGet || p == permission.SavedQueriesGetIamPolicy || p == permission.SavedQueriesUpdate
+ default:
+ return false
+ }
}
-// canManage covers sharing, deleting, and re-filing: a binding never confers
-// any of them, so sharing a saved query for editing cannot cost its owner the
-// saved query.
-func (a savedQueryAccess) canManage() bool {
- return a.isCreator || a.isAdmin
+// callerMember is the policy-member form of the caller — typed, so a service
+// account is only ever named "serviceAccounts/{email}" and a binding naming
+// one under a "users/" prefix matches nobody.
+func callerMember(user *store.UserMessage) string {
+ return common.FormatPrincipalMember(user.Email, user.Type)
}
-func (s *SavedQueryService) savedQueryAccess(ctx context.Context, savedQuery *store.SavedQueryMessage) (savedQueryAccess, error) {
- user, ok := GetUserFromContext(ctx)
- if !ok {
- return savedQueryAccess{}, connect.NewError(connect.CodeInternal, errors.Errorf("user not found"))
- }
- access := savedQueryAccess{isCreator: savedQuery.Creator == user.Email}
- if access.isCreator {
- // Nothing a binding or the backstop adds can exceed what the owner
- // already has, so skip both lookups.
- return access, nil
- }
-
- workspaceID := common.GetWorkspaceIDFromContext(ctx)
- isAdmin, err := s.iamManager.CheckProjectWidePermission(ctx, permission.SavedQueriesManage, user, workspaceID, savedQuery.ProjectID)
+// callerGroups resolves the groups that stand for the caller in bindings.
+// Only end users belong to groups on this surface: a service account or
+// workload identity is never a grantee, so the group path must not widen for
+// them even when a group lists their email.
+func (s *SavedQueryService) callerGroups(ctx context.Context, user *store.UserMessage) ([]string, error) {
+ switch user.Type {
+ case storepb.PrincipalType_SERVICE_ACCOUNT, storepb.PrincipalType_WORKLOAD_IDENTITY:
+ return nil, nil
+ default:
+ }
+ groups, err := s.iamManager.GetUserGroups(ctx, common.GetWorkspaceIDFromContext(ctx), user.Email)
if err != nil {
- return savedQueryAccess{}, connect.NewError(connect.CodeInternal, errors.Errorf("failed to check permission with error: %v", err.Error()))
+ return nil, connect.NewError(connect.CodeInternal, errors.Errorf("failed to resolve groups: %v", err))
}
- access.isAdmin = isAdmin
+ return groups, nil
+}
- if len(savedQuery.Bindings) > 0 {
- principals, err := s.iamManager.PrincipalMembers(ctx, workspaceID, user)
- if err != nil {
- return savedQueryAccess{}, connect.NewError(connect.CodeInternal, errors.Errorf("failed to resolve principals: %v", err))
+// hasSavedQueryPermission is the access rule: the creator holds every
+// permission on their saved query; a binding grants what bindingGrants says,
+// to members it names directly or through one of their groups; a project- or
+// workspace-level role grant reaches every saved query in the project.
+// Bindings are checked before the role walk: the sources are OR'd, so the
+// order is outcome-identical, and for the common grantee case the bindings
+// answer with string compares on the already-fetched row.
+func (s *SavedQueryService) hasSavedQueryPermission(ctx context.Context, user *store.UserMessage, savedQuery *store.SavedQueryMessage, p permission.Permission) (bool, error) {
+ if savedQuery.Creator == user.Email {
+ return true, nil
+ }
+ member := callerMember(user)
+ // The caller's groups, resolved once and only when a granting binding
+ // actually names a group.
+ var groups map[string]bool
+ for _, binding := range savedQuery.Bindings {
+ if !bindingGrants(binding.Level, p) {
+ continue
}
- principalSet := make(map[string]bool, len(principals))
- for _, principal := range principals {
- principalSet[principal] = true
- }
- for _, binding := range savedQuery.Bindings {
- if binding.Level <= access.level {
+ for _, m := range binding.Members {
+ if m == member {
+ return true, nil
+ }
+ if !strings.HasPrefix(m, common.GroupPrefix) {
continue
}
- for _, member := range binding.Members {
- if principalSet[member] {
- access.level = binding.Level
- break
+ if groups == nil {
+ list, err := s.callerGroups(ctx, user)
+ if err != nil {
+ return false, err
+ }
+ groups = make(map[string]bool, len(list))
+ for _, group := range list {
+ groups[group] = true
}
}
+ if groups[m] {
+ return true, nil
+ }
}
}
- return access, nil
+ ok, err := s.iamManager.CheckProjectWidePermission(ctx, p, user, common.GetWorkspaceIDFromContext(ctx), savedQuery.ProjectID)
+ if err != nil {
+ return false, connect.NewError(connect.CodeInternal, errors.Errorf("failed to check permission with error: %v", err))
+ }
+ return ok, nil
}
// convertToAPISavedQuery converts a store message to the API shape. The
diff --git a/backend/common/permission/permission.go b/backend/common/permission/permission.go
index 95393d8cb9..7870c44ca6 100644
--- a/backend/common/permission/permission.go
+++ b/backend/common/permission/permission.go
@@ -108,9 +108,13 @@ const (
RolloutsGet Permission = "bb.rollouts.get"
RolloutsList Permission = "bb.rollouts.list"
SavedQueriesCreate Permission = "bb.savedQueries.create"
- SavedQueriesSearch Permission = "bb.savedQueries.search"
+ SavedQueriesDelete Permission = "bb.savedQueries.delete"
+ SavedQueriesGet Permission = "bb.savedQueries.get"
+ SavedQueriesGetIamPolicy Permission = "bb.savedQueries.getIamPolicy"
SavedQueriesList Permission = "bb.savedQueries.list"
- SavedQueriesManage Permission = "bb.savedQueries.manage"
+ SavedQueriesSearch Permission = "bb.savedQueries.search"
+ SavedQueriesSetIamPolicy Permission = "bb.savedQueries.setIamPolicy"
+ SavedQueriesUpdate Permission = "bb.savedQueries.update"
ServiceAccountsCreate Permission = "bb.serviceAccounts.create"
ServiceAccountsDelete Permission = "bb.serviceAccounts.delete"
ServiceAccountsGet Permission = "bb.serviceAccounts.get"
diff --git a/backend/common/permission/permission.yaml b/backend/common/permission/permission.yaml
index a3c83ef2bc..8921d3e5f5 100644
--- a/backend/common/permission/permission.yaml
+++ b/backend/common/permission/permission.yaml
@@ -100,9 +100,13 @@ permissions:
- bb.rollouts.get
- bb.rollouts.list
- bb.savedQueries.create
- - bb.savedQueries.search
+ - bb.savedQueries.delete
+ - bb.savedQueries.get
+ - bb.savedQueries.getIamPolicy
- bb.savedQueries.list
- - bb.savedQueries.manage
+ - bb.savedQueries.search
+ - bb.savedQueries.setIamPolicy
+ - bb.savedQueries.update
- bb.serviceAccounts.create
- bb.serviceAccounts.delete
- bb.serviceAccounts.get
diff --git a/backend/common/resource_name.go b/backend/common/resource_name.go
index b4f7d3754c..166fecf874 100644
--- a/backend/common/resource_name.go
+++ b/backend/common/resource_name.go
@@ -637,6 +637,23 @@ func FormatGroupEmail(email string) string {
return fmt.Sprintf("%s%s", GroupPrefix, email)
}
+// FormatPrincipalMember returns the policy-member form of a principal by its
+// type: users/{email}, serviceAccounts/{email}, or workloadIdentities/{email}.
+// A service account never appears under users/, which is what lets member
+// validation and matching go by prefix alone. The single source for every
+// evaluator — IAM, saved-query bindings, member formatting — so the switches
+// cannot drift.
+func FormatPrincipalMember(email string, principalType storepb.PrincipalType) string {
+ switch principalType {
+ case storepb.PrincipalType_SERVICE_ACCOUNT:
+ return FormatServiceAccountEmail(email)
+ case storepb.PrincipalType_WORKLOAD_IDENTITY:
+ return FormatWorkloadIdentityEmail(email)
+ default:
+ return FormatUserEmail(email)
+ }
+}
+
// IsWorkloadIdentityEmail checks if the email is a workload identity email.
func IsWorkloadIdentityEmail(email string) bool {
return strings.HasSuffix(email, fmt.Sprintf("@%s", WorkloadIdentitySuffix)) || isProjectLevelEmail(email, WorkloadIdentitySuffix)
diff --git a/backend/component/iam/manager.go b/backend/component/iam/manager.go
index 3a191bdf38..ec0e7cd671 100644
--- a/backend/component/iam/manager.go
+++ b/backend/component/iam/manager.go
@@ -120,23 +120,6 @@ func (m *Manager) GetUserGroups(ctx context.Context, workspaceID string, email s
return m.store.GetUserGroupsSnapshot(ctx, workspaceID, common.FormatUserEmail(email))
}
-// PrincipalMembers returns the policy members that stand for a caller: itself,
-// in the form its principal type dictates, plus each group it belongs to.
-//
-// This is the derivation check() uses, exposed for policy surfaces that
-// evaluate their own bindings instead of going through CheckPermission. Taking
-// the caller's type from formatUserNameByType is what keeps a service account
-// out of a "users/" member, so a binding naming one there matches nobody --
-// which is why a policy's write path can validate members by prefix alone.
-// Groups are named by reference and never expanded.
-func (m *Manager) PrincipalMembers(ctx context.Context, workspaceID string, user *store.UserMessage) ([]string, error) {
- groups, err := m.GetUserGroups(ctx, workspaceID, user.Email)
- if err != nil {
- return nil, err
- }
- return append([]string{formatUserNameByType(user)}, groups...), nil
-}
-
func check(user *store.UserMessage, p permission.Permission, policy *storepb.IamPolicy, getPermissions func(role string) map[permission.Permission]bool, getGroupMembers func(groupName string) map[string]bool, skipAllUsers bool, projectWideOnly bool) bool {
userName := formatUserNameByType(user)
@@ -186,12 +169,5 @@ func check(user *store.UserMessage, p permission.Permission, policy *storepb.Iam
// For service accounts: serviceAccounts/{email}
// For workload identities: workloadIdentities/{email}
func formatUserNameByType(user *store.UserMessage) string {
- switch user.Type {
- case storepb.PrincipalType_SERVICE_ACCOUNT:
- return common.FormatServiceAccountEmail(user.Email)
- case storepb.PrincipalType_WORKLOAD_IDENTITY:
- return common.FormatWorkloadIdentityEmail(user.Email)
- default:
- return common.FormatUserEmail(user.Email)
- }
+ return common.FormatPrincipalMember(user.Email, user.Type)
}
diff --git a/backend/component/iam/manager_test.go b/backend/component/iam/manager_test.go
index cf6e6511bd..224c113e0c 100644
--- a/backend/component/iam/manager_test.go
+++ b/backend/component/iam/manager_test.go
@@ -182,9 +182,9 @@ func TestCheckProjectWideOnlySkipsResourceScopedBindings(t *testing.T) {
t.Run(tc.name, func(t *testing.T) {
policy := policyWithCondition(tc.expression)
require.Equal(t, tc.wantProjectWide,
- check(testUser, permission.SavedQueriesManage, policy, getPermissions, getGroupMembers, false, true /* projectWideOnly */))
+ check(testUser, permission.SavedQueriesGet, policy, getPermissions, getGroupMembers, false, true /* projectWideOnly */))
require.Equal(t, tc.wantGeneric,
- check(testUser, permission.SavedQueriesManage, policy, getPermissions, getGroupMembers, false, false /* projectWideOnly */))
+ check(testUser, permission.SavedQueriesGet, policy, getPermissions, getGroupMembers, false, false /* projectWideOnly */))
})
}
}
diff --git a/backend/generated-go/v1/saved_query_service.pb.go b/backend/generated-go/v1/saved_query_service.pb.go
index d1668b78ba..948ac0bdec 100644
--- a/backend/generated-go/v1/saved_query_service.pb.go
+++ b/backend/generated-go/v1/saved_query_service.pb.go
@@ -26,16 +26,17 @@ const (
_ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)
)
-// Nested because bytebase.v1 already defines a package-scoped EDITOR
-// (DatabaseChangeMode), and enum values live in the enclosing scope.
+// Nested to avoid colliding with the package-scoped EDITOR in
+// DatabaseChangeMode.
type SavedQueryBinding_Level int32
const (
SavedQueryBinding_LEVEL_UNSPECIFIED SavedQueryBinding_Level = 0
- // Open and read the saved query.
+ // Holds bb.savedQueries.get and bb.savedQueries.getIamPolicy on the
+ // saved query: open and read it, and see who it is shared with.
SavedQueryBinding_VIEWER SavedQueryBinding_Level = 1
- // VIEWER, plus write the title, content, and connected database. Sharing
- // and deletion stay with the creator and admins.
+ // VIEWER, plus bb.savedQueries.update: write the title, content,
+ // database, and folder. Not deletion, not setIamPolicy.
SavedQueryBinding_EDITOR SavedQueryBinding_Level = 2
)
@@ -196,10 +197,8 @@ type ListSavedQueriesRequest struct {
// The maximum number of saved queries to return. The service may return
// fewer. Defaults to 10; values above 1000 are coerced to 1000.
PageSize int32 `protobuf:"varint,3,opt,name=page_size,json=pageSize,proto3" json:"page_size,omitempty"`
- // A page token from a previous ListSavedQueries call. Every other parameter
- // must match the call that returned it: the token carries the offset reached
- // so far, so changing `filter` or `page_size` mid-pagination reinterprets
- // that offset against a different result set.
+ // A page token from a previous ListSavedQueries call. Keep every other
+ // parameter the same as the call that returned it.
PageToken string `protobuf:"bytes,4,opt,name=page_token,json=pageToken,proto3" json:"page_token,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
@@ -426,6 +425,7 @@ type UpdateSavedQueryRequest struct {
SavedQuery *SavedQuery `protobuf:"bytes,1,opt,name=saved_query,json=savedQuery,proto3" json:"saved_query,omitempty"`
// Fields to update, relative to the saved query (`title`, not
// `saved_query.title`). Supported: `title`, `content`, `database`, `folder`.
+ // At least one path is required.
UpdateMask *fieldmaskpb.FieldMask `protobuf:"bytes,2,opt,name=update_mask,json=updateMask,proto3" json:"update_mask,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
@@ -533,14 +533,11 @@ type MoveMySavedQueriesRequest struct {
state protoimpl.MessageState `protogen:"open.v1"`
// Format: projects/{project}
Parent string `protobuf:"bytes,1,opt,name=parent,proto3" json:"parent,omitempty"`
- // The saved queries to move. Set this or `source_folder`, not both.
- // Format: projects/{project}/savedQueries/{savedQuery}
- Names []string `protobuf:"bytes,2,rep,name=names,proto3" json:"names,omitempty"`
- // Move everything filed under this path, descendants included, e.g. "a/b".
- // Set this or `names`, not both.
- SourceFolder string `protobuf:"bytes,3,opt,name=source_folder,json=sourceFolder,proto3" json:"source_folder,omitempty"`
- // Where they land. A path like "a/b/c"; empty unfiles them.
- TargetFolder string `protobuf:"bytes,4,opt,name=target_folder,json=targetFolder,proto3" json:"target_folder,omitempty"`
+ // The folder to move, descendants included, e.g. "a/b".
+ SourceFolder string `protobuf:"bytes,2,opt,name=source_folder,json=sourceFolder,proto3" json:"source_folder,omitempty"`
+ // Where it lands. A path like "a/b/c"; empty drops the `source_folder`
+ // prefix, promoting the folder's contents toward the root.
+ TargetFolder string `protobuf:"bytes,3,opt,name=target_folder,json=targetFolder,proto3" json:"target_folder,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
@@ -582,13 +579,6 @@ func (x *MoveMySavedQueriesRequest) GetParent() string {
return ""
}
-func (x *MoveMySavedQueriesRequest) GetNames() []string {
- if x != nil {
- return x.Names
- }
- return nil
-}
-
func (x *MoveMySavedQueriesRequest) GetSourceFolder() string {
if x != nil {
return x.SourceFolder
@@ -605,7 +595,7 @@ func (x *MoveMySavedQueriesRequest) GetTargetFolder() string {
type MoveMySavedQueriesResponse struct {
state protoimpl.MessageState `protogen:"open.v1"`
- // How many moved. Fewer than were named when some are not the caller's.
+ // How many moved.
MovedCount int32 `protobuf:"varint,1,opt,name=moved_count,json=movedCount,proto3" json:"moved_count,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
@@ -697,8 +687,8 @@ type SetSavedQueryPolicyRequest struct {
state protoimpl.MessageState `protogen:"open.v1"`
// Format: projects/{project}/savedQueries/{savedQuery}
Resource string `protobuf:"bytes,1,opt,name=resource,proto3" json:"resource,omitempty"`
- // Replaces the stored policy in full: a member absent from it loses their
- // grant, and a policy with no bindings makes the saved query private again.
+ // The new policy, replacing the stored one in full. Empty `bindings` makes
+ // the saved query private again.
Policy *SavedQueryPolicy `protobuf:"bytes,2,opt,name=policy,proto3" json:"policy,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
@@ -748,9 +738,8 @@ func (x *SetSavedQueryPolicyRequest) GetPolicy() *SavedQueryPolicy {
return nil
}
-// Who a saved query is shared with, and at what level. A saved query with no
-// bindings is private. The creator is never a binding member: ownership comes
-// from creating the saved query and cannot be granted away.
+// Who a saved query is shared with, and at what level. No bindings means
+// private. The creator is never a binding member; ownership cannot be granted.
type SavedQueryPolicy struct {
state protoimpl.MessageState `protogen:"open.v1"`
// At most one binding per level. A member listed under two levels is
@@ -807,23 +796,15 @@ func (x *SavedQueryPolicy) GetEtag() string {
return ""
}
-// Binds members to one access level on one saved query. Not bytebase.v1.Binding
-// because per-object access here is a capability, not a role.
+// Binds members to one access level on one saved query.
type SavedQueryBinding struct {
state protoimpl.MessageState `protogen:"open.v1"`
Level SavedQueryBinding_Level `protobuf:"varint,1,opt,name=level,proto3,enum=bytebase.v1.SavedQueryBinding_Level" json:"level,omitempty"`
- // The principals granted `level`, in bytebase.v1.Binding.members format,
- // restricted to "user:{email}" and "group:{email}" -- prefix-checked, as
- // project and workspace IAM check their own members.
- //
- // Service accounts and workload identities are not grantees: they own and
- // run their own saved queries and reach them as the creator. Naming one
- // under a "user:" prefix grants nothing rather than being rejected, because
- // a caller's member is derived from their principal type, so such a binding
- // matches nobody.
+ // The members granted `level`: "user:{email}" or "group:{email}" only.
//
- // A group is stored as a reference and never expanded, so its membership
- // stays live and a large group costs no more than a small one.
+ // Service accounts cannot be grantees — they reach their own saved queries
+ // as the creator. Naming one under "user:" grants nothing rather than
+ // failing. Groups are stored as references, so membership stays live.
Members []string `protobuf:"bytes,2,rep,name=members,proto3" json:"members,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
@@ -928,16 +909,16 @@ type SearchSavedQueriesRequest struct {
// - name: the saved query name. Supports "==" and "in [...]".
// - title: the title. Supports "contains".
// - creator: the creator in "users/{email}" format. Supports "==" and "!=".
- // - shared: true selects only saved queries the caller reaches through a
- // binding, excluding their own and any seen through
- // bb.savedQueries.manage; false selects the rest. Supports "==".
+ // - shared: whether a binding shares the saved query with the caller. Their
+ // own saved queries, and ones visible only through a project-level
+ // bb.savedQueries.get, are not "shared". Supports "==".
// - starred: whether the caller starred it. Supports "==".
// - folder: the exact folder path. Supports "==".
//
- // The SQL Editor's views are `creator == "users/{me}"` for My and
- // `shared == true` for Shared. Prefer `shared` over `creator !=` for the
- // latter: for an admin, `creator !=` also matches saved queries nobody
- // shared with them.
+ // Use `creator == "users/{me}"` for a My view and `shared == true` for a
+ // Shared view. Prefer `shared` over `creator !=`: with a project-level
+ // bb.savedQueries.get, `creator !=` also matches saved queries nobody
+ // shared with the caller.
//
// For example:
// creator == "users/[email protected]"
@@ -949,11 +930,8 @@ type SearchSavedQueriesRequest struct {
// The maximum number of saved queries to return. The service may return
// fewer. Defaults to 10; values above 1000 are coerced to 1000.
PageSize int32 `protobuf:"varint,3,opt,name=page_size,json=pageSize,proto3" json:"page_size,omitempty"`
- // A page token from a previous SearchSavedQueries call. Every other
- // parameter must match the call that returned it: the token carries the
- // offset reached so far, so changing `filter` or `page_size` mid-pagination
- // reinterprets that offset against a different result set and can skip or
- // repeat rows.
+ // A page token from a previous SearchSavedQueries call. Keep every other
+ // parameter the same as the call that returned it.
PageToken string `protobuf:"bytes,4,opt,name=page_token,json=pageToken,proto3" json:"page_token,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
@@ -1085,20 +1063,20 @@ type SavedQuery struct {
Database string `protobuf:"bytes,3,opt,name=database,proto3" json:"database,omitempty"`
// The title of the saved query.
Title string `protobuf:"bytes,4,opt,name=title,proto3" json:"title,omitempty"`
- // The fixed owner. Ownership does not transfer.
+ // The owner. Ownership does not transfer.
// Format: users/{email}
Creator string `protobuf:"bytes,5,opt,name=creator,proto3" json:"creator,omitempty"`
CreateTime *timestamppb.Timestamp `protobuf:"bytes,6,opt,name=create_time,json=createTime,proto3" json:"create_time,omitempty"`
UpdateTime *timestamppb.Timestamp `protobuf:"bytes,7,opt,name=update_time,json=updateTime,proto3" json:"update_time,omitempty"`
- // The SQL text. SearchSavedQueries truncates it; when it is shorter than
- // `content_size`, GetSavedQuery returns the whole thing.
+ // The SQL text. SearchSavedQueries returns a truncated preview;
+ // GetSavedQuery returns the full text.
Content []byte `protobuf:"bytes,8,opt,name=content,proto3" json:"content,omitempty"`
// The full size of the content, which may exceed the `content` returned.
ContentSize int64 `protobuf:"varint,9,opt,name=content_size,json=contentSize,proto3" json:"content_size,omitempty"`
// Whether the calling user starred it.
Starred bool `protobuf:"varint,11,opt,name=starred,proto3" json:"starred,omitempty"`
- // The folder holding this saved query, set by its creator or an admin. A
- // path like "a/b/c"; empty means unfiled.
+ // The folder holding this saved query. A path like "a/b/c"; empty means
+ // unfiled.
Folder string `protobuf:"bytes,13,opt,name=folder,proto3" json:"folder,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
@@ -1220,9 +1198,10 @@ const file_v1_saved_query_service_proto_rawDesc = "" +
"\x06parent\x18\x01 \x01(\tB\x1c\xe0A\x02\xfaA\x16\n" +
"\x14bytebase.com/ProjectR\x06parent\x12=\n" +
"\vsaved_query\x18\x02 \x01(\v2\x17.bytebase.v1.SavedQueryB\x03\xe0A\x02R\n" +
- "savedQuery\"/\n" +
- "\x14GetSavedQueryRequest\x12\x17\n" +
- "\x04name\x18\x01 \x01(\tB\x03\xe0A\x02R\x04name\"\xa3\x01\n" +
+ "savedQuery\"K\n" +
+ "\x14GetSavedQueryRequest\x123\n" +
+ "\x04name\x18\x01 \x01(\tB\x1f\xe0A\x02\xfaA\x19\n" +
+ "\x17bytebase.com/SavedQueryR\x04name\"\xa3\x01\n" +
"\x17ListSavedQueriesRequest\x124\n" +
"\x06parent\x18\x01 \x01(\tB\x1c\xe0A\x02\xfaA\x16\n" +
"\x14bytebase.com/ProjectR\x06parent\x12\x16\n" +
@@ -1243,16 +1222,16 @@ const file_v1_saved_query_service_proto_rawDesc = "" +
"\vsaved_query\x18\x01 \x01(\v2\x17.bytebase.v1.SavedQueryB\x03\xe0A\x02R\n" +
"savedQuery\x12;\n" +
"\vupdate_mask\x18\x02 \x01(\v2\x1a.google.protobuf.FieldMaskR\n" +
- "updateMask\"P\n" +
- "\x1bUpdateSavedQueryStarRequest\x12\x17\n" +
- "\x04name\x18\x01 \x01(\tB\x03\xe0A\x02R\x04name\x12\x18\n" +
- "\astarred\x18\x02 \x01(\bR\astarred\"\xc5\x01\n" +
+ "updateMask\"l\n" +
+ "\x1bUpdateSavedQueryStarRequest\x123\n" +
+ "\x04name\x18\x01 \x01(\tB\x1f\xe0A\x02\xfaA\x19\n" +
+ "\x17bytebase.com/SavedQueryR\x04name\x12\x18\n" +
+ "\astarred\x18\x02 \x01(\bR\astarred\"\xb4\x01\n" +
"\x19MoveMySavedQueriesRequest\x124\n" +
"\x06parent\x18\x01 \x01(\tB\x1c\xe0A\x02\xfaA\x16\n" +
- "\x14bytebase.com/ProjectR\x06parent\x12\x14\n" +
- "\x05names\x18\x02 \x03(\tR\x05names\x12-\n" +
- "\rsource_folder\x18\x03 \x01(\tB\b\xbaH\x05r\x03\x18\x80\x02R\fsourceFolder\x12-\n" +
- "\rtarget_folder\x18\x04 \x01(\tB\b\xbaH\x05r\x03\x18\x80\x02R\ftargetFolder\"=\n" +
+ "\x14bytebase.com/ProjectR\x06parent\x122\n" +
+ "\rsource_folder\x18\x02 \x01(\tB\r\xe0A\x02\xbaH\ar\x05\x10\x01\x18\x80\x02R\fsourceFolder\x12-\n" +
+ "\rtarget_folder\x18\x03 \x01(\tB\b\xbaH\x05r\x03\x18\x80\x02R\ftargetFolder\"=\n" +
"\x1aMoveMySavedQueriesResponse\x12\x1f\n" +
"\vmoved_count\x18\x01 \x01(\x05R\n" +
"movedCount\"Y\n" +
@@ -1304,7 +1283,7 @@ const file_v1_saved_query_service_proto_rawDesc = "" +
"\astarred\x18\v \x01(\bB\x03\xe0A\x03R\astarred\x12 \n" +
"\x06folder\x18\r \x01(\tB\b\xbaH\x05r\x03\x18\x80\x02R\x06folder:K\xeaAH\n" +
"\x17bytebase.com/SavedQuery\x12-projects/{project}/savedQueries/{saved_query}J\x04\b\n" +
- "\x10\vJ\x04\b\f\x10\r2\xa0\x0f\n" +
+ "\x10\vJ\x04\b\f\x10\r2\xae\x0f\n" +
"\x11SavedQueryService\x12\xc3\x01\n" +
"\x10CreateSavedQuery\x12$.bytebase.v1.CreateSavedQueryRequest\x1a\x17.bytebase.v1.SavedQuery\"p\xdaA\x12parent,saved_query\x8a\xea0\x16bb.savedQueries.create\x90\xea0\x01\x98\xea0\x01\x82\xd3\xe4\x93\x023:\vsaved_query\"$/v1/{parent=projects/*}/savedQueries\x12\x84\x01\n" +
"\rGetSavedQuery\x12!.bytebase.v1.GetSavedQueryRequest\x1a\x17.bytebase.v1.SavedQuery\"7\xdaA\x04name\x90\xea0\x02\x82\xd3\xe4\x93\x02&\x12$/v1/{name=projects/*/savedQueries/*}\x12\xb2\x01\n" +
@@ -1312,8 +1291,8 @@ const file_v1_saved_query_service_proto_rawDesc = "" +
"\x12SearchSavedQueries\x12&.bytebase.v1.SearchSavedQueriesRequest\x1a'.bytebase.v1.SearchSavedQueriesResponse\"C\xdaA\x06parent\x90\xea0\x02\x82\xd3\xe4\x93\x020:\x01*\"+/v1/{parent=projects/*}/savedQueries:search\x12\xc0\x01\n" +
"\x17SearchSavedQueryFolders\x12+.bytebase.v1.SearchSavedQueryFoldersRequest\x1a,.bytebase.v1.SearchSavedQueryFoldersResponse\"J\xdaA\x06parent\x90\xea0\x02\x82\xd3\xe4\x93\x027:\x01*\"2/v1/{parent=projects/*}/savedQueries:searchFolders\x12\xba\x01\n" +
"\x10UpdateSavedQuery\x12$.bytebase.v1.UpdateSavedQueryRequest\x1a\x17.bytebase.v1.SavedQuery\"g\xdaA\x17saved_query,update_mask\x90\xea0\x02\x98\xea0\x01\x82\xd3\xe4\x93\x02?:\vsaved_query20/v1/{saved_query.name=projects/*/savedQueries/*}\x12\xa8\x01\n" +
- "\x14UpdateSavedQueryStar\x12(.bytebase.v1.UpdateSavedQueryStarRequest\x1a\x17.bytebase.v1.SavedQuery\"M\xdaA\fname,starred\x90\xea0\x02\x82\xd3\xe4\x93\x024:\x01*\"//v1/{name=projects/*/savedQueries/*}:updateStar\x12\xbc\x01\n" +
- "\x12MoveMySavedQueries\x12&.bytebase.v1.MoveMySavedQueriesRequest\x1a'.bytebase.v1.MoveMySavedQueriesResponse\"U\xdaA\x14parent,target_folder\x90\xea0\x02\x98\xea0\x01\x82\xd3\xe4\x93\x020:\x01*\"+/v1/{parent=projects/*}/savedQueries:moveMy\x12\x8d\x01\n" +
+ "\x14UpdateSavedQueryStar\x12(.bytebase.v1.UpdateSavedQueryStarRequest\x1a\x17.bytebase.v1.SavedQuery\"M\xdaA\fname,starred\x90\xea0\x02\x82\xd3\xe4\x93\x024:\x01*\"//v1/{name=projects/*/savedQueries/*}:updateStar\x12\xca\x01\n" +
+ "\x12MoveMySavedQueries\x12&.bytebase.v1.MoveMySavedQueriesRequest\x1a'.bytebase.v1.MoveMySavedQueriesResponse\"c\xdaA\"parent,source_folder,target_folder\x90\xea0\x02\x98\xea0\x01\x82\xd3\xe4\x93\x020:\x01*\"+/v1/{parent=projects/*}/savedQueries:moveMy\x12\x8d\x01\n" +
"\x10DeleteSavedQuery\x12$.bytebase.v1.DeleteSavedQueryRequest\x1a\x16.google.protobuf.Empty\";\xdaA\x04name\x90\xea0\x02\x98\xea0\x01\x82\xd3\xe4\x93\x02&*$/v1/{name=projects/*/savedQueries/*}\x12\xa8\x01\n" +
"\x13GetSavedQueryPolicy\x12'.bytebase.v1.GetSavedQueryPolicyRequest\x1a\x1d.bytebase.v1.SavedQueryPolicy\"I\xdaA\bresource\x90\xea0\x02\x82\xd3\xe4\x93\x024\x122/v1/{resource=projects/*/savedQueries/*}:getPolicy\x12\xb6\x01\n" +
"\x13SetSavedQueryPolicy\x12'.bytebase.v1.SetSavedQueryPolicyRequest\x1a\x1d.bytebase.v1.SavedQueryPolicy\"W\xdaA\x0fresource,policy\x90\xea0\x02\x98\xea0\x01\x82\xd3\xe4\x93\x027:\x01*\"2/v1/{resource=projects/*/savedQueries/*}:setPolicyB\xac\x01\n" +
diff --git a/backend/generated-go/v1/saved_query_service_equal.pb.go b/backend/generated-go/v1/saved_query_service_equal.pb.go
index 41680b7221..6f03fc0faa 100644
--- a/backend/generated-go/v1/saved_query_service_equal.pb.go
+++ b/backend/generated-go/v1/saved_query_service_equal.pb.go
@@ -160,14 +160,6 @@ func (x *MoveMySavedQueriesRequest) Equal(y *MoveMySavedQueriesRequest) bool {
if x.Parent != y.Parent {
return false
}
- if len(x.Names) != len(y.Names) {
- return false
- }
- for i := 0; i < len(x.Names); i++ {
- if x.Names[i] != y.Names[i] {
- return false
- }
- }
if x.SourceFolder != y.SourceFolder {
return false
}
diff --git a/backend/generated-go/v1/saved_query_service_grpc.pb.go b/backend/generated-go/v1/saved_query_service_grpc.pb.go
index c171627628..dc9f385d23 100644
--- a/backend/generated-go/v1/saved_query_service_grpc.pb.go
+++ b/backend/generated-go/v1/saved_query_service_grpc.pb.go
@@ -37,92 +37,73 @@ const (
//
// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream.
//
-// SavedQueryService manages saved queries for SQL Editor query development.
+// SavedQueryService manages saved queries in the SQL Editor.
//
-// A saved query is private to its creator until shared. Three things grant
-// access to one: being its creator (the fixed owner), holding a VIEWER or
-// EDITOR binding on it, and holding bb.savedQueries.manage, the admin backstop
-// that reaches private saved queries too. Bindings are managed through the
-// GetSavedQueryPolicy/SetSavedQueryPolicy pair.
+// A saved query is private to its creator until shared. Permissions come from
+// three places:
+// - The creator owns the saved query and holds every permission on it.
+// - A VIEWER binding grants bb.savedQueries.get and getIamPolicy; an EDITOR
+// binding adds update.
+// - Permissions granted on the project or workspace apply to every saved
+// query in the project, private ones included.
//
-// Two gates sit on top of that: bb.savedQueries.search gates discovery, and
-// running a saved query needs the SQL Editor's own database permissions.
+// A caller without a method's permission gets NotFound, not
+// PermissionDenied, so private names stay unprobeable. Running a saved query
+// is governed by the SQL Editor's database permissions, not by this service.
type SavedQueryServiceClient interface {
- // Create a saved query. The creator becomes its fixed owner, and the saved
- // query starts private.
- // Permissions required: bb.savedQueries.create on the parent project
+ // Create a saved query. The creator becomes the owner and the saved query
+ // starts private.
+ // Permissions required: bb.savedQueries.create on the project
CreateSavedQuery(ctx context.Context, in *CreateSavedQueryRequest, opts ...grpc.CallOption) (*SavedQuery, error)
- // Get a saved query with its full content. An unreadable saved query returns
- // NotFound rather than PermissionDenied, so it stays unprobeable by name.
- // Permissions required: creator, a VIEWER or EDITOR binding, or bb.savedQueries.manage
+ // Get a saved query with its full content.
+ // Permissions required: bb.savedQueries.get (creator, VIEWER/EDITOR
+ // binding, or project-level grant)
GetSavedQuery(ctx context.Context, in *GetSavedQueryRequest, opts ...grpc.CallOption) (*SavedQuery, error)
- // List saved queries for auditing. Bindings are ignored: the permission
- // alone reads every matched saved query's content, private ones included.
- // Returns whole statements rather than Search's previews, and accepts
- // "projects/-" to span every project.
- // Permissions required: bb.savedQueries.list on the parent project, or
- // workspace-wide when the parent is "projects/-"
+ // List saved queries for auditing. The permission alone grants reading
+ // every matched saved query with full content, private ones included;
+ // bindings are ignored. Use parent "projects/-" for all projects.
+ // Permissions required: bb.savedQueries.list on the project, or on the
+ // workspace when the parent is "projects/-"
ListSavedQueries(ctx context.Context, in *ListSavedQueriesRequest, opts ...grpc.CallOption) (*ListSavedQueriesResponse, error)
- // Search saved queries in one project: the SQL Editor's list path, returning
- // content previews.
- //
- // Caller-scoped, always: the caller's own saved queries plus those a binding
- // shares with them. bb.savedQueries.manage does not widen it — an admin
- // reading everyone's saved queries uses ListSavedQueries, which is built for
- // that. The permission here gates discovery only and grants access to
- // nothing by itself.
+ // Search saved queries in one project. Returns content previews of the
+ // saved queries the caller can read, the same access rule as GetSavedQuery.
// Permissions required: bb.savedQueries.search on the project
SearchSavedQueries(ctx context.Context, in *SearchSavedQueriesRequest, opts ...grpc.CallOption) (*SearchSavedQueriesResponse, error)
- // Search the folder paths holding saved queries the caller can read. Folders
- // are a derived view over the `folder` field rather than a resource
- // collection, so this is a custom method, caller-scoped like
- // SearchSavedQueries.
- //
- // A path is returned when at least one readable saved query sits in it —
- // including one somebody else filed and shared, since a client seeds its
- // folder tree from here and cannot expand into a folder it never learns
- // about. Use the filter to split your own folders (`creator == "users/me"`)
- // from the ones reaching you through a grant (`shared == true`).
+ // Search folder paths. A path is returned when it holds at least one saved
+ // query the caller can read, the same access rule as SearchSavedQueries.
// Permissions required: bb.savedQueries.search on the project
SearchSavedQueryFolders(ctx context.Context, in *SearchSavedQueryFoldersRequest, opts ...grpc.CallOption) (*SearchSavedQueryFoldersResponse, error)
- // Update a saved query. `title`, `content`, and `database` need write access;
- // `folder` is creator/admin only, because filing is organization rather than
- // editing. `database` must belong to the saved query's own project. An
- // unreadable saved query returns NotFound; a VIEWER who cannot write gets
- // PermissionDenied.
- // Permissions required: creator, an EDITOR binding, or bb.savedQueries.manage
+ // Update a saved query. `database` must belong to the saved query's project.
+ // Permissions required: bb.savedQueries.update (creator, EDITOR binding, or
+ // project-level grant)
UpdateSavedQuery(ctx context.Context, in *UpdateSavedQueryRequest, opts ...grpc.CallOption) (*SavedQuery, error)
- // Star or unstar a saved query for the caller. Stars are personal: yours are
- // invisible to everyone else and grant nothing. You can star any saved query
- // you created or have been granted access to; anything else answers
- // NotFound, so names stay unprobeable.
- // Permissions required: creator, or a VIEWER or EDITOR binding
+ // Star or unstar a saved query for the caller. Stars are personal: nobody
+ // else sees them and they grant nothing. The caller can star any saved
+ // query they can read. When access is lost the star is hidden, not
+ // deleted; it comes back if access returns.
+ // Permissions required: bb.savedQueries.get (creator, VIEWER/EDITOR
+ // binding, or project-level grant)
UpdateSavedQueryStar(ctx context.Context, in *UpdateSavedQueryStarRequest, opts ...grpc.CallOption) (*SavedQuery, error)
- // Move the caller's own saved queries into a folder, named individually or a
- // whole folder at a time. Moving a folder carries its descendants, so renaming "a/b" to
- // "a/c" also moves "a/b/deep" -- one call, not one per path.
- //
- // Filing is personal organization, so only the creator's own move: a folder
- // is that person's tree, and neither a binding nor the admin backstop
- // reaches into it. The response counts what moved.
+ // Move the caller's saved queries filed under `source_folder`, descendants
+ // included, into `target_folder`: renaming "a/b" to "a/c" also moves
+ // "a/b/deep". Only the caller's own saved queries move; the response counts
+ // how many did. Re-filing a single saved query is UpdateSavedQuery's
+ // `folder` field.
// Permissions required: creator
MoveMySavedQueries(ctx context.Context, in *MoveMySavedQueriesRequest, opts ...grpc.CallOption) (*MoveMySavedQueriesResponse, error)
- // Delete a saved query and every user's stars on it. An EDITOR binding never
- // carries deletion. An unreadable saved query returns NotFound; a grantee
- // who can read but not delete gets PermissionDenied.
- // Permissions required: creator, or bb.savedQueries.manage
+ // Delete a saved query and every user's stars on it. An EDITOR binding
+ // cannot delete.
+ // Permissions required: bb.savedQueries.delete (creator or project-level
+ // grant)
DeleteSavedQuery(ctx context.Context, in *DeleteSavedQueryRequest, opts ...grpc.CallOption) (*emptypb.Empty, error)
// Get a saved query's sharing policy: who it is shared with, at what level.
- //
- // Anyone who can read the saved query can read its policy, which is how a
- // grantee learns whether they may edit it. Callers who cannot read the
- // saved query get NotFound.
- // Permissions required: creator, a VIEWER or EDITOR binding, or bb.savedQueries.manage
+ // Permissions required: bb.savedQueries.getIamPolicy (creator, VIEWER/EDITOR
+ // binding, or project-level grant)
GetSavedQueryPolicy(ctx context.Context, in *GetSavedQueryPolicyRequest, opts ...grpc.CallOption) (*SavedQueryPolicy, error)
// Replace a saved query's sharing policy in full. `policy.etag` must match
- // the stored policy or the call fails with ABORTED, so a stale write cannot
- // reinstate a grant somebody just revoked.
- // Permissions required: creator, or bb.savedQueries.manage
+ // the stored policy; a mismatch fails with ABORTED.
+ // Permissions required: bb.savedQueries.setIamPolicy (creator or
+ // project-level grant; no predefined role carries it)
SetSavedQueryPolicy(ctx context.Context, in *SetSavedQueryPolicyRequest, opts ...grpc.CallOption) (*SavedQueryPolicy, error)
}
@@ -248,92 +229,73 @@ func (c *savedQueryServiceClient) SetSavedQueryPolicy(ctx context.Context, in *S
// All implementations must embed UnimplementedSavedQueryServiceServer
// for forward compatibility.
//
-// SavedQueryService manages saved queries for SQL Editor query development.
+// SavedQueryService manages saved queries in the SQL Editor.
//
-// A saved query is private to its creator until shared. Three things grant
-// access to one: being its creator (the fixed owner), holding a VIEWER or
-// EDITOR binding on it, and holding bb.savedQueries.manage, the admin backstop
-// that reaches private saved queries too. Bindings are managed through the
-// GetSavedQueryPolicy/SetSavedQueryPolicy pair.
+// A saved query is private to its creator until shared. Permissions come from
+// three places:
+// - The creator owns the saved query and holds every permission on it.
+// - A VIEWER binding grants bb.savedQueries.get and getIamPolicy; an EDITOR
+// binding adds update.
+// - Permissions granted on the project or workspace apply to every saved
+// query in the project, private ones included.
//
-// Two gates sit on top of that: bb.savedQueries.search gates discovery, and
-// running a saved query needs the SQL Editor's own database permissions.
+// A caller without a method's permission gets NotFound, not
+// PermissionDenied, so private names stay unprobeable. Running a saved query
+// is governed by the SQL Editor's database permissions, not by this service.
type SavedQueryServiceServer interface {
- // Create a saved query. The creator becomes its fixed owner, and the saved
- // query starts private.
- // Permissions required: bb.savedQueries.create on the parent project
+ // Create a saved query. The creator becomes the owner and the saved query
+ // starts private.
+ // Permissions required: bb.savedQueries.create on the project
CreateSavedQuery(context.Context, *CreateSavedQueryRequest) (*SavedQuery, error)
- // Get a saved query with its full content. An unreadable saved query returns
- // NotFound rather than PermissionDenied, so it stays unprobeable by name.
- // Permissions required: creator, a VIEWER or EDITOR binding, or bb.savedQueries.manage
+ // Get a saved query with its full content.
+ // Permissions required: bb.savedQueries.get (creator, VIEWER/EDITOR
+ // binding, or project-level grant)
GetSavedQuery(context.Context, *GetSavedQueryRequest) (*SavedQuery, error)
- // List saved queries for auditing. Bindings are ignored: the permission
- // alone reads every matched saved query's content, private ones included.
- // Returns whole statements rather than Search's previews, and accepts
- // "projects/-" to span every project.
- // Permissions required: bb.savedQueries.list on the parent project, or
- // workspace-wide when the parent is "projects/-"
+ // List saved queries for auditing. The permission alone grants reading
+ // every matched saved query with full content, private ones included;
+ // bindings are ignored. Use parent "projects/-" for all projects.
+ // Permissions required: bb.savedQueries.list on the project, or on the
+ // workspace when the parent is "projects/-"
ListSavedQueries(context.Context, *ListSavedQueriesRequest) (*ListSavedQueriesResponse, error)
- // Search saved queries in one project: the SQL Editor's list path, returning
- // content previews.
- //
- // Caller-scoped, always: the caller's own saved queries plus those a binding
- // shares with them. bb.savedQueries.manage does not widen it — an admin
- // reading everyone's saved queries uses ListSavedQueries, which is built for
- // that. The permission here gates discovery only and grants access to
- // nothing by itself.
+ // Search saved queries in one project. Returns content previews of the
+ // saved queries the caller can read, the same access rule as GetSavedQuery.
// Permissions required: bb.savedQueries.search on the project
SearchSavedQueries(context.Context, *SearchSavedQueriesRequest) (*SearchSavedQueriesResponse, error)
- // Search the folder paths holding saved queries the caller can read. Folders
- // are a derived view over the `folder` field rather than a resource
- // collection, so this is a custom method, caller-scoped like
- // SearchSavedQueries.
- //
- // A path is returned when at least one readable saved query sits in it —
- // including one somebody else filed and shared, since a client seeds its
- // folder tree from here and cannot expand into a folder it never learns
- // about. Use the filter to split your own folders (`creator == "users/me"`)
- // from the ones reaching you through a grant (`shared == true`).
+ // Search folder paths. A path is returned when it holds at least one saved
+ // query the caller can read, the same access rule as SearchSavedQueries.
// Permissions required: bb.savedQueries.search on the project
SearchSavedQueryFolders(context.Context, *SearchSavedQueryFoldersRequest) (*SearchSavedQueryFoldersResponse, error)
- // Update a saved query. `title`, `content`, and `database` need write access;
- // `folder` is creator/admin only, because filing is organization rather than
- // editing. `database` must belong to the saved query's own project. An
- // unreadable saved query returns NotFound; a VIEWER who cannot write gets
- // PermissionDenied.
- // Permissions required: creator, an EDITOR binding, or bb.savedQueries.manage
+ // Update a saved query. `database` must belong to the saved query's project.
+ // Permissions required: bb.savedQueries.update (creator, EDITOR binding, or
+ // project-level grant)
UpdateSavedQuery(context.Context, *UpdateSavedQueryRequest) (*SavedQuery, error)
- // Star or unstar a saved query for the caller. Stars are personal: yours are
- // invisible to everyone else and grant nothing. You can star any saved query
- // you created or have been granted access to; anything else answers
- // NotFound, so names stay unprobeable.
- // Permissions required: creator, or a VIEWER or EDITOR binding
+ // Star or unstar a saved query for the caller. Stars are personal: nobody
+ // else sees them and they grant nothing. The caller can star any saved
+ // query they can read. When access is lost the star is hidden, not
+ // deleted; it comes back if access returns.
+ // Permissions required: bb.savedQueries.get (creator, VIEWER/EDITOR
+ // binding, or project-level grant)
UpdateSavedQueryStar(context.Context, *UpdateSavedQueryStarRequest) (*SavedQuery, error)
- // Move the caller's own saved queries into a folder, named individually or a
- // whole folder at a time. Moving a folder carries its descendants, so renaming "a/b" to
- // "a/c" also moves "a/b/deep" -- one call, not one per path.
- //
- // Filing is personal organization, so only the creator's own move: a folder
- // is that person's tree, and neither a binding nor the admin backstop
- // reaches into it. The response counts what moved.
+ // Move the caller's saved queries filed under `source_folder`, descendants
+ // included, into `target_folder`: renaming "a/b" to "a/c" also moves
+ // "a/b/deep". Only the caller's own saved queries move; the response counts
+ // how many did. Re-filing a single saved query is UpdateSavedQuery's
+ // `folder` field.
// Permissions required: creator
MoveMySavedQueries(context.Context, *MoveMySavedQueriesRequest) (*MoveMySavedQueriesResponse, error)
- // Delete a saved query and every user's stars on it. An EDITOR binding never
- // carries deletion. An unreadable saved query returns NotFound; a grantee
- // who can read but not delete gets PermissionDenied.
- // Permissions required: creator, or bb.savedQueries.manage
+ // Delete a saved query and every user's stars on it. An EDITOR binding
+ // cannot delete.
+ // Permissions required: bb.savedQueries.delete (creator or project-level
+ // grant)
DeleteSavedQuery(context.Context, *DeleteSavedQueryRequest) (*emptypb.Empty, error)
// Get a saved query's sharing policy: who it is shared with, at what level.
- //
- // Anyone who can read the saved query can read its policy, which is how a
- // grantee learns whether they may edit it. Callers who cannot read the
- // saved query get NotFound.
- // Permissions required: creator, a VIEWER or EDITOR binding, or bb.savedQueries.manage
+ // Permissions required: bb.savedQueries.getIamPolicy (creator, VIEWER/EDITOR
+ // binding, or project-level grant)
GetSavedQueryPolicy(context.Context, *GetSavedQueryPolicyRequest) (*SavedQueryPolicy, error)
// Replace a saved query's sharing policy in full. `policy.etag` must match
- // the stored policy or the call fails with ABORTED, so a stale write cannot
- // reinstate a grant somebody just revoked.
- // Permissions required: creator, or bb.savedQueries.manage
+ // the stored policy; a mismatch fails with ABORTED.
+ // Permissions required: bb.savedQueries.setIamPolicy (creator or
+ // project-level grant; no predefined role carries it)
SetSavedQueryPolicy(context.Context, *SetSavedQueryPolicyRequest) (*SavedQueryPolicy, error)
mustEmbedUnimplementedSavedQueryServiceServer()
}
diff --git a/backend/generated-go/v1/v1connect/saved_query_service.connect.go b/backend/generated-go/v1/v1connect/saved_query_service.connect.go
index e0c4a6c551..5f2053ef97 100644
--- a/backend/generated-go/v1/v1connect/saved_query_service.connect.go
+++ b/backend/generated-go/v1/v1connect/saved_query_service.connect.go
@@ -71,81 +71,59 @@ const (
// SavedQueryServiceClient is a client for the bytebase.v1.SavedQueryService service.
type SavedQueryServiceClient interface {
- // Create a saved query. The creator becomes its fixed owner, and the saved
- // query starts private.
- // Permissions required: bb.savedQueries.create on the parent project
+ // Create a saved query. The creator becomes the owner and the saved query
+ // starts private.
+ // Permissions required: bb.savedQueries.create on the project
CreateSavedQuery(context.Context, *connect.Request[v1.CreateSavedQueryRequest]) (*connect.Response[v1.SavedQuery], error)
- // Get a saved query with its full content. An unreadable saved query returns
- // NotFound rather than PermissionDenied, so it stays unprobeable by name.
- // Permissions required: creator, a VIEWER or EDITOR binding, or bb.savedQueries.manage
+ // Get a saved query with its full content.
+ // Permissions required: bb.savedQueries.get (creator, VIEWER/EDITOR
+ // binding, or project-level grant)
GetSavedQuery(context.Context, *connect.Request[v1.GetSavedQueryRequest]) (*connect.Response[v1.SavedQuery], error)
- // List saved queries for auditing. Bindings are ignored: the permission
- // alone reads every matched saved query's content, private ones included.
- // Returns whole statements rather than Search's previews, and accepts
- // "projects/-" to span every project.
- // Permissions required: bb.savedQueries.list on the parent project, or
- // workspace-wide when the parent is "projects/-"
+ // List saved queries for auditing. The permission alone grants reading
+ // every matched saved query with full content, private ones included;
+ // bindings are ignored. Use parent "projects/-" for all projects.
+ // Permissions required: bb.savedQueries.list on the project, or on the
+ // workspace when the parent is "projects/-"
ListSavedQueries(context.Context, *connect.Request[v1.ListSavedQueriesRequest]) (*connect.Response[v1.ListSavedQueriesResponse], error)
- // Search saved queries in one project: the SQL Editor's list path, returning
- // content previews.
- //
- // Caller-scoped, always: the caller's own saved queries plus those a binding
- // shares with them. bb.savedQueries.manage does not widen it — an admin
- // reading everyone's saved queries uses ListSavedQueries, which is built for
- // that. The permission here gates discovery only and grants access to
- // nothing by itself.
+ // Search saved queries in one project. Returns content previews of the
+ // saved queries the caller can read, the same access rule as GetSavedQuery.
// Permissions required: bb.savedQueries.search on the project
SearchSavedQueries(context.Context, *connect.Request[v1.SearchSavedQueriesRequest]) (*connect.Response[v1.SearchSavedQueriesResponse], error)
- // Search the folder paths holding saved queries the caller can read. Folders
- // are a derived view over the `folder` field rather than a resource
- // collection, so this is a custom method, caller-scoped like
- // SearchSavedQueries.
- //
- // A path is returned when at least one readable saved query sits in it —
- // including one somebody else filed and shared, since a client seeds its
- // folder tree from here and cannot expand into a folder it never learns
- // about. Use the filter to split your own folders (`creator == "users/me"`)
- // from the ones reaching you through a grant (`shared == true`).
+ // Search folder paths. A path is returned when it holds at least one saved
+ // query the caller can read, the same access rule as SearchSavedQueries.
// Permissions required: bb.savedQueries.search on the project
SearchSavedQueryFolders(context.Context, *connect.Request[v1.SearchSavedQueryFoldersRequest]) (*connect.Response[v1.SearchSavedQueryFoldersResponse], error)
- // Update a saved query. `title`, `content`, and `database` need write access;
- // `folder` is creator/admin only, because filing is organization rather than
- // editing. `database` must belong to the saved query's own project. An
- // unreadable saved query returns NotFound; a VIEWER who cannot write gets
- // PermissionDenied.
- // Permissions required: creator, an EDITOR binding, or bb.savedQueries.manage
+ // Update a saved query. `database` must belong to the saved query's project.
+ // Permissions required: bb.savedQueries.update (creator, EDITOR binding, or
+ // project-level grant)
UpdateSavedQuery(context.Context, *connect.Request[v1.UpdateSavedQueryRequest]) (*connect.Response[v1.SavedQuery], error)
- // Star or unstar a saved query for the caller. Stars are personal: yours are
- // invisible to everyone else and grant nothing. You can star any saved query
- // you created or have been granted access to; anything else answers
- // NotFound, so names stay unprobeable.
- // Permissions required: creator, or a VIEWER or EDITOR binding
+ // Star or unstar a saved query for the caller. Stars are personal: nobody
+ // else sees them and they grant nothing. The caller can star any saved
+ // query they can read. When access is lost the star is hidden, not
+ // deleted; it comes back if access returns.
+ // Permissions required: bb.savedQueries.get (creator, VIEWER/EDITOR
+ // binding, or project-level grant)
UpdateSavedQueryStar(context.Context, *connect.Request[v1.UpdateSavedQueryStarRequest]) (*connect.Response[v1.SavedQuery], error)
- // Move the caller's own saved queries into a folder, named individually or a
- // whole folder at a time. Moving a folder carries its descendants, so renaming "a/b" to
- // "a/c" also moves "a/b/deep" -- one call, not one per path.
- //
- // Filing is personal organization, so only the creator's own move: a folder
- // is that person's tree, and neither a binding nor the admin backstop
- // reaches into it. The response counts what moved.
+ // Move the caller's saved queries filed under `source_folder`, descendants
+ // included, into `target_folder`: renaming "a/b" to "a/c" also moves
+ // "a/b/deep". Only the caller's own saved queries move; the response counts
+ // how many did. Re-filing a single saved query is UpdateSavedQuery's
+ // `folder` field.
// Permissions required: creator
MoveMySavedQueries(context.Context, *connect.Request[v1.MoveMySavedQueriesRequest]) (*connect.Response[v1.MoveMySavedQueriesResponse], error)
- // Delete a saved query and every user's stars on it. An EDITOR binding never
- // carries deletion. An unreadable saved query returns NotFound; a grantee
- // who can read but not delete gets PermissionDenied.
- // Permissions required: creator, or bb.savedQueries.manage
+ // Delete a saved query and every user's stars on it. An EDITOR binding
+ // cannot delete.
+ // Permissions required: bb.savedQueries.delete (creator or project-level
+ // grant)
DeleteSavedQuery(context.Context, *connect.Request[v1.DeleteSavedQueryRequest]) (*connect.Response[emptypb.Empty], error)
// Get a saved query's sharing policy: who it is shared with, at what level.
- //
- // Anyone who can read the saved query can read its policy, which is how a
- // grantee learns whether they may edit it. Callers who cannot read the
- // saved query get NotFound.
- // Permissions required: creator, a VIEWER or EDITOR binding, or bb.savedQueries.manage
+ // Permissions required: bb.savedQueries.getIamPolicy (creator, VIEWER/EDITOR
+ // binding, or project-level grant)
GetSavedQueryPolicy(context.Context, *connect.Request[v1.GetSavedQueryPolicyRequest]) (*connect.Response[v1.SavedQueryPolicy], error)
// Replace a saved query's sharing policy in full. `policy.etag` must match
- // the stored policy or the call fails with ABORTED, so a stale write cannot
- // reinstate a grant somebody just revoked.
- // Permissions required: creator, or bb.savedQueries.manage
+ // the stored policy; a mismatch fails with ABORTED.
+ // Permissions required: bb.savedQueries.setIamPolicy (creator or
+ // project-level grant; no predefined role carries it)
SetSavedQueryPolicy(context.Context, *connect.Request[v1.SetSavedQueryPolicyRequest]) (*connect.Response[v1.SavedQueryPolicy], error)
}
@@ -301,81 +279,59 @@ func (c *savedQueryServiceClient) SetSavedQueryPolicy(ctx context.Context, req *
// SavedQueryServiceHandler is an implementation of the bytebase.v1.SavedQueryService service.
type SavedQueryServiceHandler interface {
- // Create a saved query. The creator becomes its fixed owner, and the saved
- // query starts private.
- // Permissions required: bb.savedQueries.create on the parent project
+ // Create a saved query. The creator becomes the owner and the saved query
+ // starts private.
+ // Permissions required: bb.savedQueries.create on the project
CreateSavedQuery(context.Context, *connect.Request[v1.CreateSavedQueryRequest]) (*connect.Response[v1.SavedQuery], error)
- // Get a saved query with its full content. An unreadable saved query returns
- // NotFound rather than PermissionDenied, so it stays unprobeable by name.
- // Permissions required: creator, a VIEWER or EDITOR binding, or bb.savedQueries.manage
+ // Get a saved query with its full content.
+ // Permissions required: bb.savedQueries.get (creator, VIEWER/EDITOR
+ // binding, or project-level grant)
GetSavedQuery(context.Context, *connect.Request[v1.GetSavedQueryRequest]) (*connect.Response[v1.SavedQuery], error)
- // List saved queries for auditing. Bindings are ignored: the permission
- // alone reads every matched saved query's content, private ones included.
- // Returns whole statements rather than Search's previews, and accepts
- // "projects/-" to span every project.
- // Permissions required: bb.savedQueries.list on the parent project, or
- // workspace-wide when the parent is "projects/-"
+ // List saved queries for auditing. The permission alone grants reading
+ // every matched saved query with full content, private ones included;
+ // bindings are ignored. Use parent "projects/-" for all projects.
+ // Permissions required: bb.savedQueries.list on the project, or on the
+ // workspace when the parent is "projects/-"
ListSavedQueries(context.Context, *connect.Request[v1.ListSavedQueriesRequest]) (*connect.Response[v1.ListSavedQueriesResponse], error)
- // Search saved queries in one project: the SQL Editor's list path, returning
- // content previews.
- //
- // Caller-scoped, always: the caller's own saved queries plus those a binding
- // shares with them. bb.savedQueries.manage does not widen it — an admin
- // reading everyone's saved queries uses ListSavedQueries, which is built for
- // that. The permission here gates discovery only and grants access to
- // nothing by itself.
+ // Search saved queries in one project. Returns content previews of the
+ // saved queries the caller can read, the same access rule as GetSavedQuery.
// Permissions required: bb.savedQueries.search on the project
SearchSavedQueries(context.Context, *connect.Request[v1.SearchSavedQueriesRequest]) (*connect.Response[v1.SearchSavedQueriesResponse], error)
- // Search the folder paths holding saved queries the caller can read. Folders
- // are a derived view over the `folder` field rather than a resource
- // collection, so this is a custom method, caller-scoped like
- // SearchSavedQueries.
- //
- // A path is returned when at least one readable saved query sits in it —
- // including one somebody else filed and shared, since a client seeds its
- // folder tree from here and cannot expand into a folder it never learns
- // about. Use the filter to split your own folders (`creator == "users/me"`)
- // from the ones reaching you through a grant (`shared == true`).
+ // Search folder paths. A path is returned when it holds at least one saved
+ // query the caller can read, the same access rule as SearchSavedQueries.
// Permissions required: bb.savedQueries.search on the project
SearchSavedQueryFolders(context.Context, *connect.Request[v1.SearchSavedQueryFoldersRequest]) (*connect.Response[v1.SearchSavedQueryFoldersResponse], error)
- // Update a saved query. `title`, `content`, and `database` need write access;
- // `folder` is creator/admin only, because filing is organization rather than
- // editing. `database` must belong to the saved query's own project. An
- // unreadable saved query returns NotFound; a VIEWER who cannot write gets
- // PermissionDenied.
- // Permissions required: creator, an EDITOR binding, or bb.savedQueries.manage
+ // Update a saved query. `database` must belong to the saved query's project.
+ // Permissions required: bb.savedQueries.update (creator, EDITOR binding, or
+ // project-level grant)
UpdateSavedQuery(context.Context, *connect.Request[v1.UpdateSavedQueryRequest]) (*connect.Response[v1.SavedQuery], error)
- // Star or unstar a saved query for the caller. Stars are personal: yours are
- // invisible to everyone else and grant nothing. You can star any saved query
- // you created or have been granted access to; anything else answers
- // NotFound, so names stay unprobeable.
- // Permissions required: creator, or a VIEWER or EDITOR binding
+ // Star or unstar a saved query for the caller. Stars are personal: nobody
+ // else sees them and they grant nothing. The caller can star any saved
+ // query they can read. When access is lost the star is hidden, not
+ // deleted; it comes back if access returns.
+ // Permissions required: bb.savedQueries.get (creator, VIEWER/EDITOR
+ // binding, or project-level grant)
UpdateSavedQueryStar(context.Context, *connect.Request[v1.UpdateSavedQueryStarRequest]) (*connect.Response[v1.SavedQuery], error)
- // Move the caller's own saved queries into a folder, named individually or a
- // whole folder at a time. Moving a folder carries its descendants, so renaming "a/b" to
- // "a/c" also moves "a/b/deep" -- one call, not one per path.
- //
- // Filing is personal organization, so only the creator's own move: a folder
- // is that person's tree, and neither a binding nor the admin backstop
- // reaches into it. The response counts what moved.
+ // Move the caller's saved queries filed under `source_folder`, descendants
+ // included, into `target_folder`: renaming "a/b" to "a/c" also moves
+ // "a/b/deep". Only the caller's own saved queries move; the response counts
+ // how many did. Re-filing a single saved query is UpdateSavedQuery's
+ // `folder` field.
// Permissions required: creator
MoveMySavedQueries(context.Context, *connect.Request[v1.MoveMySavedQueriesRequest]) (*connect.Response[v1.MoveMySavedQueriesResponse], error)
- // Delete a saved query and every user's stars on it. An EDITOR binding never
- // carries deletion. An unreadable saved query returns NotFound; a grantee
- // who can read but not delete gets PermissionDenied.
- // Permissions required: creator, or bb.savedQueries.manage
+ // Delete a saved query and every user's stars on it. An EDITOR binding
+ // cannot delete.
+ // Permissions required: bb.savedQueries.delete (creator or project-level
+ // grant)
DeleteSavedQuery(context.Context, *connect.Request[v1.DeleteSavedQueryRequest]) (*connect.Response[emptypb.Empty], error)
// Get a saved query's sharing policy: who it is shared with, at what level.
- //
- // Anyone who can read the saved query can read its policy, which is how a
- // grantee learns whether they may edit it. Callers who cannot read the
- // saved query get NotFound.
- // Permissions required: creator, a VIEWER or EDITOR binding, or bb.savedQueries.manage
+ // Permissions required: bb.savedQueries.getIamPolicy (creator, VIEWER/EDITOR
+ // binding, or project-level grant)
GetSavedQueryPolicy(context.Context, *connect.Request[v1.GetSavedQueryPolicyRequest]) (*connect.Response[v1.SavedQueryPolicy], error)
// Replace a saved query's sharing policy in full. `policy.etag` must match
- // the stored policy or the call fails with ABORTED, so a stale write cannot
- // reinstate a grant somebody just revoked.
- // Permissions required: creator, or bb.savedQueries.manage
+ // the stored policy; a mismatch fails with ABORTED.
+ // Permissions required: bb.savedQueries.setIamPolicy (creator or
+ // project-level grant; no predefined role carries it)
SetSavedQueryPolicy(context.Context, *connect.Request[v1.SetSavedQueryPolicyRequest]) (*connect.Response[v1.SavedQueryPolicy], error)
}
diff --git a/backend/migrator/migration/3.22/0009##split_saved_query_manage.sql b/backend/migrator/migration/3.22/0009##split_saved_query_manage.sql
new file mode 100644
index 0000000000..7f86e2c08c
--- /dev/null
+++ b/backend/migrator/migration/3.22/0009##split_saved_query_manage.sql
@@ -0,0 +1,19 @@
+-- Split the admin backstop bb.savedQueries.manage into the per-verb
+-- permissions it covered, minus re-share: get, getIamPolicy, update, delete.
+-- Custom roles reach here from two populations: pre-release 3.22 builds that
+-- created bb.savedQueries.manage directly, and every shipped release, whose
+-- bb.worksheets.manage custom roles 0007 renames into it during the same
+-- upgrade. setIamPolicy is deliberately not granted: sharing retires to the
+-- creator for migrated custom roles exactly as it does for the predefined
+-- admin roles, and granting it back is an explicit custom-role edit.
+-- Predefined roles are code.
+UPDATE role
+SET permissions = jsonb_set(permissions, '{permissions}', (
+ SELECT COALESCE(jsonb_agg(DISTINCT expanded.v), '[]'::jsonb)
+ FROM jsonb_array_elements_text(permissions->'permissions') AS p,
+ LATERAL unnest(CASE WHEN p = 'bb.savedQueries.manage'
+ THEN ARRAY['bb.savedQueries.get', 'bb.savedQueries.getIamPolicy', 'bb.savedQueries.update', 'bb.savedQueries.delete']
+ ELSE ARRAY[p]
+ END) AS expanded(v)))
+WHERE jsonb_typeof(permissions->'permissions') = 'array'
+ AND permissions->'permissions' ? 'bb.savedQueries.manage';
diff --git a/backend/migrator/migration/LATEST.sql b/backend/migrator/migration/LATEST.sql
index 36918f239f..4627bcdf6b 100644
--- a/backend/migrator/migration/LATEST.sql
+++ b/backend/migrator/migration/LATEST.sql
@@ -366,9 +366,9 @@ CREATE TABLE saved_query (
project text NOT NULL REFERENCES project(resource_id),
name text NOT NULL,
statement text NOT NULL,
- -- The folder path this saved query lives in ("a/b/c", '' = unfiled), set
- -- by its creator (or an admin). A folder is a path on rows, so empty
- -- folders cannot exist.
+ -- The folder path this saved query lives in ("a/b/c", '' = unfiled),
+ -- written under the ordinary update permission like any other field. A
+ -- folder is a path on rows, so empty folders cannot exist.
folder text NOT NULL DEFAULT '',
-- Stored as SavedQueryPayload (proto/store/store/saved_query.proto); the
-- connected database is a soft reference kept as its canonical name.
diff --git a/backend/migrator/migrator_test.go b/backend/migrator/migrator_test.go
index fa6940d55a..66bc212075 100644
--- a/backend/migrator/migrator_test.go
+++ b/backend/migrator/migrator_test.go
@@ -21,8 +21,8 @@ import (
func TestLatestVersion(t *testing.T) {
files, err := getSortedVersionedFiles()
require.NoError(t, err)
- require.Equal(t, semver.MustParse("3.22.8"), *files[len(files)-1].version)
- require.Equal(t, "migration/3.22/0008##saved_query_bindings.sql", files[len(files)-1].path)
+ require.Equal(t, semver.MustParse("3.22.9"), *files[len(files)-1].version)
+ require.Equal(t, "migration/3.22/0009##split_saved_query_manage.sql", files[len(files)-1].path)
}
func TestVersionUnique(t *testing.T) {
diff --git a/backend/migrator/split_saved_query_manage_test.go b/backend/migrator/split_saved_query_manage_test.go
new file mode 100644
index 0000000000..db159f8cf7
--- /dev/null
+++ b/backend/migrator/split_saved_query_manage_test.go
@@ -0,0 +1,76 @@
+package migrator
+
+import (
+ "context"
+ "encoding/json"
+ "testing"
+
+ "github.com/stretchr/testify/require"
+
+ "github.com/bytebase/bytebase/backend/common/testcontainer"
+)
+
+// TestSplitSavedQueryManageMigration exercises 3.22/0009's jsonb transform:
+// bb.savedQueries.manage expands to the four per-verb permissions —
+// deliberately without setIamPolicy — deduplicated, while rows without
+// manage and rows with a non-array permissions payload stay untouched.
+func TestSplitSavedQueryManageMigration(t *testing.T) {
+ if testing.Short() {
+ t.Skip("skipping testcontainer test in short mode")
+ }
+ ctx := context.Background()
+ pg := testcontainer.GetTestPgContainer(ctx, t)
+ defer pg.Close(ctx)
+ db := pg.GetDB()
+
+ _, err := db.ExecContext(ctx, `
+ CREATE TABLE role (
+ resource_id text NOT NULL PRIMARY KEY,
+ permissions jsonb NOT NULL DEFAULT '{}'
+ );
+ INSERT INTO role (resource_id, permissions) VALUES
+ ('manage-holder', '{"permissions": ["bb.savedQueries.manage", "bb.savedQueries.get", "bb.projects.get"]}'),
+ ('no-manage', '{"permissions": ["bb.savedQueries.search", "bb.projects.get"]}'),
+ ('non-array', '{"permissions": {"oops": true}}'),
+ ('empty', '{}');
+ `)
+ require.NoError(t, err)
+
+ migration, err := migrationFS.ReadFile("migration/3.22/0009##split_saved_query_manage.sql")
+ require.NoError(t, err)
+ _, err = db.ExecContext(ctx, string(migration))
+ require.NoError(t, err)
+
+ permissionsOf := func(roleID string) []string {
+ var raw []byte
+ require.NoError(t, db.QueryRowContext(ctx, `SELECT permissions->'permissions' FROM role WHERE resource_id = $1`, roleID).Scan(&raw))
+ if string(raw) == "null" {
+ return nil
+ }
+ var list []string
+ require.NoError(t, json.Unmarshal(raw, &list))
+ return list
+ }
+
+ // manage expands to the four verbs, deduplicated against the get the
+ // role already held; setIamPolicy is deliberately absent.
+ require.ElementsMatch(t, []string{
+ "bb.projects.get",
+ "bb.savedQueries.delete",
+ "bb.savedQueries.get",
+ "bb.savedQueries.getIamPolicy",
+ "bb.savedQueries.update",
+ }, permissionsOf("manage-holder"))
+ require.NotContains(t, permissionsOf("manage-holder"), "bb.savedQueries.setIamPolicy")
+
+ // Rows without manage keep their permissions verbatim.
+ require.Equal(t, []string{"bb.savedQueries.search", "bb.projects.get"}, permissionsOf("no-manage"))
+
+ // Non-array and empty payloads are untouched rather than mangled.
+ var nonArray string
+ require.NoError(t, db.QueryRowContext(ctx, `SELECT permissions::text FROM role WHERE resource_id = 'non-array'`).Scan(&nonArray))
+ require.JSONEq(t, `{"permissions": {"oops": true}}`, nonArray)
+ var empty string
+ require.NoError(t, db.QueryRowContext(ctx, `SELECT permissions::text FROM role WHERE resource_id = 'empty'`).Scan(&empty))
+ require.JSONEq(t, `{}`, empty)
+}
diff --git a/backend/store/predefined_roles.go b/backend/store/predefined_roles.go
index 38a7ca21c6..361919a80b 100644
--- a/backend/store/predefined_roles.go
+++ b/backend/store/predefined_roles.go
@@ -157,8 +157,11 @@ var PredefinedRoles = []*RoleMessage{
permission.UsersUpdateEmail,
permission.SavedQueriesCreate,
permission.SavedQueriesSearch,
+ permission.SavedQueriesGet,
+ permission.SavedQueriesGetIamPolicy,
permission.SavedQueriesList,
- permission.SavedQueriesManage,
+ permission.SavedQueriesUpdate,
+ permission.SavedQueriesDelete,
permission.WorkspacesGetIamPolicy,
permission.WorkspacesUpdate,
permission.WorkspacesDelete,
@@ -297,8 +300,11 @@ var PredefinedRoles = []*RoleMessage{
permission.GroupsList,
permission.SavedQueriesCreate,
permission.SavedQueriesSearch,
+ permission.SavedQueriesGet,
+ permission.SavedQueriesGetIamPolicy,
permission.SavedQueriesList,
- permission.SavedQueriesManage,
+ permission.SavedQueriesUpdate,
+ permission.SavedQueriesDelete,
permission.WorkspacesGetIamPolicy,
permission.ServiceAccountsGet,
permission.ServiceAccountsList,
@@ -426,8 +432,11 @@ var PredefinedRoles = []*RoleMessage{
permission.TaskRunsList,
permission.SavedQueriesCreate,
permission.SavedQueriesSearch,
+ permission.SavedQueriesGet,
+ permission.SavedQueriesGetIamPolicy,
permission.SavedQueriesList,
- permission.SavedQueriesManage,
+ permission.SavedQueriesUpdate,
+ permission.SavedQueriesDelete,
permission.ServiceAccountsCreate,
permission.ServiceAccountsDelete,
permission.ServiceAccountsGet,
diff --git a/backend/store/saved_query.go b/backend/store/saved_query.go
index dc20b209fd..6f430ea26a 100644
--- a/backend/store/saved_query.go
+++ b/backend/store/saved_query.go
@@ -59,10 +59,11 @@ type FindSavedQueryMessage struct {
PrincipalEmail string
// AccessMembers restricts results to saved queries the caller can read:
- // their own, plus any whose bindings name one of these principals
- // ("user:{email}" and "group:{email}" — the caller and their groups).
- // Leave nil to skip the access clause entirely, which is what the auditor
- // List does.
+ // their own, plus any whose bindings name one of these principals in the
+ // stored member form ("users/{email}" and "groups/{email}" — the caller
+ // and their groups).
+ // Leave nil to skip the access clause entirely: the auditor List, and
+ // Search for a caller with project-level bb.savedQueries.get.
//
// Must describe the same caller as PrincipalEmail: the clause reads "own"
// from PrincipalEmail and "granted" from here. Setting one without the
@@ -84,8 +85,12 @@ type FindSavedQueryMessage struct {
// PatchSavedQueryMessage is the message to patch a saved query.
type PatchSavedQueryMessage struct {
ResourceID string
- Title *string
- Statement *string
+ // ProjectID scopes the write to the project the caller was authorized in:
+ // a purge reassigns surviving saved queries to the default project, and a
+ // patch racing it must not land on the reassigned row.
+ ProjectID string
+ Title *string
+ Statement *string
// Database sets the connected database ("" clears it).
Database *string
// Folder re-files the saved query ("" = unfiled).
@@ -229,9 +234,15 @@ func (s *Store) ListSavedQueries(ctx context.Context, find *FindSavedQueryMessag
}
// bindingProbe builds the jsonb containment operand that matches any binding
-// naming this principal, e.g. `[{"members":["user:[email protected]"]}]`. `@>` on a
-// jsonb array is "contains an element containing this", so one probe per
-// principal, BitmapOr'd by the planner, answers "shared with me".
+// naming this principal, e.g. `[{"members":["users/[email protected]"]}]` — the
+// stored member form. `@>` on a jsonb array is "contains an element
+// containing this", so one probe per principal, BitmapOr'd by the planner,
+// answers "shared with me".
+//
+// The probe is level-blind on purpose: every current level's bundle grants
+// get (bindingGrants in api/v1/saved_query_service.go). A future level that
+// does not grant get must add a level term here, or Search would return
+// previews GetSavedQuery denies.
func bindingProbe(member string) (string, error) {
probe, err := json.Marshal([]map[string]any{{"members": []string{member}}})
if err != nil {
@@ -426,7 +437,7 @@ func (s *Store) PatchSavedQuery(ctx context.Context, patch *PatchSavedQueryMessa
}
}
- query, args, err := qb.Q().Space("UPDATE saved_query SET ? WHERE resource_id = ?", set, patch.ResourceID).ToSQL()
+ query, args, err := qb.Q().Space("UPDATE saved_query SET ? WHERE resource_id = ? AND project = ?", set, patch.ResourceID, patch.ProjectID).ToSQL()
if err != nil {
return errors.Wrapf(err, "failed to build sql")
}
@@ -436,14 +447,32 @@ func (s *Store) PatchSavedQuery(ctx context.Context, patch *PatchSavedQueryMessa
return nil
}
-// DeleteSavedQuery deletes an existing saved query by resource ID. Star rows
-// are deleted first, in full primary-key order — explicitly, not via the FK
-// cascade (which would lock the parent first) — matching the star and purge
-// lock order so a delete racing a star toggle or a purge cannot deadlock.
-func (s *Store) DeleteSavedQuery(ctx context.Context, resourceID string) error {
+// DeleteSavedQuery deletes an existing saved query and reports whether it was
+// still there to delete. Star rows are deleted first, in full primary-key
+// order — explicitly, not via the FK cascade (which would lock the parent
+// first) — matching the star and purge lock order so a delete racing a star
+// toggle or a purge cannot deadlock.
+//
+// Both statements scope by the project the caller was authorized in: a purge
+// reassigns surviving saved queries to the default project, and a delete
+// racing it must not land on the reassigned row. The row delete is the
+// arbiter — when it matches nothing (row gone, or reassigned after the star
+// statement's unlocked parent snapshot), the transaction rolls back, which
+// also restores any stars the first statement removed, and the caller gets
+// false to answer NotFound.
+//
+// Lifecycle policy (per the store's purge-fence rule): writers on existing
+// rows — delete, patch, star — require the row in the authorized project,
+// not an active project. Archived projects are unreachable through every
+// read path (the project.deleted = FALSE fence on the fetches), so the only
+// archival exposure is a write already in flight when the archive lands,
+// and that completing is an ordinary serialization of concurrent requests.
+// Only creation, which adds a row a purge cannot see, requires an active
+// project.
+func (s *Store) DeleteSavedQuery(ctx context.Context, projectID, resourceID string) (bool, error) {
tx, err := s.GetDB().BeginTx(ctx, nil)
if err != nil {
- return errors.Wrap(err, "failed to begin transaction")
+ return false, errors.Wrap(err, "failed to begin transaction")
}
defer tx.Rollback()
@@ -453,16 +482,28 @@ func (s *Store) DeleteSavedQuery(ctx context.Context, resourceID string) error {
SELECT saved_query, principal
FROM saved_query_star
WHERE saved_query = $1
+ AND EXISTS (
+ SELECT 1 FROM saved_query
+ WHERE resource_id = $1 AND project = $2
+ )
ORDER BY saved_query, principal
FOR UPDATE
)
- `, resourceID); err != nil {
- return errors.Wrapf(err, "failed to delete stars for saved query %s", resourceID)
+ `, resourceID, projectID); err != nil {
+ return false, errors.Wrapf(err, "failed to delete stars for saved query %s", resourceID)
}
- if _, err := tx.ExecContext(ctx, `DELETE FROM saved_query WHERE resource_id = $1`, resourceID); err != nil {
- return err
+ result, err := tx.ExecContext(ctx, `DELETE FROM saved_query WHERE resource_id = $1 AND project = $2`, resourceID, projectID)
+ if err != nil {
+ return false, err
}
- return tx.Commit()
+ deleted, err := result.RowsAffected()
+ if err != nil {
+ return false, errors.Wrap(err, "failed to count deleted saved queries")
+ }
+ if deleted == 0 {
+ return false, nil
+ }
+ return true, tx.Commit()
}
// SetSavedQueryStar stars or unstars a saved query for a principal, and
@@ -472,9 +513,12 @@ func (s *Store) DeleteSavedQuery(ctx context.Context, resourceID string) error {
// that cannot be locked in advance — that case alone takes the parent fence
// (lock the saved_query row), and its inserted key is novel so it never
// contends with a purge's existing-child locks. The parent fence is also the
-// only path that can observe a concurrent delete, which it reports as false
-// rather than an error so the caller decides what a vanished row means.
-func (s *Store) SetSavedQueryStar(ctx context.Context, savedQueryResourceID, principal string, starred bool) (bool, error) {
+// only path that can observe a concurrent delete or purge reassignment — it
+// requires the row in the project the caller was authorized in — and reports
+// either as false rather than an error so the caller decides what a vanished
+// row means. Removing an existing star stays project-blind: the star is the
+// caller's own marker, removable wherever its row went.
+func (s *Store) SetSavedQueryStar(ctx context.Context, projectID, savedQueryResourceID, principal string, starred bool) (bool, error) {
tx, err := s.GetDB().BeginTx(ctx, nil)
if err != nil {
return false, errors.Wrap(err, "failed to begin transaction")
@@ -499,9 +543,9 @@ func (s *Store) SetSavedQueryStar(ctx context.Context, savedQueryResourceID, pri
if err := tx.QueryRowContext(ctx, `
SELECT 1
FROM saved_query
- WHERE resource_id = $1
+ WHERE resource_id = $1 AND project = $2
FOR UPDATE
- `, savedQueryResourceID).Scan(&one); err != nil {
+ `, savedQueryResourceID, projectID).Scan(&one); err != nil {
if errors.Is(err, sql.ErrNoRows) {
return false, nil
}
@@ -533,46 +577,15 @@ func (s *Store) SetSavedQueryStar(ctx context.Context, savedQueryResourceID, pri
}
// BatchUpdateSavedQueryFolder re-files the given saved queries into folder.
-// The rows are locked in full primary-key order (resource_id) before the
-// update, so two overlapping batches can never lock in opposing orders; a
-// row deleted mid-batch simply updates zero rows.
-// MoveSavedQueries files the named saved queries, restricted to one creator:
-// filing is personal organization, so rows belonging to anyone else are not
-// selected and the count reports what actually moved.
-//
-// The CTE takes every row lock in primary-key order before the update touches
-// anything -- the store's batch rule, so two overlapping moves serialize
-// instead of deadlocking -- and one statement needs no explicit transaction.
-func (s *Store) MoveSavedQueries(ctx context.Context, projectID, creator string, resourceIDs []string, folder string) (int, error) {
- if len(resourceIDs) == 0 {
- return 0, nil
- }
- result, err := s.GetDB().ExecContext(ctx, `
- WITH locked AS (
- SELECT resource_id FROM saved_query
- WHERE resource_id = ANY($1) AND project = $2 AND creator = $3
- ORDER BY resource_id
- FOR UPDATE
- )
- UPDATE saved_query SET folder = $4, updated_at = now()
- WHERE resource_id IN (SELECT resource_id FROM locked)
- `, resourceIDs, projectID, creator, folder)
- if err != nil {
- return 0, errors.Wrap(err, "failed to move saved queries")
- }
- moved, err := result.RowsAffected()
- if err != nil {
- return 0, errors.Wrap(err, "failed to count moved saved queries")
- }
- return int(moved), nil
-}
-
// MoveSavedQueryFolder rewrites the folder prefix for one creator's saved
// queries: moving "a/b" to "a/c" also moves "a/b/deep" to "a/c/deep". The
// suffix keeps each descendant's own tail, and ltrim drops the separator when
// the target is empty so a row is unfiled rather than left at "/deep".
//
-// Locks in primary-key order like MoveSavedQueries, for the same reason.
+// The CTE takes every row lock in full primary-key order (resource_id) before
+// the update touches anything -- the store's batch rule, so two overlapping
+// moves serialize instead of deadlocking -- and one statement needs no
+// explicit transaction. A row deleted mid-move simply updates zero rows.
func (s *Store) MoveSavedQueryFolder(ctx context.Context, projectID, creator, source, target string) (int, error) {
if source == "" {
return 0, errors.New("source folder cannot be empty")
@@ -599,24 +612,22 @@ func (s *Store) MoveSavedQueryFolder(ctx context.Context, projectID, creator, so
return int(moved), nil
}
-// ListSavedQueryFolderPaths returns the distinct folder paths of the saved
-// queries in a project that match filterQ. A non-nil creator restricts the
-// paths to that creator's rows, which is how the API layer applies the same
-// read rule the rows themselves carry: your own always, everyone's only with
-// the admin backstop.
// ListSavedQueryFolderPaths returns the distinct folder paths of the saved
// queries a caller can read, narrowed by filterQ. Access is the same predicate
-// SearchSavedQueries applies, and for the same reason: a folder is only useful
-// if its contents are reachable. Scoping these to the caller's *own* rows
-// instead would hide a shared saved query filed by its creator — the tree is
-// seeded from here, and a row whose folder has no node can never be expanded
-// into.
-func (s *Store) ListSavedQueryFolderPaths(ctx context.Context, projectID string, principalEmail string, accessMembers []string, filterQ *qb.Query) ([]string, error) {
+// SearchSavedQueries applies (nil accessMembers skips the clause, for a
+// caller with project-level bb.savedQueries.get), and for the same reason: a
+// folder is only useful if its contents are reachable. Scoping these to the
+// caller's *own* rows instead would hide a shared saved query filed by its
+// creator — the tree is seeded from here, and a row whose folder has no node
+// can never be expanded into. workspaceID fences the project to the caller's
+// workspace and to active projects, exactly as the List query does.
+func (s *Store) ListSavedQueryFolderPaths(ctx context.Context, workspaceID string, projectID string, principalEmail string, accessMembers []string, filterQ *qb.Query) ([]string, error) {
q := qb.Q().Space(`
SELECT DISTINCT folder
FROM saved_query
WHERE TRUE`)
q.And("saved_query.project = ?", projectID)
+ q.And("EXISTS (SELECT 1 FROM project WHERE project.resource_id = saved_query.project AND project.workspace = ? AND project.deleted = FALSE)", workspaceID)
q.And("saved_query.folder <> ''")
if accessMembers != nil {
access := qb.Q().Space("saved_query.creator = ?", principalEmail)
@@ -741,8 +752,9 @@ func GetSearchSavedQueryFilter(ctx context.Context, s *Store, caller string, acc
return nil, errors.Errorf("invalid starred value %v, expect true or false", value)
case "shared":
// Reached through a binding, which is narrower than "somebody else
- // created it": an admin sees saved queries nobody shared with them,
- // and those must not show up in a Shared view.
+ // created it": a project-level bb.savedQueries.get holder sees
+ // saved queries nobody shared with them, and those must not show
+ // up in a Shared view.
shared, ok := value.(bool)
if !ok {
return nil, errors.Errorf("invalid shared value %v, expect true or false", value)
diff --git a/backend/store/saved_query_lock_order_test.go b/backend/store/saved_query_lock_order_test.go
index fa198bd9c6..9d1e5a842f 100644
--- a/backend/store/saved_query_lock_order_test.go
+++ b/backend/store/saved_query_lock_order_test.go
@@ -118,9 +118,11 @@ func TestSavedQueryFirstStarAndDeleteProjectLockOrder(t *testing.T) {
// The first star takes the parent fence on the saved_query row the
// parked purge holds via its re-parent update.
+ starApplied := make(chan bool, 1)
starResult := make(chan error, 1)
go func() {
- _, err := fixture.store.SetSavedQueryStar(fixture.ctx, "saved-query-a", "[email protected]", true)
+ applied, err := fixture.store.SetSavedQueryStar(fixture.ctx, "project-a", "saved-query-a", "[email protected]", true)
+ starApplied <- applied
starResult <- err
}()
waitForBackendBlockedByPID(fixture.ctx, t, fixture.db, purgePID)
@@ -128,8 +130,11 @@ func TestSavedQueryFirstStarAndDeleteProjectLockOrder(t *testing.T) {
requireMaintenanceResult(t, deleteResult)
requireMaintenanceResult(t, starResult)
- // The row survived the purge by re-parenting, so the star landed.
- require.Equal(t, 1, savedQueryStarCount(t, fixture))
+ // The row survived the purge by re-parenting into the default project,
+ // so the fence re-evaluates against the committed reassignment and the
+ // star authorized in project-a does not land.
+ require.False(t, <-starApplied)
+ require.Equal(t, 0, savedQueryStarCount(t, fixture))
})
t.Run("star first", func(t *testing.T) {
@@ -141,7 +146,7 @@ func TestSavedQueryFirstStarAndDeleteProjectLockOrder(t *testing.T) {
starResult := make(chan error, 1)
go func() {
- _, err := fixture.store.SetSavedQueryStar(fixture.ctx, "saved-query-a", "[email protected]", true)
+ _, err := fixture.store.SetSavedQueryStar(fixture.ctx, "project-a", "saved-query-a", "[email protected]", true)
starResult <- err
}()
waitForMaintenanceBarrier(fixture.ctx, t, fixture.db, barrierID)
@@ -176,7 +181,10 @@ func TestSavedQueryDeleteAndStarToggleLockOrder(t *testing.T) {
"AFTER DELETE ON saved_query FOR EACH ROW")
deleteResult := make(chan error, 1)
- go func() { deleteResult <- fixture.store.DeleteSavedQuery(fixture.ctx, "saved-query-a") }()
+ go func() {
+ _, err := fixture.store.DeleteSavedQuery(fixture.ctx, "default", "saved-query-a")
+ deleteResult <- err
+ }()
waitForMaintenanceBarrier(fixture.ctx, t, fixture.db, barrierID)
deletePID := maintenanceBarrierWaitingPID(fixture.ctx, t, fixture.db, barrierID)
@@ -185,7 +193,7 @@ func TestSavedQueryDeleteAndStarToggleLockOrder(t *testing.T) {
starResult := make(chan error, 1)
var starApplied bool
go func() {
- applied, err := fixture.store.SetSavedQueryStar(fixture.ctx, "saved-query-a", "[email protected]", true)
+ applied, err := fixture.store.SetSavedQueryStar(fixture.ctx, "default", "saved-query-a", "[email protected]", true)
starApplied = applied
starResult <- err
}()
@@ -216,14 +224,17 @@ func TestSavedQueryDeleteAndStarToggleLockOrder(t *testing.T) {
// barrier with the child lock held.
unstarResult := make(chan error, 1)
go func() {
- _, err := fixture.store.SetSavedQueryStar(fixture.ctx, "saved-query-a", "[email protected]", false)
+ _, err := fixture.store.SetSavedQueryStar(fixture.ctx, "default", "saved-query-a", "[email protected]", false)
unstarResult <- err
}()
waitForMaintenanceBarrier(fixture.ctx, t, fixture.db, barrierID)
unstarPID := maintenanceBarrierWaitingPID(fixture.ctx, t, fixture.db, barrierID)
deleteResult := make(chan error, 1)
- go func() { deleteResult <- fixture.store.DeleteSavedQuery(fixture.ctx, "saved-query-a") }()
+ go func() {
+ _, err := fixture.store.DeleteSavedQuery(fixture.ctx, "default", "saved-query-a")
+ deleteResult <- err
+ }()
waitForBackendBlockedByPID(fixture.ctx, t, fixture.db, unstarPID)
barrier.release(t)
@@ -272,7 +283,10 @@ func TestSavedQueryDeleteAndDeleteProjectLockOrder(t *testing.T) {
purgePID := maintenanceBarrierWaitingPID(fixture.ctx, t, fixture.db, barrierID)
deleteResult := make(chan error, 1)
- go func() { deleteResult <- fixture.store.DeleteSavedQuery(fixture.ctx, "saved-query-a") }()
+ go func() {
+ _, err := fixture.store.DeleteSavedQuery(fixture.ctx, "project-a", "saved-query-a")
+ deleteResult <- err
+ }()
waitForBackendBlockedByPID(fixture.ctx, t, fixture.db, purgePID)
barrier.release(t)
@@ -289,7 +303,10 @@ func TestSavedQueryDeleteAndDeleteProjectLockOrder(t *testing.T) {
"AFTER DELETE ON saved_query_star FOR EACH ROW")
deleteResult := make(chan error, 1)
- go func() { deleteResult <- fixture.store.DeleteSavedQuery(fixture.ctx, "saved-query-a") }()
+ go func() {
+ _, err := fixture.store.DeleteSavedQuery(fixture.ctx, "project-a", "saved-query-a")
+ deleteResult <- err
+ }()
waitForMaintenanceBarrier(fixture.ctx, t, fixture.db, barrierID)
deletePID := maintenanceBarrierWaitingPID(fixture.ctx, t, fixture.db, barrierID)
@@ -308,7 +325,7 @@ func TestSavedQueryBatchFolderMovesLockOrder(t *testing.T) {
const seedSQL = `
INSERT INTO saved_query (resource_id, creator, project, name, statement, folder) VALUES
('saved-query-a', '[email protected]', 'default', 'A', '', 'start'),
- ('saved-query-b', '[email protected]', 'default', 'B', '', 'start');
+ ('saved-query-b', '[email protected]', 'default', 'B', '', 'start/sub');
`
fixture := newProjectDeletionLockOrderFixture(t, seedSQL)
@@ -317,22 +334,25 @@ func TestSavedQueryBatchFolderMovesLockOrder(t *testing.T) {
installMaintenanceLockBarrier(t, fixture.db, barrierID,
"AFTER UPDATE OF folder ON saved_query FOR EACH ROW")
- // Two overlapping batches with intersecting, reverse-ordered targets:
- // both lock in full primary-key order, so the second serializes behind
- // the first instead of deadlocking.
+ // Two overlapping folder moves over the same rows: both lock in full
+ // primary-key order, so the second serializes behind the first instead of
+ // deadlocking, re-evaluates its predicate against the committed rename,
+ // and moves nothing.
firstResult := make(chan error, 1)
go func() {
- _, err := fixture.store.MoveSavedQueries(fixture.ctx, "default", "[email protected]",
- []string{"saved-query-a", "saved-query-b"}, "one")
+ _, err := fixture.store.MoveSavedQueryFolder(fixture.ctx, "default", "[email protected]",
+ "start", "one")
firstResult <- err
}()
waitForMaintenanceBarrier(fixture.ctx, t, fixture.db, barrierID)
firstPID := maintenanceBarrierWaitingPID(fixture.ctx, t, fixture.db, barrierID)
+ secondMoved := make(chan int, 1)
secondResult := make(chan error, 1)
go func() {
- _, err := fixture.store.MoveSavedQueries(fixture.ctx, "default", "[email protected]",
- []string{"saved-query-b", "saved-query-a"}, "two")
+ moved, err := fixture.store.MoveSavedQueryFolder(fixture.ctx, "default", "[email protected]",
+ "start", "two")
+ secondMoved <- moved
secondResult <- err
}()
waitForBackendBlockedByPID(fixture.ctx, t, fixture.db, firstPID)
@@ -340,6 +360,7 @@ func TestSavedQueryBatchFolderMovesLockOrder(t *testing.T) {
requireMaintenanceResult(t, firstResult)
requireMaintenanceResult(t, secondResult)
+ require.Equal(t, 0, <-secondMoved)
var folders []string
rows, err := fixture.db.QueryContext(fixture.ctx,
@@ -352,7 +373,7 @@ func TestSavedQueryBatchFolderMovesLockOrder(t *testing.T) {
folders = append(folders, folder)
}
require.NoError(t, rows.Err())
- require.Equal(t, []string{"two", "two"}, folders)
+ require.Equal(t, []string{"one", "one/sub"}, folders)
}
// TestCreateSavedQueryRejectsInactiveProject covers the shared fence's outcome
@@ -574,3 +595,42 @@ func TestSavedQueryFolderPrefixMovesLockOrder(t *testing.T) {
}, folders(t, fixture))
})
}
+
+// TestSavedQueryWritersProjectScoped locks the purge-reassignment fence: a
+// purge moves surviving saved queries to the default project, so a write
+// authorized in the original project must not land on the reassigned row.
+// Every non-purge writer scopes by (resource_id, project).
+func TestSavedQueryWritersProjectScoped(t *testing.T) {
+ const seedSQL = `
+ INSERT INTO saved_query (resource_id, creator, project, name, statement, folder)
+ VALUES ('saved-query-a', '[email protected]', 'project-a', 'Saved Query A', '', 'kept');
+ INSERT INTO saved_query_star (saved_query, principal) VALUES ('saved-query-a', '[email protected]');
+ `
+ fixture := newProjectDeletionLockOrderFixture(t, seedSQL)
+
+ // Simulate the purge's re-parenting having happened after the caller's
+ // authorization in project-a.
+ _, err := fixture.db.ExecContext(fixture.ctx,
+ "UPDATE saved_query SET project = 'default' WHERE resource_id = 'saved-query-a'")
+ require.NoError(t, err)
+
+ title := "raced"
+ require.NoError(t, fixture.store.PatchSavedQuery(fixture.ctx, &store.PatchSavedQueryMessage{
+ ResourceID: "saved-query-a",
+ ProjectID: "project-a",
+ Title: &title,
+ }))
+ deleted, err := fixture.store.DeleteSavedQuery(fixture.ctx, "project-a", "saved-query-a")
+ require.NoError(t, err)
+ require.False(t, deleted, "a delete authorized in the old project must not land")
+ applied, err := fixture.store.SetSavedQueryStar(fixture.ctx, "project-a", "saved-query-a", "[email protected]", true)
+ require.NoError(t, err)
+ require.False(t, applied, "first star must take the parent fence in the authorized project")
+
+ var name, folder string
+ require.NoError(t, fixture.db.QueryRowContext(fixture.ctx,
+ "SELECT name, folder FROM saved_query WHERE resource_id = 'saved-query-a'").Scan(&name, &folder))
+ require.Equal(t, "Saved Query A", name, "a patch authorized in the old project must not land")
+ require.Equal(t, "kept", folder)
+ require.Equal(t, 1, savedQueryStarCount(t, fixture))
+}
diff --git a/backend/tests/saved_query_test.go b/backend/tests/saved_query_test.go
index b430e46cb4..7204c41867 100644
--- a/backend/tests/saved_query_test.go
+++ b/backend/tests/saved_query_test.go
@@ -374,13 +374,15 @@ func TestMoveSavedQueries(t *testing.T) {
a.Empty(searchByFolder("old"))
a.Empty(searchByFolder("old/child"))
- // Naming saved queries moves exactly those, descendants irrelevant.
- moved, err = move(&v1pb.MoveMySavedQueriesRequest{
- Names: []string{directSavedQuery.Name, childSavedQuery.Name},
- TargetFolder: "selected",
- })
- a.NoError(err)
- a.Equal(int32(2), moved)
+ // Re-filing single saved queries is UpdateSavedQuery's folder field.
+ for _, name := range []string{directSavedQuery.Name, childSavedQuery.Name} {
+ refiled, err := ctl.savedQueryServiceClient.UpdateSavedQuery(ctx, connect.NewRequest(&v1pb.UpdateSavedQueryRequest{
+ SavedQuery: &v1pb.SavedQuery{Name: name, Folder: "selected"},
+ UpdateMask: &fieldmaskpb.FieldMask{Paths: []string{"folder"}},
+ }))
+ a.NoError(err)
+ a.Equal("selected", refiled.Msg.Folder)
+ }
a.ElementsMatch([]string{directSavedQuery.Name, childSavedQuery.Name}, searchByFolder("selected"))
a.ElementsMatch([]string{otherSavedQuery.Name}, searchByFolder("other"))
@@ -397,17 +399,10 @@ func TestMoveSavedQueries(t *testing.T) {
a.Equal(connect.CodeInvalidArgument, connect.CodeOf(err))
a.ElementsMatch([]string{directSavedQuery.Name, childSavedQuery.Name}, searchByFolder("boxed"))
- // Exactly one of names / source_folder.
+ // source_folder is required.
_, err = move(&v1pb.MoveMySavedQueriesRequest{TargetFolder: "x"})
a.Error(err)
a.Equal(connect.CodeInvalidArgument, connect.CodeOf(err))
- _, err = move(&v1pb.MoveMySavedQueriesRequest{
- Names: []string{directSavedQuery.Name},
- SourceFolder: "boxed",
- TargetFolder: "x",
- })
- a.Error(err)
- a.Equal(connect.CodeInvalidArgument, connect.CodeOf(err))
// A folder cannot swallow itself.
_, err = move(&v1pb.MoveMySavedQueriesRequest{SourceFolder: "boxed", TargetFolder: "boxed/inner"})
@@ -503,15 +498,14 @@ func TestSearchSavedQueryFoldersReturnsCallerFolders(t *testing.T) {
a.Empty(notMineForOther.Msg.Folders)
// Unfiltered means "every folder holding a saved query I can read". The
- // search family is caller-scoped even for an admin -- bb.savedQueries.manage
- // does not widen it, and everyone's rows come from ListSavedQueries instead
- // -- so the other creator's folders are absent until something is shared.
+ // workspace admin holds project-level bb.savedQueries.get, which reads
+ // every row, so the other creator's folders show up too.
ctl.authInterceptor.token = ownerToken
ownerFolders, err := ctl.savedQueryServiceClient.SearchSavedQueryFolders(ctx, connect.NewRequest(&v1pb.SearchSavedQueryFoldersRequest{
Parent: ctl.project.Name,
}))
a.NoError(err)
- a.Equal([]string{"owner", "owner-second", "owner/child"}, ownerFolders.Msg.Folders)
+ a.Equal([]string{"owner", "owner-second", "owner/child", "theirs", "theirs/deep"}, ownerFolders.Msg.Folders)
ownFolders, err := ctl.savedQueryServiceClient.SearchSavedQueryFolders(ctx, connect.NewRequest(&v1pb.SearchSavedQueryFoldersRequest{
Parent: ctl.project.Name,
@@ -754,9 +748,9 @@ func findSavedQueryByName(savedQueries []*v1pb.SavedQuery, name string) *v1pb.Sa
}
// TestSavedQuerySharing covers the per-object grant model end to end: a
-// private saved query is invisible to a co-member, a VIEWER binding makes it
-// readable but not writable, EDITOR makes it writable but never deletable, and
-// the policy write is compare-and-swap.
+// private saved query is invisible to a co-member, a VIEWER binding grants
+// get, an EDITOR binding grants get + update but never deletion, and the
+// policy write is compare-and-swap.
func TestSavedQuerySharing(t *testing.T) {
t.Parallel()
a := require.New(t)
@@ -894,7 +888,7 @@ func TestSavedQuerySharing(t *testing.T) {
UpdateMask: &fieldmaskpb.FieldMask{Paths: []string{"title"}},
}))
a.Error(err)
- a.Equal(connect.CodePermissionDenied, connect.CodeOf(err), "a VIEWER can see the row, so hiding it would be wrong")
+ a.Equal(connect.CodeNotFound, connect.CodeOf(err), "a missing permission answers NotFound, the one masking rule")
// Grantees read their own level through the policy; they cannot rewrite it.
policy, err := ctl.savedQueryServiceClient.GetSavedQueryPolicy(ctx, connect.NewRequest(&v1pb.GetSavedQueryPolicyRequest{
@@ -909,12 +903,13 @@ func TestSavedQuerySharing(t *testing.T) {
Policy: &v1pb.SavedQueryPolicy{Etag: policy.Msg.Etag},
}))
a.Error(err)
- a.Equal(connect.CodePermissionDenied, connect.CodeOf(err))
+ a.Equal(connect.CodeNotFound, connect.CodeOf(err))
})
editorPolicy := setPolicy(v1pb.SavedQueryBinding_EDITOR, viewerPolicy.Etag)
- // EDITOR: writes content, but never deletes and never re-files.
+ // EDITOR: holds get and update — content and folder both write — but
+ // never deletes.
asGrantee(func() {
updated, err := ctl.savedQueryServiceClient.UpdateSavedQuery(ctx, connect.NewRequest(&v1pb.UpdateSavedQueryRequest{
SavedQuery: &v1pb.SavedQuery{Name: savedQuery.Name, Content: []byte("SELECT 2;")},
@@ -923,18 +918,18 @@ func TestSavedQuerySharing(t *testing.T) {
a.NoError(err)
a.True(bytes.Equal([]byte("SELECT 2;"), updated.Msg.Content))
- _, err = ctl.savedQueryServiceClient.UpdateSavedQuery(ctx, connect.NewRequest(&v1pb.UpdateSavedQueryRequest{
+ refiled, err := ctl.savedQueryServiceClient.UpdateSavedQuery(ctx, connect.NewRequest(&v1pb.UpdateSavedQueryRequest{
SavedQuery: &v1pb.SavedQuery{Name: savedQuery.Name, Folder: "grantee"},
UpdateMask: &fieldmaskpb.FieldMask{Paths: []string{"folder"}},
}))
- a.Error(err)
- a.Equal(connect.CodePermissionDenied, connect.CodeOf(err), "filing is organization, not editing")
+ a.NoError(err)
+ a.Equal("grantee", refiled.Msg.Folder)
_, err = ctl.savedQueryServiceClient.DeleteSavedQuery(ctx, connect.NewRequest(&v1pb.DeleteSavedQueryRequest{
Name: savedQuery.Name,
}))
a.Error(err)
- a.Equal(connect.CodePermissionDenied, connect.CodeOf(err), "sharing for editing must not cost the owner the saved query")
+ a.Equal(connect.CodeNotFound, connect.CodeOf(err), "sharing for editing must not cost the owner the saved query")
})
// Revoking drops the grantee back to invisible.
@@ -952,3 +947,205 @@ func TestSavedQuerySharing(t *testing.T) {
a.Equal(connect.CodeNotFound, connect.CodeOf(err))
})
}
+
+// TestSavedQueryPerVerbRoleGrants covers the project-level permissions one by
+// one: get reads a private saved query (and widens Search) without granting
+// update or delete; update writes without granting delete; sharing is the
+// creator's alone whatever the role carries.
+func TestSavedQueryPerVerbRoleGrants(t *testing.T) {
+ t.Parallel()
+ a := require.New(t)
+ ctx := context.Background()
+ ctl := &controller{}
+ ctx, err := ctl.StartServerWithExternalPg(ctx)
+ a.NoError(err)
+ defer ctl.Close(ctx)
+
+ ownerToken := ctl.authInterceptor.token
+
+ created, err := ctl.savedQueryServiceClient.CreateSavedQuery(ctx, connect.NewRequest(&v1pb.CreateSavedQueryRequest{
+ Parent: ctl.project.Name,
+ SavedQuery: &v1pb.SavedQuery{
+ Title: "per-verb target",
+ Content: []byte("SELECT 1;"),
+ },
+ }))
+ a.NoError(err)
+ savedQuery := created.Msg
+
+ auditorEmail := fmt.Sprintf("saved-query-verb-%[email protected]", generateRandomString("user"))
+ const auditorPassword = "1024bytebase"
+ auditor, err := ctl.userServiceClient.CreateUser(ctx, connect.NewRequest(&v1pb.CreateUserRequest{
+ User: &v1pb.User{
+ Email: auditorEmail,
+ Password: auditorPassword,
+ Title: "Saved Query Verb User",
+ },
+ }))
+ a.NoError(err)
+ _, err = ctl.addMemberToWorkspaceIAM(ctx, auditor.Msg.Workspace, fmt.Sprintf("user:%s", auditorEmail), "roles/workspaceMember")
+ a.NoError(err)
+
+ grantRole := func(permissions ...string) {
+ roleID := generateRandomString("saved-query-verb-role")
+ _, err := ctl.roleServiceClient.CreateRole(ctx, connect.NewRequest(&v1pb.CreateRoleRequest{
+ Role: &v1pb.Role{
+ Title: roleID,
+ Permissions: permissions,
+ },
+ RoleId: roleID,
+ }))
+ a.NoError(err)
+ policyResp, err := ctl.projectServiceClient.GetIamPolicy(ctx, connect.NewRequest(&v1pb.GetIamPolicyRequest{
+ Resource: ctl.project.Name,
+ }))
+ a.NoError(err)
+ policy := policyResp.Msg
+ policy.Bindings = append(policy.Bindings, &v1pb.Binding{
+ Role: fmt.Sprintf("roles/%s", roleID),
+ Members: []string{fmt.Sprintf("user:%s", auditorEmail)},
+ })
+ _, err = ctl.projectServiceClient.SetIamPolicy(ctx, connect.NewRequest(&v1pb.SetIamPolicyRequest{
+ Resource: ctl.project.Name,
+ Policy: policy,
+ }))
+ a.NoError(err)
+ }
+
+ loginResp, err := ctl.authServiceClient.Login(ctx, connect.NewRequest(&v1pb.LoginRequest{
+ Email: auditorEmail,
+ Password: auditorPassword,
+ }))
+ a.NoError(err)
+ auditorToken := loginResp.Msg.Token
+
+ asAuditor := func(f func()) {
+ ctl.authInterceptor.token = auditorToken
+ defer func() { ctl.authInterceptor.token = ownerToken }()
+ f()
+ }
+
+ // get alone: reads the private saved query, widens Search, stars it —
+ // and stops there: no update, no delete, no re-share.
+ grantRole("bb.savedQueries.search", "bb.savedQueries.get")
+ asAuditor(func() {
+ getResp, err := ctl.savedQueryServiceClient.GetSavedQuery(ctx, connect.NewRequest(&v1pb.GetSavedQueryRequest{
+ Name: savedQuery.Name,
+ }))
+ a.NoError(err)
+ a.Equal("per-verb target", getResp.Msg.Title)
+
+ searchResp, err := ctl.savedQueryServiceClient.SearchSavedQueries(ctx, connect.NewRequest(&v1pb.SearchSavedQueriesRequest{
+ Parent: ctl.project.Name,
+ }))
+ a.NoError(err)
+ a.Contains(savedQueryNames(searchResp.Msg.SavedQueries), savedQuery.Name)
+
+ // Visible through the role grant, not through a binding, so the
+ // Shared view stays empty.
+ sharedResp, err := ctl.savedQueryServiceClient.SearchSavedQueries(ctx, connect.NewRequest(&v1pb.SearchSavedQueriesRequest{
+ Parent: ctl.project.Name,
+ Filter: "shared == true",
+ }))
+ a.NoError(err)
+ a.NotContains(savedQueryNames(sharedResp.Msg.SavedQueries), savedQuery.Name)
+
+ starResp, err := ctl.savedQueryServiceClient.UpdateSavedQueryStar(ctx, connect.NewRequest(&v1pb.UpdateSavedQueryStarRequest{
+ Name: savedQuery.Name,
+ Starred: true,
+ }))
+ a.NoError(err)
+ a.True(starResp.Msg.Starred)
+
+ _, err = ctl.savedQueryServiceClient.UpdateSavedQuery(ctx, connect.NewRequest(&v1pb.UpdateSavedQueryRequest{
+ SavedQuery: &v1pb.SavedQuery{Name: savedQuery.Name, Title: "renamed by get"},
+ UpdateMask: &fieldmaskpb.FieldMask{Paths: []string{"title"}},
+ }))
+ a.Error(err)
+ a.Equal(connect.CodeNotFound, connect.CodeOf(err))
+
+ _, err = ctl.savedQueryServiceClient.DeleteSavedQuery(ctx, connect.NewRequest(&v1pb.DeleteSavedQueryRequest{
+ Name: savedQuery.Name,
+ }))
+ a.Error(err)
+ a.Equal(connect.CodeNotFound, connect.CodeOf(err))
+
+ // The policy pair has its own permissions: get alone reads neither.
+ _, err = ctl.savedQueryServiceClient.GetSavedQueryPolicy(ctx, connect.NewRequest(&v1pb.GetSavedQueryPolicyRequest{
+ Resource: savedQuery.Name,
+ }))
+ a.Error(err)
+ a.Equal(connect.CodeNotFound, connect.CodeOf(err))
+ _, err = ctl.savedQueryServiceClient.SetSavedQueryPolicy(ctx, connect.NewRequest(&v1pb.SetSavedQueryPolicyRequest{
+ Resource: savedQuery.Name,
+ Policy: &v1pb.SavedQueryPolicy{},
+ }))
+ a.Error(err)
+ a.Equal(connect.CodeNotFound, connect.CodeOf(err), "no predefined role carries setIamPolicy")
+ })
+
+ // update on top: writes content and re-files, still no delete.
+ grantRole("bb.savedQueries.update")
+ asAuditor(func() {
+ updated, err := ctl.savedQueryServiceClient.UpdateSavedQuery(ctx, connect.NewRequest(&v1pb.UpdateSavedQueryRequest{
+ SavedQuery: &v1pb.SavedQuery{Name: savedQuery.Name, Content: []byte("SELECT 2;")},
+ UpdateMask: &fieldmaskpb.FieldMask{Paths: []string{"content"}},
+ }))
+ a.NoError(err)
+ a.True(bytes.Equal([]byte("SELECT 2;"), updated.Msg.Content))
+
+ refiled, err := ctl.savedQueryServiceClient.UpdateSavedQuery(ctx, connect.NewRequest(&v1pb.UpdateSavedQueryRequest{
+ SavedQuery: &v1pb.SavedQuery{Name: savedQuery.Name, Folder: "verbed"},
+ UpdateMask: &fieldmaskpb.FieldMask{Paths: []string{"folder"}},
+ }))
+ a.NoError(err)
+ a.Equal("verbed", refiled.Msg.Folder)
+
+ // An empty mask is rejected: it would touch nothing yet return the
+ // full content — a read in update's clothing.
+ _, err = ctl.savedQueryServiceClient.UpdateSavedQuery(ctx, connect.NewRequest(&v1pb.UpdateSavedQueryRequest{
+ SavedQuery: &v1pb.SavedQuery{Name: savedQuery.Name},
+ UpdateMask: &fieldmaskpb.FieldMask{},
+ }))
+ a.Error(err)
+ a.Equal(connect.CodeInvalidArgument, connect.CodeOf(err))
+
+ _, err = ctl.savedQueryServiceClient.DeleteSavedQuery(ctx, connect.NewRequest(&v1pb.DeleteSavedQueryRequest{
+ Name: savedQuery.Name,
+ }))
+ a.Error(err)
+ a.Equal(connect.CodeNotFound, connect.CodeOf(err))
+ })
+
+ // The policy pair, granted: reads the policy and rewrites it — the
+ // re-share capability that no predefined role carries and only an
+ // explicit custom-role grant confers.
+ grantRole("bb.savedQueries.getIamPolicy", "bb.savedQueries.setIamPolicy")
+ asAuditor(func() {
+ policyResp, err := ctl.savedQueryServiceClient.GetSavedQueryPolicy(ctx, connect.NewRequest(&v1pb.GetSavedQueryPolicyRequest{
+ Resource: savedQuery.Name,
+ }))
+ a.NoError(err)
+ updated, err := ctl.savedQueryServiceClient.SetSavedQueryPolicy(ctx, connect.NewRequest(&v1pb.SetSavedQueryPolicyRequest{
+ Resource: savedQuery.Name,
+ Policy: &v1pb.SavedQueryPolicy{
+ Etag: policyResp.Msg.Etag,
+ Bindings: []*v1pb.SavedQueryBinding{{
+ Level: v1pb.SavedQueryBinding_VIEWER,
+ Members: []string{fmt.Sprintf("user:%s", auditorEmail)},
+ }},
+ },
+ }))
+ a.NoError(err)
+ a.Len(updated.Msg.Bindings, 1)
+ })
+
+ // delete on top: the saved query goes, stars and all.
+ grantRole("bb.savedQueries.delete")
+ asAuditor(func() {
+ _, err := ctl.savedQueryServiceClient.DeleteSavedQuery(ctx, connect.NewRequest(&v1pb.DeleteSavedQueryRequest{
+ Name: savedQuery.Name,
+ }))
+ a.NoError(err)
+ })
+}
diff --git a/backend/utils/utils.go b/backend/utils/utils.go
index 4ae3484348..aa920920c5 100644
--- a/backend/utils/utils.go
+++ b/backend/utils/utils.go
@@ -261,12 +261,5 @@ func extractEmailFromUserIdentifier(identifier string) (string, error) {
// For service accounts: serviceAccounts/{email}
// For workload identities: workloadIdentities/{email}
func formatMemberNameByType(user *store.UserMessage) string {
- switch user.Type {
- case storepb.PrincipalType_SERVICE_ACCOUNT:
- return common.FormatServiceAccountEmail(user.Email)
- case storepb.PrincipalType_WORKLOAD_IDENTITY:
- return common.FormatWorkloadIdentityEmail(user.Email)
- default:
- return common.FormatUserEmail(user.Email)
- }
+ return common.FormatPrincipalMember(user.Email, user.Type)
}
diff --git a/docs/design/saved-queries-model.md b/docs/design/saved-queries-model.md
index 8cf47a2d09..fe922844b4 100644
--- a/docs/design/saved-queries-model.md
+++ b/docs/design/saved-queries-model.md
@@ -6,6 +6,16 @@ Replaces the three-state visibility flag with the industry-consensus model:
per-object graduated grants to users and groups, private by default, with
per-project discovery.
+Amended 2026-08-14: the single admin backstop `bb.savedQueries.manage` is
+split into per-verb permissions — `get`, `update`, `delete`, and the policy
+pair `getIamPolicy`/`setIamPolicy` — so saved-query access is standard IAM
+evaluation: the saved query is a sub-project policy attachment point, the
+creator its owner holding full per-object permissions, the sharing levels
+fixed permission bundles, and a project- or workspace-level role grant
+reaching every saved query in scope. No predefined role carries
+`setIamPolicy`, so sharing stays the creator's by default. See The
+permissions, and Alternatives: A single `manage` backstop.
+
## Background
Saved queries (renamed from worksheets) are personal SQL scratchpads in the
@@ -45,14 +55,16 @@ Cited throughout as G1–G8.
2. **Private by default**; per-object **VIEWER / EDITOR** grants to `user:`
and `group:` principals. No grantable owner tier.
3. **BigQuery-layered gates**: a per-object grant carries content access;
- *discovery* (Search, always per-project and always caller-scoped) is gated
+ *discovery* (Search, always per-project, returning what the caller can
+ read) is gated
by a dedicated `bb.savedQueries.search` permission carried by the human
project roles — automation roles stay off the surface;
*running* is gated by the SQL Editor's own database permissions. Leaving
a project ends discovery and run; explicit grants persist until
revoked.
-4. The **creator is the fixed owner** (no transfer); admins
- (`bb.savedQueries.manage`) manage any saved query in scope, private
+4. The **creator is the fixed owner** (no transfer), holding every
+ permission on their own saved query; roles granting per-verb
+ `bb.savedQueries.*` permissions reach any saved query in scope, private
included.
5. **Creation is gated** by `bb.savedQueries.create` on the parent project.
6. A cross-project **auditor** (`bb.savedQueries.list`) enumerates/filters
@@ -65,7 +77,9 @@ Cited throughout as G1–G8.
API change.
The frontend mirrors these rules for control visibility only; enforcement is
-server-side.
+server-side. Where the mirror cannot reproduce an evaluation — a binding
+condition beyond the canonical expiry form — it hides the control rather than
+showing one the server denies.
### Non-goals
@@ -167,9 +181,8 @@ Alternatives the rejected options.
Exactly new BigQuery's enforcement — `codeViewer` reads the asset while
`dataform.repositories.list` gates listing and `bigquery.jobUser` gates
running; here, a VIEWER/EDITOR binding reads/edits,
- `bb.savedQueries.search` — or `manage`, the admin backstop — gates
- `SearchSavedQueries` (per-project), and running always passes the SQL
- Editor's database grants. The real cost:
+ `bb.savedQueries.search` gates `SearchSavedQueries` (per-project), and
+ running always passes the SQL Editor's database grants. The real cost:
removing a user from a project ends discovery and run but not
explicitly granted content access — the grants themselves are the
revocation surface (see Model: Offboarding). The stricter
@@ -178,27 +191,36 @@ Alternatives the rejected options.
4. **Creator = fixed owner, no transfer** (G4). Scratchpad-grade
simplicity: no extra tier, no orphan-guard machinery; the admin backstop
and fork-a-copy cover the departed-creator case.
-5. **Admin (`manage`) reads private.** Peer parity (`dataform.admin`,
- Databricks workspace admins), and what makes incident response and orphan
- cleanup possible. Two things sit outside it: **starring**, which is
- personal — you star what you created or were granted, and your stars are
- yours alone — and the bulk **`MoveMySavedQueries`**, caller-scoped by name,
- though a single `UpdateSavedQuery` still lets an admin re-file one saved
- query. The real
- tradeoff: admins can read private drafts, and reads are not audited — the audit log records changes, not
- lookups (see API and authorization: Audit events). The control on admin
- access is therefore who holds `manage` (never a default member role),
- not an after-the-fact read trail; an admin *write* to someone else's
- query is audited like any other write.
+5. **Per-verb role permissions are the admin backstop** (amended
+ 2026-08-14; originally a single `bb.savedQueries.manage`). A project- or
+ workspace-level grant of `get`, `getIamPolicy`, `update`, or `delete`
+ reaches any saved query in scope, private included — peer parity
+ (`dataform.admin`, Databricks workspace admins), and what makes incident
+ response and orphan cleanup possible. **Sharing** has a verb too,
+ `setIamPolicy`, but no predefined role carries it, so nobody re-grants a
+ saved query out from under its creator unless a custom role says so. One
+ thing sits outside the verbs: the bulk
+ **`MoveMySavedQueries`**, which re-files only the caller's own folder
+ tree, though a single `UpdateSavedQuery` still moves one saved query for
+ anyone holding `update`. **Starring** follows `read` — a personal marker on anything
+ you can reach, granting nothing, yours alone. The real tradeoff:
+ role-`get` holders read private drafts, and reads are not audited — the
+ audit log records changes, not lookups (see API and authorization: Audit
+ events). The control on admin access is therefore who holds the verbs
+ (never a default member role), not an after-the-fact read trail; an
+ admin *write* to someone else's query is audited like any other write.
6. **A purpose-built level policy, not the role-based `IamPolicy` proto.**
Per-object access is a *capability* (view/edit), as every peer models
it; reusing `IamPolicy` would force per-object pseudo-roles and a
resource-level role store. The cost — a second policy shape in the API —
is softened by both shapes reducing to *(members, capability)*, so the
bindings can be re-expressed as `IamPolicy` later without a data change.
+ The levels are fixed permission bundles — VIEWER = `{get, getIamPolicy}`,
+ EDITOR = VIEWER + `{update}` — so that later re-expression is a rename,
+ not a re-evaluation.
7. **A `bb.savedQueries.list` auditor permission** (G6). Governance needs
- grant-independent, cross-project enumeration; `list` is the read-only
- counterpart to `manage`. It can read all content in scope — that is its
+ grant-independent, cross-project enumeration; `list` is the bulk
+ counterpart to per-object `get`. It can read all content in scope — that is its
purpose — so it is granted deliberately, never in default member roles.
8. **Hard cutover, no legacy shim.** The feature is UI-owned and the
frontend ships in-repo the same release; after the rename, a shim is an
@@ -221,14 +243,16 @@ Three things grant access to a saved query, and nothing else does:
transfers and cannot be granted away (G4).
- **Binding.** A VIEWER or EDITOR grant to a `user:` or `group:` principal,
stored on the saved query itself. A saved query with no bindings is private.
-- **Admin backstop.** `bb.savedQueries.manage` reaches any saved query in
- scope, private ones included — matching `dataform.admin` and Databricks
- workspace admins, and what makes incident response and orphan cleanup
- possible (decision 5).
+- **Role permission.** A project- or workspace-level grant of a per-verb
+ `bb.savedQueries.*` permission reaches any saved query in scope, private
+ ones included — matching `dataform.admin` and Databricks workspace
+ admins, and what makes incident response and orphan cleanup possible
+ (decision 5). The saved query is thus a sub-project policy attachment
+ point: owner, then object bindings, then the project's own IAM.
```
-Grant levels: VIEWER (open, read) < EDITOR (+ write title/content/database)
-Principals: user:{email} | group:{email}
+Levels: VIEWER = {get, getIamPolicy} EDITOR = VIEWER + {update}
+Principals: user:{email} | group:{email}
```
The creator may be any principal type — a user, a service account, a workload
@@ -242,66 +266,105 @@ the types above; the store holds the resource-name form the IAM policy
payloads hold, `users/{email}` and `groups/{email}`, converted once on write
as `convertToStoreIamPolicyMember` does for a project policy.
-The read path then converts nothing: `iam.PrincipalMembers` already yields a
-caller's members in stored form, so the access clause compares them to
-`bindings` directly. It also keeps principal typing in one place — a caller's
-own member comes from `formatUserNameByType`, so a service account is only
-ever named `serviceAccounts/{email}` and a binding naming one under a user
-prefix matches nobody. That is what lets the write path validate members by
-prefix alone, exactly as project IAM does.
+The read path then converts nothing: the caller's members resolve in stored
+form — their own typed name plus `iam.GetUserGroups` — so the access clause
+compares them to `bindings` directly. Principal typing stays load-bearing: a
+service account is only ever named `serviceAccounts/{email}`, so a binding
+naming one under a user prefix matches nobody. That is what lets the write
+path validate members by prefix alone, exactly as project IAM does.
#### The rules
Every RPC gate derives from these (G1). `u` is the caller, `P` a project, `s`
-a saved query; "holds" means any of `u`'s role bindings — project-level,
-direct or via a group, or workspace-level — grants the permission.
+a saved query; `proj(u, P, v)` means any of `u`'s role bindings —
+project-level, direct or via a group, or workspace-level — grants
+`bb.savedQueries.<v>` on `P`.
```
-admin(u, P) = u holds bb.savedQueries.manage on P
-grant(s, u) = max level (VIEWER|EDITOR) among s.bindings matching principals(u)
-
-create(u, P) = u holds bb.savedQueries.create on P
-discover(u, P) = u holds bb.savedQueries.search on P -- gates Search, not content
-read(s, u) = admin(u, s.project) OR u == s.creator OR grant(s, u) >= VIEWER
-write(s, u) = admin(u, s.project) OR u == s.creator OR grant(s, u) >= EDITOR
-star(s, u) = u == s.creator OR grant(s, u) >= VIEWER -- personal, own or shared
-move(s, u) = u == s.creator -- MoveMySavedQueries
-share(s, u) = admin(u, s.project) OR u == s.creator
-delete(s, u) = admin(u, s.project) OR u == s.creator
+bind(s, u, v) = a binding in s.bindings names principals(u) and its level
+ carries v: VIEWER carries get, getIamPolicy; EDITOR adds update
+
+create(u, P) = proj(u, P, create)
+discover(u, P) = proj(u, P, search) -- gates Search, not content
+read(s, u) = u == s.creator OR bind(s, u, get) OR proj(u, s.project, get)
+write(s, u) = u == s.creator OR bind(s, u, update) OR proj(u, s.project, update)
+star(s, u) = read(s, u) -- personal, grants nothing
+move(s, u) = u == s.creator -- MoveMySavedQueries
+readPolicy(s, u) = u == s.creator OR bind(s, u, getIamPolicy) OR proj(u, s.project, getIamPolicy)
+share(s, u) = u == s.creator OR proj(u, s.project, setIamPolicy)
+delete(s, u) = u == s.creator OR proj(u, s.project, delete)
```
-#### The four permissions
+Every per-object RPC answers NotFound, never PermissionDenied, when its one
+permission check fails — reads and writes alike — so a name stays
+unprobeable. The blunt edge is deliberate: a VIEWER whose update is denied
+gets the same NotFound as a stranger; one rule, no per-capability
+distinction. A role granting `update` or `delete` without `get` can act on
+names it already knows but discover nothing. Write verbs read what they
+touch: `update` alone returns the updated saved query, content included,
+and `setIamPolicy` alone can grant its holder the rest. Confidentiality
+against a role means withholding the verb, not a pairing rule.
+
+#### The permissions
| Permission | Meaning |
|---|---|
| `bb.savedQueries.create` | Create saved queries in the project |
| `bb.savedQueries.search` | Discover: Search and the folder list, results still filtered to `read(s,u)` |
-| `bb.savedQueries.list` | Audit: enumerate in scope, read-only, ignoring bindings |
-| `bb.savedQueries.manage` | Admin backstop: read, write, re-file, re-share, and delete anything in scope, private included. Not star |
-
-There is no `get` permission — bindings decide reads, so `bb.worksheets.get`
-is dropped rather than renamed. `search` is dedicated rather than riding on
-`bb.projects.get` (see Alternatives) so a custom role can control the
-saved-query surface independently of project visibility.
-
-| Role | create | search | list | manage |
-|---|:--:|:--:|:--:|:--:|
-| `workspaceAdmin`, `workspaceDBA` | ✓ | ✓ | ✓ | ✓ |
-| `projectOwner` | ✓ | ✓ | ✓ | ✓ |
-| `projectDeveloper`, `sqlEditorUser`, `sqlEditorReadUser`, `projectViewer` | ✓ | ✓ | | |
-| `projectReleaser`, `gitopsServiceAgent` | | | | |
-
-Two things this table encodes. `list` and `manage` read other people's content
-by design, so neither belongs in a default member role (decision 7). And the
-automation roles carry nothing at all, which keeps CI principals off the
-saved-query surface entirely — the property that makes the share-with-project
-role filter meaningful.
-
-The discovery gate is `search` alone, not "search or manage". The search family
-is caller-scoped, so letting `manage` through would show a role only its own
-rows — no use to it, and one more rule to explain. Admins read everyone's saved
-queries through `ListSavedQueries`, and every predefined role holding `manage`
-holds `search` too.
+| `bb.savedQueries.get` | Read any saved query in scope: Get, star eligibility |
+| `bb.savedQueries.update` | Write any saved query in scope, the `folder` field included |
+| `bb.savedQueries.delete` | Delete any saved query in scope |
+| `bb.savedQueries.getIamPolicy` | Read any saved query's sharing policy in scope |
+| `bb.savedQueries.setIamPolicy` | Replace any saved query's sharing policy in scope; no predefined role carries it |
+| `bb.savedQueries.list` | Audit: enumerate in scope, full content, ignoring bindings |
+
+One permission per verb, named for its RPC (`list` for `ListSavedQueries`,
+`delete` for `DeleteSavedQuery`, …), evaluated exactly like the rest of the
+permission vocabulary. The binding levels are fixed bundles of the same
+verbs — VIEWER = `{get, getIamPolicy}`, EDITOR = VIEWER + `{update}` — and
+the owner holds full per-object permissions. `setIamPolicy` sits in no
+bundle and no predefined role, so sharing is the creator's unless a custom
+role grants it deliberately.
+
+`bb.savedQueries.get` is a role-scope verb, not the grantee read path —
+bindings decide grantee reads, so the old `bb.worksheets.get` ("read
+shared") is still dropped rather than renamed. `search` is dedicated rather
+than riding on `bb.projects.get` (see Alternatives) so a custom role can
+control the saved-query surface independently of project visibility.
+
+Two deliberate asymmetries:
+
+- **The policy pair has its own permissions**, `getIamPolicy` and
+ `setIamPolicy`, mirroring `bb.projects.get/setIamPolicy`. The VIEWER and
+ EDITOR bundles carry `getIamPolicy`, so a grantee can always learn their
+ own level; `setIamPolicy` sits in no bundle and no predefined role, so
+ sharing is the creator's by default and admin re-sharing is a deliberate
+ custom-role grant.
+- **`list` is strictly stronger than `get` in information terms** — whole
+ statements, bindings ignored — yet does not satisfy `GetSavedQuery` by
+ name: per-method permissions stay per-method, and roles holding `list`
+ should hold `get` (every predefined one does).
+
+| Role | create | search | get | getIamPolicy | update | delete | setIamPolicy | list |
+|---|:--:|:--:|:--:|:--:|:--:|:--:|:--:|:--:|
+| `workspaceAdmin`, `workspaceDBA` | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | | ✓ |
+| `projectOwner` | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | | ✓ |
+| `projectDeveloper`, `sqlEditorUser`, `sqlEditorReadUser`, `projectViewer` | ✓ | ✓ | | | | | | |
+| `projectReleaser`, `gitopsServiceAgent` | | | | | | | | |
+
+Two things this table encodes. Every verb except `create` and `search`
+reaches other people's private content by design — that is what a
+project-wide grant means on a private-by-default resource — so none of them
+belongs in a default member role (decision 7): ordinary SQL Editor use
+needs only `create + search`, with reads and writes flowing from creator
+and bindings. And the automation roles carry nothing at all, which keeps CI
+principals off the saved-query surface entirely — the property that makes
+the share-with-project role filter meaningful.
+
+The discovery gate is `search` alone: without it the search family is
+denied outright, whatever the caller could read. With it, results carry
+every saved query the caller holds `get` on — own, shared, or role-granted
+— the same access rule as `GetSavedQuery`.
#### Layered gates
@@ -309,7 +372,7 @@ Access is three independent layers, exactly as new BigQuery enforces them (G3):
| Layer | Gate | BigQuery analog |
|---|---|---|
-| Content | the binding on the saved query | `dataform.codeViewer` / `codeEditor` |
+| Content | the binding on the saved query, or a role-granted verb | `dataform.codeViewer` / `codeEditor` |
| Discovery | `bb.savedQueries.search` on the project | `dataform.repositories.list` |
| Running | the SQL Editor's own database permissions | `bigquery.jobUser` |
@@ -336,7 +399,8 @@ Three levers, blunt to precise:
1. **Workspace deactivation** ends everything at once.
2. **Group membership** revokes every group-held grant in one edit, since a
group binding names the live group rather than a frozen expansion.
-3. **`SetSavedQueryPolicy`** strips a direct grant on one saved query.
+3. **`SetSavedQueryPolicy`** (the creator, or a custom role granting
+ `setIamPolicy`) strips a direct grant on one saved query.
Users can always see what they hold: `SearchSavedQueries` with `shared == true`
returns everything shared with the caller.
@@ -351,7 +415,8 @@ their drafts), but there is no `member` filter and bindings are not on the
`GetSavedQueryPolicy` per saved query as an admin.
That is a scope cut, not a model limitation: the grants exist, are readable,
-and are revocable per query — only the sweep over them is missing, and a
+and are revocable per query — by its creator; an admin's blunt lever is
+deleting the query — only the sweep over them is missing, and a
`member ==` filter slots in later as a purely additive change. The audit's
Problem-1 complaint was never retention itself but *implicit* retention:
flag-derived access with no grant to see, audit, or revoke. Grants are now
@@ -374,7 +439,7 @@ Four things are skipped:
| Skipped | Why |
|---|---|
| Roles without `search` | A CI releaser is deliberately off this surface; sweeping it in would put it back on |
-| Roles with `manage` | Admins reach the query through the backstop, so a binding is redundant *and* would outlive the admin role, leaving a former operator deep-link access |
+| Roles with `get` | Their holders reach the query through the role grant, so a binding is redundant *and* would outlive the role, leaving a former operator deep-link access |
| `allUsers` members | The policy accepts only `user:`/`group:`, and freezing a workspace-wide audience into per-user grants is the member explosion the snapshot exists to avoid. The dialog surfaces the skip so the sharer can grant a group instead |
| Conditioned bindings | A time-bounded grant cannot be faithfully frozen into an unconditional one; under-granting beats silently making expiring access permanent |
@@ -408,11 +473,11 @@ Two properties matter:
an `etag`; the write must present it, and a mismatch aborts for refetch. A
full-replacement write may never silently overwrite a concurrent revocation
— the offboarding race.
-- **`GetSavedQueryPolicy` is gated on `read(s,u)`**, the same predicate as
- reading the saved query itself, and returns the whole policy. That is what
- lets a grantee discover whether they may edit, which is the only way to
- know now that nothing caller-relative rides on the resource. Writing the
- policy still needs `share(s,u)`.
+- **`GetSavedQueryPolicy` is gated on `readPolicy(s,u)`** — the bundles
+ carry `getIamPolicy` — and returns the whole policy. That is what lets a
+ grantee discover whether they may edit, which is the only way to know now
+ that nothing caller-relative rides on the resource. Writing the policy
+ still needs `share(s,u)`.
An earlier revision filtered the response so a grantee saw only their own
bindings. Dropped as unnecessary: any authenticated user can already list
@@ -436,22 +501,22 @@ database" in the UI.
**Per-RPC access.** `CreateSavedQuery` and `ListSavedQueries` are IAM — one
family permission at the interceptor — and both re-check the permission source
in-handler to reject resource-conditioned bindings (see Conditioned role
-bindings). The search family is CUSTOM because its gate is
-`discover(u,P) ∨ admin(u,P)`, an OR the single-permission interceptor cannot
-express. Every object method is a CUSTOM per-row predicate.
+bindings). The search family is CUSTOM so the same source re-check runs
+beside its read-scoped access clause; its permission is `search` alone.
+Every object method is a CUSTOM per-row predicate.
| RPC | Auth | Gate | Content / audit |
|---|---|---|---|
| `CreateSavedQuery` | IAM `create` + source re-check | creator becomes owner | writes own; audited |
-| `SearchSavedQueries` | CUSTOM | `discover` → the caller's own rows plus those a binding grants; admins not widened | previews; unaudited |
+| `SearchSavedQueries` | CUSTOM | `discover` gate; returns rows where `read(s,u)` holds | previews; unaudited |
| `ListSavedQueries` | IAM `list` + source re-check | all rows matching `filter`; `projects/-` allowed | full content; unaudited |
| `GetSavedQuery` | CUSTOM | `read(s,u)`; NotFound when unreadable | full content; unaudited |
-| `UpdateSavedQuery` | CUSTOM | title/content/database `write(s,u)`; `folder` creator/admin | returns content; audited |
+| `UpdateSavedQuery` | CUSTOM | `write(s,u)` | returns content; audited |
| `DeleteSavedQuery` | CUSTOM | `delete(s,u)` | — ; audited |
-| `GetSavedQueryPolicy` | CUSTOM | `read(s,u)`; NotFound when unreadable | policy only; unaudited |
+| `GetSavedQueryPolicy` | CUSTOM | `readPolicy(s,u)`; NotFound when unreadable | policy only; unaudited |
| `SetSavedQueryPolicy` | CUSTOM | `share(s,u)` + etag CAS | policy only; audited |
| `UpdateSavedQueryStar` | CUSTOM | `read(s,u)` — star any readable query | — ; unaudited |
-| `MoveMySavedQueries` | CUSTOM | the caller's own rows only, by name or by folder (descendants included) | count only; audited |
+| `MoveMySavedQueries` | CUSTOM | the caller's own rows under `source_folder` (descendants included); single re-files ride `UpdateSavedQuery` | count only; audited |
| `SearchSavedQueryFolders` | CUSTOM | `discover` → folder paths of readable rows, same access clause as Search | paths only; unaudited |
Duplicate and fork need no RPC: read what you can already see, then
@@ -465,12 +530,14 @@ Two enumeration surfaces for two use cases, not redundant:
|---|---|---|
| For | The SQL Editor | Governance |
| Scope | One project | One project, or `projects/-` |
-| Bindings | Respected; admins not widened | Ignored |
+| Bindings | Respected; project-level `get` adds the rest | Ignored |
| Content | Previews | Whole statements |
| Views | `creator == me`, `shared == true`, `starred == true` | `creator ==` |
-They no longer overlap: Search is caller-scoped even for an admin, so
-everyone's rows come only from List. One boundary is deliberately left out: a member has no
+For a role-`get` holder the two overlap in reach within one project; they
+stay two surfaces because Search serves the SQL Editor (previews, filter
+views) while List serves governance (whole statements, `projects/-`).
+One boundary is deliberately left out: a member has no
cross-project "all my own queries" view, since discovery is per-project
(peer-consistent with BigQuery and Databricks) and the only `projects/-` path is
the privileged audit List. A self-scoped cross-project view is safe to add later
@@ -491,12 +558,12 @@ mutates a saved query or its policy is annotated — `CreateSavedQuery`,
derivable from the method rather than from who the caller happened to be, and
draws the same line as the rest of the v1 API.
-Two privileged reads are left unaudited deliberately: `GetSavedQuery` and
-`SearchSavedQueries` under the admin backstop, and the binding-bypassing
-`ListSavedQueries`. Both are governance surfaces gated by permissions no
-default member role carries (decision 7), so the control is *who holds
-`list`/`manage`*, not a trail behind them — and a read trail on the SQL Editor's
-hot path would be mostly people reading their own drafts.
+Privileged reads are left unaudited deliberately: `GetSavedQuery` and
+`SearchSavedQueries` under a role-granted `get`, and the binding-bypassing
+`ListSavedQueries` — all gated by permissions no default member role
+carries (decision 7), so the control is *who holds `get`/`list`*, not a
+trail behind them — and a read trail on the SQL Editor's hot path would be
+mostly people reading their own drafts.
Two costs, stated plainly:
@@ -544,6 +611,15 @@ project-derived-principal hack rejected in Alternatives. The blast radius is
small, since sharing was a coarse and little-used flag. Called out in the
release notes; historical audit-log entries keep the old names as records.
+The 2026-08-14 permission split rides the same upgrade train as the rename:
+custom roles reach the split migration carrying `bb.savedQueries.manage`
+either from a pre-release build or — the shipped population — from
+`bb.worksheets.manage` renamed by the earlier migration in the same run. The
+split expands it to `get` + `getIamPolicy` + `update` + `delete`;
+`setIamPolicy` is deliberately withheld, so re-share retires for migrated
+custom roles exactly as it does for the predefined admin roles, and granting
+it back is an explicit custom-role edit called out in the release notes.
+
### Storage and query scalability
@@ -591,8 +667,9 @@ default opclass, and containment is all these queries do. The list query
filters the table directly, one probe per principal:
```sql
--- The search gate already passed at the interceptor. An admin drops the
--- whole access clause. Paging is the platform's LIMIT/OFFSET page token.
+-- The search gate already passed. A caller with project-level get drops the
+-- whole access clause, as List does. Paging is the platform's LIMIT/OFFSET
+-- page token.
SELECT s.* FROM saved_query s
WHERE s.project = $P
AND ( s.creator = $me -- own (incl. private)
@@ -615,8 +692,9 @@ Honest per-tab costs (G7):
cold enough to need no index of its own.
- **Starred**: my rows in `saved_query_star` via its `principal` btree —
row existence is the star. Fetch the (naturally small) set, join, drop
- rows I can no longer read (lazily deleting stale stars), sort.
- `O(my stars)` — bounded by my own behavior.
+ rows I can no longer read from the view — the star row itself persists,
+ hidden, so re-granted access restores the bookmark; rows are removed only
+ with the saved query. `O(my stars)` — bounded by my own behavior.
- **Shared with me**: the only tab touching groups — `K+1` GIN probes for
`K` groups, BitmapOr'd into my accessible set `S`, then sorted per page:
`O(S log S)` — the honest cost of the no-extra-table choice, acceptable
@@ -689,10 +767,22 @@ lock-ordering):
**not** via the FK cascade, which would lock the parent first — matching
the star and purge order so a delete racing a star toggle or a purge
cannot deadlock.
-- **Purge is child-before-parent.** `BatchDeleteProjects`' hard-delete path
- deletes `saved_query_star` (child) before `saved_query`, and `saved_query`
- before `project` (as it deletes `worksheet` today) — locking existing
- child rows ahead of their parents, per the rule.
+- **Purge is child-before-parent, and re-parents human rows.** The
+ hard-delete path deletes the stars and saved queries of project service
+ accounts and workload identities (stars first), then reassigns the
+ remaining, human-created saved queries to the default project — locking
+ existing child rows ahead of their parents, per the rule. Because a
+ surviving row changes project mid-purge, **every non-purge writer scopes
+ its predicate by `(resource_id, project)`** — patch, delete, and the
+ first-star parent fence — so a write authorized in the purged project
+ cannot land on the reassigned row; it updates zero rows and surfaces as
+ NotFound (the fenced delete rolls back its star cleanup). The declared
+ lifecycle policy: writers on existing rows require the row in the
+ authorized project, not an active project — archived projects are already
+ unreachable through every read path, so a write racing an archive is an
+ ordinary serialization of concurrent requests, and restore does not
+ promise to resurrect a row whose authorized delete won that race. Only
+ creation requires an active project.
Two invariants cover every writer. **(1) Child before parent** for
existing-row writes/deletes; the *only* parent-first step is a new-child
@@ -709,8 +799,8 @@ delete) before mutating. Required before
implementation: deterministic real-PostgreSQL regression tests for **both**
acquisition orders of each contending pair — create↔purge,
first-star↔purge, delete↔star-toggle, delete↔purge over a query with
-multiple stars, and two overlapping `MoveMySavedQueries` with
-intersecting, reverse-ordered targets — asserting the terminal outcomes — project (or query) deleted, no orphaned
+multiple stars, and two overlapping `MoveMySavedQueries` over
+the same folder — asserting the terminal outcomes — project (or query) deleted, no orphaned
saved query or star, and **no** FK failure or deadlock (`40P01`) in either
direction (absence of `40P01` alone is insufficient).
@@ -725,13 +815,17 @@ direction (absence of `40P01` alone is insufficient).
list — BigQuery's behavior, and the reason nothing caller-relative beyond
`starred` sits on the resource. The editor calls `GetSavedQueryPolicy`
alongside `GetSavedQuery` and reads its own binding from the response;
- creator and admin status the UI already knows. In **My** everything is
+ creator status and the caller's role-granted verbs the UI already knows.
+ In **My** everything is
writable anyway, so only **Shared** ever resolves to view-only.
-- Share dialog (creator or admin): add `user:`/`group:` at VIEWER/EDITOR;
+- Share dialog (creator, or a custom role granting `setIamPolicy`): add
+ `user:`/`group:` at VIEWER/EDITOR;
the picker suggests project members/groups (a non-member grantee opens
via link but cannot browse the project or run — see Model). **Share with
- project** = the snapshot shortcut (Model). Admins
- get a manage affordance on any query. Duplicate is always available.
+ project** = the snapshot shortcut (Model). Role holders see per-verb
+ affordances on any query — edit (`update`), delete (`delete`), share
+ (`setIamPolicy`, no predefined role) — and sharing stays the creator's by
+ default. Duplicate is always available.
Later dialog polish (search, suggested principals, per-row revoke) needs
no schema or API change — the bindings already carry it.
@@ -753,11 +847,10 @@ deferred.
existence is the star. Star any readable query; my star is invisible to
you. Powers the Starred view.
- **Folders (Phase 1 — personal)**: in every peer a query lives in exactly
- one folder, set by its owner; you never re-file someone else's item.
- Storage follows the semantic: the location is the `saved_query.folder`
- **path column on the object** ("a/b/c", '' = unfiled), set via
- `UpdateSavedQuery` (creator/admin only — re-filing is organization, not
- editing), bulk rename/move via `MoveMySavedQueries`. Folders never
+ one folder. Storage follows the semantic: the location is the
+ `saved_query.folder` **path column on the object** ("a/b/c", '' =
+ unfiled), set via `UpdateSavedQuery` as an ordinary `write` field, bulk
+ rename/move via `MoveMySavedQueries`. Folders never
grant access; a folder is a path on rows, so empty folders cannot exist.
Today's per-user organizer re-foldering (everyone re-files everything) is
dropped as the outlier. A query shared with you appears in
@@ -821,10 +914,29 @@ Sources: [Snowflake worksheets](https://docs.snowflake.com/en/user-guide/ui-snow
widens every project-visible query) and is coarse. The
share-with-project snapshot is the honest cost.
- **Classic-BigQuery-style permission family** (`get`/`update` on roles
- deciding read/edit of all shared queries) — the deprecated generation of
- the reference product; the sharer cannot scope who edits. An earlier
- revision recommended it for proximity to current RBAC; proximity is not a
- direction.
+ deciding read/edit of all shared queries, *instead of* per-object grants)
+ — the deprecated generation of the reference product; the sharer cannot
+ scope who edits. An earlier revision recommended it for proximity to
+ current RBAC; proximity is not a direction. The 2026-08-14 split is not
+ this: sharing stays per-object; the per-verb permissions are the admin
+ backstop's vocabulary, not the sharing mechanism.
+- **A single `manage` backstop** (the 2026-08-09 revision as first
+ implemented) — one coarse admin permission covering read, write, delete,
+ and policy administration, honestly named and easy to audit. Replaced
+ 2026-08-14: it was a lump the rest of the permission vocabulary does not
+ have, it hid the sub-project IAM shape (owner → bindings → project
+ roles), and it blocked custom-role granularity — read-only support
+ (`get` alone), cleanup-only (`delete` alone). What is given
+ up: the single scary knob; mitigated by the roles table (only admin roles
+ hold the verbs, none holds `setIamPolicy`) and the proto comment stating
+ that every verb except `create`/`search` reaches private content.
+- **No policy permissions** (policy read riding on `get`, policy write
+ creator-only with no permission — an interim revision of this amendment)
+ — dropped for uniformity: a method whose permission line names another
+ method's verb reads wrong, and a permissionless write is invisible to
+ IAM. The grantee-must-see-their-own-level requirement is met by the
+ bundles carrying `getIamPolicy` instead, and the creator-only default by
+ granting `setIamPolicy` to no predefined role (see The permissions).
- **Keep the mode flag** (status quo) — no path to per-user/per-group
sharing; it is Problem 2.
- **Reuse the `bytebase.v1.IamPolicy` proto per query** — role-based, would
@@ -862,7 +974,10 @@ Sources: [Snowflake worksheets](https://docs.snowflake.com/en/user-guide/ui-snow
rejected: discovery stays per-project, as in every peer.
- **Privacy-preserving admin** (delete-without-read) — used in an earlier
revision, dropped for peer parity and workable incident response
- (decision 5); narrow `manage` back if the privacy guarantee matters more.
+ (decision 5). The per-verb split makes it expressible after all: a role
+ granting `delete` without `get` deletes names it learns out of band while
+ discovering nothing — the single-check NotFound mask no longer re-checks
+ read on writes.
- **Grantable OWNER / transfer** — briefly adopted, removed as overkill: a
tier plus orphan-guard for cases the admin backstop and fork already
cover. Re-adding an OWNER level later is additive.
diff --git a/frontend/src/locales/en-US.json b/frontend/src/locales/en-US.json
index ff39204030..8e3087e008 100644
--- a/frontend/src/locales/en-US.json
+++ b/frontend/src/locales/en-US.json
@@ -2896,7 +2896,6 @@
"non-empty-folder-title": "Non-empty folder"
},
"mine": "Mine",
- "move-saved-queries": "Move saved queries",
"notifications": {
"duplicate-success": "Saved query duplicated"
},
diff --git a/frontend/src/locales/es-ES.json b/frontend/src/locales/es-ES.json
index 3ad062116d..97595ade8f 100644
--- a/frontend/src/locales/es-ES.json
+++ b/frontend/src/locales/es-ES.json
@@ -2896,7 +2896,6 @@
"non-empty-folder-title": "Carpeta no vacía"
},
"mine": "Mío",
- "move-saved-queries": "Mover consultas guardadas",
"notifications": {
"duplicate-success": "Consulta guardada duplicada"
},
diff --git a/frontend/src/locales/ja-JP.json b/frontend/src/locales/ja-JP.json
index 0a3147951b..7eb6aeb5e8 100644
--- a/frontend/src/locales/ja-JP.json
+++ b/frontend/src/locales/ja-JP.json
@@ -2896,7 +2896,6 @@
"non-empty-folder-title": "空でないフォルダ"
},
"mine": "マイクエリ",
- "move-saved-queries": "保存済みクエリを移動する",
"notifications": {
"duplicate-success": "保存済みクエリを複製しました"
},
diff --git a/frontend/src/locales/vi-VN.json b/frontend/src/locales/vi-VN.json
index 909d426e20..201384444f 100644
--- a/frontend/src/locales/vi-VN.json
+++ b/frontend/src/locales/vi-VN.json
@@ -2896,7 +2896,6 @@
"non-empty-folder-title": "Thư mục không trống"
},
"mine": "Của tôi",
- "move-saved-queries": "Di chuyển truy vấn đã lưu",
"notifications": {
"duplicate-success": "Đã nhân bản truy vấn đã lưu"
},
diff --git a/frontend/src/locales/zh-CN.json b/frontend/src/locales/zh-CN.json
index 026444a15f..04e8b3b5c0 100644
--- a/frontend/src/locales/zh-CN.json
+++ b/frontend/src/locales/zh-CN.json
@@ -2896,7 +2896,6 @@
"non-empty-folder-title": "非空文件夹"
},
"mine": "我的",
- "move-saved-queries": "移动已保存的查询",
"notifications": {
"duplicate-success": "查询已复制"
},
diff --git a/frontend/src/modules/sql-editor/components/SavedQueryPane.test.tsx b/frontend/src/modules/sql-editor/components/SavedQueryPane.test.tsx
index f160ca4f28..306ce286ce 100644
--- a/frontend/src/modules/sql-editor/components/SavedQueryPane.test.tsx
+++ b/frontend/src/modules/sql-editor/components/SavedQueryPane.test.tsx
@@ -472,138 +472,18 @@ describe("SavedQueryPane", () => {
);
expect(myTree?.getAttribute("data-multi-select-mode")).toBe("true");
- // Toolbar buttons rendered — Move + Cancel stay inline; destructive
- // Delete is tucked into the More menu for the narrow saved query pane.
+ // Toolbar buttons rendered — Cancel and Delete both fit inline now that
+ // the move-to-folder action is gone (no peer offers bulk query move).
const toolbarButtons = Array.from(
container.querySelectorAll("[data-testid='button']")
).map((el) => el.textContent?.trim());
expect(toolbarButtons).toEqual(
- expect.arrayContaining(["sheet.move-saved-queries", "common.cancel"])
+ expect.arrayContaining(["common.cancel", "common.delete"])
);
- expect(toolbarButtons).not.toContain("common.delete");
- const menuItems = Array.from(
- container.querySelectorAll("[data-testid='dropdown-menu-item']")
- ).map((el) => el.textContent?.trim());
- expect(menuItems).toContain("common.delete");
+ expect(toolbarButtons).not.toContain("sheet.move-saved-queries");
expect(toolbarButtons).not.toContain("common.n-selected");
unmount();
});
- test("5. Move modal opens and submit calls batchUpdateSavedQueryFolders", async () => {
- const { batchUpdateSavedQueryFolders, getFoldersForSavedQuery } =
- setupDefaultMocks();
- const { container, render, unmount } = renderIntoContainer(
- <SavedQueryPane />
- );
- render();
-
- // Step 1: enter multi-select and check a saved query
- act(() => {
- container
- .querySelector("[data-testid='sheet-tree-my-enter-multi-select']")
- ?.dispatchEvent(new MouseEvent("click", { bubbles: true }));
- });
- act(() => {
- container
- .querySelector("[data-testid='sheet-tree-my-check-ws']")
- ?.dispatchEvent(new MouseEvent("click", { bubbles: true }));
- });
-
- // Step 2: click the "move-saved-queries" toolbar button to open the modal
- const moveButton = Array.from(
- container.querySelectorAll("[data-testid='button']")
- ).find((el) => el.textContent?.trim() === "sheet.move-saved-queries") as
- | HTMLButtonElement
- | undefined;
- expect(moveButton).not.toBeUndefined();
-
- act(() => {
- moveButton?.dispatchEvent(new MouseEvent("click", { bubbles: true }));
- });
-
- // Dialog should be open now — FolderForm is rendered
- const folderForm = container.querySelector("[data-testid='folder-form']");
- expect(folderForm).not.toBeNull();
-
- // Step 3: change the folder target via the mocked FolderForm's setter
- act(() => {
- container
- .querySelector("[data-testid='folder-form-set-target']")
- ?.dispatchEvent(new MouseEvent("click", { bubbles: true }));
- });
-
- const saveButton = Array.from(
- container.querySelectorAll("[data-testid='button']")
- ).find((el) => el.textContent?.trim() === "common.save");
- expect(saveButton).not.toBeUndefined();
-
- await act(async () => {
- saveButton?.dispatchEvent(new MouseEvent("click", { bubbles: true }));
- });
-
- expect(getFoldersForSavedQuery).toHaveBeenCalledWith("/some/folder");
- expect(batchUpdateSavedQueryFolders).toHaveBeenCalledWith([
- { name: "savedQueries/ws1", folders: ["/some/folder"] },
- ]);
-
- unmount();
- });
-
- test("5b. Move modal can move saved queries to the root folder", async () => {
- const { batchUpdateSavedQueryFolders, getFoldersForSavedQuery } =
- setupDefaultMocks();
- const { container, render, unmount } = renderIntoContainer(
- <SavedQueryPane />
- );
- render();
-
- act(() => {
- container
- .querySelector("[data-testid='sheet-tree-my-enter-multi-select']")
- ?.dispatchEvent(new MouseEvent("click", { bubbles: true }));
- });
- act(() => {
- container
- .querySelector("[data-testid='sheet-tree-my-check-ws']")
- ?.dispatchEvent(new MouseEvent("click", { bubbles: true }));
- });
-
- const moveButton = Array.from(
- container.querySelectorAll("[data-testid='button']")
- ).find((el) => el.textContent?.trim() === "sheet.move-saved-queries");
- act(() => {
- moveButton?.dispatchEvent(new MouseEvent("click", { bubbles: true }));
- });
-
- act(() => {
- container
- .querySelector("[data-testid='folder-form-set-target']")
- ?.dispatchEvent(new MouseEvent("click", { bubbles: true }));
- });
-
- const folderForm = container.querySelector("[data-testid='folder-form']");
- expect(folderForm?.getAttribute("data-include-root")).toBe("true");
-
- act(() => {
- container
- .querySelector("[data-testid='folder-form-set-root']")
- ?.dispatchEvent(new MouseEvent("click", { bubbles: true }));
- });
-
- const saveButton = Array.from(
- container.querySelectorAll("[data-testid='button']")
- ).find((el) => el.textContent?.trim() === "common.save");
-
- await act(async () => {
- saveButton?.dispatchEvent(new MouseEvent("click", { bubbles: true }));
- });
-
- expect(getFoldersForSavedQuery).toHaveBeenCalledWith("/my");
- expect(batchUpdateSavedQueryFolders).toHaveBeenCalledWith([
- { name: "savedQueries/ws1", folders: [] },
- ]);
-
- unmount();
- });
});
diff --git a/frontend/src/modules/sql-editor/components/SavedQueryPane.tsx b/frontend/src/modules/sql-editor/components/SavedQueryPane.tsx
index f800e9bc15..cf6bc84477 100644
--- a/frontend/src/modules/sql-editor/components/SavedQueryPane.tsx
+++ b/frontend/src/modules/sql-editor/components/SavedQueryPane.tsx
@@ -2,18 +2,16 @@
* SavedQueryPane — React port of SavedQueryPane.vue (Stage 12, Phase 4).
*
* Hosts the SQL editor's saved query sidebar: search, filter menu, multi-select
- * toolbar, move-to-folder dialog, and one SheetTree per visible view.
+ * toolbar, and one SheetTree per visible view.
*/
-import { FolderInputIcon, FunnelIcon, TrashIcon, XIcon } from "lucide-react";
+import { FunnelIcon, TrashIcon, XIcon } from "lucide-react";
import { useEffect, useMemo, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import {
type SelectionAction,
SelectionActionBar,
} from "@/components/SelectionActionBar";
-import { Button } from "@/components/ui/button";
-import { Dialog, DialogContent, DialogTitle } from "@/components/ui/dialog";
import {
DropdownMenu,
DropdownMenuContent,
@@ -30,7 +28,6 @@ import {
useSheetContextByView,
} from "@/modules/sql-editor/model/Sheet";
import { FilterMenuItem } from "./FilterMenuItem";
-import { FolderForm } from "./FolderForm";
import { SheetTree, type SheetTreeHandle } from "./SheetTree";
function collectSelectableNodes(
@@ -47,18 +44,14 @@ export function SavedQueryPane() {
const { t } = useTranslation();
const sheetContext = useSheetContext();
- const { filter, filterChanged, batchUpdateSavedQueryFolders, setFilter } =
- sheetContext;
+ const { filter, filterChanged, setFilter } = sheetContext;
const myViewContext = useSheetContextByView("my");
- const { getFoldersForSavedQuery } = myViewContext;
const mineSheetTreeRef = useRef<SheetTreeHandle>(null);
const [multiSelectMode, setMultiSelectMode] = useState(false);
const [checkedNodes, setCheckedNodes] = useState<SavedQueryFolderNode[]>([]);
- const [showReorgModal, setShowReorgModal] = useState(false);
- const [pendingMoveFolder, setPendingMoveFolder] = useState("");
const [loading, setLoading] = useState(false);
const [showFilterMenu, setShowFilterMenu] = useState(false);
@@ -76,13 +69,6 @@ export function SavedQueryPane() {
return results;
}, [filter.showShared, filter.showDraft]);
- const checkedSavedQueries = useMemo(
- () =>
- checkedNodes
- .filter((node) => node.savedQuery)
- .map((node) => node.savedQuery!.name),
- [checkedNodes]
- );
const selectableNodes = useMemo(
() => collectSelectableNodes(myViewContext.sheetTree),
[myViewContext.sheetTree]
@@ -112,37 +98,7 @@ export function SavedQueryPane() {
}
};
- const handleMoveSavedQueries = async () => {
- setLoading(true);
- try {
- const folders = getFoldersForSavedQuery(pendingMoveFolder);
- await batchUpdateSavedQueryFolders(
- checkedSavedQueries.map((savedQuery) => ({ name: savedQuery, folders }))
- );
- setShowReorgModal(false);
- setMultiSelectMode(false);
- setPendingMoveFolder("");
- } finally {
- setLoading(false);
- }
- };
-
- const closeReorgModal = () => {
- setShowReorgModal(false);
- setPendingMoveFolder("");
- };
-
const batchActions: SelectionAction[] = [
- {
- key: "move",
- label: t("sheet.move-saved-queries"),
- icon: FolderInputIcon,
- onClick: () => {
- setPendingMoveFolder("");
- setShowReorgModal(true);
- },
- disabled: checkedSavedQueries.length === 0 || loading,
- },
{
key: "cancel",
label: t("common.cancel"),
@@ -228,7 +184,7 @@ export function SavedQueryPane() {
// Non-"my" trees intentionally omit multi-select callbacks. Vue
// bound v-model only on the `my` tree; wiring them everywhere let
// a shared/draft right-click populate the my tree's checkedNodes,
- // which the toolbar's Delete + Move-to-folder flows act on.
+ // which the toolbar's Delete flow acts on.
<SheetTree key={view} view={view} />
))}
{!hasAnyView && (
@@ -254,30 +210,6 @@ export function SavedQueryPane() {
density="compact"
/>
)}
-
- <Dialog
- open={showReorgModal}
- onOpenChange={(open) => !open && closeReorgModal()}
- >
- <DialogContent className="w-lg max-w-[calc(100vw-8rem)] p-6">
- <DialogTitle>{t("sheet.move-saved-queries")}</DialogTitle>
- <div className="mt-3 flex flex-col gap-y-3">
- <FolderForm
- folder={pendingMoveFolder}
- onFolderChange={setPendingMoveFolder}
- includeRoot
- />
- <div className="flex justify-end gap-x-2 mt-4">
- <Button appearance="outline" onClick={closeReorgModal}>
- {t("common.close")}
- </Button>
- <Button onClick={handleMoveSavedQueries} disabled={loading}>
- {t("common.save")}
- </Button>
- </div>
- </div>
- </DialogContent>
- </Dialog>
</div>
);
}
diff --git a/frontend/src/modules/sql-editor/components/SharePopoverBody.test.tsx b/frontend/src/modules/sql-editor/components/SharePopoverBody.test.tsx
index 8971a00831..d19ffcbf81 100644
--- a/frontend/src/modules/sql-editor/components/SharePopoverBody.test.tsx
+++ b/frontend/src/modules/sql-editor/components/SharePopoverBody.test.tsx
@@ -50,6 +50,11 @@ vi.mock("@/stores/app", () => {
vi.mock("@/utils", () => ({
extractProjectResourceName: mocks.extractProjectResourceName,
extractSavedQueryID: mocks.extractSavedQueryID,
+ // Mirrors the real helper: the creator, or a project-level
+ // bb.savedQueries.setIamPolicy.
+ isSavedQueryShareableV1: (sheet: { creator: string }) =>
+ sheet.creator === "users/[email protected]" ||
+ mocks.hasProjectPermissionV2(),
}));
vi.mock("@/utils/iam/permission", () => ({
@@ -146,7 +151,7 @@ describe("SharePopoverBody", () => {
unmount();
});
- test("a non-creator without manage gets a read-only grant editor", () => {
+ test("a non-creator without setIamPolicy gets a read-only grant editor", () => {
mocks.hasProjectPermissionV2.mockReturnValue(false);
const { render, unmount } = renderIntoContainer(
<SharePopoverBody
diff --git a/frontend/src/modules/sql-editor/components/SharePopoverBody.tsx b/frontend/src/modules/sql-editor/components/SharePopoverBody.tsx
index e96ba77ea7..143a67a005 100644
--- a/frontend/src/modules/sql-editor/components/SharePopoverBody.tsx
+++ b/frontend/src/modules/sql-editor/components/SharePopoverBody.tsx
@@ -7,8 +7,11 @@ import { Button } from "@/components/ui/button";
import { writeTextToClipboard } from "@/lib/clipboard";
import { useAppStore } from "@/stores/app";
import type { SavedQuery } from "@/types/proto-es/v1/saved_query_service_pb";
-import { extractProjectResourceName, extractSavedQueryID } from "@/utils";
-import { hasProjectPermissionV2 } from "@/utils/iam/permission";
+import {
+ extractProjectResourceName,
+ extractSavedQueryID,
+ isSavedQueryShareableV1,
+} from "@/utils";
import { SavedQueryGrantEditor } from "./SavedQueryGrantEditor";
@@ -26,18 +29,13 @@ export function SharePopoverBody({ savedQuery }: Props) {
const { t } = useTranslation();
const workspaceExternalURL = useAppStore((s) => s.serverInfo?.externalUrl);
const currentUser = useAppStore((s) => s.currentUser);
- const getProjectByName = useAppStore((s) => s.getProjectByName);
- // Sharing and deletion are creator-or-admin; a binding never confers them.
+ // Sharing: the creator, or a project-level bb.savedQueries.setIamPolicy.
// Both inputs are already on the client, so this needs no extra request.
const canManage = useMemo(() => {
- if (!savedQuery) return false;
- if (savedQuery.creator === `users/${currentUser?.email}`) return true;
- const project = getProjectByName(savedQuery.project);
- return project
- ? hasProjectPermissionV2(project, "bb.savedQueries.manage")
- : false;
- }, [savedQuery, currentUser, getProjectByName]);
+ if (!savedQuery || !currentUser) return false;
+ return isSavedQueryShareableV1(savedQuery);
+ }, [savedQuery, currentUser]);
const sharedTabLink = useMemo(() => {
if (!savedQuery) return "";
diff --git a/frontend/src/modules/sql-editor/components/SheetTree.tsx b/frontend/src/modules/sql-editor/components/SheetTree.tsx
index 38f4158d5f..d0706fabf7 100644
--- a/frontend/src/modules/sql-editor/components/SheetTree.tsx
+++ b/frontend/src/modules/sql-editor/components/SheetTree.tsx
@@ -69,7 +69,10 @@ import { useSQLEditorStore as useSQLEditorReactStore } from "@/modules/sql-edito
import { useSQLEditorEditorState } from "@/modules/sql-editor/store/editor";
import { getSQLEditorTabsState } from "@/modules/sql-editor/store/tab";
import { useAppStore } from "@/stores/app";
-import { canSearchSavedQueriesInProject } from "@/utils";
+import {
+ canSearchSavedQueriesInProject,
+ isSavedQueryWritableV1,
+} from "@/utils";
import { filterNode } from "./filterNode";
import { SharePopoverBody } from "./SharePopoverBody";
import { TreeNodePrefix } from "./TreeNodePrefix";
@@ -643,9 +646,23 @@ export function SheetTree({
cleanup();
return;
}
- await useAppStore
- .getState()
- .patchSavedQuery({ ...savedQuery, title: newTitle }, ["title"]);
+ try {
+ await useAppStore
+ .getState()
+ .patchSavedQuery({ ...savedQuery, title: newTitle }, ["title"]);
+ } catch (error) {
+ // The global middleware ignores NotFound — and a permission denial
+ // is masked as NotFound — so surface the failure here or the rename
+ // silently never persists.
+ useAppStore.getState().notify({
+ module: "bytebase",
+ style: "CRITICAL",
+ title: t("common.error"),
+ description: error instanceof Error ? error.message : String(error),
+ });
+ cleanup();
+ return;
+ }
const tabsState = getSQLEditorTabsState();
const tab = Array.from(tabsState.tabsById.values()).find(
(t) => t.savedQuery === savedQuery.name
@@ -1611,16 +1628,26 @@ export function SheetTree({
: "[&_[role=treeitem]]:overflow-hidden"
)}
onMove={handleMove}
- // Dragging re-files, and only your own saved queries can be re-filed,
- // so the Shared tree is browse-only rather than accepting a drop the
- // server declines.
+ // Dragging re-files, which is UpdateSavedQuery's folder field, so a
+ // Shared-tree saved query is draggable exactly when the caller can
+ // update it — the predicate that gates rename. Folders stay pinned
+ // outside the my tree: MoveMySavedQueries rewrites only the caller's
+ // own rows, so dragging a shared folder would move nothing.
disableDrag={
- view !== "my" || !!editingNode || multiSelectMode
+ view === "draft" || !!editingNode || multiSelectMode
? true
- : ({ data }) => !!data.loadMore
+ : ({ data }) => {
+ if (data.loadMore) return true;
+ if (view === "my") return false;
+ if (!data.savedQuery) return true;
+ const entity = useAppStore
+ .getState()
+ .getSavedQueryByName(data.savedQuery.name);
+ return !entity || !isSavedQueryWritableV1(entity);
+ }
}
disableDrop={
- view !== "my" || !!editingNode || multiSelectMode
+ view === "draft" || !!editingNode || multiSelectMode
? true
: ({ parentNode: p, dragNodes }) =>
!!p?.data.data.savedQuery ||
diff --git a/frontend/src/modules/sql-editor/components/useDropdown.test.ts b/frontend/src/modules/sql-editor/components/useDropdown.test.ts
index 9d6cf732a1..5970ec061a 100644
--- a/frontend/src/modules/sql-editor/components/useDropdown.test.ts
+++ b/frontend/src/modules/sql-editor/components/useDropdown.test.ts
@@ -11,6 +11,14 @@ const mocks = vi.hoisted(() => ({
currentUser: { email: "[email protected]" },
savedQuery: undefined as SavedQuery | undefined,
isSavedQueryWritableV1: vi.fn(() => true),
+ // Mirror the real predicates' creator arm; role-grant cases override
+ // per test.
+ isSavedQueryDeletableV1: vi.fn(
+ (sheet: SavedQuery) => sheet.creator === "users/[email protected]"
+ ),
+ isSavedQueryShareableV1: vi.fn(
+ (sheet: SavedQuery) => sheet.creator === "users/[email protected]"
+ ),
canCreateSavedQueryInProject: vi.fn(() => true),
}));
@@ -31,6 +39,8 @@ vi.mock("@/stores/app", () => ({
vi.mock("@/utils", () => ({
isSavedQueryWritableV1: mocks.isSavedQueryWritableV1,
+ isSavedQueryDeletableV1: mocks.isSavedQueryDeletableV1,
+ isSavedQueryShareableV1: mocks.isSavedQueryShareableV1,
canCreateSavedQueryInProject: mocks.canCreateSavedQueryInProject,
}));
@@ -90,6 +100,27 @@ describe("useDropdown", () => {
).toEqual(["duplicate", "rename"]);
});
+ test("role-granted delete and share reach shared saved queries", () => {
+ mocks.savedQuery = {
+ name: "projects/proj/savedQueries/sheet",
+ creator: "users/[email protected]",
+ } as SavedQuery;
+ mocks.isSavedQueryDeletableV1.mockReturnValue(true);
+ mocks.isSavedQueryShareableV1.mockReturnValue(true);
+
+ const { result } = renderHook(() =>
+ useDropdown("shared", baseFilter, false)
+ );
+
+ act(() => {
+ result.current.handleContextMenu(event, savedQueryNode);
+ });
+
+ expect(
+ result.current.options.map((item) => item.type === "item" && item.key)
+ ).toEqual(["duplicate", "share", "rename", "delete"]);
+ });
+
test("keeps delete for writable my saved queries", () => {
mocks.savedQuery = {
name: "projects/proj/savedQueries/sheet",
diff --git a/frontend/src/modules/sql-editor/components/useDropdown.ts b/frontend/src/modules/sql-editor/components/useDropdown.ts
index 333be53d2c..dc1e168918 100644
--- a/frontend/src/modules/sql-editor/components/useDropdown.ts
+++ b/frontend/src/modules/sql-editor/components/useDropdown.ts
@@ -17,7 +17,12 @@ import type {
} from "@/modules/sql-editor/model/Sheet";
import { useSQLEditorEditorState } from "@/modules/sql-editor/store/editor";
import { useAppStore } from "@/stores/app";
-import { canCreateSavedQueryInProject, isSavedQueryWritableV1 } from "@/utils";
+import {
+ canCreateSavedQueryInProject,
+ isSavedQueryDeletableV1,
+ isSavedQueryShareableV1,
+ isSavedQueryWritableV1,
+} from "@/utils";
// ---------------------------------------------------------------------------
// Types
@@ -47,7 +52,7 @@ export function useDropdown(
// Only the "my" tree is wired to the parent's multi-select state. For
// other views (shared / draft) the context-menu entry is hidden so a
// right-click on a shared saved query cannot populate the my tree's
- // checkedNodes — which the toolbar's Delete + Move-to-folder flows act on.
+ // checkedNodes — which the toolbar's Delete flow acts on.
canMultiSelect = false
) {
const { t } = useTranslation();
@@ -109,24 +114,27 @@ export function useDropdown(
label: isCreator ? t("common.duplicate") : t("common.fork"),
});
}
- if (isCreator) {
+ // Per-verb affordances mirroring the server: share follows
+ // setIamPolicy (creator, or a custom role), delete follows the delete
+ // verb (creator, or a role grant) — so an admin doing orphan cleanup
+ // sees Delete on shared rows too.
+ if (isSavedQueryShareableV1(savedQueryEntity)) {
items.push({
key: "share",
label: t("common.share"),
});
}
- const canWriteSheet = isSavedQueryWritableV1(savedQueryEntity);
- if (canWriteSheet) {
+ if (isSavedQueryWritableV1(savedQueryEntity)) {
items.push({
key: "rename",
label: t("sql-editor.tab.context-menu.actions.rename"),
});
- if (viewMode === "my") {
- items.push({
- key: "delete",
- label: t("common.delete"),
- });
- }
+ }
+ if (isSavedQueryDeletableV1(savedQueryEntity)) {
+ items.push({
+ key: "delete",
+ label: t("common.delete"),
+ });
}
if (canMultiSelect) {
items.push({
diff --git a/frontend/src/modules/sql-editor/model/Sheet/context.test.tsx b/frontend/src/modules/sql-editor/model/Sheet/context.test.tsx
index 9a83fead97..c9ec2c5fdf 100644
--- a/frontend/src/modules/sql-editor/model/Sheet/context.test.tsx
+++ b/frontend/src/modules/sql-editor/model/Sheet/context.test.tsx
@@ -22,10 +22,12 @@ type AppState = {
fetchSavedQueryList: ReturnType<typeof vi.fn>;
updateSavedQueryStar: ReturnType<typeof vi.fn>;
moveMySavedQueries: ReturnType<typeof vi.fn>;
+ patchSavedQuery: ReturnType<typeof vi.fn>;
};
const mocks = vi.hoisted(() => {
let appState: AppState;
+ const isSavedQueryWritableV1 = vi.fn();
const appSubscribers = new Set<(state: AppState, prev: AppState) => void>();
const keyForSavedQuery = (name: string) => `${name.split("/").pop()}:FULL`;
@@ -53,6 +55,7 @@ const mocks = vi.hoisted(() => {
return {
getAppState: () => appState,
+ isSavedQueryWritableV1,
resetAppState: () => {
appSubscribers.clear();
appState = {
@@ -78,6 +81,7 @@ const mocks = vi.hoisted(() => {
}),
updateSavedQueryStar: vi.fn(),
moveMySavedQueries: vi.fn(async () => 0),
+ patchSavedQuery: vi.fn(async () => undefined),
patchSavedQueryFolderInCache: vi.fn(),
};
},
@@ -107,6 +111,14 @@ vi.mock("@/stores/app", () => ({
useAppStore: mocks.useAppStore,
}));
+// The real predicate reads registration bridges the mocked store never
+// installs, so it is stubbed; the default (set in beforeEach) mirrors its
+// creator arm.
+vi.mock("@/utils", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("@/utils")>()),
+ isSavedQueryWritableV1: mocks.isSavedQueryWritableV1,
+}));
+
vi.mock("@/modules/sql-editor/store/editor", () => ({
getSQLEditorEditorState: () => ({ project: "projects/proj1" }),
subscribeSQLEditorEditorState: mocks.subscribeSQLEditorEditorState,
@@ -126,6 +138,9 @@ describe("sheet context", () => {
beforeEach(() => {
vi.useFakeTimers();
mocks.resetAppState();
+ mocks.isSavedQueryWritableV1.mockImplementation(
+ (sheet: SavedQuery) => sheet.creator === "users/[email protected]"
+ );
window.localStorage.clear();
container = document.createElement("div");
document.body.appendChild(container);
@@ -900,7 +915,7 @@ describe("sheet context", () => {
expect(viewContext!.hasMoreForFolder("/my/alpha")).toBe(false);
});
- test("batch updates saved query folders with one name filter per target folder", async () => {
+ test("batch updates saved query folders via UpdateSavedQuery per row", async () => {
const { provideSheetContext, useSheetContext } = await import("./context");
let sheetContext: ReturnType<typeof useSheetContext> | undefined;
@@ -915,6 +930,23 @@ describe("sheet context", () => {
root.render(<Probe />);
});
+ // Re-filing patches the cached row, so the rows must be in the cache and
+ // writable by the caller (the default stub passes creator rows).
+ mocks.addSavedQueries([
+ create(SavedQuerySchema, {
+ name: "projects/proj1/savedQueries/1",
+ project: "projects/proj1",
+ creator: "users/[email protected]",
+ title: "one",
+ }),
+ create(SavedQuerySchema, {
+ name: "projects/proj1/savedQueries/2",
+ project: "projects/proj1",
+ creator: "users/[email protected]",
+ title: "two",
+ }),
+ ]);
+
await act(async () => {
await sheetContext!.batchUpdateSavedQueryFolders([
{ name: "projects/proj1/savedQueries/1", folders: ["target"] },
@@ -922,23 +954,100 @@ describe("sheet context", () => {
]);
});
- expect(mocks.getAppState().moveMySavedQueries).toHaveBeenCalledTimes(1);
- expect(mocks.getAppState().moveMySavedQueries).toHaveBeenCalledWith(
- "projects/proj1",
- {
- names: [
- "projects/proj1/savedQueries/1",
- "projects/proj1/savedQueries/2",
- ],
- targetFolder: "target",
- }
+ expect(mocks.getAppState().moveMySavedQueries).not.toHaveBeenCalled();
+ expect(mocks.getAppState().patchSavedQuery).toHaveBeenCalledTimes(2);
+ expect(mocks.getAppState().patchSavedQuery).toHaveBeenCalledWith(
+ expect.objectContaining({
+ name: "projects/proj1/savedQueries/1",
+ folder: "target",
+ }),
+ ["folder"]
+ );
+ expect(mocks.getAppState().patchSavedQuery).toHaveBeenCalledWith(
+ expect.objectContaining({
+ name: "projects/proj1/savedQueries/2",
+ folder: "target",
+ }),
+ ["folder"]
+ );
+ // Both cache views are re-filed per row so the tree rebuild does not snap
+ // the rows back to the old folder.
+ expect(
+ mocks.getAppState().patchSavedQueryFolderInCache
+ ).toHaveBeenCalledWith(["projects/proj1/savedQueries/1"], "target");
+ expect(
+ mocks.getAppState().patchSavedQueryFolderInCache
+ ).toHaveBeenCalledWith(["projects/proj1/savedQueries/2"], "target");
+ });
+
+ test("re-files shared rows the caller can update and skips the rest", async () => {
+ const { provideSheetContext, useSheetContext } = await import("./context");
+ let sheetContext: ReturnType<typeof useSheetContext> | undefined;
+
+ const Probe = () => {
+ provideSheetContext();
+ sheetContext = useSheetContext();
+ return null;
+ };
+
+ root = createRoot(container);
+ await act(async () => {
+ root.render(<Probe />);
+ });
+
+ // The server lets an EDITOR grantee (or a project-level update grant)
+ // re-file somebody else's saved query — folder is an ordinary update
+ // field — so the move keys off writability, not ownership.
+ mocks.addSavedQueries([
+ create(SavedQuerySchema, {
+ name: "projects/proj1/savedQueries/editable-shared",
+ project: "projects/proj1",
+ creator: "users/[email protected]",
+ title: "editable",
+ }),
+ create(SavedQuerySchema, {
+ name: "projects/proj1/savedQueries/readonly-shared",
+ project: "projects/proj1",
+ creator: "users/[email protected]",
+ title: "read-only",
+ }),
+ ]);
+ mocks.isSavedQueryWritableV1.mockImplementation(
+ (sheet: SavedQuery) =>
+ sheet.name === "projects/proj1/savedQueries/editable-shared"
+ );
+
+ await act(async () => {
+ await sheetContext!.batchUpdateSavedQueryFolders([
+ {
+ name: "projects/proj1/savedQueries/editable-shared",
+ folders: ["target"],
+ },
+ {
+ name: "projects/proj1/savedQueries/readonly-shared",
+ folders: ["target"],
+ },
+ ]);
+ });
+
+ expect(mocks.getAppState().patchSavedQuery).toHaveBeenCalledTimes(1);
+ expect(mocks.getAppState().patchSavedQuery).toHaveBeenCalledWith(
+ expect.objectContaining({
+ name: "projects/proj1/savedQueries/editable-shared",
+ folder: "target",
+ }),
+ ["folder"]
);
- // The batch RPC answers with a count, so the moved rows are mirrored into
- // the cache — otherwise the tree rebuild snaps them back to the old folder.
expect(
mocks.getAppState().patchSavedQueryFolderInCache
).toHaveBeenCalledWith(
- ["projects/proj1/savedQueries/1", "projects/proj1/savedQueries/2"],
+ ["projects/proj1/savedQueries/editable-shared"],
+ "target"
+ );
+ expect(
+ mocks.getAppState().patchSavedQueryFolderInCache
+ ).not.toHaveBeenCalledWith(
+ ["projects/proj1/savedQueries/readonly-shared"],
"target"
);
});
diff --git a/frontend/src/modules/sql-editor/model/Sheet/context.ts b/frontend/src/modules/sql-editor/model/Sheet/context.ts
index dfd2e45925..cec6fbd6b8 100644
--- a/frontend/src/modules/sql-editor/model/Sheet/context.ts
+++ b/frontend/src/modules/sql-editor/model/Sheet/context.ts
@@ -25,6 +25,7 @@ import {
getDefaultPagination,
getSheetStatement,
isSavedQueryReadableV1,
+ isSavedQueryWritableV1,
storageKeySqlEditorSavedQueryFolder,
storageKeySqlEditorSavedQueryTree,
workspaceCacheScope,
@@ -1245,18 +1246,18 @@ const batchUpdateSavedQueryFolders = async (
affectedFolderKeysByView.set(view, keys);
};
- const requestByKey = new Map<
- string,
- { parent: string; folders: string[]; names: string[] }
- >();
- const currentUserName = `users/${useAppStore.getState().currentUser?.email}`;
+ // Re-filing rides UpdateSavedQuery's folder field — MoveMySavedQueries
+ // moves whole folders only. The row is always cached here (it came off the
+ // tree), and it moves exactly when the caller can update it — the predicate
+ // that gates rename — so an EDITOR grantee re-files a shared saved query
+ // while a row the server would refuse is skipped rather than patched into
+ // a NotFound the cache would contradict.
+ const updates: { current: SavedQuery; folder: string }[] = [];
for (const savedQuery of savedQueries) {
const current = useAppStore.getState().getSavedQueryByName(savedQuery.name);
- // Only the creator's own rows move. Sending somebody else's would come
- // back with nothing moved while the cache patch below claimed otherwise.
- if (current && current.creator !== currentUserName) continue;
- const view = current ? viewForSavedQuery(current) : undefined;
- if (current && (view === "my" || view === "shared")) {
+ if (!current || !isSavedQueryWritableV1(current)) continue;
+ const view = viewForSavedQuery(current);
+ if (view === "my" || view === "shared") {
addAffectedFolderKey(
view,
getPwdForSavedQuery(view, {
@@ -1265,36 +1266,17 @@ const batchUpdateSavedQueryFolders = async (
);
addAffectedFolderKey(view, getPwdForSavedQuery(view, savedQuery));
}
-
- const index = savedQuery.name.lastIndexOf("/savedQueries/");
- if (index < 0) {
- continue;
- }
- const parent = savedQuery.name.slice(0, index);
- const key = JSON.stringify([parent, savedQuery.folders]);
- const request = requestByKey.get(key);
- if (request) {
- request.names.push(savedQuery.name);
- } else {
- requestByKey.set(key, {
- parent,
- folders: savedQuery.folders,
- names: [savedQuery.name],
- });
- }
+ updates.push({ current, folder: savedQuery.folders.join("/") });
}
- const requests = [...requestByKey.values()];
- if (requests.length === 0) return;
+ if (updates.length === 0) return;
await Promise.all(
- requests.map(async (request) => {
- const folder = request.folders.join("/");
- await useAppStore.getState().moveMySavedQueries(request.parent, {
- names: request.names,
- targetFolder: folder,
- });
+ updates.map(async ({ current, folder }) => {
+ await useAppStore
+ .getState()
+ .patchSavedQuery({ ...current, folder }, ["folder"]);
useAppStore
.getState()
- .patchSavedQueryFolderInCache(request.names, folder);
+ .patchSavedQueryFolderInCache([current.name], folder);
})
);
for (const [view, folderKeys] of affectedFolderKeysByView) {
diff --git a/frontend/src/stores/app/iam.ts b/frontend/src/stores/app/iam.ts
index f1d1fa4650..6475deeb2a 100644
--- a/frontend/src/stores/app/iam.ts
+++ b/frontend/src/stores/app/iam.ts
@@ -20,7 +20,7 @@ import { ListRolesRequestSchema } from "@/types/proto-es/v1/role_service_pb";
import { ALL_USERS_USER_EMAIL, groupBindingPrefix } from "@/types/v1/user";
import { getUserListInBinding, isBindingPolicyExpired } from "@/utils/v1/iam";
import type { AppSliceCreator, IamSlice } from "./types";
-import { bindingMatchesUser } from "./utils";
+import { bindingMatchesUser, projectWideBindings } from "./utils";
// Merge a member's role set into a policy clone: drop the member from roles it
// no longer holds, add it to roles it gained, and append bindings for brand-new
@@ -391,4 +391,27 @@ export const createIamSlice: AppSliceCreator<IamSlice> = (set, get) => ({
roleByName.get(roleName)?.permissions.includes(permission)
);
},
+
+ // Mirrors the server's CheckProjectWidePermission: like
+ // hasProjectPermission, but a binding whose condition scopes resources
+ // confers nothing — a data-slice grant must not widen to project-wide
+ // surfaces such as the saved-query permissions. The workspace policy skips
+ // allUsers in SaaS mode and a condition the client cannot positively
+ // evaluate hides the grant, both exactly as the server evaluates.
+ hasProjectWidePermission: (project, permission) => {
+ const user = get().currentUser;
+ if (!user) return false;
+ const roleByName = new Map(get().roles.map((role) => [role.name, role]));
+ const bindings = [
+ ...projectWideBindings(get().workspacePolicy, user, {
+ skipAllUsers: get().isSaaSMode(),
+ }),
+ ...projectWideBindings(get().projectPoliciesByName[project.name], user, {
+ skipAllUsers: false,
+ }),
+ ];
+ return bindings.some((binding) =>
+ roleByName.get(binding.role)?.permissions.includes(permission)
+ );
+ },
});
diff --git a/frontend/src/stores/app/index.ts b/frontend/src/stores/app/index.ts
index d392d7fc48..e9e8fc3eb7 100644
--- a/frontend/src/stores/app/index.ts
+++ b/frontend/src/stores/app/index.ts
@@ -87,6 +87,8 @@ registerPermissionCheckers({
useAppStore.getState().hasWorkspacePermission(permission),
hasProjectPermission: (project, permission) =>
useAppStore.getState().hasProjectPermission(project, permission),
+ hasProjectWidePermission: (project, permission) =>
+ useAppStore.getState().hasProjectWidePermission(project, permission),
});
// Back the subscription / environment reads in shared `@/utils` helpers with
diff --git a/frontend/src/stores/app/savedQuery.ts b/frontend/src/stores/app/savedQuery.ts
index ed3da2736f..48c6ad518a 100644
--- a/frontend/src/stores/app/savedQuery.ts
+++ b/frontend/src/stores/app/savedQuery.ts
@@ -250,7 +250,6 @@ export const createSavedQuerySlice: AppSliceCreator<SavedQuerySlice> = (
const response = await savedQueryServiceClientConnect.moveMySavedQueries(
createProto(MoveMySavedQueriesRequestSchema, {
parent,
- names: params.names,
sourceFolder: params.sourceFolder,
targetFolder: params.targetFolder,
})
diff --git a/frontend/src/stores/app/types.ts b/frontend/src/stores/app/types.ts
index d761e9d448..2dcb7a7a4b 100644
--- a/frontend/src/stores/app/types.ts
+++ b/frontend/src/stores/app/types.ts
@@ -374,6 +374,10 @@ export type IamSlice = {
getWorkspaceRolesByName: (name: string) => Set<string>;
hasWorkspacePermission: (permission: Permission) => boolean;
hasProjectPermission: (project: Project, permission: Permission) => boolean;
+ hasProjectWidePermission: (
+ project: Project,
+ permission: Permission
+ ) => boolean;
};
export interface ProjectFilter {
@@ -652,16 +656,15 @@ export type SavedQuerySlice = {
deleteSavedQueryByName: (name: string) => Promise<void>;
updateSavedQueryStar: (name: string, starred: boolean) => Promise<void>;
/**
- * Move saved queries into a folder: either `names` (specific saved queries)
- * or `sourceFolder` (that folder and its descendants), never both. Only the
- * caller's own saved queries move, so the returned count can be smaller than
- * what was named.
+ * Move the caller's saved queries filed under `sourceFolder`, descendants
+ * included, into `targetFolder`. Only the caller's own saved queries move;
+ * the returned count reports how many did. Re-filing a single saved query
+ * is `patchSavedQuery` with the `folder` field.
*/
moveMySavedQueries: (
parent: string,
params: {
- names?: string[];
- sourceFolder?: string;
+ sourceFolder: string;
targetFolder: string;
}
) => Promise<number>;
diff --git a/frontend/src/stores/app/utils.test.ts b/frontend/src/stores/app/utils.test.ts
index 2dab85acb9..85747e590c 100644
--- a/frontend/src/stores/app/utils.test.ts
+++ b/frontend/src/stores/app/utils.test.ts
@@ -1,5 +1,11 @@
+import { create, type MessageInitShape } from "@bufbuild/protobuf";
import { describe, expect, test } from "vitest";
-import { buildDatabaseFilter } from "./utils";
+import {
+ BindingSchema,
+ IamPolicySchema,
+} from "@/types/proto-es/v1/iam_policy_pb";
+import { UserSchema } from "@/types/proto-es/v1/user_service_pb";
+import { buildDatabaseFilter, projectWideBindings } from "./utils";
describe("buildDatabaseFilter", () => {
test("escapes the database name query as a CEL string literal", () => {
@@ -8,3 +14,97 @@ describe("buildDatabaseFilter", () => {
);
});
});
+
+describe("projectWideBindings", () => {
+ const me = create(UserSchema, {
+ name: "users/[email protected]",
+ groups: ["groups/eng"],
+ });
+
+ const policyWith = (bindings: MessageInitShape<typeof BindingSchema>[]) =>
+ create(IamPolicySchema, {
+ bindings: bindings.map((binding) => create(BindingSchema, binding)),
+ });
+
+ const roles = (policy: ReturnType<typeof policyWith>, skipAllUsers = false) =>
+ projectWideBindings(policy, me, { skipAllUsers }).map((b) => b.role);
+
+ test("matches the user directly, via group, and via allUsers", () => {
+ const policy = policyWith([
+ { role: "roles/direct", members: ["user:[email protected]"] },
+ { role: "roles/viaGroup", members: ["group:eng"] },
+ { role: "roles/viaAllUsers", members: ["allUsers"] },
+ { role: "roles/somebodyElse", members: ["user:[email protected]"] },
+ ]);
+ expect(roles(policy)).toEqual([
+ "roles/direct",
+ "roles/viaGroup",
+ "roles/viaAllUsers",
+ ]);
+ });
+
+ test("skips allUsers when asked, as the server does for workspace policy in SaaS mode", () => {
+ const policy = policyWith([
+ { role: "roles/direct", members: ["user:[email protected]"] },
+ { role: "roles/viaAllUsers", members: ["allUsers"] },
+ ]);
+ expect(roles(policy, true)).toEqual(["roles/direct"]);
+ });
+
+ test("a resource-scoped condition confers nothing", () => {
+ const policy = policyWith([
+ {
+ role: "roles/scoped",
+ members: ["user:[email protected]"],
+ condition: {
+ expression: 'resource.database == "instances/i/databases/d"',
+ },
+ },
+ ]);
+ expect(roles(policy)).toEqual([]);
+ });
+
+ test("honors the canonical expiry form in both directions", () => {
+ const policy = policyWith([
+ {
+ role: "roles/live",
+ members: ["user:[email protected]"],
+ condition: {
+ expression: 'request.time < timestamp("2099-01-01T00:00:00Z")',
+ },
+ },
+ {
+ role: "roles/expired",
+ members: ["user:[email protected]"],
+ condition: {
+ expression: 'request.time < timestamp("2000-01-01T00:00:00Z")',
+ },
+ },
+ ]);
+ expect(roles(policy)).toEqual(["roles/live"]);
+ });
+
+ test("a time-only condition outside the canonical form hides the grant", () => {
+ // The server evaluates the full CEL expression and would grant both of
+ // these until 2099; the client cannot, so it hides the affordance
+ // rather than showing one whose expiry it would never notice.
+ const policy = policyWith([
+ {
+ role: "roles/reversed",
+ members: ["user:[email protected]"],
+ condition: {
+ expression: 'timestamp("2099-01-01T00:00:00Z") > request.time',
+ },
+ },
+ {
+ role: "roles/window",
+ members: ["user:[email protected]"],
+ condition: {
+ expression:
+ 'request.time > timestamp("2000-01-01T00:00:00Z") && request.time < timestamp("2099-01-01T00:00:00Z")',
+ },
+ },
+ ]);
+ expect(roles(policy)).toEqual([]);
+ });
+});
diff --git a/frontend/src/stores/app/utils.ts b/frontend/src/stores/app/utils.ts
index ef22ae0f65..5bf74c39d1 100644
--- a/frontend/src/stores/app/utils.ts
+++ b/frontend/src/stores/app/utils.ts
@@ -18,6 +18,7 @@ import {
import { isValidInstanceName } from "@/types/v1/instance";
import { workspaceCacheScope } from "@/utils/storage-keys";
import { escapeCELStringLiteral } from "@/utils/v1/cel";
+import { bindingScopesResources } from "@/utils/v1/iam";
import type { AppStoreState } from "./types";
export const MAX_RECENT_PROJECT = 5;
@@ -199,6 +200,65 @@ export function bindingMatchesUser(
});
}
+// The canonical expiry condition is the only non-empty form the client
+// evaluates, and the whole expression must be it — matching a substring would
+// let a lower-bounded window ("not before") read as already granting.
+const CANONICAL_EXPIRY_CONDITION =
+ /^\s*request\.time\s*<\s*timestamp\(\s*"([^"]+)"\s*\)\s*$/;
+
+// Whether the client can positively evaluate the binding's condition as
+// granting right now. The server evaluates the full CEL expression; the
+// client recognizes the empty condition and the canonical expiry form, and
+// treats everything else as not granting — the affordance hides rather than
+// dangling on an RPC the server will deny. An unparsable timestamp compares
+// as NaN, which also reads as not granting.
+function conditionGrantsNow(binding: Binding): boolean {
+ const expression = binding.condition?.expression ?? "";
+ if (expression.trim() === "") {
+ return true;
+ }
+ const match = expression.match(CANONICAL_EXPIRY_CONDITION);
+ if (!match) {
+ return false;
+ }
+ return new Date(match[1]) > new Date();
+}
+
+// Mirrors the server's project-wide binding filter (iam.Manager's check with
+// projectWideOnly): the member must match explicitly — allUsers is skipped
+// for the workspace policy in SaaS mode, where workspace members must be
+// explicit, while a project-level allUsers means "all workspace members" —
+// a condition that scopes resources confers nothing, and a condition the
+// client cannot positively evaluate hides the grant instead of showing an
+// affordance the server denies.
+export function projectWideBindings(
+ policy: AppStoreState["workspacePolicy"],
+ user: User,
+ { skipAllUsers }: { skipAllUsers: boolean }
+): Binding[] {
+ if (!policy || !user.name) {
+ return [];
+ }
+ const userGroups = new Set(user.groups);
+ return policy.bindings.filter((binding) => {
+ if (bindingScopesResources(binding)) {
+ return false;
+ }
+ if (!conditionGrantsNow(binding)) {
+ return false;
+ }
+ return binding.members.some((member) => {
+ const names = bindingMemberToNames(member);
+ return names.some(
+ (name) =>
+ name === user.name ||
+ (name === ALL_USERS_NAME && !skipAllUsers) ||
+ (name.startsWith("groups/") && userGroups.has(name))
+ );
+ });
+ });
+}
+
export function defaultProjectName(get: () => AppStoreState) {
return get().serverInfo?.defaultProject ?? "";
}
diff --git a/frontend/src/types/iam/permission-generated.ts b/frontend/src/types/iam/permission-generated.ts
index 123e758d93..b357acb916 100644
--- a/frontend/src/types/iam/permission-generated.ts
+++ b/frontend/src/types/iam/permission-generated.ts
@@ -103,9 +103,13 @@ export type Permission =
| "bb.rollouts.get"
| "bb.rollouts.list"
| "bb.savedQueries.create"
- | "bb.savedQueries.search"
+ | "bb.savedQueries.delete"
+ | "bb.savedQueries.get"
+ | "bb.savedQueries.getIamPolicy"
| "bb.savedQueries.list"
- | "bb.savedQueries.manage"
+ | "bb.savedQueries.search"
+ | "bb.savedQueries.setIamPolicy"
+ | "bb.savedQueries.update"
| "bb.serviceAccounts.create"
| "bb.serviceAccounts.delete"
| "bb.serviceAccounts.get"
diff --git a/frontend/src/types/proto-es/v1/saved_query_service_pb.d.ts b/frontend/src/types/proto-es/v1/saved_query_service_pb.d.ts
index 65f7acf630..89a783b841 100644
--- a/frontend/src/types/proto-es/v1/saved_query_service_pb.d.ts
+++ b/frontend/src/types/proto-es/v1/saved_query_service_pb.d.ts
@@ -89,10 +89,8 @@ export declare type ListSavedQueriesRequest = Message<"bytebase.v1.ListSavedQuer
pageSize: number;
/**
- * A page token from a previous ListSavedQueries call. Every other parameter
- * must match the call that returned it: the token carries the offset reached
- * so far, so changing `filter` or `page_size` mid-pagination reinterprets
- * that offset against a different result set.
+ * A page token from a previous ListSavedQueries call. Keep every other
+ * parameter the same as the call that returned it.
*
* @generated from field: string page_token = 4;
*/
@@ -190,6 +188,7 @@ export declare type UpdateSavedQueryRequest = Message<"bytebase.v1.UpdateSavedQu
/**
* Fields to update, relative to the saved query (`title`, not
* `saved_query.title`). Supported: `title`, `content`, `database`, `folder`.
+ * At least one path is required.
*
* @generated from field: google.protobuf.FieldMask update_mask = 2;
*/
@@ -239,25 +238,17 @@ export declare type MoveMySavedQueriesRequest = Message<"bytebase.v1.MoveMySaved
parent: string;
/**
- * The saved queries to move. Set this or `source_folder`, not both.
- * Format: projects/{project}/savedQueries/{savedQuery}
- *
- * @generated from field: repeated string names = 2;
- */
- names: string[];
-
- /**
- * Move everything filed under this path, descendants included, e.g. "a/b".
- * Set this or `names`, not both.
+ * The folder to move, descendants included, e.g. "a/b".
*
- * @generated from field: string source_folder = 3;
+ * @generated from field: string source_folder = 2;
*/
sourceFolder: string;
/**
- * Where they land. A path like "a/b/c"; empty unfiles them.
+ * Where it lands. A path like "a/b/c"; empty drops the `source_folder`
+ * prefix, promoting the folder's contents toward the root.
*
- * @generated from field: string target_folder = 4;
+ * @generated from field: string target_folder = 3;
*/
targetFolder: string;
};
@@ -273,7 +264,7 @@ export declare const MoveMySavedQueriesRequestSchema: GenMessage<MoveMySavedQuer
*/
export declare type MoveMySavedQueriesResponse = Message<"bytebase.v1.MoveMySavedQueriesResponse"> & {
/**
- * How many moved. Fewer than were named when some are not the caller's.
+ * How many moved.
*
* @generated from field: int32 moved_count = 1;
*/
@@ -316,8 +307,8 @@ export declare type SetSavedQueryPolicyRequest = Message<"bytebase.v1.SetSavedQu
resource: string;
/**
- * Replaces the stored policy in full: a member absent from it loses their
- * grant, and a policy with no bindings makes the saved query private again.
+ * The new policy, replacing the stored one in full. Empty `bindings` makes
+ * the saved query private again.
*
* @generated from field: bytebase.v1.SavedQueryPolicy policy = 2;
*/
@@ -331,9 +322,8 @@ export declare type SetSavedQueryPolicyRequest = Message<"bytebase.v1.SetSavedQu
export declare const SetSavedQueryPolicyRequestSchema: GenMessage<SetSavedQueryPolicyRequest>;
/**
- * Who a saved query is shared with, and at what level. A saved query with no
- * bindings is private. The creator is never a binding member: ownership comes
- * from creating the saved query and cannot be granted away.
+ * Who a saved query is shared with, and at what level. No bindings means
+ * private. The creator is never a binding member; ownership cannot be granted.
*
* @generated from message bytebase.v1.SavedQueryPolicy
*/
@@ -362,8 +352,7 @@ export declare type SavedQueryPolicy = Message<"bytebase.v1.SavedQueryPolicy"> &
export declare const SavedQueryPolicySchema: GenMessage<SavedQueryPolicy>;
/**
- * Binds members to one access level on one saved query. Not bytebase.v1.Binding
- * because per-object access here is a capability, not a role.
+ * Binds members to one access level on one saved query.
*
* @generated from message bytebase.v1.SavedQueryBinding
*/
@@ -374,18 +363,11 @@ export declare type SavedQueryBinding = Message<"bytebase.v1.SavedQueryBinding">
level: SavedQueryBinding_Level;
/**
- * The principals granted `level`, in bytebase.v1.Binding.members format,
- * restricted to "user:{email}" and "group:{email}" -- prefix-checked, as
- * project and workspace IAM check their own members.
- *
- * Service accounts and workload identities are not grantees: they own and
- * run their own saved queries and reach them as the creator. Naming one
- * under a "user:" prefix grants nothing rather than being rejected, because
- * a caller's member is derived from their principal type, so such a binding
- * matches nobody.
+ * The members granted `level`: "user:{email}" or "group:{email}" only.
*
- * A group is stored as a reference and never expanded, so its membership
- * stays live and a large group costs no more than a small one.
+ * Service accounts cannot be grantees — they reach their own saved queries
+ * as the creator. Naming one under "user:" grants nothing rather than
+ * failing. Groups are stored as references, so membership stays live.
*
* @generated from field: repeated string members = 2;
*/
@@ -399,8 +381,8 @@ export declare type SavedQueryBinding = Message<"bytebase.v1.SavedQueryBinding">
export declare const SavedQueryBindingSchema: GenMessage<SavedQueryBinding>;
/**
- * Nested because bytebase.v1 already defines a package-scoped EDITOR
- * (DatabaseChangeMode), and enum values live in the enclosing scope.
+ * Nested to avoid colliding with the package-scoped EDITOR in
+ * DatabaseChangeMode.
*
* @generated from enum bytebase.v1.SavedQueryBinding.Level
*/
@@ -411,15 +393,16 @@ export enum SavedQueryBinding_Level {
LEVEL_UNSPECIFIED = 0,
/**
- * Open and read the saved query.
+ * Holds bb.savedQueries.get and bb.savedQueries.getIamPolicy on the
+ * saved query: open and read it, and see who it is shared with.
*
* @generated from enum value: VIEWER = 1;
*/
VIEWER = 1,
/**
- * VIEWER, plus write the title, content, and connected database. Sharing
- * and deletion stay with the creator and admins.
+ * VIEWER, plus bb.savedQueries.update: write the title, content,
+ * database, and folder. Not deletion, not setIamPolicy.
*
* @generated from enum value: EDITOR = 2;
*/
@@ -467,16 +450,16 @@ export declare type SearchSavedQueriesRequest = Message<"bytebase.v1.SearchSaved
* - name: the saved query name. Supports "==" and "in [...]".
* - title: the title. Supports "contains".
* - creator: the creator in "users/{email}" format. Supports "==" and "!=".
- * - shared: true selects only saved queries the caller reaches through a
- * binding, excluding their own and any seen through
- * bb.savedQueries.manage; false selects the rest. Supports "==".
+ * - shared: whether a binding shares the saved query with the caller. Their
+ * own saved queries, and ones visible only through a project-level
+ * bb.savedQueries.get, are not "shared". Supports "==".
* - starred: whether the caller starred it. Supports "==".
* - folder: the exact folder path. Supports "==".
*
- * The SQL Editor's views are `creator == "users/{me}"` for My and
- * `shared == true` for Shared. Prefer `shared` over `creator !=` for the
- * latter: for an admin, `creator !=` also matches saved queries nobody
- * shared with them.
+ * Use `creator == "users/{me}"` for a My view and `shared == true` for a
+ * Shared view. Prefer `shared` over `creator !=`: with a project-level
+ * bb.savedQueries.get, `creator !=` also matches saved queries nobody
+ * shared with the caller.
*
* For example:
* creator == "users/[email protected]"
@@ -498,11 +481,8 @@ export declare type SearchSavedQueriesRequest = Message<"bytebase.v1.SearchSaved
pageSize: number;
/**
- * A page token from a previous SearchSavedQueries call. Every other
- * parameter must match the call that returned it: the token carries the
- * offset reached so far, so changing `filter` or `page_size` mid-pagination
- * reinterprets that offset against a different result set and can skip or
- * repeat rows.
+ * A page token from a previous SearchSavedQueries call. Keep every other
+ * parameter the same as the call that returned it.
*
* @generated from field: string page_token = 4;
*/
@@ -576,7 +556,7 @@ export declare type SavedQuery = Message<"bytebase.v1.SavedQuery"> & {
title: string;
/**
- * The fixed owner. Ownership does not transfer.
+ * The owner. Ownership does not transfer.
* Format: users/{email}
*
* @generated from field: string creator = 5;
@@ -594,8 +574,8 @@ export declare type SavedQuery = Message<"bytebase.v1.SavedQuery"> & {
updateTime?: Timestamp | undefined;
/**
- * The SQL text. SearchSavedQueries truncates it; when it is shorter than
- * `content_size`, GetSavedQuery returns the whole thing.
+ * The SQL text. SearchSavedQueries returns a truncated preview;
+ * GetSavedQuery returns the full text.
*
* @generated from field: bytes content = 8;
*/
@@ -616,8 +596,8 @@ export declare type SavedQuery = Message<"bytebase.v1.SavedQuery"> & {
starred: boolean;
/**
- * The folder holding this saved query, set by its creator or an admin. A
- * path like "a/b/c"; empty means unfiled.
+ * The folder holding this saved query. A path like "a/b/c"; empty means
+ * unfiled.
*
* @generated from field: string folder = 13;
*/
@@ -631,24 +611,26 @@ export declare type SavedQuery = Message<"bytebase.v1.SavedQuery"> & {
export declare const SavedQuerySchema: GenMessage<SavedQuery>;
/**
- * SavedQueryService manages saved queries for SQL Editor query development.
+ * SavedQueryService manages saved queries in the SQL Editor.
*
- * A saved query is private to its creator until shared. Three things grant
- * access to one: being its creator (the fixed owner), holding a VIEWER or
- * EDITOR binding on it, and holding bb.savedQueries.manage, the admin backstop
- * that reaches private saved queries too. Bindings are managed through the
- * GetSavedQueryPolicy/SetSavedQueryPolicy pair.
- *
- * Two gates sit on top of that: bb.savedQueries.search gates discovery, and
- * running a saved query needs the SQL Editor's own database permissions.
+ * A saved query is private to its creator until shared. Permissions come from
+ * three places:
+ * - The creator owns the saved query and holds every permission on it.
+ * - A VIEWER binding grants bb.savedQueries.get and getIamPolicy; an EDITOR
+ * binding adds update.
+ * - Permissions granted on the project or workspace apply to every saved
+ * query in the project, private ones included.
+ * A caller without a method's permission gets NotFound, not
+ * PermissionDenied, so private names stay unprobeable. Running a saved query
+ * is governed by the SQL Editor's database permissions, not by this service.
*
* @generated from service bytebase.v1.SavedQueryService
*/
export declare const SavedQueryService: GenService<{
/**
- * Create a saved query. The creator becomes its fixed owner, and the saved
- * query starts private.
- * Permissions required: bb.savedQueries.create on the parent project
+ * Create a saved query. The creator becomes the owner and the saved query
+ * starts private.
+ * Permissions required: bb.savedQueries.create on the project
*
* @generated from rpc bytebase.v1.SavedQueryService.CreateSavedQuery
*/
@@ -658,9 +640,9 @@ export declare const SavedQueryService: GenService<{
output: typeof SavedQuerySchema;
},
/**
- * Get a saved query with its full content. An unreadable saved query returns
- * NotFound rather than PermissionDenied, so it stays unprobeable by name.
- * Permissions required: creator, a VIEWER or EDITOR binding, or bb.savedQueries.manage
+ * Get a saved query with its full content.
+ * Permissions required: bb.savedQueries.get (creator, VIEWER/EDITOR
+ * binding, or project-level grant)
*
* @generated from rpc bytebase.v1.SavedQueryService.GetSavedQuery
*/
@@ -670,12 +652,11 @@ export declare const SavedQueryService: GenService<{
output: typeof SavedQuerySchema;
},
/**
- * List saved queries for auditing. Bindings are ignored: the permission
- * alone reads every matched saved query's content, private ones included.
- * Returns whole statements rather than Search's previews, and accepts
- * "projects/-" to span every project.
- * Permissions required: bb.savedQueries.list on the parent project, or
- * workspace-wide when the parent is "projects/-"
+ * List saved queries for auditing. The permission alone grants reading
+ * every matched saved query with full content, private ones included;
+ * bindings are ignored. Use parent "projects/-" for all projects.
+ * Permissions required: bb.savedQueries.list on the project, or on the
+ * workspace when the parent is "projects/-"
*
* @generated from rpc bytebase.v1.SavedQueryService.ListSavedQueries
*/
@@ -685,14 +666,8 @@ export declare const SavedQueryService: GenService<{
output: typeof ListSavedQueriesResponseSchema;
},
/**
- * Search saved queries in one project: the SQL Editor's list path, returning
- * content previews.
- *
- * Caller-scoped, always: the caller's own saved queries plus those a binding
- * shares with them. bb.savedQueries.manage does not widen it — an admin
- * reading everyone's saved queries uses ListSavedQueries, which is built for
- * that. The permission here gates discovery only and grants access to
- * nothing by itself.
+ * Search saved queries in one project. Returns content previews of the
+ * saved queries the caller can read, the same access rule as GetSavedQuery.
* Permissions required: bb.savedQueries.search on the project
*
* @generated from rpc bytebase.v1.SavedQueryService.SearchSavedQueries
@@ -703,16 +678,8 @@ export declare const SavedQueryService: GenService<{
output: typeof SearchSavedQueriesResponseSchema;
},
/**
- * Search the folder paths holding saved queries the caller can read. Folders
- * are a derived view over the `folder` field rather than a resource
- * collection, so this is a custom method, caller-scoped like
- * SearchSavedQueries.
- *
- * A path is returned when at least one readable saved query sits in it —
- * including one somebody else filed and shared, since a client seeds its
- * folder tree from here and cannot expand into a folder it never learns
- * about. Use the filter to split your own folders (`creator == "users/me"`)
- * from the ones reaching you through a grant (`shared == true`).
+ * Search folder paths. A path is returned when it holds at least one saved
+ * query the caller can read, the same access rule as SearchSavedQueries.
* Permissions required: bb.savedQueries.search on the project
*
* @generated from rpc bytebase.v1.SavedQueryService.SearchSavedQueryFolders
@@ -723,12 +690,9 @@ export declare const SavedQueryService: GenService<{
output: typeof SearchSavedQueryFoldersResponseSchema;
},
/**
- * Update a saved query. `title`, `content`, and `database` need write access;
- * `folder` is creator/admin only, because filing is organization rather than
- * editing. `database` must belong to the saved query's own project. An
- * unreadable saved query returns NotFound; a VIEWER who cannot write gets
- * PermissionDenied.
- * Permissions required: creator, an EDITOR binding, or bb.savedQueries.manage
+ * Update a saved query. `database` must belong to the saved query's project.
+ * Permissions required: bb.savedQueries.update (creator, EDITOR binding, or
+ * project-level grant)
*
* @generated from rpc bytebase.v1.SavedQueryService.UpdateSavedQuery
*/
@@ -738,11 +702,12 @@ export declare const SavedQueryService: GenService<{
output: typeof SavedQuerySchema;
},
/**
- * Star or unstar a saved query for the caller. Stars are personal: yours are
- * invisible to everyone else and grant nothing. You can star any saved query
- * you created or have been granted access to; anything else answers
- * NotFound, so names stay unprobeable.
- * Permissions required: creator, or a VIEWER or EDITOR binding
+ * Star or unstar a saved query for the caller. Stars are personal: nobody
+ * else sees them and they grant nothing. The caller can star any saved
+ * query they can read. When access is lost the star is hidden, not
+ * deleted; it comes back if access returns.
+ * Permissions required: bb.savedQueries.get (creator, VIEWER/EDITOR
+ * binding, or project-level grant)
*
* @generated from rpc bytebase.v1.SavedQueryService.UpdateSavedQueryStar
*/
@@ -752,13 +717,11 @@ export declare const SavedQueryService: GenService<{
output: typeof SavedQuerySchema;
},
/**
- * Move the caller's own saved queries into a folder, named individually or a
- * whole folder at a time. Moving a folder carries its descendants, so renaming "a/b" to
- * "a/c" also moves "a/b/deep" -- one call, not one per path.
- *
- * Filing is personal organization, so only the creator's own move: a folder
- * is that person's tree, and neither a binding nor the admin backstop
- * reaches into it. The response counts what moved.
+ * Move the caller's saved queries filed under `source_folder`, descendants
+ * included, into `target_folder`: renaming "a/b" to "a/c" also moves
+ * "a/b/deep". Only the caller's own saved queries move; the response counts
+ * how many did. Re-filing a single saved query is UpdateSavedQuery's
+ * `folder` field.
* Permissions required: creator
*
* @generated from rpc bytebase.v1.SavedQueryService.MoveMySavedQueries
@@ -769,10 +732,10 @@ export declare const SavedQueryService: GenService<{
output: typeof MoveMySavedQueriesResponseSchema;
},
/**
- * Delete a saved query and every user's stars on it. An EDITOR binding never
- * carries deletion. An unreadable saved query returns NotFound; a grantee
- * who can read but not delete gets PermissionDenied.
- * Permissions required: creator, or bb.savedQueries.manage
+ * Delete a saved query and every user's stars on it. An EDITOR binding
+ * cannot delete.
+ * Permissions required: bb.savedQueries.delete (creator or project-level
+ * grant)
*
* @generated from rpc bytebase.v1.SavedQueryService.DeleteSavedQuery
*/
@@ -783,11 +746,8 @@ export declare const SavedQueryService: GenService<{
},
/**
* Get a saved query's sharing policy: who it is shared with, at what level.
- *
- * Anyone who can read the saved query can read its policy, which is how a
- * grantee learns whether they may edit it. Callers who cannot read the
- * saved query get NotFound.
- * Permissions required: creator, a VIEWER or EDITOR binding, or bb.savedQueries.manage
+ * Permissions required: bb.savedQueries.getIamPolicy (creator, VIEWER/EDITOR
+ * binding, or project-level grant)
*
* @generated from rpc bytebase.v1.SavedQueryService.GetSavedQueryPolicy
*/
@@ -798,9 +758,9 @@ export declare const SavedQueryService: GenService<{
},
/**
* Replace a saved query's sharing policy in full. `policy.etag` must match
- * the stored policy or the call fails with ABORTED, so a stale write cannot
- * reinstate a grant somebody just revoked.
- * Permissions required: creator, or bb.savedQueries.manage
+ * the stored policy; a mismatch fails with ABORTED.
+ * Permissions required: bb.savedQueries.setIamPolicy (creator or
+ * project-level grant; no predefined role carries it)
*
* @generated from rpc bytebase.v1.SavedQueryService.SetSavedQueryPolicy
*/
diff --git a/frontend/src/types/proto-es/v1/saved_query_service_pb.js b/frontend/src/types/proto-es/v1/saved_query_service_pb.js
index 5e16634297..c27e158938 100644
--- a/frontend/src/types/proto-es/v1/saved_query_service_pb.js
+++ b/frontend/src/types/proto-es/v1/saved_query_service_pb.js
@@ -15,7 +15,7 @@ import { file_v1_annotation } from "./annotation_pb";
* Describes the file v1/saved_query_service.proto.
*/
export const file_v1_saved_query_service = /*@__PURE__*/
- fileDesc("Chx2MS9zYXZlZF9xdWVyeV9zZXJ2aWNlLnByb3RvEgtieXRlYmFzZS52MSJ6ChdDcmVhdGVTYXZlZFF1ZXJ5UmVxdWVzdBIsCgZwYXJlbnQYASABKAlCHOBBAvpBFgoUYnl0ZWJhc2UuY29tL1Byb2plY3QSMQoLc2F2ZWRfcXVlcnkYAiABKAsyFy5ieXRlYmFzZS52MS5TYXZlZFF1ZXJ5QgPgQQIiKQoUR2V0U2F2ZWRRdWVyeVJlcXVlc3QSEQoEbmFtZRgBIAEoCUID4EECIn4KF0xpc3RTYXZlZFF1ZXJpZXNSZXF1ZXN0EiwKBnBhcmVudBgBIAEoCUIc4EEC+kEWChRieXRlYmFzZS5jb20vUHJvamVjdBIOCgZmaWx0ZXIYAiABKAkSEQoJcGFnZV9zaXplGAMgASgFEhIKCnBhZ2VfdG9rZW4YBCABKAkiYwoYTGlzdFNhdmVkUXVlcmllc1Jlc3BvbnNlEi4KDXNhdmVkX3F1ZXJpZXMYASADKAsyFy5ieXRlYmFzZS52MS5TYXZlZFF1ZXJ5EhcKD25leHRfcGFnZV90b2tlbhgCIAEoCSJeCh5TZWFyY2hTYXZlZFF1ZXJ5Rm9sZGVyc1JlcXVlc3QSLAoGcGFyZW50GAEgASgJQhzgQQL6QRYKFGJ5dGViYXNlLmNvbS9Qcm9qZWN0Eg4KBmZpbHRlchgCIAEoCSIyCh9TZWFyY2hTYXZlZFF1ZXJ5Rm9sZGVyc1Jlc3BvbnNlEg8KB2ZvbGRlcnMYASADKAkifQoXVXBkYXRlU2F2ZWRRdWVyeVJlcXVlc3QSMQoLc2F2ZWRfcXVlcnkYASABKAsyFy5ieXRlYmFzZS52MS5TYXZlZFF1ZXJ5QgPgQQISLwoLdXBkYXRlX21hc2sYAiABKAsyGi5nb29nbGUucHJvdG9idWYuRmllbGRNYXNrIkEKG1VwZGF0ZVNhdmVkUXVlcnlTdGFyUmVxdWVzdBIRCgRuYW1lGAEgASgJQgPgQQISDwoHc3RhcnJlZBgCIAEoCCKaAQoZTW92ZU15U2F2ZWRRdWVyaWVzUmVxdWVzdBIsCgZwYXJlbnQYASABKAlCHOBBAvpBFgoUYnl0ZWJhc2UuY29tL1Byb2plY3QSDQoFbmFtZXMYAiADKAkSHwoNc291cmNlX2ZvbGRlchgDIAEoCUIIukgFcgMYgAISHwoNdGFyZ2V0X2ZvbGRlchgEIAEoCUIIukgFcgMYgAIiMQoaTW92ZU15U2F2ZWRRdWVyaWVzUmVzcG9uc2USEwoLbW92ZWRfY291bnQYASABKAUiTwoaR2V0U2F2ZWRRdWVyeVBvbGljeVJlcXVlc3QSMQoIcmVzb3VyY2UYASABKAlCH+BBAvpBGQoXYnl0ZWJhc2UuY29tL1NhdmVkUXVlcnkigwEKGlNldFNhdmVkUXVlcnlQb2xpY3lSZXF1ZXN0EjEKCHJlc291cmNlGAEgASgJQh/gQQL6QRkKF2J5dGViYXNlLmNvbS9TYXZlZFF1ZXJ5EjIKBnBvbGljeRgCIAEoCzIdLmJ5dGViYXNlLnYxLlNhdmVkUXVlcnlQb2xpY3lCA+BBAiJSChBTYXZlZFF1ZXJ5UG9saWN5EjAKCGJpbmRpbmdzGAEgAygLMh4uYnl0ZWJhc2UudjEuU2F2ZWRRdWVyeUJpbmRpbmcSDAoEZXRhZxgCIAEoCSKjAQoRU2F2ZWRRdWVyeUJpbmRpbmcSOAoFbGV2ZWwYASABKA4yJC5ieXRlYmFzZS52MS5TYXZlZFF1ZXJ5QmluZGluZy5MZXZlbEID4EECEhwKB21lbWJlcnMYAiADKAlCC+BBArpIBZIBAggBIjYKBUxldmVsEhUKEUxFVkVMX1VOU1BFQ0lGSUVEEAASCgoGVklFV0VSEAESCgoGRURJVE9SEAIiSAoXRGVsZXRlU2F2ZWRRdWVyeVJlcXVlc3QSLQoEbmFtZRgBIAEoCUIf4EEC+kEZChdieXRlYmFzZS5jb20vU2F2ZWRRdWVyeSKAAQoZU2VhcmNoU2F2ZWRRdWVyaWVzUmVxdWVzdBIsCgZwYXJlbnQYASABKAlCHOBBAvpBFgoUYnl0ZWJhc2UuY29tL1Byb2plY3QSDgoGZmlsdGVyGAIgASgJEhEKCXBhZ2Vfc2l6ZRgDIAEoBRISCgpwYWdlX3Rva2VuGAQgASgJImUKGlNlYXJjaFNhdmVkUXVlcmllc1Jlc3BvbnNlEi4KDXNhdmVkX3F1ZXJpZXMYASADKAsyFy5ieXRlYmFzZS52MS5TYXZlZFF1ZXJ5EhcKD25leHRfcGFnZV90b2tlbhgCIAEoCSKiAwoKU2F2ZWRRdWVyeRIUCgRuYW1lGAEgASgJQgbgQQLgQQUSFAoHcHJvamVjdBgCIAEoCUID4EEDEhAKCGRhdGFiYXNlGAMgASgJEhoKBXRpdGxlGAQgASgJQgvgQQK6SAVyAxjIARIUCgdjcmVhdG9yGAUgASgJQgPgQQMSNAoLY3JlYXRlX3RpbWUYBiABKAsyGi5nb29nbGUucHJvdG9idWYuVGltZXN0YW1wQgPgQQMSNAoLdXBkYXRlX3RpbWUYByABKAsyGi5nb29nbGUucHJvdG9idWYuVGltZXN0YW1wQgPgQQMSFAoHY29udGVudBgIIAEoDEID4EECEhkKDGNvbnRlbnRfc2l6ZRgJIAEoA0ID4EEDEhQKB3N0YXJyZWQYCyABKAhCA+BBAxIYCgZmb2xkZXIYDSABKAlCCLpIBXIDGIACOkvqQUgKF2J5dGViYXNlLmNvbS9TYXZlZFF1ZXJ5Ei1wcm9qZWN0cy97cHJvamVjdH0vc2F2ZWRRdWVyaWVzL3tzYXZlZF9xdWVyeX1KBAgKEAtKBAgMEA0yoA8KEVNhdmVkUXVlcnlTZXJ2aWNlEsMBChBDcmVhdGVTYXZlZFF1ZXJ5EiQuYnl0ZWJhc2UudjEuQ3JlYXRlU2F2ZWRRdWVyeVJlcXVlc3QaFy5ieXRlYmFzZS52MS5TYXZlZFF1ZXJ5InDaQRJwYXJlbnQsc2F2ZWRfcXVlcnmK6jAWYmIuc2F2ZWRRdWVyaWVzLmNyZWF0ZZDqMAGY6jABgtPkkwIzOgtzYXZlZF9xdWVyeSIkL3YxL3twYXJlbnQ9cHJvamVjdHMvKn0vc2F2ZWRRdWVyaWVzEoQBCg1HZXRTYXZlZFF1ZXJ5EiEuYnl0ZWJhc2UudjEuR2V0U2F2ZWRRdWVyeVJlcXVlc3QaFy5ieXRlYmFzZS52MS5TYXZlZFF1ZXJ5IjfaQQRuYW1lkOowAoLT5JMCJhIkL3YxL3tuYW1lPXByb2plY3RzLyovc2F2ZWRRdWVyaWVzLyp9ErIBChBMaXN0U2F2ZWRRdWVyaWVzEiQuYnl0ZWJhc2UudjEuTGlzdFNhdmVkUXVlcmllc1JlcXVlc3QaJS5ieXRlYmFzZS52MS5MaXN0U2F2ZWRRdWVyaWVzUmVzcG9uc2UiUdpBBnBhcmVudIrqMBRiYi5zYXZlZFF1ZXJpZXMubGlzdJDqMAGC0+STAiYSJC92MS97cGFyZW50PXByb2plY3RzLyp9L3NhdmVkUXVlcmllcxKqAQoSU2VhcmNoU2F2ZWRRdWVyaWVzEiYuYnl0ZWJhc2UudjEuU2VhcmNoU2F2ZWRRdWVyaWVzUmVxdWVzdBonLmJ5dGViYXNlLnYxLlNlYXJjaFNhdmVkUXVlcmllc1Jlc3BvbnNlIkPaQQZwYXJlbnSQ6jACgtPkkwIwOgEqIisvdjEve3BhcmVudD1wcm9qZWN0cy8qfS9zYXZlZFF1ZXJpZXM6c2VhcmNoEsABChdTZWFyY2hTYXZlZFF1ZXJ5Rm9sZGVycxIrLmJ5dGViYXNlLnYxLlNlYXJjaFNhdmVkUXVlcnlGb2xkZXJzUmVxdWVzdBosLmJ5dGViYXNlLnYxLlNlYXJjaFNhdmVkUXVlcnlGb2xkZXJzUmVzcG9uc2UiStpBBnBhcmVudJDqMAKC0+STAjc6ASoiMi92MS97cGFyZW50PXByb2plY3RzLyp9L3NhdmVkUXVlcmllczpzZWFyY2hGb2xkZXJzEroBChBVcGRhdGVTYXZlZFF1ZXJ5EiQuYnl0ZWJhc2UudjEuVXBkYXRlU2F2ZWRRdWVyeVJlcXVlc3QaFy5ieXRlYmFzZS52MS5TYXZlZFF1ZXJ5ImfaQRdzYXZlZF9xdWVyeSx1cGRhdGVfbWFza5DqMAKY6jABgtPkkwI/OgtzYXZlZF9xdWVyeTIwL3YxL3tzYXZlZF9xdWVyeS5uYW1lPXByb2plY3RzLyovc2F2ZWRRdWVyaWVzLyp9EqgBChRVcGRhdGVTYXZlZFF1ZXJ5U3RhchIoLmJ5dGViYXNlLnYxLlVwZGF0ZVNhdmVkUXVlcnlTdGFyUmVxdWVzdBoXLmJ5dGViYXNlLnYxLlNhdmVkUXVlcnkiTdpBDG5hbWUsc3RhcnJlZJDqMAKC0+STAjQ6ASoiLy92MS97bmFtZT1wcm9qZWN0cy8qL3NhdmVkUXVlcmllcy8qfTp1cGRhdGVTdGFyErwBChJNb3ZlTXlTYXZlZFF1ZXJpZXMSJi5ieXRlYmFzZS52MS5Nb3ZlTXlTYXZlZFF1ZXJpZXNSZXF1ZXN0GicuYnl0ZWJhc2UudjEuTW92ZU15U2F2ZWRRdWVyaWVzUmVzcG9uc2UiVdpBFHBhcmVudCx0YXJnZXRfZm9sZGVykOowApjqMAGC0+STAjA6ASoiKy92MS97cGFyZW50PXByb2plY3RzLyp9L3NhdmVkUXVlcmllczptb3ZlTXkSjQEKEERlbGV0ZVNhdmVkUXVlcnkSJC5ieXRlYmFzZS52MS5EZWxldGVTYXZlZFF1ZXJ5UmVxdWVzdBoWLmdvb2dsZS5wcm90b2J1Zi5FbXB0eSI72kEEbmFtZZDqMAKY6jABgtPkkwImKiQvdjEve25hbWU9cHJvamVjdHMvKi9zYXZlZFF1ZXJpZXMvKn0SqAEKE0dldFNhdmVkUXVlcnlQb2xpY3kSJy5ieXRlYmFzZS52MS5HZXRTYXZlZFF1ZXJ5UG9saWN5UmVxdWVzdBodLmJ5dGViYXNlLnYxLlNhdmVkUXVlcnlQb2xpY3kiSdpBCHJlc291cmNlkOowAoLT5JMCNBIyL3YxL3tyZXNvdXJjZT1wcm9qZWN0cy8qL3NhdmVkUXVlcmllcy8qfTpnZXRQb2xpY3kStgEKE1NldFNhdmVkUXVlcnlQb2xpY3kSJy5ieXRlYmFzZS52MS5TZXRTYXZlZFF1ZXJ5UG9saWN5UmVxdWVzdBodLmJ5dGViYXNlLnYxLlNhdmVkUXVlcnlQb2xpY3kiV9pBD3Jlc291cmNlLHBvbGljeZDqMAKY6jABgtPkkwI3OgEqIjIvdjEve3Jlc291cmNlPXByb2plY3RzLyovc2F2ZWRRdWVyaWVzLyp9OnNldFBvbGljeUKsAQoPY29tLmJ5dGViYXNlLnYxQhZTYXZlZFF1ZXJ5U2VydmljZVByb3RvUAFaNGdpdGh1Yi5jb20vYnl0ZWJhc2UvYnl0ZWJhc2UvYmFja2VuZC9nZW5lcmF0ZWQtZ28vdjGiAgNCWFiqAgtCeXRlYmFzZS5WMcoCC0J5dGViYXNlXFYx4gIXQnl0ZWJhc2VcVjFcR1BCTWV0YWRhdGHqAgxCeXRlYmFzZTo6VjFiBnByb3RvMw", [file_buf_validate_validate, file_google_api_annotations, file_google_api_client, file_google_api_field_behavior, file_google_api_resource, file_google_protobuf_empty, file_google_protobuf_field_mask, file_google_protobuf_timestamp, file_v1_annotation]);
+ fileDesc("Chx2MS9zYXZlZF9xdWVyeV9zZXJ2aWNlLnByb3RvEgtieXRlYmFzZS52MSJ6ChdDcmVhdGVTYXZlZFF1ZXJ5UmVxdWVzdBIsCgZwYXJlbnQYASABKAlCHOBBAvpBFgoUYnl0ZWJhc2UuY29tL1Byb2plY3QSMQoLc2F2ZWRfcXVlcnkYAiABKAsyFy5ieXRlYmFzZS52MS5TYXZlZFF1ZXJ5QgPgQQIiRQoUR2V0U2F2ZWRRdWVyeVJlcXVlc3QSLQoEbmFtZRgBIAEoCUIf4EEC+kEZChdieXRlYmFzZS5jb20vU2F2ZWRRdWVyeSJ+ChdMaXN0U2F2ZWRRdWVyaWVzUmVxdWVzdBIsCgZwYXJlbnQYASABKAlCHOBBAvpBFgoUYnl0ZWJhc2UuY29tL1Byb2plY3QSDgoGZmlsdGVyGAIgASgJEhEKCXBhZ2Vfc2l6ZRgDIAEoBRISCgpwYWdlX3Rva2VuGAQgASgJImMKGExpc3RTYXZlZFF1ZXJpZXNSZXNwb25zZRIuCg1zYXZlZF9xdWVyaWVzGAEgAygLMhcuYnl0ZWJhc2UudjEuU2F2ZWRRdWVyeRIXCg9uZXh0X3BhZ2VfdG9rZW4YAiABKAkiXgoeU2VhcmNoU2F2ZWRRdWVyeUZvbGRlcnNSZXF1ZXN0EiwKBnBhcmVudBgBIAEoCUIc4EEC+kEWChRieXRlYmFzZS5jb20vUHJvamVjdBIOCgZmaWx0ZXIYAiABKAkiMgofU2VhcmNoU2F2ZWRRdWVyeUZvbGRlcnNSZXNwb25zZRIPCgdmb2xkZXJzGAEgAygJIn0KF1VwZGF0ZVNhdmVkUXVlcnlSZXF1ZXN0EjEKC3NhdmVkX3F1ZXJ5GAEgASgLMhcuYnl0ZWJhc2UudjEuU2F2ZWRRdWVyeUID4EECEi8KC3VwZGF0ZV9tYXNrGAIgASgLMhouZ29vZ2xlLnByb3RvYnVmLkZpZWxkTWFzayJdChtVcGRhdGVTYXZlZFF1ZXJ5U3RhclJlcXVlc3QSLQoEbmFtZRgBIAEoCUIf4EEC+kEZChdieXRlYmFzZS5jb20vU2F2ZWRRdWVyeRIPCgdzdGFycmVkGAIgASgIIpABChlNb3ZlTXlTYXZlZFF1ZXJpZXNSZXF1ZXN0EiwKBnBhcmVudBgBIAEoCUIc4EEC+kEWChRieXRlYmFzZS5jb20vUHJvamVjdBIkCg1zb3VyY2VfZm9sZGVyGAIgASgJQg3gQQK6SAdyBRABGIACEh8KDXRhcmdldF9mb2xkZXIYAyABKAlCCLpIBXIDGIACIjEKGk1vdmVNeVNhdmVkUXVlcmllc1Jlc3BvbnNlEhMKC21vdmVkX2NvdW50GAEgASgFIk8KGkdldFNhdmVkUXVlcnlQb2xpY3lSZXF1ZXN0EjEKCHJlc291cmNlGAEgASgJQh/gQQL6QRkKF2J5dGViYXNlLmNvbS9TYXZlZFF1ZXJ5IoMBChpTZXRTYXZlZFF1ZXJ5UG9saWN5UmVxdWVzdBIxCghyZXNvdXJjZRgBIAEoCUIf4EEC+kEZChdieXRlYmFzZS5jb20vU2F2ZWRRdWVyeRIyCgZwb2xpY3kYAiABKAsyHS5ieXRlYmFzZS52MS5TYXZlZFF1ZXJ5UG9saWN5QgPgQQIiUgoQU2F2ZWRRdWVyeVBvbGljeRIwCghiaW5kaW5ncxgBIAMoCzIeLmJ5dGViYXNlLnYxLlNhdmVkUXVlcnlCaW5kaW5nEgwKBGV0YWcYAiABKAkiowEKEVNhdmVkUXVlcnlCaW5kaW5nEjgKBWxldmVsGAEgASgOMiQuYnl0ZWJhc2UudjEuU2F2ZWRRdWVyeUJpbmRpbmcuTGV2ZWxCA+BBAhIcCgdtZW1iZXJzGAIgAygJQgvgQQK6SAWSAQIIASI2CgVMZXZlbBIVChFMRVZFTF9VTlNQRUNJRklFRBAAEgoKBlZJRVdFUhABEgoKBkVESVRPUhACIkgKF0RlbGV0ZVNhdmVkUXVlcnlSZXF1ZXN0Ei0KBG5hbWUYASABKAlCH+BBAvpBGQoXYnl0ZWJhc2UuY29tL1NhdmVkUXVlcnkigAEKGVNlYXJjaFNhdmVkUXVlcmllc1JlcXVlc3QSLAoGcGFyZW50GAEgASgJQhzgQQL6QRYKFGJ5dGViYXNlLmNvbS9Qcm9qZWN0Eg4KBmZpbHRlchgCIAEoCRIRCglwYWdlX3NpemUYAyABKAUSEgoKcGFnZV90b2tlbhgEIAEoCSJlChpTZWFyY2hTYXZlZFF1ZXJpZXNSZXNwb25zZRIuCg1zYXZlZF9xdWVyaWVzGAEgAygLMhcuYnl0ZWJhc2UudjEuU2F2ZWRRdWVyeRIXCg9uZXh0X3BhZ2VfdG9rZW4YAiABKAkiogMKClNhdmVkUXVlcnkSFAoEbmFtZRgBIAEoCUIG4EEC4EEFEhQKB3Byb2plY3QYAiABKAlCA+BBAxIQCghkYXRhYmFzZRgDIAEoCRIaCgV0aXRsZRgEIAEoCUIL4EECukgFcgMYyAESFAoHY3JlYXRvchgFIAEoCUID4EEDEjQKC2NyZWF0ZV90aW1lGAYgASgLMhouZ29vZ2xlLnByb3RvYnVmLlRpbWVzdGFtcEID4EEDEjQKC3VwZGF0ZV90aW1lGAcgASgLMhouZ29vZ2xlLnByb3RvYnVmLlRpbWVzdGFtcEID4EEDEhQKB2NvbnRlbnQYCCABKAxCA+BBAhIZCgxjb250ZW50X3NpemUYCSABKANCA+BBAxIUCgdzdGFycmVkGAsgASgIQgPgQQMSGAoGZm9sZGVyGA0gASgJQgi6SAVyAxiAAjpL6kFIChdieXRlYmFzZS5jb20vU2F2ZWRRdWVyeRItcHJvamVjdHMve3Byb2plY3R9L3NhdmVkUXVlcmllcy97c2F2ZWRfcXVlcnl9SgQIChALSgQIDBANMq4PChFTYXZlZFF1ZXJ5U2VydmljZRLDAQoQQ3JlYXRlU2F2ZWRRdWVyeRIkLmJ5dGViYXNlLnYxLkNyZWF0ZVNhdmVkUXVlcnlSZXF1ZXN0GhcuYnl0ZWJhc2UudjEuU2F2ZWRRdWVyeSJw2kEScGFyZW50LHNhdmVkX3F1ZXJ5iuowFmJiLnNhdmVkUXVlcmllcy5jcmVhdGWQ6jABmOowAYLT5JMCMzoLc2F2ZWRfcXVlcnkiJC92MS97cGFyZW50PXByb2plY3RzLyp9L3NhdmVkUXVlcmllcxKEAQoNR2V0U2F2ZWRRdWVyeRIhLmJ5dGViYXNlLnYxLkdldFNhdmVkUXVlcnlSZXF1ZXN0GhcuYnl0ZWJhc2UudjEuU2F2ZWRRdWVyeSI32kEEbmFtZZDqMAKC0+STAiYSJC92MS97bmFtZT1wcm9qZWN0cy8qL3NhdmVkUXVlcmllcy8qfRKyAQoQTGlzdFNhdmVkUXVlcmllcxIkLmJ5dGViYXNlLnYxLkxpc3RTYXZlZFF1ZXJpZXNSZXF1ZXN0GiUuYnl0ZWJhc2UudjEuTGlzdFNhdmVkUXVlcmllc1Jlc3BvbnNlIlHaQQZwYXJlbnSK6jAUYmIuc2F2ZWRRdWVyaWVzLmxpc3SQ6jABgtPkkwImEiQvdjEve3BhcmVudD1wcm9qZWN0cy8qfS9zYXZlZFF1ZXJpZXMSqgEKElNlYXJjaFNhdmVkUXVlcmllcxImLmJ5dGViYXNlLnYxLlNlYXJjaFNhdmVkUXVlcmllc1JlcXVlc3QaJy5ieXRlYmFzZS52MS5TZWFyY2hTYXZlZFF1ZXJpZXNSZXNwb25zZSJD2kEGcGFyZW50kOowAoLT5JMCMDoBKiIrL3YxL3twYXJlbnQ9cHJvamVjdHMvKn0vc2F2ZWRRdWVyaWVzOnNlYXJjaBLAAQoXU2VhcmNoU2F2ZWRRdWVyeUZvbGRlcnMSKy5ieXRlYmFzZS52MS5TZWFyY2hTYXZlZFF1ZXJ5Rm9sZGVyc1JlcXVlc3QaLC5ieXRlYmFzZS52MS5TZWFyY2hTYXZlZFF1ZXJ5Rm9sZGVyc1Jlc3BvbnNlIkraQQZwYXJlbnSQ6jACgtPkkwI3OgEqIjIvdjEve3BhcmVudD1wcm9qZWN0cy8qfS9zYXZlZFF1ZXJpZXM6c2VhcmNoRm9sZGVycxK6AQoQVXBkYXRlU2F2ZWRRdWVyeRIkLmJ5dGViYXNlLnYxLlVwZGF0ZVNhdmVkUXVlcnlSZXF1ZXN0GhcuYnl0ZWJhc2UudjEuU2F2ZWRRdWVyeSJn2kEXc2F2ZWRfcXVlcnksdXBkYXRlX21hc2uQ6jACmOowAYLT5JMCPzoLc2F2ZWRfcXVlcnkyMC92MS97c2F2ZWRfcXVlcnkubmFtZT1wcm9qZWN0cy8qL3NhdmVkUXVlcmllcy8qfRKoAQoUVXBkYXRlU2F2ZWRRdWVyeVN0YXISKC5ieXRlYmFzZS52MS5VcGRhdGVTYXZlZFF1ZXJ5U3RhclJlcXVlc3QaFy5ieXRlYmFzZS52MS5TYXZlZFF1ZXJ5Ik3aQQxuYW1lLHN0YXJyZWSQ6jACgtPkkwI0OgEqIi8vdjEve25hbWU9cHJvamVjdHMvKi9zYXZlZFF1ZXJpZXMvKn06dXBkYXRlU3RhchLKAQoSTW92ZU15U2F2ZWRRdWVyaWVzEiYuYnl0ZWJhc2UudjEuTW92ZU15U2F2ZWRRdWVyaWVzUmVxdWVzdBonLmJ5dGViYXNlLnYxLk1vdmVNeVNhdmVkUXVlcmllc1Jlc3BvbnNlImPaQSJwYXJlbnQsc291cmNlX2ZvbGRlcix0YXJnZXRfZm9sZGVykOowApjqMAGC0+STAjA6ASoiKy92MS97cGFyZW50PXByb2plY3RzLyp9L3NhdmVkUXVlcmllczptb3ZlTXkSjQEKEERlbGV0ZVNhdmVkUXVlcnkSJC5ieXRlYmFzZS52MS5EZWxldGVTYXZlZFF1ZXJ5UmVxdWVzdBoWLmdvb2dsZS5wcm90b2J1Zi5FbXB0eSI72kEEbmFtZZDqMAKY6jABgtPkkwImKiQvdjEve25hbWU9cHJvamVjdHMvKi9zYXZlZFF1ZXJpZXMvKn0SqAEKE0dldFNhdmVkUXVlcnlQb2xpY3kSJy5ieXRlYmFzZS52MS5HZXRTYXZlZFF1ZXJ5UG9saWN5UmVxdWVzdBodLmJ5dGViYXNlLnYxLlNhdmVkUXVlcnlQb2xpY3kiSdpBCHJlc291cmNlkOowAoLT5JMCNBIyL3YxL3tyZXNvdXJjZT1wcm9qZWN0cy8qL3NhdmVkUXVlcmllcy8qfTpnZXRQb2xpY3kStgEKE1NldFNhdmVkUXVlcnlQb2xpY3kSJy5ieXRlYmFzZS52MS5TZXRTYXZlZFF1ZXJ5UG9saWN5UmVxdWVzdBodLmJ5dGViYXNlLnYxLlNhdmVkUXVlcnlQb2xpY3kiV9pBD3Jlc291cmNlLHBvbGljeZDqMAKY6jABgtPkkwI3OgEqIjIvdjEve3Jlc291cmNlPXByb2plY3RzLyovc2F2ZWRRdWVyaWVzLyp9OnNldFBvbGljeUKsAQoPY29tLmJ5dGViYXNlLnYxQhZTYXZlZFF1ZXJ5U2VydmljZVByb3RvUAFaNGdpdGh1Yi5jb20vYnl0ZWJhc2UvYnl0ZWJhc2UvYmFja2VuZC9nZW5lcmF0ZWQtZ28vdjGiAgNCWFiqAgtCeXRlYmFzZS5WMcoCC0J5dGViYXNlXFYx4gIXQnl0ZWJhc2VcVjFcR1BCTWV0YWRhdGHqAgxCeXRlYmFzZTo6VjFiBnByb3RvMw", [file_buf_validate_validate, file_google_api_annotations, file_google_api_client, file_google_api_field_behavior, file_google_api_resource, file_google_protobuf_empty, file_google_protobuf_field_mask, file_google_protobuf_timestamp, file_v1_annotation]);
/**
* Describes the message bytebase.v1.CreateSavedQueryRequest.
@@ -122,8 +122,8 @@ export const SavedQueryBinding_LevelSchema = /*@__PURE__*/
enumDesc(file_v1_saved_query_service, 13, 0);
/**
- * Nested because bytebase.v1 already defines a package-scoped EDITOR
- * (DatabaseChangeMode), and enum values live in the enclosing scope.
+ * Nested to avoid colliding with the package-scoped EDITOR in
+ * DatabaseChangeMode.
*
* @generated from enum bytebase.v1.SavedQueryBinding.Level
*/
@@ -159,16 +159,18 @@ export const SavedQuerySchema = /*@__PURE__*/
messageDesc(file_v1_saved_query_service, 17);
/**
- * SavedQueryService manages saved queries for SQL Editor query development.
+ * SavedQueryService manages saved queries in the SQL Editor.
*
- * A saved query is private to its creator until shared. Three things grant
- * access to one: being its creator (the fixed owner), holding a VIEWER or
- * EDITOR binding on it, and holding bb.savedQueries.manage, the admin backstop
- * that reaches private saved queries too. Bindings are managed through the
- * GetSavedQueryPolicy/SetSavedQueryPolicy pair.
- *
- * Two gates sit on top of that: bb.savedQueries.search gates discovery, and
- * running a saved query needs the SQL Editor's own database permissions.
+ * A saved query is private to its creator until shared. Permissions come from
+ * three places:
+ * - The creator owns the saved query and holds every permission on it.
+ * - A VIEWER binding grants bb.savedQueries.get and getIamPolicy; an EDITOR
+ * binding adds update.
+ * - Permissions granted on the project or workspace apply to every saved
+ * query in the project, private ones included.
+ * A caller without a method's permission gets NotFound, not
+ * PermissionDenied, so private names stay unprobeable. Running a saved query
+ * is governed by the SQL Editor's database permissions, not by this service.
*
* @generated from service bytebase.v1.SavedQueryService
*/
diff --git a/frontend/src/utils/iam/permission.ts b/frontend/src/utils/iam/permission.ts
index c0ac4c337a..3a1bd639ef 100644
--- a/frontend/src/utils/iam/permission.ts
+++ b/frontend/src/utils/iam/permission.ts
@@ -17,13 +17,16 @@ type ProjectChecker = (project: Project, permission: Permission) => boolean;
// well before any render-time permission check).
let workspaceChecker: WorkspaceChecker = () => false;
let projectChecker: ProjectChecker = () => false;
+let projectWideChecker: ProjectChecker = () => false;
export const registerPermissionCheckers = (checkers: {
hasWorkspacePermission: WorkspaceChecker;
hasProjectPermission: ProjectChecker;
+ hasProjectWidePermission: ProjectChecker;
}): void => {
workspaceChecker = checkers.hasWorkspacePermission;
projectChecker = checkers.hasProjectPermission;
+ projectWideChecker = checkers.hasProjectWidePermission;
};
export const hasWorkspacePermissionV2 = (permission: Permission): boolean =>
@@ -36,3 +39,12 @@ export const hasProjectPermissionV2 = (
project: Project,
permission: Permission
): boolean => projectChecker(project, permission);
+
+// hasProjectWidePermissionV2 mirrors the server's CheckProjectWidePermission:
+// a binding whose condition scopes resources confers nothing. Surfaces the
+// server gates project-wide (the saved-query permissions) use this so the UI
+// never offers what the RPC will deny.
+export const hasProjectWidePermissionV2 = (
+ project: Project,
+ permission: Permission
+): boolean => projectWideChecker(project, permission);
diff --git a/frontend/src/utils/v1/iam.test.ts b/frontend/src/utils/v1/iam.test.ts
index 883c4f37b4..3bf0486817 100644
--- a/frontend/src/utils/v1/iam.test.ts
+++ b/frontend/src/utils/v1/iam.test.ts
@@ -1,107 +1,90 @@
import { create } from "@bufbuild/protobuf";
import { describe, expect, test } from "vitest";
-import { ExprSchema as ConditionExprSchema } from "@/types/proto-es/google/type/expr_pb";
import {
- BindingSchema,
- IamPolicySchema,
-} from "@/types/proto-es/v1/iam_policy_pb";
-import { revokeMemberFromBinding } from "./iam";
-
-// A database-scoped grant with no expiration. Several users granted the same
-// database via separate access requests end up as separate single-member
-// bindings that share this exact role + condition expression.
-const DB_SCOPED =
- '(resource.database in ["instances/nf-prod-jfapp/databases/ekb_app2"])';
-
-const grant = (member: string) =>
- create(BindingSchema, {
- role: "roles/sqlEditorReadUser",
- members: [member],
- condition: create(ConditionExprSchema, { expression: DB_SCOPED }),
+ type Expr,
+ ExprSchema,
+} from "@/types/proto-es/google/api/expr/v1alpha1/syntax_pb";
+import type { Binding } from "@/types/proto-es/v1/iam_policy_pb";
+import { bindingScopesResources } from "./iam";
+
+const binding = (expression?: string, parsedExpr?: Expr) =>
+ ({
+ condition: expression === undefined ? undefined : { expression },
+ parsedExpr,
+ }) as Binding;
+
+const ident = (name: string) =>
+ create(ExprSchema, { exprKind: { case: "identExpr", value: { name } } });
+const select = (operand: Expr, field: string) =>
+ create(ExprSchema, {
+ exprKind: { case: "selectExpr", value: { operand, field } },
});
-
-describe("revokeMemberFromBinding", () => {
- test("revokes the clicked binding when several bindings share role and condition", () => {
- const grantA = grant("user:[email protected]");
- const grantB = grant("user:[email protected]");
- const policy = create(IamPolicySchema, { bindings: [grantA, grantB] });
-
- const result = revokeMemberFromBinding(
- policy,
- grantB,
- );
-
- const members = result.bindings.flatMap((b) => b.members);
- expect(members).not.toContain("user:[email protected]");
- expect(members).toContain("user:[email protected]");
- });
-
- test("removes only the targeted member from a shared multi-member binding", () => {
- const binding = create(BindingSchema, {
- role: "roles/sqlEditorReadUser",
- members: [
- ],
- condition: create(ConditionExprSchema, { expression: DB_SCOPED }),
- });
- const policy = create(IamPolicySchema, { bindings: [binding] });
-
- const result = revokeMemberFromBinding(
- policy,
- binding,
- );
-
- expect(result.bindings).toHaveLength(1);
- expect(result.bindings[0].members).toEqual([
- ]);
+const call = (fn: string, args: Expr[]) =>
+ create(ExprSchema, {
+ exprKind: { case: "callExpr", value: { function: fn, args } },
});
- test("drops the binding once its last member is revoked", () => {
- const binding = grant("user:[email protected]");
- const policy = create(IamPolicySchema, { bindings: [binding] });
-
- const result = revokeMemberFromBinding(
- policy,
- binding,
- );
-
- expect(result.bindings).toHaveLength(0);
+// Mirrors the server's rule: any condition attribute other than request.time
+// scopes the binding away from project-wide surfaces.
+describe("bindingScopesResources", () => {
+ test("no condition or expiry-only conditions are project-wide", () => {
+ expect(bindingScopesResources(binding())).toBe(false);
+ expect(bindingScopesResources(binding(""))).toBe(false);
+ expect(
+ bindingScopesResources(
+ binding('request.time < timestamp("2099-01-01T00:00:00Z")')
+ )
+ ).toBe(false);
});
- test("does not mutate the input policy", () => {
- const grantA = grant("user:[email protected]");
- const grantB = grant("user:[email protected]");
- const policy = create(IamPolicySchema, { bindings: [grantA, grantB] });
-
- revokeMemberFromBinding(policy, grantB, "user:[email protected]");
-
- expect(policy.bindings).toHaveLength(2);
- expect(policy.bindings[1].members).toEqual(["user:[email protected]"]);
+ test("resource attributes scope the binding (string fallback)", () => {
+ expect(
+ bindingScopesResources(
+ binding('resource.database == "instances/i/databases/d"')
+ )
+ ).toBe(true);
+ expect(
+ bindingScopesResources(
+ binding(
+ 'resource.environment_id == "prod" && request.time < timestamp("2099-01-01T00:00:00Z")'
+ )
+ )
+ ).toBe(true);
+ expect(
+ bindingScopesResources(binding('resource.schema_name == "public"'))
+ ).toBe(true);
});
- test("falls back to role + condition + membership when the target is not the same reference", () => {
- const grantA = grant("user:[email protected]");
- const grantB = grant("user:[email protected]");
- const policy = create(IamPolicySchema, { bindings: [grantA, grantB] });
- // A structurally-equal copy with a different object identity, e.g. after a
- // round-trip through the cache.
- const targetCopy = grant("user:[email protected]");
-
- const result = revokeMemberFromBinding(
- policy,
- targetCopy,
- );
-
- const members = result.bindings.flatMap((b) => b.members);
- expect(members).not.toContain("user:[email protected]");
- expect(members).toContain("user:[email protected]");
+ test("the parsed condition is authoritative when present", () => {
+ const requestTimeOnly = call("_<_", [
+ select(ident("request"), "time"),
+ call("timestamp", []),
+ ]);
+ expect(
+ bindingScopesResources(
+ binding(
+ 'request.time < timestamp("2099-01-01T00:00:00Z")',
+ requestTimeOnly
+ )
+ )
+ ).toBe(false);
+
+ const resourceScoped = call("_==_", [
+ select(ident("resource"), "database"),
+ ]);
+ // Whitespace-formatted CEL ("resource . database") defeats the substring
+ // fallback, but the parsed AST still names the reference — the server
+ // walks the same tree.
+ expect(
+ bindingScopesResources(
+ binding(
+ 'resource . database == "instances/i/databases/d"',
+ resourceScoped
+ )
+ )
+ ).toBe(true);
+
+ const mixed = call("_&&_", [requestTimeOnly, resourceScoped]);
+ expect(bindingScopesResources(binding("...", mixed))).toBe(true);
});
});
diff --git a/frontend/src/utils/v1/iam.ts b/frontend/src/utils/v1/iam.ts
index 60d6b382c6..8b059f4213 100644
--- a/frontend/src/utils/v1/iam.ts
+++ b/frontend/src/utils/v1/iam.ts
@@ -31,6 +31,72 @@ import { appStoreUtilBridge } from "@/utils/app-store-bridge";
import { convertFromExpr } from "@/utils/issue/cel";
import { ensureUserFullName } from "@/utils/v1/user";
+// expressionReferencesResources walks a parsed CEL condition for any
+// reference other than request.time — the server's rule for a binding that
+// scopes resources rather than just expiry.
+const expressionReferencesResources = (expr: Expr | undefined): boolean => {
+ if (!expr) return false;
+ switch (expr.exprKind?.case) {
+ case "identExpr":
+ return expr.exprKind.value.name !== "request";
+ case "selectExpr": {
+ const select = expr.exprKind.value;
+ const operand = select.operand;
+ if (
+ operand?.exprKind?.case === "identExpr" &&
+ operand.exprKind.value.name === "request"
+ ) {
+ // request.time is the one attribute a project-wide grant may carry.
+ return select.field !== "time";
+ }
+ return expressionReferencesResources(operand);
+ }
+ case "callExpr": {
+ const call = expr.exprKind.value;
+ return (
+ expressionReferencesResources(call.target) ||
+ call.args.some(expressionReferencesResources)
+ );
+ }
+ case "listExpr":
+ return expr.exprKind.value.elements.some(expressionReferencesResources);
+ case "structExpr":
+ return expr.exprKind.value.entries.some(
+ (entry) =>
+ expressionReferencesResources(entry.value) ||
+ (entry.keyKind?.case === "mapKey" &&
+ expressionReferencesResources(entry.keyKind.value))
+ );
+ case "comprehensionExpr": {
+ const comprehension = expr.exprKind.value;
+ return [
+ comprehension.iterRange,
+ comprehension.accuInit,
+ comprehension.loopCondition,
+ comprehension.loopStep,
+ comprehension.result,
+ ].some(expressionReferencesResources);
+ }
+ default:
+ return false;
+ }
+};
+
+// Mirrors the server's project-wide permission rule: a binding whose
+// condition scopes resources — it references anything other than
+// request.time — confers no project-wide permission. The server attaches the
+// parsed condition to every binding it returns, so the check walks the AST
+// exactly as the server's conditionScopesResources does; without one it
+// falls back to a substring test, which is exact for canonical expressions
+// because every IAM condition attribute other than request.time lives under
+// `resource.`.
+export const bindingScopesResources = (binding: Binding): boolean => {
+ if (binding.parsedExpr) {
+ return expressionReferencesResources(binding.parsedExpr);
+ }
+ return (binding.condition?.expression ?? "").includes("resource.");
+};
+
export const isBindingPolicyExpired = (binding: Binding): boolean => {
if (binding.parsedExpr) {
const conditionExpr = convertFromExpr(binding.parsedExpr);
diff --git a/frontend/src/utils/v1/savedQuery.test.ts b/frontend/src/utils/v1/savedQuery.test.ts
new file mode 100644
index 0000000000..e981f06079
--- /dev/null
+++ b/frontend/src/utils/v1/savedQuery.test.ts
@@ -0,0 +1,110 @@
+import { beforeEach, describe, expect, test, vi } from "vitest";
+import type { SavedQuery } from "@/types/proto-es/v1/saved_query_service_pb";
+import { SavedQueryBinding_Level } from "@/types/proto-es/v1/saved_query_service_pb";
+
+const mocks = vi.hoisted(() => ({
+ currentUser: { email: "[email protected]" },
+ level: 0 as SavedQueryBinding_Level,
+ hasProjectWidePermissionV2: vi.fn(
+ (_project: unknown, _permission: string): boolean => false
+ ),
+}));
+
+vi.mock("@/stores", () => ({
+ getCurrentUserV1: () => mocks.currentUser,
+}));
+
+vi.mock("@/stores/app/projectAccess", () => ({
+ getProjectByName: (name: string) => ({ name }),
+}));
+
+vi.mock("@/stores/app/savedQueryAccess", () => ({
+ getSavedQueryLevel: () => mocks.level,
+}));
+
+vi.mock("@/utils", () => ({
+ hasProjectWidePermissionV2: mocks.hasProjectWidePermissionV2,
+}));
+
+import {
+ isSavedQueryDeletableV1,
+ isSavedQueryReadableV1,
+ isSavedQueryShareableV1,
+ isSavedQueryWritableV1,
+} from "./savedQuery";
+
+const sheet = (creator: string) =>
+ ({
+ name: "projects/proj/savedQueries/sq",
+ project: "projects/proj",
+ creator,
+ }) as SavedQuery;
+
+const mine = sheet("users/[email protected]");
+const theirs = sheet("users/[email protected]");
+
+describe("saved query access predicates", () => {
+ beforeEach(() => {
+ mocks.level = SavedQueryBinding_Level.LEVEL_UNSPECIFIED;
+ mocks.hasProjectWidePermissionV2.mockReset();
+ mocks.hasProjectWidePermissionV2.mockReturnValue(false);
+ });
+
+ test("the creator holds every predicate", () => {
+ expect(isSavedQueryReadableV1(mine)).toBe(true);
+ expect(isSavedQueryWritableV1(mine)).toBe(true);
+ expect(isSavedQueryDeletableV1(mine)).toBe(true);
+ expect(isSavedQueryShareableV1(mine)).toBe(true);
+ });
+
+ test("a VIEWER binding grants read only", () => {
+ mocks.level = SavedQueryBinding_Level.VIEWER;
+ expect(isSavedQueryReadableV1(theirs)).toBe(true);
+ expect(isSavedQueryWritableV1(theirs)).toBe(false);
+ expect(isSavedQueryDeletableV1(theirs)).toBe(false);
+ expect(isSavedQueryShareableV1(theirs)).toBe(false);
+ });
+
+ test("an EDITOR binding grants read and write, never delete or share", () => {
+ mocks.level = SavedQueryBinding_Level.EDITOR;
+ expect(isSavedQueryReadableV1(theirs)).toBe(true);
+ expect(isSavedQueryWritableV1(theirs)).toBe(true);
+ expect(isSavedQueryDeletableV1(theirs)).toBe(false);
+ expect(isSavedQueryShareableV1(theirs)).toBe(false);
+ });
+
+ test("each predicate asks for exactly its project-level verb", () => {
+ const byVerb = (verb: string) =>
+ mocks.hasProjectWidePermissionV2.mockImplementation(
+ (_project: unknown, permission: string) => permission === verb
+ );
+
+ byVerb("bb.savedQueries.get");
+ expect(isSavedQueryReadableV1(theirs)).toBe(true);
+ expect(isSavedQueryWritableV1(theirs)).toBe(false);
+
+ byVerb("bb.savedQueries.update");
+ expect(isSavedQueryWritableV1(theirs)).toBe(true);
+ expect(isSavedQueryDeletableV1(theirs)).toBe(false);
+
+ byVerb("bb.savedQueries.delete");
+ expect(isSavedQueryDeletableV1(theirs)).toBe(true);
+ expect(isSavedQueryShareableV1(theirs)).toBe(false);
+
+ // setIamPolicy alone is not enough: the write is compare-and-swap over
+ // the policy's etag, which only getIamPolicy can read.
+ byVerb("bb.savedQueries.setIamPolicy");
+ expect(isSavedQueryShareableV1(theirs)).toBe(false);
+
+ byVerb("bb.savedQueries.getIamPolicy");
+ expect(isSavedQueryShareableV1(theirs)).toBe(false);
+
+ mocks.hasProjectWidePermissionV2.mockImplementation(
+ (_project: unknown, permission: string) =>
+ permission === "bb.savedQueries.setIamPolicy" ||
+ permission === "bb.savedQueries.getIamPolicy"
+ );
+ expect(isSavedQueryShareableV1(theirs)).toBe(true);
+ expect(isSavedQueryReadableV1(theirs)).toBe(false);
+ });
+});
diff --git a/frontend/src/utils/v1/savedQuery.ts b/frontend/src/utils/v1/savedQuery.ts
index 0dc1c61cbd..4fc4fc9242 100644
--- a/frontend/src/utils/v1/savedQuery.ts
+++ b/frontend/src/utils/v1/savedQuery.ts
@@ -7,7 +7,7 @@ import {
type SavedQuery,
SavedQueryBinding_Level,
} from "@/types/proto-es/v1/saved_query_service_pb";
-import { hasProjectPermissionV2 } from "@/utils";
+import { hasProjectWidePermissionV2 } from "@/utils";
export const extractSavedQueryID = (name: string) => {
const pattern = /(?:^|\/)savedQueries\/([^/]+)(?:$|\/)/;
@@ -16,59 +16,85 @@ export const extractSavedQueryID = (name: string) => {
};
// Browsing saved queries takes bb.savedQueries.search on the project, which is
-// the server's whole discovery gate -- manage does not substitute for it, since
-// the search family is caller-scoped and an admin reads everyone's saved
-// queries through ListSavedQueries instead. A SQL role can grant query access
+// the server's whole discovery gate. A SQL role can grant query access
// without search, in which case the tree stays empty rather than firing
// requests that can only come back denied.
+//
+// All checks in this file are project-wide, mirroring the server: a binding
+// whose condition scopes resources confers no saved-query permission.
export const canSearchSavedQueriesInProject = (project: string) =>
- hasProjectPermissionV2(getProjectByName(project), "bb.savedQueries.search");
+ hasProjectWidePermissionV2(
+ getProjectByName(project),
+ "bb.savedQueries.search"
+ );
// Creating a saved query takes bb.savedQueries.create on the project. A role
// can grant SQL Editor access without it, so entry points that would persist a
// new saved query check this first -- the editor stays usable, it just keeps
// the work local.
export const canCreateSavedQueryInProject = (project: string) =>
- hasProjectPermissionV2(getProjectByName(project), "bb.savedQueries.create");
+ hasProjectWidePermissionV2(
+ getProjectByName(project),
+ "bb.savedQueries.create"
+ );
-// Three things grant access to a saved query, mirroring the server: being its
-// creator, holding a VIEWER or EDITOR binding on it, and holding
-// "bb.savedQueries.manage" (the admin backstop).
-//
-// The backstop is checked on the saved query's own project, mirroring the
-// server: a project-level grant (Project Owner, or a custom project role)
-// is enough, and the project check already falls back to workspace grants.
+// Access mirrors the server: the creator owns the saved query and holds every
+// permission on it; a VIEWER binding grants bb.savedQueries.get and an EDITOR
+// binding grants get + update on that saved query; the same permissions
+// granted on the project reach every saved query there. The project check
+// already falls back to workspace grants.
//
// The grant level is not on the resource -- nothing caller-relative is -- so it
// comes from the policy, resolved and cached by the app store when a saved
// query somebody else created is fetched. An unresolved level reads as "no
// grant", which is why the store awaits that resolution before handing the
// saved query to callers of these predicates.
-const isCreatorOrAdmin = (sheet: SavedQuery) => {
- const currentUser = getCurrentUserV1();
- if (extractUserEmail(sheet.creator) === currentUser.email) {
- return true;
- }
- return hasProjectPermissionV2(
- getProjectByName(sheet.project),
- "bb.savedQueries.manage"
+const isCreator = (sheet: SavedQuery) =>
+ extractUserEmail(sheet.creator) === getCurrentUserV1().email;
+
+const hasProjectVerb = (
+ sheet: SavedQuery,
+ permission:
+ | "bb.savedQueries.get"
+ | "bb.savedQueries.update"
+ | "bb.savedQueries.delete"
+ | "bb.savedQueries.getIamPolicy"
+ | "bb.savedQueries.setIamPolicy"
+) => hasProjectWidePermissionV2(getProjectByName(sheet.project), permission);
+
+const bindingGrantsGet = (sheet: SavedQuery) => {
+ const level = getSavedQueryLevel(sheet.name);
+ return (
+ level === SavedQueryBinding_Level.VIEWER ||
+ level === SavedQueryBinding_Level.EDITOR
);
};
-const grantedLevel = (sheet: SavedQuery) => getSavedQueryLevel(sheet.name);
+const bindingGrantsUpdate = (sheet: SavedQuery) =>
+ getSavedQueryLevel(sheet.name) === SavedQueryBinding_Level.EDITOR;
export const isSavedQueryReadableV1 = (sheet: SavedQuery) =>
- isCreatorOrAdmin(sheet) ||
- grantedLevel(sheet) >= SavedQueryBinding_Level.VIEWER;
+ isCreator(sheet) ||
+ bindingGrantsGet(sheet) ||
+ hasProjectVerb(sheet, "bb.savedQueries.get");
export const isSavedQueryWritableV1 = (sheet: SavedQuery) =>
- isCreatorOrAdmin(sheet) ||
- grantedLevel(sheet) >= SavedQueryBinding_Level.EDITOR;
+ isCreator(sheet) ||
+ bindingGrantsUpdate(sheet) ||
+ hasProjectVerb(sheet, "bb.savedQueries.update");
+
+// Bindings never carry deletion.
+export const isSavedQueryDeletableV1 = (sheet: SavedQuery) =>
+ isCreator(sheet) || hasProjectVerb(sheet, "bb.savedQueries.delete");
-// Sharing, deleting, and re-filing are creator-or-admin: a binding never
-// confers them, so an EDITOR grantee must not see those affordances.
-export const isSavedQueryManageableV1 = (sheet: SavedQuery) =>
- isCreatorOrAdmin(sheet);
+// Sharing: the creator, or a project-level bb.savedQueries.setIamPolicy —
+// which no predefined role carries. The write is compare-and-swap over the
+// policy's etag, so exercising it requires reading the policy first: the
+// affordance demands getIamPolicy alongside setIamPolicy.
+export const isSavedQueryShareableV1 = (sheet: SavedQuery) =>
+ isCreator(sheet) ||
+ (hasProjectVerb(sheet, "bb.savedQueries.setIamPolicy") &&
+ hasProjectVerb(sheet, "bb.savedQueries.getIamPolicy"));
// `extractSavedQueryConnection` moved to `@/lib/sqlEditorConnection`
// so the database lookup can go through the React app store without
diff --git a/proto/gen/grpc-doc/openapi.yaml b/proto/gen/grpc-doc/openapi.yaml
index 7c5f3195b2..cb821f0473 100644
--- a/proto/gen/grpc-doc/openapi.yaml
+++ b/proto/gen/grpc-doc/openapi.yaml
@@ -13690,12 +13690,11 @@ paths:
- SavedQueryService
summary: ListSavedQueries
description: |-
- List saved queries for auditing. Bindings are ignored: the permission
- alone reads every matched saved query's content, private ones included.
- Returns whole statements rather than Search's previews, and accepts
- "projects/-" to span every project.
- Permissions required: bb.savedQueries.list on the parent project, or
- workspace-wide when the parent is "projects/-"
+ List saved queries for auditing. The permission alone grants reading
+ every matched saved query with full content, private ones included;
+ bindings are ignored. Use parent "projects/-" for all projects.
+ Permissions required: bb.savedQueries.list on the project, or on the
+ workspace when the parent is "projects/-"
operationId: SavedQueryService_ListSavedQueries
parameters:
- name: project
@@ -13729,10 +13728,8 @@ paths:
- name: pageToken
in: query
description: |-
- A page token from a previous ListSavedQueries call. Every other parameter
- must match the call that returned it: the token carries the offset reached
- so far, so changing `filter` or `page_size` mid-pagination reinterprets
- that offset against a different result set.
+ A page token from a previous ListSavedQueries call. Keep every other
+ parameter the same as the call that returned it.
schema:
type: string
title: page_token
@@ -13748,9 +13745,9 @@ paths:
- SavedQueryService
summary: CreateSavedQuery
description: |-
- Create a saved query. The creator becomes its fixed owner, and the saved
- query starts private.
- Permissions required: bb.savedQueries.create on the parent project
+ Create a saved query. The creator becomes the owner and the saved query
+ starts private.
+ Permissions required: bb.savedQueries.create on the project
operationId: SavedQueryService_CreateSavedQuery
parameters:
- name: project
@@ -13780,9 +13777,9 @@ paths:
- SavedQueryService
summary: GetSavedQuery
description: |-
- Get a saved query with its full content. An unreadable saved query returns
- NotFound rather than PermissionDenied, so it stays unprobeable by name.
- Permissions required: creator, a VIEWER or EDITOR binding, or bb.savedQueries.manage
+ Get a saved query with its full content.
+ Permissions required: bb.savedQueries.get (creator, VIEWER/EDITOR
+ binding, or project-level grant)
operationId: SavedQueryService_GetSavedQuery
parameters:
- name: project
@@ -13809,10 +13806,10 @@ paths:
- SavedQueryService
summary: DeleteSavedQuery
description: |-
- Delete a saved query and every user's stars on it. An EDITOR binding never
- carries deletion. An unreadable saved query returns NotFound; a grantee
- who can read but not delete gets PermissionDenied.
- Permissions required: creator, or bb.savedQueries.manage
+ Delete a saved query and every user's stars on it. An EDITOR binding
+ cannot delete.
+ Permissions required: bb.savedQueries.delete (creator or project-level
+ grant)
operationId: SavedQueryService_DeleteSavedQuery
parameters:
- name: project
@@ -13839,12 +13836,9 @@ paths:
- SavedQueryService
summary: UpdateSavedQuery
description: |-
- Update a saved query. `title`, `content`, and `database` need write access;
- `folder` is creator/admin only, because filing is organization rather than
- editing. `database` must belong to the saved query's own project. An
- unreadable saved query returns NotFound; a VIEWER who cannot write gets
- PermissionDenied.
- Permissions required: creator, an EDITOR binding, or bb.savedQueries.manage
+ Update a saved query. `database` must belong to the saved query's project.
+ Permissions required: bb.savedQueries.update (creator, EDITOR binding, or
+ project-level grant)
operationId: SavedQueryService_UpdateSavedQuery
parameters:
- name: project
@@ -14086,12 +14080,11 @@ paths:
get:
tags:
- SavedQueryService
- summary: 'Get a saved query''s sharing policy: who it is shared with, at what level.'
+ summary: GetSavedQueryPolicy
description: |-
- Anyone who can read the saved query can read its policy, which is how a
- grantee learns whether they may edit it. Callers who cannot read the
- saved query get NotFound.
- Permissions required: creator, a VIEWER or EDITOR binding, or bb.savedQueries.manage
+ Get a saved query's sharing policy: who it is shared with, at what level.
+ Permissions required: bb.savedQueries.getIamPolicy (creator, VIEWER/EDITOR
+ binding, or project-level grant)
operationId: SavedQueryService_GetSavedQueryPolicy
parameters:
- name: project
@@ -14120,9 +14113,9 @@ paths:
summary: SetSavedQueryPolicy
description: |-
Replace a saved query's sharing policy in full. `policy.etag` must match
- the stored policy or the call fails with ABORTED, so a stale write cannot
- reinstate a grant somebody just revoked.
- Permissions required: creator, or bb.savedQueries.manage
+ the stored policy; a mismatch fails with ABORTED.
+ Permissions required: bb.savedQueries.setIamPolicy (creator or
+ project-level grant; no predefined role carries it)
operationId: SavedQueryService_SetSavedQueryPolicy
parameters:
- name: project
@@ -14146,8 +14139,8 @@ paths:
policy:
title: policy
description: |-
- Replaces the stored policy in full: a member absent from it loses their
- grant, and a policy with no bindings makes the saved query private again.
+ The new policy, replacing the stored one in full. Empty `bindings` makes
+ the saved query private again.
$ref: '#/components/schemas/bytebase.v1.SavedQueryPolicy'
title: SetSavedQueryPolicyRequest
required:
@@ -14167,11 +14160,12 @@ paths:
- SavedQueryService
summary: UpdateSavedQueryStar
description: |-
- Star or unstar a saved query for the caller. Stars are personal: yours are
- invisible to everyone else and grant nothing. You can star any saved query
- you created or have been granted access to; anything else answers
- NotFound, so names stay unprobeable.
- Permissions required: creator, or a VIEWER or EDITOR binding
+ Star or unstar a saved query for the caller. Stars are personal: nobody
+ else sees them and they grant nothing. The caller can star any saved
+ query they can read. When access is lost the star is hidden, not
+ deleted; it comes back if access returns.
+ Permissions required: bb.savedQueries.get (creator, VIEWER/EDITOR
+ binding, or project-level grant)
operationId: SavedQueryService_UpdateSavedQueryStar
parameters:
- name: project
@@ -14210,14 +14204,13 @@ paths:
post:
tags:
- SavedQueryService
- summary: |-
- Move the caller's own saved queries into a folder, named individually or a
- whole folder at a time. Moving a folder carries its descendants, so renaming "a/b" to
- "a/c" also moves "a/b/deep" -- one call, not one per path.
- description: |-
- Filing is personal organization, so only the creator's own move: a folder
- is that person's tree, and neither a binding nor the admin backstop
- reaches into it. The response counts what moved.
+ summary: MoveMySavedQueries
+ description: |-
+ Move the caller's saved queries filed under `source_folder`, descendants
+ included, into `target_folder`: renaming "a/b" to "a/c" also moves
+ "a/b/deep". Only the caller's own saved queries move; the response counts
+ how many did. Re-filing a single saved query is UpdateSavedQuery's
+ `folder` field.
Permissions required: creator
operationId: SavedQueryService_MoveMySavedQueries
parameters:
@@ -14233,27 +14226,22 @@ paths:
schema:
type: object
properties:
- names:
- type: array
- items:
- type: string
- title: names
- description: |-
- The saved queries to move. Set this or `source_folder`, not both.
- Format: projects/{project}/savedQueries/{savedQuery}
sourceFolder:
type: string
title: source_folder
maxLength: 256
- description: |-
- Move everything filed under this path, descendants included, e.g. "a/b".
- Set this or `names`, not both.
+ minLength: 1
+ description: The folder to move, descendants included, e.g. "a/b".
targetFolder:
type: string
title: target_folder
maxLength: 256
- description: Where they land. A path like "a/b/c"; empty unfiles them.
+ description: |-
+ Where it lands. A path like "a/b/c"; empty drops the `source_folder`
+ prefix, promoting the folder's contents toward the root.
title: MoveMySavedQueriesRequest
+ required:
+ - sourceFolder
additionalProperties: false
required: true
responses:
@@ -14267,15 +14255,10 @@ paths:
post:
tags:
- SavedQueryService
- summary: |-
- Search saved queries in one project: the SQL Editor's list path, returning
- content previews.
- description: |-
- Caller-scoped, always: the caller's own saved queries plus those a binding
- shares with them. bb.savedQueries.manage does not widen it — an admin
- reading everyone's saved queries uses ListSavedQueries, which is built for
- that. The permission here gates discovery only and grants access to
- nothing by itself.
+ summary: SearchSavedQueries
+ description: |-
+ Search saved queries in one project. Returns content previews of the
+ saved queries the caller can read, the same access rule as GetSavedQuery.
Permissions required: bb.savedQueries.search on the project
operationId: SavedQueryService_SearchSavedQueries
parameters:
@@ -14301,16 +14284,16 @@ paths:
- name: the saved query name. Supports "==" and "in [...]".
- title: the title. Supports "contains".
- creator: the creator in "users/{email}" format. Supports "==" and "!=".
- - shared: true selects only saved queries the caller reaches through a
- binding, excluding their own and any seen through
- bb.savedQueries.manage; false selects the rest. Supports "==".
+ - shared: whether a binding shares the saved query with the caller. Their
+ own saved queries, and ones visible only through a project-level
+ bb.savedQueries.get, are not "shared". Supports "==".
- starred: whether the caller starred it. Supports "==".
- folder: the exact folder path. Supports "==".
- The SQL Editor's views are `creator == "users/{me}"` for My and
- `shared == true` for Shared. Prefer `shared` over `creator !=` for the
- latter: for an admin, `creator !=` also matches saved queries nobody
- shared with them.
+ Use `creator == "users/{me}"` for a My view and `shared == true` for a
+ Shared view. Prefer `shared` over `creator !=`: with a project-level
+ bb.savedQueries.get, `creator !=` also matches saved queries nobody
+ shared with the caller.
For example:
creator == "users/[email protected]"
@@ -14329,11 +14312,8 @@ paths:
type: string
title: page_token
description: |-
- A page token from a previous SearchSavedQueries call. Every other
- parameter must match the call that returned it: the token carries the
- offset reached so far, so changing `filter` or `page_size` mid-pagination
- reinterprets that offset against a different result set and can skip or
- repeat rows.
+ A page token from a previous SearchSavedQueries call. Keep every other
+ parameter the same as the call that returned it.
title: SearchSavedQueriesRequest
additionalProperties: false
required: true
@@ -14348,17 +14328,10 @@ paths:
post:
tags:
- SavedQueryService
- summary: |-
- Search the folder paths holding saved queries the caller can read. Folders
- are a derived view over the `folder` field rather than a resource
- collection, so this is a custom method, caller-scoped like
- SearchSavedQueries.
- description: |-
- A path is returned when at least one readable saved query sits in it —
- including one somebody else filed and shared, since a client seeds its
- folder tree from here and cannot expand into a folder it never learns
- about. Use the filter to split your own folders (`creator == "users/me"`)
- from the ones reaching you through a grant (`shared == true`).
+ summary: SearchSavedQueryFolders
+ description: |-
+ Search folder paths. A path is returned when it holds at least one saved
+ query the caller can read, the same access rule as SearchSavedQueries.
Permissions required: bb.savedQueries.search on the project
operationId: SavedQueryService_SearchSavedQueryFolders
parameters:
@@ -25553,10 +25526,8 @@ components:
type: string
title: page_token
description: |-
- A page token from a previous ListSavedQueries call. Every other parameter
- must match the call that returned it: the token carries the offset reached
- so far, so changing `filter` or `page_size` mid-pagination reinterprets
- that offset against a different result set.
+ A page token from a previous ListSavedQueries call. Keep every other
+ parameter the same as the call that returned it.
title: ListSavedQueriesRequest
required:
- parent
@@ -26184,29 +26155,23 @@ components:
type: string
title: parent
description: 'Format: projects/{project}'
- names:
- type: array
- items:
- type: string
- title: names
- description: |-
- The saved queries to move. Set this or `source_folder`, not both.
- Format: projects/{project}/savedQueries/{savedQuery}
sourceFolder:
type: string
title: source_folder
maxLength: 256
- description: |-
- Move everything filed under this path, descendants included, e.g. "a/b".
- Set this or `names`, not both.
+ minLength: 1
+ description: The folder to move, descendants included, e.g. "a/b".
targetFolder:
type: string
title: target_folder
maxLength: 256
- description: Where they land. A path like "a/b/c"; empty unfiles them.
+ description: |-
+ Where it lands. A path like "a/b/c"; empty drops the `source_folder`
+ prefix, promoting the folder's contents toward the root.
title: MoveMySavedQueriesRequest
required:
- parent
+ - sourceFolder
additionalProperties: false
bytebase.v1.MoveMySavedQueriesResponse:
type: object
@@ -26215,7 +26180,7 @@ components:
type: integer
title: moved_count
format: int32
- description: How many moved. Fewer than were named when some are not the caller's.
+ description: How many moved.
title: MoveMySavedQueriesResponse
additionalProperties: false
bytebase.v1.OAuth2AuthStyle:
@@ -28870,7 +28835,7 @@ components:
type: string
title: creator
description: |-
- The fixed owner. Ownership does not transfer.
+ The owner. Ownership does not transfer.
Format: users/{email}
readOnly: true
createTime:
@@ -28886,8 +28851,8 @@ components:
title: content
format: byte
description: |-
- The SQL text. SearchSavedQueries truncates it; when it is shorter than
- `content_size`, GetSavedQuery returns the whole thing.
+ The SQL text. SearchSavedQueries returns a truncated preview;
+ GetSavedQuery returns the full text.
contentSize:
type:
- integer
@@ -28906,8 +28871,8 @@ components:
title: folder
maxLength: 256
description: |-
- The folder holding this saved query, set by its creator or an admin. A
- path like "a/b/c"; empty means unfiled.
+ The folder holding this saved query. A path like "a/b/c"; empty means
+ unfiled.
title: SavedQuery
required:
- name
@@ -28927,26 +28892,17 @@ components:
title: members
minItems: 1
description: |-
- The principals granted `level`, in bytebase.v1.Binding.members format,
- restricted to "user:{email}" and "group:{email}" -- prefix-checked, as
- project and workspace IAM check their own members.
-
- Service accounts and workload identities are not grantees: they own and
- run their own saved queries and reach them as the creator. Naming one
- under a "user:" prefix grants nothing rather than being rejected, because
- a caller's member is derived from their principal type, so such a binding
- matches nobody.
+ The members granted `level`: "user:{email}" or "group:{email}" only.
- A group is stored as a reference and never expanded, so its membership
- stays live and a large group costs no more than a small one.
+ Service accounts cannot be grantees — they reach their own saved queries
+ as the creator. Naming one under "user:" grants nothing rather than
+ failing. Groups are stored as references, so membership stays live.
title: SavedQueryBinding
required:
- level
- members
additionalProperties: false
- description: |-
- Binds members to one access level on one saved query. Not bytebase.v1.Binding
- because per-object access here is a capability, not a role.
+ description: Binds members to one access level on one saved query.
bytebase.v1.SavedQueryBinding.Level:
type: string
title: Level
@@ -28955,8 +28911,8 @@ components:
- VIEWER
- EDITOR
description: |-
- Nested because bytebase.v1 already defines a package-scoped EDITOR
- (DatabaseChangeMode), and enum values live in the enclosing scope.
+ Nested to avoid colliding with the package-scoped EDITOR in
+ DatabaseChangeMode.
bytebase.v1.SavedQueryPolicy:
type: object
properties:
@@ -28977,9 +28933,8 @@ components:
title: SavedQueryPolicy
additionalProperties: false
description: |-
- Who a saved query is shared with, and at what level. A saved query with no
- bindings is private. The creator is never a binding member: ownership comes
- from creating the saved query and cannot be granted away.
+ Who a saved query is shared with, and at what level. No bindings means
+ private. The creator is never a binding member; ownership cannot be granted.
bytebase.v1.SchemaCatalog:
type: object
properties:
@@ -29469,16 +29424,16 @@ components:
- name: the saved query name. Supports "==" and "in [...]".
- title: the title. Supports "contains".
- creator: the creator in "users/{email}" format. Supports "==" and "!=".
- - shared: true selects only saved queries the caller reaches through a
- binding, excluding their own and any seen through
- bb.savedQueries.manage; false selects the rest. Supports "==".
+ - shared: whether a binding shares the saved query with the caller. Their
+ own saved queries, and ones visible only through a project-level
+ bb.savedQueries.get, are not "shared". Supports "==".
- starred: whether the caller starred it. Supports "==".
- folder: the exact folder path. Supports "==".
- The SQL Editor's views are `creator == "users/{me}"` for My and
- `shared == true` for Shared. Prefer `shared` over `creator !=` for the
- latter: for an admin, `creator !=` also matches saved queries nobody
- shared with them.
+ Use `creator == "users/{me}"` for a My view and `shared == true` for a
+ Shared view. Prefer `shared` over `creator !=`: with a project-level
+ bb.savedQueries.get, `creator !=` also matches saved queries nobody
+ shared with the caller.
For example:
creator == "users/[email protected]"
@@ -29497,11 +29452,8 @@ components:
type: string
title: page_token
description: |-
- A page token from a previous SearchSavedQueries call. Every other
- parameter must match the call that returned it: the token carries the
- offset reached so far, so changing `filter` or `page_size` mid-pagination
- reinterprets that offset against a different result set and can skip or
- repeat rows.
+ A page token from a previous SearchSavedQueries call. Keep every other
+ parameter the same as the call that returned it.
title: SearchSavedQueriesRequest
required:
- parent
@@ -29736,8 +29688,8 @@ components:
policy:
title: policy
description: |-
- Replaces the stored policy in full: a member absent from it loses their
- grant, and a policy with no bindings makes the saved query private again.
+ The new policy, replacing the stored one in full. Empty `bindings` makes
+ the saved query private again.
$ref: '#/components/schemas/bytebase.v1.SavedQueryPolicy'
title: SetSavedQueryPolicyRequest
required:
@@ -31986,6 +31938,7 @@ components:
description: |-
Fields to update, relative to the saved query (`title`, not
`saved_query.title`). Supported: `title`, `content`, `database`, `folder`.
+ At least one path is required.
$ref: '#/components/schemas/google.protobuf.FieldMask'
title: UpdateSavedQueryRequest
required:
@@ -34066,16 +34019,18 @@ tags:
description: RoleService manages workspace roles and permissions.
- name: SavedQueryService
description: |-
- SavedQueryService manages saved queries for SQL Editor query development.
-
- A saved query is private to its creator until shared. Three things grant
- access to one: being its creator (the fixed owner), holding a VIEWER or
- EDITOR binding on it, and holding bb.savedQueries.manage, the admin backstop
- that reaches private saved queries too. Bindings are managed through the
- GetSavedQueryPolicy/SetSavedQueryPolicy pair.
-
- Two gates sit on top of that: bb.savedQueries.search gates discovery, and
- running a saved query needs the SQL Editor's own database permissions.
+ SavedQueryService manages saved queries in the SQL Editor.
+
+ A saved query is private to its creator until shared. Permissions come from
+ three places:
+ - The creator owns the saved query and holds every permission on it.
+ - A VIEWER binding grants bb.savedQueries.get and getIamPolicy; an EDITOR
+ binding adds update.
+ - Permissions granted on the project or workspace apply to every saved
+ query in the project, private ones included.
+ A caller without a method's permission gets NotFound, not
+ PermissionDenied, so private names stay unprobeable. Running a saved query
+ is governed by the SQL Editor's database permissions, not by this service.
- name: ServiceAccountService
description: ServiceAccountService manages service accounts for API integrations.
- name: SheetService
diff --git a/proto/gen/grpc-doc/v1/README.md b/proto/gen/grpc-doc/v1/README.md
index 6cd6971258..8ff78ebfc5 100644
--- a/proto/gen/grpc-doc/v1/README.md
+++ b/proto/gen/grpc-doc/v1/README.md
@@ -11126,7 +11126,7 @@ Supported fields: - creator: the creator in &#34;users/{email}&#34; format. Supp
For example: creator == &#34;users/[email protected]&#34; |
| page_size | [int32](#int32) | | The maximum number of saved queries to return. The service may return fewer. Defaults to 10; values above 1000 are coerced to 1000. |
-| page_token | [string](#string) | | A page token from a previous ListSavedQueries call. Every other parameter must match the call that returned it: the token carries the offset reached so far, so changing `filter` or `page_size` mid-pagination reinterprets that offset against a different result set. |
+| page_token | [string](#string) | | A page token from a previous ListSavedQueries call. Keep every other parameter the same as the call that returned it. |
@@ -11158,9 +11158,8 @@ For example: creator == &#34;users/[email protected]&#34; |
| Field | Type | Label | Description |
| ----- | ---- | ----- | ----------- |
| parent | [string](#string) | | Format: projects/{project} |
-| names | [string](#string) | repeated | The saved queries to move. Set this or `source_folder`, not both. Format: projects/{project}/savedQueries/{savedQuery} |
-| source_folder | [string](#string) | | Move everything filed under this path, descendants included, e.g. &#34;a/b&#34;. Set this or `names`, not both. |
-| target_folder | [string](#string) | | Where they land. A path like &#34;a/b/c&#34;; empty unfiles them. |
+| source_folder | [string](#string) | | The folder to move, descendants included, e.g. &#34;a/b&#34;. |
+| target_folder | [string](#string) | | Where it lands. A path like &#34;a/b/c&#34;; empty drops the `source_folder` prefix, promoting the folder&#39;s contents toward the root. |
@@ -11175,7 +11174,7 @@ For example: creator == &#34;users/[email protected]&#34; |
| Field | Type | Label | Description |
| ----- | ---- | ----- | ----------- |
-| moved_count | [int32](#int32) | | How many moved. Fewer than were named when some are not the caller&#39;s. |
+| moved_count | [int32](#int32) | | How many moved. |
@@ -11194,13 +11193,13 @@ For example: creator == &#34;users/[email protected]&#34; |
| project | [string](#string) | | Format: projects/{project} |
| database | [string](#string) | | The connected database, which must belong to the saved query&#39;s own project. Empty when none is connected, or when the database no longer exists. Format: instances/{instance}/databases/{database} |
| title | [string](#string) | | The title of the saved query. |
-| creator | [string](#string) | | The fixed owner. Ownership does not transfer. Format: users/{email} |
+| creator | [string](#string) | | The owner. Ownership does not transfer. Format: users/{email} |
| create_time | [google.protobuf.Timestamp](#google-protobuf-Timestamp) | | |
| update_time | [google.protobuf.Timestamp](#google-protobuf-Timestamp) | | |
-| content | [bytes](#bytes) | | The SQL text. SearchSavedQueries truncates it; when it is shorter than `content_size`, GetSavedQuery returns the whole thing. |
+| content | [bytes](#bytes) | | The SQL text. SearchSavedQueries returns a truncated preview; GetSavedQuery returns the full text. |
| content_size | [int64](#int64) | | The full size of the content, which may exceed the `content` returned. |
| starred | [bool](#bool) | | Whether the calling user starred it. |
-| folder | [string](#string) | | The folder holding this saved query, set by its creator or an admin. A path like &#34;a/b/c&#34;; empty means unfiled. |
+| folder | [string](#string) | | The folder holding this saved query. A path like &#34;a/b/c&#34;; empty means unfiled. |
@@ -11210,18 +11209,15 @@ For example: creator == &#34;users/[email protected]&#34; |
<a name="bytebase-v1-SavedQueryBinding"></a>
### SavedQueryBinding
-Binds members to one access level on one saved query. Not bytebase.v1.Binding
-because per-object access here is a capability, not a role.
+Binds members to one access level on one saved query.
| Field | Type | Label | Description |
| ----- | ---- | ----- | ----------- |
| level | [SavedQueryBinding.Level](#bytebase-v1-SavedQueryBinding-Level) | | |
-| members | [string](#string) | repeated | The principals granted `level`, in bytebase.v1.Binding.members format, restricted to &#34;user:{email}&#34; and &#34;group:{email}&#34; -- prefix-checked, as project and workspace IAM check their own members.
+| members | [string](#string) | repeated | The members granted `level`: &#34;user:{email}&#34; or &#34;group:{email}&#34; only.
-Service accounts and workload identities are not grantees: they own and run their own saved queries and reach them as the creator. Naming one under a &#34;user:&#34; prefix grants nothing rather than being rejected, because a caller&#39;s member is derived from their principal type, so such a binding matches nobody.
-
-A group is stored as a reference and never expanded, so its membership stays live and a large group costs no more than a small one. |
+Service accounts cannot be grantees — they reach their own saved queries as the creator. Naming one under &#34;user:&#34; grants nothing rather than failing. Groups are stored as references, so membership stays live. |
@@ -11231,9 +11227,8 @@ A group is stored as a reference and never expanded, so its membership stays liv
<a name="bytebase-v1-SavedQueryPolicy"></a>
### SavedQueryPolicy
-Who a saved query is shared with, and at what level. A saved query with no
-bindings is private. The creator is never a binding member: ownership comes
-from creating the saved query and cannot be granted away.
+Who a saved query is shared with, and at what level. No bindings means
+private. The creator is never a binding member; ownership cannot be granted.
| Field | Type | Label | Description |
@@ -11257,13 +11252,13 @@ from creating the saved query and cannot be granted away.
| parent | [string](#string) | | Format: projects/{project} |
| filter | [string](#string) | | Filter the result, in CEL. See https://github.com/google/cel-spec
-Supported fields: - name: the saved query name. Supports &#34;==&#34; and &#34;in [...]&#34;. - title: the title. Supports &#34;contains&#34;. - creator: the creator in &#34;users/{email}&#34; format. Supports &#34;==&#34; and &#34;!=&#34;. - shared: true selects only saved queries the caller reaches through a binding, excluding their own and any seen through bb.savedQueries.manage; false selects the rest. Supports &#34;==&#34;. - starred: whether the caller starred it. Supports &#34;==&#34;. - folder: the exact folder path. Supports &#34;==&#34;.
+Supported fields: - name: the saved query name. Supports &#34;==&#34; and &#34;in [...]&#34;. - title: the title. Supports &#34;contains&#34;. - creator: the creator in &#34;users/{email}&#34; format. Supports &#34;==&#34; and &#34;!=&#34;. - shared: whether a binding shares the saved query with the caller. Their own saved queries, and ones visible only through a project-level bb.savedQueries.get, are not &#34;shared&#34;. Supports &#34;==&#34;. - starred: whether the caller starred it. Supports &#34;==&#34;. - folder: the exact folder path. Supports &#34;==&#34;.
-The SQL Editor&#39;s views are `creator == &#34;users/{me}&#34;` for My and `shared == true` for Shared. Prefer `shared` over `creator !=` for the latter: for an admin, `creator !=` also matches saved queries nobody shared with them.
+Use `creator == &#34;users/{me}&#34;` for a My view and `shared == true` for a Shared view. Prefer `shared` over `creator !=`: with a project-level bb.savedQueries.get, `creator !=` also matches saved queries nobody shared with the caller.
For example: creator == &#34;users/[email protected]&#34; shared == true starred == true title.contains(&#34;weekly report&#34;) folder == &#34;foo/bar&#34; |
| page_size | [int32](#int32) | | The maximum number of saved queries to return. The service may return fewer. Defaults to 10; values above 1000 are coerced to 1000. |
-| page_token | [string](#string) | | A page token from a previous SearchSavedQueries call. Every other parameter must match the call that returned it: the token carries the offset reached so far, so changing `filter` or `page_size` mid-pagination reinterprets that offset against a different result set and can skip or repeat rows. |
+| page_token | [string](#string) | | A page token from a previous SearchSavedQueries call. Keep every other parameter the same as the call that returned it. |
@@ -11326,7 +11321,7 @@ For example: creator == &#34;users/[email protected]&#34; shared == true starred
| Field | Type | Label | Description |
| ----- | ---- | ----- | ----------- |
| resource | [string](#string) | | Format: projects/{project}/savedQueries/{savedQuery} |
-| policy | [SavedQueryPolicy](#bytebase-v1-SavedQueryPolicy) | | Replaces the stored policy in full: a member absent from it loses their grant, and a policy with no bindings makes the saved query private again. |
+| policy | [SavedQueryPolicy](#bytebase-v1-SavedQueryPolicy) | | The new policy, replacing the stored one in full. Empty `bindings` makes the saved query private again. |
@@ -11342,7 +11337,7 @@ For example: creator == &#34;users/[email protected]&#34; shared == true starred
| Field | Type | Label | Description |
| ----- | ---- | ----- | ----------- |
| saved_query | [SavedQuery](#bytebase-v1-SavedQuery) | | `saved_query.name` identifies the saved query to update. Format: projects/{project}/savedQueries/{savedQuery} |
-| update_mask | [google.protobuf.FieldMask](#google-protobuf-FieldMask) | | Fields to update, relative to the saved query (`title`, not `saved_query.title`). Supported: `title`, `content`, `database`, `folder`. |
+| update_mask | [google.protobuf.FieldMask](#google-protobuf-FieldMask) | | Fields to update, relative to the saved query (`title`, not `saved_query.title`). Supported: `title`, `content`, `database`, `folder`. At least one path is required. |
@@ -11370,14 +11365,14 @@ For example: creator == &#34;users/[email protected]&#34; shared == true starred
<a name="bytebase-v1-SavedQueryBinding-Level"></a>
### SavedQueryBinding.Level
-Nested because bytebase.v1 already defines a package-scoped EDITOR
-(DatabaseChangeMode), and enum values live in the enclosing scope.
+Nested to avoid colliding with the package-scoped EDITOR in
+DatabaseChangeMode.
| Name | Number | Description |
| ---- | ------ | ----------- |
| LEVEL_UNSPECIFIED | 0 | |
-| VIEWER | 1 | Open and read the saved query. |
-| EDITOR | 2 | VIEWER, plus write the title, content, and connected database. Sharing and deletion stay with the creator and admins. |
+| VIEWER | 1 | Holds bb.savedQueries.get and bb.savedQueries.getIamPolicy on the saved query: open and read it, and see who it is shared with. |
+| EDITOR | 2 | VIEWER, plus bb.savedQueries.update: write the title, content, database, and folder. Not deletion, not setIamPolicy. |
@@ -11388,38 +11383,32 @@ Nested because bytebase.v1 already defines a package-scoped EDITOR
<a name="bytebase-v1-SavedQueryService"></a>
### SavedQueryService
-SavedQueryService manages saved queries for SQL Editor query development.
-
-A saved query is private to its creator until shared. Three things grant
-access to one: being its creator (the fixed owner), holding a VIEWER or
-EDITOR binding on it, and holding bb.savedQueries.manage, the admin backstop
-that reaches private saved queries too. Bindings are managed through the
-GetSavedQueryPolicy/SetSavedQueryPolicy pair.
-
-Two gates sit on top of that: bb.savedQueries.search gates discovery, and
-running a saved query needs the SQL Editor&#39;s own database permissions.
+SavedQueryService manages saved queries in the SQL Editor.
+
+A saved query is private to its creator until shared. Permissions come from
+three places:
+- The creator owns the saved query and holds every permission on it.
+- A VIEWER binding grants bb.savedQueries.get and getIamPolicy; an EDITOR
+ binding adds update.
+- Permissions granted on the project or workspace apply to every saved
+ query in the project, private ones included.
+A caller without a method&#39;s permission gets NotFound, not
+PermissionDenied, so private names stay unprobeable. Running a saved query
+is governed by the SQL Editor&#39;s database permissions, not by this service.
| Method Name | Request Type | Response Type | Description |
| ----------- | ------------ | ------------- | ------------|
-| CreateSavedQuery | [CreateSavedQueryRequest](#bytebase-v1-CreateSavedQueryRequest) | [SavedQuery](#bytebase-v1-SavedQuery) | Create a saved query. The creator becomes its fixed owner, and the saved query starts private. Permissions required: bb.savedQueries.create on the parent project |
-| GetSavedQuery | [GetSavedQueryRequest](#bytebase-v1-GetSavedQueryRequest) | [SavedQuery](#bytebase-v1-SavedQuery) | Get a saved query with its full content. An unreadable saved query returns NotFound rather than PermissionDenied, so it stays unprobeable by name. Permissions required: creator, a VIEWER or EDITOR binding, or bb.savedQueries.manage |
-| ListSavedQueries | [ListSavedQueriesRequest](#bytebase-v1-ListSavedQueriesRequest) | [ListSavedQueriesResponse](#bytebase-v1-ListSavedQueriesResponse) | List saved queries for auditing. Bindings are ignored: the permission alone reads every matched saved query&#39;s content, private ones included. Returns whole statements rather than Search&#39;s previews, and accepts &#34;projects/-&#34; to span every project. Permissions required: bb.savedQueries.list on the parent project, or workspace-wide when the parent is &#34;projects/-&#34; |
-| SearchSavedQueries | [SearchSavedQueriesRequest](#bytebase-v1-SearchSavedQueriesRequest) | [SearchSavedQueriesResponse](#bytebase-v1-SearchSavedQueriesResponse) | Search saved queries in one project: the SQL Editor&#39;s list path, returning content previews.
-
-Caller-scoped, always: the caller&#39;s own saved queries plus those a binding shares with them. bb.savedQueries.manage does not widen it — an admin reading everyone&#39;s saved queries uses ListSavedQueries, which is built for that. The permission here gates discovery only and grants access to nothing by itself. Permissions required: bb.savedQueries.search on the project |
-| SearchSavedQueryFolders | [SearchSavedQueryFoldersRequest](#bytebase-v1-SearchSavedQueryFoldersRequest) | [SearchSavedQueryFoldersResponse](#bytebase-v1-SearchSavedQueryFoldersResponse) | Search the folder paths holding saved queries the caller can read. Folders are a derived view over the `folder` field rather than a resource collection, so this is a custom method, caller-scoped like SearchSavedQueries.
-
-A path is returned when at least one readable saved query sits in it — including one somebody else filed and shared, since a client seeds its folder tree from here and cannot expand into a folder it never learns about. Use the filter to split your own folders (`creator == &#34;users/me&#34;`) from the ones reaching you through a grant (`shared == true`). Permissions required: bb.savedQueries.search on the project |
-| UpdateSavedQuery | [UpdateSavedQueryRequest](#bytebase-v1-UpdateSavedQueryRequest) | [SavedQuery](#bytebase-v1-SavedQuery) | Update a saved query. `title`, `content`, and `database` need write access; `folder` is creator/admin only, because filing is organization rather than editing. `database` must belong to the saved query&#39;s own project. An unreadable saved query returns NotFound; a VIEWER who cannot write gets PermissionDenied. Permissions required: creator, an EDITOR binding, or bb.savedQueries.manage |
-| UpdateSavedQueryStar | [UpdateSavedQueryStarRequest](#bytebase-v1-UpdateSavedQueryStarRequest) | [SavedQuery](#bytebase-v1-SavedQuery) | Star or unstar a saved query for the caller. Stars are personal: yours are invisible to everyone else and grant nothing. You can star any saved query you created or have been granted access to; anything else answers NotFound, so names stay unprobeable. Permissions required: creator, or a VIEWER or EDITOR binding |
-| MoveMySavedQueries | [MoveMySavedQueriesRequest](#bytebase-v1-MoveMySavedQueriesRequest) | [MoveMySavedQueriesResponse](#bytebase-v1-MoveMySavedQueriesResponse) | Move the caller&#39;s own saved queries into a folder, named individually or a whole folder at a time. Moving a folder carries its descendants, so renaming &#34;a/b&#34; to &#34;a/c&#34; also moves &#34;a/b/deep&#34; -- one call, not one per path.
-
-Filing is personal organization, so only the creator&#39;s own move: a folder is that person&#39;s tree, and neither a binding nor the admin backstop reaches into it. The response counts what moved. Permissions required: creator |
-| DeleteSavedQuery | [DeleteSavedQueryRequest](#bytebase-v1-DeleteSavedQueryRequest) | [.google.protobuf.Empty](#google-protobuf-Empty) | Delete a saved query and every user&#39;s stars on it. An EDITOR binding never carries deletion. An unreadable saved query returns NotFound; a grantee who can read but not delete gets PermissionDenied. Permissions required: creator, or bb.savedQueries.manage |
-| GetSavedQueryPolicy | [GetSavedQueryPolicyRequest](#bytebase-v1-GetSavedQueryPolicyRequest) | [SavedQueryPolicy](#bytebase-v1-SavedQueryPolicy) | Get a saved query&#39;s sharing policy: who it is shared with, at what level.
-
-Anyone who can read the saved query can read its policy, which is how a grantee learns whether they may edit it. Callers who cannot read the saved query get NotFound. Permissions required: creator, a VIEWER or EDITOR binding, or bb.savedQueries.manage |
-| SetSavedQueryPolicy | [SetSavedQueryPolicyRequest](#bytebase-v1-SetSavedQueryPolicyRequest) | [SavedQueryPolicy](#bytebase-v1-SavedQueryPolicy) | Replace a saved query&#39;s sharing policy in full. `policy.etag` must match the stored policy or the call fails with ABORTED, so a stale write cannot reinstate a grant somebody just revoked. Permissions required: creator, or bb.savedQueries.manage |
+| CreateSavedQuery | [CreateSavedQueryRequest](#bytebase-v1-CreateSavedQueryRequest) | [SavedQuery](#bytebase-v1-SavedQuery) | Create a saved query. The creator becomes the owner and the saved query starts private. Permissions required: bb.savedQueries.create on the project |
+| GetSavedQuery | [GetSavedQueryRequest](#bytebase-v1-GetSavedQueryRequest) | [SavedQuery](#bytebase-v1-SavedQuery) | Get a saved query with its full content. Permissions required: bb.savedQueries.get (creator, VIEWER/EDITOR binding, or project-level grant) |
+| ListSavedQueries | [ListSavedQueriesRequest](#bytebase-v1-ListSavedQueriesRequest) | [ListSavedQueriesResponse](#bytebase-v1-ListSavedQueriesResponse) | List saved queries for auditing. The permission alone grants reading every matched saved query with full content, private ones included; bindings are ignored. Use parent &#34;projects/-&#34; for all projects. Permissions required: bb.savedQueries.list on the project, or on the workspace when the parent is &#34;projects/-&#34; |
+| SearchSavedQueries | [SearchSavedQueriesRequest](#bytebase-v1-SearchSavedQueriesRequest) | [SearchSavedQueriesResponse](#bytebase-v1-SearchSavedQueriesResponse) | Search saved queries in one project. Returns content previews of the saved queries the caller can read, the same access rule as GetSavedQuery. Permissions required: bb.savedQueries.search on the project |
+| SearchSavedQueryFolders | [SearchSavedQueryFoldersRequest](#bytebase-v1-SearchSavedQueryFoldersRequest) | [SearchSavedQueryFoldersResponse](#bytebase-v1-SearchSavedQueryFoldersResponse) | Search folder paths. A path is returned when it holds at least one saved query the caller can read, the same access rule as SearchSavedQueries. Permissions required: bb.savedQueries.search on the project |
+| UpdateSavedQuery | [UpdateSavedQueryRequest](#bytebase-v1-UpdateSavedQueryRequest) | [SavedQuery](#bytebase-v1-SavedQuery) | Update a saved query. `database` must belong to the saved query&#39;s project. Permissions required: bb.savedQueries.update (creator, EDITOR binding, or project-level grant) |
+| UpdateSavedQueryStar | [UpdateSavedQueryStarRequest](#bytebase-v1-UpdateSavedQueryStarRequest) | [SavedQuery](#bytebase-v1-SavedQuery) | Star or unstar a saved query for the caller. Stars are personal: nobody else sees them and they grant nothing. The caller can star any saved query they can read. When access is lost the star is hidden, not deleted; it comes back if access returns. Permissions required: bb.savedQueries.get (creator, VIEWER/EDITOR binding, or project-level grant) |
+| MoveMySavedQueries | [MoveMySavedQueriesRequest](#bytebase-v1-MoveMySavedQueriesRequest) | [MoveMySavedQueriesResponse](#bytebase-v1-MoveMySavedQueriesResponse) | Move the caller&#39;s saved queries filed under `source_folder`, descendants included, into `target_folder`: renaming &#34;a/b&#34; to &#34;a/c&#34; also moves &#34;a/b/deep&#34;. Only the caller&#39;s own saved queries move; the response counts how many did. Re-filing a single saved query is UpdateSavedQuery&#39;s `folder` field. Permissions required: creator |
+| DeleteSavedQuery | [DeleteSavedQueryRequest](#bytebase-v1-DeleteSavedQueryRequest) | [.google.protobuf.Empty](#google-protobuf-Empty) | Delete a saved query and every user&#39;s stars on it. An EDITOR binding cannot delete. Permissions required: bb.savedQueries.delete (creator or project-level grant) |
+| GetSavedQueryPolicy | [GetSavedQueryPolicyRequest](#bytebase-v1-GetSavedQueryPolicyRequest) | [SavedQueryPolicy](#bytebase-v1-SavedQueryPolicy) | Get a saved query&#39;s sharing policy: who it is shared with, at what level. Permissions required: bb.savedQueries.getIamPolicy (creator, VIEWER/EDITOR binding, or project-level grant) |
+| SetSavedQueryPolicy | [SetSavedQueryPolicyRequest](#bytebase-v1-SetSavedQueryPolicyRequest) | [SavedQueryPolicy](#bytebase-v1-SavedQueryPolicy) | Replace a saved query&#39;s sharing policy in full. `policy.etag` must match the stored policy; a mismatch fails with ABORTED. Permissions required: bb.savedQueries.setIamPolicy (creator or project-level grant; no predefined role carries it) |
diff --git a/proto/gen/grpc-doc/v1/index.html b/proto/gen/grpc-doc/v1/index.html
index 25c66eb2e4..9dbbd9af09 100644
--- a/proto/gen/grpc-doc/v1/index.html
+++ b/proto/gen/grpc-doc/v1/index.html
@@ -31755,10 +31755,8 @@ fewer. Defaults to 10; values above 1000 are coerced to 1000. </p></td>
<td>page_token</td>
<td><a href="#string">string</a></td>
<td></td>
- <td><p>A page token from a previous ListSavedQueries call. Every other parameter
-must match the call that returned it: the token carries the offset reached
-so far, so changing `filter` or `page_size` mid-pagination reinterprets
-that offset against a different result set. </p></td>
+ <td><p>A page token from a previous ListSavedQueries call. Keep every other
+parameter the same as the call that returned it. </p></td>
</tr>
</tbody>
@@ -31817,27 +31815,19 @@ on the last page. </p></td>
<td><p>Format: projects/{project} </p></td>
</tr>
- <tr>
- <td>names</td>
- <td><a href="#string">string</a></td>
- <td>repeated</td>
- <td><p>The saved queries to move. Set this or `source_folder`, not both.
-Format: projects/{project}/savedQueries/{savedQuery} </p></td>
- </tr>
-
<tr>
<td>source_folder</td>
<td><a href="#string">string</a></td>
<td></td>
- <td><p>Move everything filed under this path, descendants included, e.g. &#34;a/b&#34;.
-Set this or `names`, not both. </p></td>
+ <td><p>The folder to move, descendants included, e.g. &#34;a/b&#34;. </p></td>
</tr>
<tr>
<td>target_folder</td>
<td><a href="#string">string</a></td>
<td></td>
- <td><p>Where they land. A path like &#34;a/b/c&#34;; empty unfiles them. </p></td>
+ <td><p>Where it lands. A path like &#34;a/b/c&#34;; empty drops the `source_folder`
+prefix, promoting the folder&#39;s contents toward the root. </p></td>
</tr>
</tbody>
@@ -31861,7 +31851,7 @@ Set this or `names`, not both. </p></td>
<td>moved_count</td>
<td><a href="#int32">int32</a></td>
<td></td>
- <td><p>How many moved. Fewer than were named when some are not the caller&#39;s. </p></td>
+ <td><p>How many moved. </p></td>
</tr>
</tbody>
@@ -31917,7 +31907,7 @@ Format: instances/{instance}/databases/{database} </p></td>
<td>creator</td>
<td><a href="#string">string</a></td>
<td></td>
- <td><p>The fixed owner. Ownership does not transfer.
+ <td><p>The owner. Ownership does not transfer.
Format: users/{email} </p></td>
</tr>
@@ -31939,8 +31929,8 @@ Format: users/{email} </p></td>
<td>content</td>
<td><a href="#bytes">bytes</a></td>
<td></td>
- <td><p>The SQL text. SearchSavedQueries truncates it; when it is shorter than
-`content_size`, GetSavedQuery returns the whole thing. </p></td>
+ <td><p>The SQL text. SearchSavedQueries returns a truncated preview;
+GetSavedQuery returns the full text. </p></td>
</tr>
<tr>
@@ -31961,8 +31951,8 @@ Format: users/{email} </p></td>
<td>folder</td>
<td><a href="#string">string</a></td>
<td></td>
- <td><p>The folder holding this saved query, set by its creator or an admin. A
-path like &#34;a/b/c&#34;; empty means unfiled. </p></td>
+ <td><p>The folder holding this saved query. A path like &#34;a/b/c&#34;; empty means
+unfiled. </p></td>
</tr>
</tbody>
@@ -31973,7 +31963,7 @@ path like &#34;a/b/c&#34;; empty means unfiled. </p></td>
<h3 id="bytebase.v1.SavedQueryBinding">SavedQueryBinding</h3>
- <p>Binds members to one access level on one saved query. Not bytebase.v1.Binding</p><p>because per-object access here is a capability, not a role.</p>
+ <p>Binds members to one access level on one saved query.</p>
<table class="field-table">
@@ -31993,18 +31983,11 @@ path like &#34;a/b/c&#34;; empty means unfiled. </p></td>
<td>members</td>
<td><a href="#string">string</a></td>
<td>repeated</td>
- <td><p>The principals granted `level`, in bytebase.v1.Binding.members format,
-restricted to &#34;user:{email}&#34; and &#34;group:{email}&#34; -- prefix-checked, as
-project and workspace IAM check their own members.
-
-Service accounts and workload identities are not grantees: they own and
-run their own saved queries and reach them as the creator. Naming one
-under a &#34;user:&#34; prefix grants nothing rather than being rejected, because
-a caller&#39;s member is derived from their principal type, so such a binding
-matches nobody.
+ <td><p>The members granted `level`: &#34;user:{email}&#34; or &#34;group:{email}&#34; only.
-A group is stored as a reference and never expanded, so its membership
-stays live and a large group costs no more than a small one. </p></td>
+Service accounts cannot be grantees — they reach their own saved queries
+as the creator. Naming one under &#34;user:&#34; grants nothing rather than
+failing. Groups are stored as references, so membership stays live. </p></td>
</tr>
</tbody>
@@ -32015,7 +31998,7 @@ stays live and a large group costs no more than a small one. </p></td>
<h3 id="bytebase.v1.SavedQueryPolicy">SavedQueryPolicy</h3>
- <p>Who a saved query is shared with, and at what level. A saved query with no</p><p>bindings is private. The creator is never a binding member: ownership comes</p><p>from creating the saved query and cannot be granted away.</p>
+ <p>Who a saved query is shared with, and at what level. No bindings means</p><p>private. The creator is never a binding member; ownership cannot be granted.</p>
<table class="field-table">
@@ -32074,16 +32057,16 @@ Supported fields:
- name: the saved query name. Supports &#34;==&#34; and &#34;in [...]&#34;.
- title: the title. Supports &#34;contains&#34;.
- creator: the creator in &#34;users/{email}&#34; format. Supports &#34;==&#34; and &#34;!=&#34;.
-- shared: true selects only saved queries the caller reaches through a
- binding, excluding their own and any seen through
- bb.savedQueries.manage; false selects the rest. Supports &#34;==&#34;.
+- shared: whether a binding shares the saved query with the caller. Their
+ own saved queries, and ones visible only through a project-level
+ bb.savedQueries.get, are not &#34;shared&#34;. Supports &#34;==&#34;.
- starred: whether the caller starred it. Supports &#34;==&#34;.
- folder: the exact folder path. Supports &#34;==&#34;.
-The SQL Editor&#39;s views are `creator == &#34;users/{me}&#34;` for My and
-`shared == true` for Shared. Prefer `shared` over `creator !=` for the
-latter: for an admin, `creator !=` also matches saved queries nobody
-shared with them.
+Use `creator == &#34;users/{me}&#34;` for a My view and `shared == true` for a
+Shared view. Prefer `shared` over `creator !=`: with a project-level
+bb.savedQueries.get, `creator !=` also matches saved queries nobody
+shared with the caller.
For example:
creator == &#34;users/[email protected]&#34;
@@ -32105,11 +32088,8 @@ fewer. Defaults to 10; values above 1000 are coerced to 1000. </p></td>
<td>page_token</td>
<td><a href="#string">string</a></td>
<td></td>
- <td><p>A page token from a previous SearchSavedQueries call. Every other
-parameter must match the call that returned it: the token carries the
-offset reached so far, so changing `filter` or `page_size` mid-pagination
-reinterprets that offset against a different result set and can skip or
-repeat rows. </p></td>
+ <td><p>A page token from a previous SearchSavedQueries call. Keep every other
+parameter the same as the call that returned it. </p></td>
</tr>
</tbody>
@@ -32230,8 +32210,8 @@ on saved queries (&#34;a/b/c&#34;), so empty folders cannot exist. </p></td>
<td>policy</td>
<td><a href="#bytebase.v1.SavedQueryPolicy">SavedQueryPolicy</a></td>
<td></td>
- <td><p>Replaces the stored policy in full: a member absent from it loses their
-grant, and a policy with no bindings makes the saved query private again. </p></td>
+ <td><p>The new policy, replacing the stored one in full. Empty `bindings` makes
+the saved query private again. </p></td>
</tr>
</tbody>
@@ -32264,7 +32244,8 @@ Format: projects/{project}/savedQueries/{savedQuery} </p></td>
<td><a href="#google.protobuf.FieldMask">google.protobuf.FieldMask</a></td>
<td></td>
<td><p>Fields to update, relative to the saved query (`title`, not
-`saved_query.title`). Supported: `title`, `content`, `database`, `folder`. </p></td>
+`saved_query.title`). Supported: `title`, `content`, `database`, `folder`.
+At least one path is required. </p></td>
</tr>
</tbody>
@@ -32308,7 +32289,7 @@ Format: projects/{project}/savedQueries/{savedQuery} </p></td>
<h3 id="bytebase.v1.SavedQueryBinding.Level">SavedQueryBinding.Level</h3>
- <p>Nested because bytebase.v1 already defines a package-scoped EDITOR</p><p>(DatabaseChangeMode), and enum values live in the enclosing scope.</p>
+ <p>Nested to avoid colliding with the package-scoped EDITOR in</p><p>DatabaseChangeMode.</p>
<table class="enum-table">
<thead>
<tr><td>Name</td><td>Number</td><td>Description</td></tr>
@@ -32324,14 +32305,15 @@ Format: projects/{project}/savedQueries/{savedQuery} </p></td>
<tr>
<td>VIEWER</td>
<td>1</td>
- <td><p>Open and read the saved query.</p></td>
+ <td><p>Holds bb.savedQueries.get and bb.savedQueries.getIamPolicy on the
+saved query: open and read it, and see who it is shared with.</p></td>
</tr>
<tr>
<td>EDITOR</td>
<td>2</td>
- <td><p>VIEWER, plus write the title, content, and connected database. Sharing
-and deletion stay with the creator and admins.</p></td>
+ <td><p>VIEWER, plus bb.savedQueries.update: write the title, content,
+database, and folder. Not deletion, not setIamPolicy.</p></td>
</tr>
</tbody>
@@ -32342,7 +32324,7 @@ and deletion stay with the creator and admins.</p></td>
<h3 id="bytebase.v1.SavedQueryService">SavedQueryService</h3>
- <p>SavedQueryService manages saved queries for SQL Editor query development.</p><p>A saved query is private to its creator until shared. Three things grant</p><p>access to one: being its creator (the fixed owner), holding a VIEWER or</p><p>EDITOR binding on it, and holding bb.savedQueries.manage, the admin backstop</p><p>that reaches private saved queries too. Bindings are managed through the</p><p>GetSavedQueryPolicy/SetSavedQueryPolicy pair.</p><p>Two gates sit on top of that: bb.savedQueries.search gates discovery, and</p><p>running a saved query needs the SQL Editor's own database permissions.</p>
+ <p>SavedQueryService manages saved queries in the SQL Editor.</p><p>A saved query is private to its creator until shared. Permissions come from</p><p>three places:</p><p>- The creator owns the saved query and holds every permission on it.</p><p>- A VIEWER binding grants bb.savedQueries.get and getIamPolicy; an EDITOR</p><p>binding adds update.</p><p>- Permissions granted on the project or workspace apply to every saved</p><p>query in the project, private ones included.</p><p>A caller without a method's permission gets NotFound, not</p><p>PermissionDenied, so private names stay unprobeable. Running a saved query</p><p>is governed by the SQL Editor's database permissions, not by this service.</p>
<table class="enum-table">
<thead>
<tr><td>Method Name</td><td>Request Type</td><td>Response Type</td><td>Description</td></tr>
@@ -32353,44 +32335,37 @@ and deletion stay with the creator and admins.</p></td>
<td>CreateSavedQuery</td>
<td><a href="#bytebase.v1.CreateSavedQueryRequest">CreateSavedQueryRequest</a></td>
<td><a href="#bytebase.v1.SavedQuery">SavedQuery</a></td>
- <td><p>Create a saved query. The creator becomes its fixed owner, and the saved
-query starts private.
-Permissions required: bb.savedQueries.create on the parent project</p></td>
+ <td><p>Create a saved query. The creator becomes the owner and the saved query
+starts private.
+Permissions required: bb.savedQueries.create on the project</p></td>
</tr>
<tr>
<td>GetSavedQuery</td>
<td><a href="#bytebase.v1.GetSavedQueryRequest">GetSavedQueryRequest</a></td>
<td><a href="#bytebase.v1.SavedQuery">SavedQuery</a></td>
- <td><p>Get a saved query with its full content. An unreadable saved query returns
-NotFound rather than PermissionDenied, so it stays unprobeable by name.
-Permissions required: creator, a VIEWER or EDITOR binding, or bb.savedQueries.manage</p></td>
+ <td><p>Get a saved query with its full content.
+Permissions required: bb.savedQueries.get (creator, VIEWER/EDITOR
+binding, or project-level grant)</p></td>
</tr>
<tr>
<td>ListSavedQueries</td>
<td><a href="#bytebase.v1.ListSavedQueriesRequest">ListSavedQueriesRequest</a></td>
<td><a href="#bytebase.v1.ListSavedQueriesResponse">ListSavedQueriesResponse</a></td>
- <td><p>List saved queries for auditing. Bindings are ignored: the permission
-alone reads every matched saved query&#39;s content, private ones included.
-Returns whole statements rather than Search&#39;s previews, and accepts
-&#34;projects/-&#34; to span every project.
-Permissions required: bb.savedQueries.list on the parent project, or
-workspace-wide when the parent is &#34;projects/-&#34;</p></td>
+ <td><p>List saved queries for auditing. The permission alone grants reading
+every matched saved query with full content, private ones included;
+bindings are ignored. Use parent &#34;projects/-&#34; for all projects.
+Permissions required: bb.savedQueries.list on the project, or on the
+workspace when the parent is &#34;projects/-&#34;</p></td>
</tr>
<tr>
<td>SearchSavedQueries</td>
<td><a href="#bytebase.v1.SearchSavedQueriesRequest">SearchSavedQueriesRequest</a></td>
<td><a href="#bytebase.v1.SearchSavedQueriesResponse">SearchSavedQueriesResponse</a></td>
- <td><p>Search saved queries in one project: the SQL Editor&#39;s list path, returning
-content previews.
-
-Caller-scoped, always: the caller&#39;s own saved queries plus those a binding
-shares with them. bb.savedQueries.manage does not widen it — an admin
-reading everyone&#39;s saved queries uses ListSavedQueries, which is built for
-that. The permission here gates discovery only and grants access to
-nothing by itself.
+ <td><p>Search saved queries in one project. Returns content previews of the
+saved queries the caller can read, the same access rule as GetSavedQuery.
Permissions required: bb.savedQueries.search on the project</p></td>
</tr>
@@ -32398,16 +32373,8 @@ Permissions required: bb.savedQueries.search on the project</p></td>
<td>SearchSavedQueryFolders</td>
<td><a href="#bytebase.v1.SearchSavedQueryFoldersRequest">SearchSavedQueryFoldersRequest</a></td>
<td><a href="#bytebase.v1.SearchSavedQueryFoldersResponse">SearchSavedQueryFoldersResponse</a></td>
- <td><p>Search the folder paths holding saved queries the caller can read. Folders
-are a derived view over the `folder` field rather than a resource
-collection, so this is a custom method, caller-scoped like
-SearchSavedQueries.
-
-A path is returned when at least one readable saved query sits in it —
-including one somebody else filed and shared, since a client seeds its
-folder tree from here and cannot expand into a folder it never learns
-about. Use the filter to split your own folders (`creator == &#34;users/me&#34;`)
-from the ones reaching you through a grant (`shared == true`).
+ <td><p>Search folder paths. A path is returned when it holds at least one saved
+query the caller can read, the same access rule as SearchSavedQueries.
Permissions required: bb.savedQueries.search on the project</p></td>
</tr>
@@ -32415,36 +32382,32 @@ Permissions required: bb.savedQueries.search on the project</p></td>
<td>UpdateSavedQuery</td>
<td><a href="#bytebase.v1.UpdateSavedQueryRequest">UpdateSavedQueryRequest</a></td>
<td><a href="#bytebase.v1.SavedQuery">SavedQuery</a></td>
- <td><p>Update a saved query. `title`, `content`, and `database` need write access;
-`folder` is creator/admin only, because filing is organization rather than
-editing. `database` must belong to the saved query&#39;s own project. An
-unreadable saved query returns NotFound; a VIEWER who cannot write gets
-PermissionDenied.
-Permissions required: creator, an EDITOR binding, or bb.savedQueries.manage</p></td>
+ <td><p>Update a saved query. `database` must belong to the saved query&#39;s project.
+Permissions required: bb.savedQueries.update (creator, EDITOR binding, or
+project-level grant)</p></td>
</tr>
<tr>
<td>UpdateSavedQueryStar</td>
<td><a href="#bytebase.v1.UpdateSavedQueryStarRequest">UpdateSavedQueryStarRequest</a></td>
<td><a href="#bytebase.v1.SavedQuery">SavedQuery</a></td>
- <td><p>Star or unstar a saved query for the caller. Stars are personal: yours are
-invisible to everyone else and grant nothing. You can star any saved query
-you created or have been granted access to; anything else answers
-NotFound, so names stay unprobeable.
-Permissions required: creator, or a VIEWER or EDITOR binding</p></td>
+ <td><p>Star or unstar a saved query for the caller. Stars are personal: nobody
+else sees them and they grant nothing. The caller can star any saved
+query they can read. When access is lost the star is hidden, not
+deleted; it comes back if access returns.
+Permissions required: bb.savedQueries.get (creator, VIEWER/EDITOR
+binding, or project-level grant)</p></td>
</tr>
<tr>
<td>MoveMySavedQueries</td>
<td><a href="#bytebase.v1.MoveMySavedQueriesRequest">MoveMySavedQueriesRequest</a></td>
<td><a href="#bytebase.v1.MoveMySavedQueriesResponse">MoveMySavedQueriesResponse</a></td>
- <td><p>Move the caller&#39;s own saved queries into a folder, named individually or a
-whole folder at a time. Moving a folder carries its descendants, so renaming &#34;a/b&#34; to
-&#34;a/c&#34; also moves &#34;a/b/deep&#34; -- one call, not one per path.
-
-Filing is personal organization, so only the creator&#39;s own move: a folder
-is that person&#39;s tree, and neither a binding nor the admin backstop
-reaches into it. The response counts what moved.
+ <td><p>Move the caller&#39;s saved queries filed under `source_folder`, descendants
+included, into `target_folder`: renaming &#34;a/b&#34; to &#34;a/c&#34; also moves
+&#34;a/b/deep&#34;. Only the caller&#39;s own saved queries move; the response counts
+how many did. Re-filing a single saved query is UpdateSavedQuery&#39;s
+`folder` field.
Permissions required: creator</p></td>
</tr>
@@ -32452,10 +32415,10 @@ Permissions required: creator</p></td>
<td>DeleteSavedQuery</td>
<td><a href="#bytebase.v1.DeleteSavedQueryRequest">DeleteSavedQueryRequest</a></td>
<td><a href="#google.protobuf.Empty">.google.protobuf.Empty</a></td>
- <td><p>Delete a saved query and every user&#39;s stars on it. An EDITOR binding never
-carries deletion. An unreadable saved query returns NotFound; a grantee
-who can read but not delete gets PermissionDenied.
-Permissions required: creator, or bb.savedQueries.manage</p></td>
+ <td><p>Delete a saved query and every user&#39;s stars on it. An EDITOR binding
+cannot delete.
+Permissions required: bb.savedQueries.delete (creator or project-level
+grant)</p></td>
</tr>
<tr>
@@ -32463,11 +32426,8 @@ Permissions required: creator, or bb.savedQueries.manage</p></td>
<td><a href="#bytebase.v1.GetSavedQueryPolicyRequest">GetSavedQueryPolicyRequest</a></td>
<td><a href="#bytebase.v1.SavedQueryPolicy">SavedQueryPolicy</a></td>
<td><p>Get a saved query&#39;s sharing policy: who it is shared with, at what level.
-
-Anyone who can read the saved query can read its policy, which is how a
-grantee learns whether they may edit it. Callers who cannot read the
-saved query get NotFound.
-Permissions required: creator, a VIEWER or EDITOR binding, or bb.savedQueries.manage</p></td>
+Permissions required: bb.savedQueries.getIamPolicy (creator, VIEWER/EDITOR
+binding, or project-level grant)</p></td>
</tr>
<tr>
@@ -32475,9 +32435,9 @@ Permissions required: creator, a VIEWER or EDITOR binding, or bb.savedQueries.ma
<td><a href="#bytebase.v1.SetSavedQueryPolicyRequest">SetSavedQueryPolicyRequest</a></td>
<td><a href="#bytebase.v1.SavedQueryPolicy">SavedQueryPolicy</a></td>
<td><p>Replace a saved query&#39;s sharing policy in full. `policy.etag` must match
-the stored policy or the call fails with ABORTED, so a stale write cannot
-reinstate a grant somebody just revoked.
-Permissions required: creator, or bb.savedQueries.manage</p></td>
+the stored policy; a mismatch fails with ABORTED.
+Permissions required: bb.savedQueries.setIamPolicy (creator or
+project-level grant; no predefined role carries it)</p></td>
</tr>
</tbody>
diff --git a/proto/v1/v1/saved_query_service.proto b/proto/v1/v1/saved_query_service.proto
index 69cbec27ec..b630149178 100644
--- a/proto/v1/v1/saved_query_service.proto
+++ b/proto/v1/v1/saved_query_service.proto
@@ -14,20 +14,22 @@ import "v1/annotation.proto";
option go_package = "github.com/bytebase/bytebase/backend/generated-go/v1";
-// SavedQueryService manages saved queries for SQL Editor query development.
+// SavedQueryService manages saved queries in the SQL Editor.
//
-// A saved query is private to its creator until shared. Three things grant
-// access to one: being its creator (the fixed owner), holding a VIEWER or
-// EDITOR binding on it, and holding bb.savedQueries.manage, the admin backstop
-// that reaches private saved queries too. Bindings are managed through the
-// GetSavedQueryPolicy/SetSavedQueryPolicy pair.
-//
-// Two gates sit on top of that: bb.savedQueries.search gates discovery, and
-// running a saved query needs the SQL Editor's own database permissions.
+// A saved query is private to its creator until shared. Permissions come from
+// three places:
+// - The creator owns the saved query and holds every permission on it.
+// - A VIEWER binding grants bb.savedQueries.get and getIamPolicy; an EDITOR
+// binding adds update.
+// - Permissions granted on the project or workspace apply to every saved
+// query in the project, private ones included.
+// A caller without a method's permission gets NotFound, not
+// PermissionDenied, so private names stay unprobeable. Running a saved query
+// is governed by the SQL Editor's database permissions, not by this service.
service SavedQueryService {
- // Create a saved query. The creator becomes its fixed owner, and the saved
- // query starts private.
- // Permissions required: bb.savedQueries.create on the parent project
+ // Create a saved query. The creator becomes the owner and the saved query
+ // starts private.
+ // Permissions required: bb.savedQueries.create on the project
rpc CreateSavedQuery(CreateSavedQueryRequest) returns (SavedQuery) {
option (google.api.http) = {
post: "/v1/{parent=projects/*}/savedQueries"
@@ -39,21 +41,20 @@ service SavedQueryService {
option (bytebase.v1.audit) = true;
}
- // Get a saved query with its full content. An unreadable saved query returns
- // NotFound rather than PermissionDenied, so it stays unprobeable by name.
- // Permissions required: creator, a VIEWER or EDITOR binding, or bb.savedQueries.manage
+ // Get a saved query with its full content.
+ // Permissions required: bb.savedQueries.get (creator, VIEWER/EDITOR
+ // binding, or project-level grant)
rpc GetSavedQuery(GetSavedQueryRequest) returns (SavedQuery) {
option (google.api.http) = {get: "/v1/{name=projects/*/savedQueries/*}"};
option (google.api.method_signature) = "name";
option (bytebase.v1.auth_method) = CUSTOM;
}
- // List saved queries for auditing. Bindings are ignored: the permission
- // alone reads every matched saved query's content, private ones included.
- // Returns whole statements rather than Search's previews, and accepts
- // "projects/-" to span every project.
- // Permissions required: bb.savedQueries.list on the parent project, or
- // workspace-wide when the parent is "projects/-"
+ // List saved queries for auditing. The permission alone grants reading
+ // every matched saved query with full content, private ones included;
+ // bindings are ignored. Use parent "projects/-" for all projects.
+ // Permissions required: bb.savedQueries.list on the project, or on the
+ // workspace when the parent is "projects/-"
rpc ListSavedQueries(ListSavedQueriesRequest) returns (ListSavedQueriesResponse) {
option (google.api.http) = {get: "/v1/{parent=projects/*}/savedQueries"};
option (google.api.method_signature) = "parent";
@@ -61,14 +62,8 @@ service SavedQueryService {
option (bytebase.v1.auth_method) = IAM;
}
- // Search saved queries in one project: the SQL Editor's list path, returning
- // content previews.
- //
- // Caller-scoped, always: the caller's own saved queries plus those a binding
- // shares with them. bb.savedQueries.manage does not widen it — an admin
- // reading everyone's saved queries uses ListSavedQueries, which is built for
- // that. The permission here gates discovery only and grants access to
- // nothing by itself.
+ // Search saved queries in one project. Returns content previews of the
+ // saved queries the caller can read, the same access rule as GetSavedQuery.
// Permissions required: bb.savedQueries.search on the project
rpc SearchSavedQueries(SearchSavedQueriesRequest) returns (SearchSavedQueriesResponse) {
option (google.api.http) = {
@@ -79,16 +74,8 @@ service SavedQueryService {
option (bytebase.v1.auth_method) = CUSTOM;
}
- // Search the folder paths holding saved queries the caller can read. Folders
- // are a derived view over the `folder` field rather than a resource
- // collection, so this is a custom method, caller-scoped like
- // SearchSavedQueries.
- //
- // A path is returned when at least one readable saved query sits in it —
- // including one somebody else filed and shared, since a client seeds its
- // folder tree from here and cannot expand into a folder it never learns
- // about. Use the filter to split your own folders (`creator == "users/me"`)
- // from the ones reaching you through a grant (`shared == true`).
+ // Search folder paths. A path is returned when it holds at least one saved
+ // query the caller can read, the same access rule as SearchSavedQueries.
// Permissions required: bb.savedQueries.search on the project
rpc SearchSavedQueryFolders(SearchSavedQueryFoldersRequest) returns (SearchSavedQueryFoldersResponse) {
option (google.api.http) = {
@@ -99,12 +86,9 @@ service SavedQueryService {
option (bytebase.v1.auth_method) = CUSTOM;
}
- // Update a saved query. `title`, `content`, and `database` need write access;
- // `folder` is creator/admin only, because filing is organization rather than
- // editing. `database` must belong to the saved query's own project. An
- // unreadable saved query returns NotFound; a VIEWER who cannot write gets
- // PermissionDenied.
- // Permissions required: creator, an EDITOR binding, or bb.savedQueries.manage
+ // Update a saved query. `database` must belong to the saved query's project.
+ // Permissions required: bb.savedQueries.update (creator, EDITOR binding, or
+ // project-level grant)
rpc UpdateSavedQuery(UpdateSavedQueryRequest) returns (SavedQuery) {
option (google.api.http) = {
patch: "/v1/{saved_query.name=projects/*/savedQueries/*}"
@@ -115,11 +99,12 @@ service SavedQueryService {
option (bytebase.v1.audit) = true;
}
- // Star or unstar a saved query for the caller. Stars are personal: yours are
- // invisible to everyone else and grant nothing. You can star any saved query
- // you created or have been granted access to; anything else answers
- // NotFound, so names stay unprobeable.
- // Permissions required: creator, or a VIEWER or EDITOR binding
+ // Star or unstar a saved query for the caller. Stars are personal: nobody
+ // else sees them and they grant nothing. The caller can star any saved
+ // query they can read. When access is lost the star is hidden, not
+ // deleted; it comes back if access returns.
+ // Permissions required: bb.savedQueries.get (creator, VIEWER/EDITOR
+ // binding, or project-level grant)
rpc UpdateSavedQueryStar(UpdateSavedQueryStarRequest) returns (SavedQuery) {
option (google.api.http) = {
post: "/v1/{name=projects/*/savedQueries/*}:updateStar"
@@ -129,28 +114,26 @@ service SavedQueryService {
option (bytebase.v1.auth_method) = CUSTOM;
}
- // Move the caller's own saved queries into a folder, named individually or a
- // whole folder at a time. Moving a folder carries its descendants, so renaming "a/b" to
- // "a/c" also moves "a/b/deep" -- one call, not one per path.
- //
- // Filing is personal organization, so only the creator's own move: a folder
- // is that person's tree, and neither a binding nor the admin backstop
- // reaches into it. The response counts what moved.
+ // Move the caller's saved queries filed under `source_folder`, descendants
+ // included, into `target_folder`: renaming "a/b" to "a/c" also moves
+ // "a/b/deep". Only the caller's own saved queries move; the response counts
+ // how many did. Re-filing a single saved query is UpdateSavedQuery's
+ // `folder` field.
// Permissions required: creator
rpc MoveMySavedQueries(MoveMySavedQueriesRequest) returns (MoveMySavedQueriesResponse) {
option (google.api.http) = {
post: "/v1/{parent=projects/*}/savedQueries:moveMy"
body: "*"
};
- option (google.api.method_signature) = "parent,target_folder";
+ option (google.api.method_signature) = "parent,source_folder,target_folder";
option (bytebase.v1.auth_method) = CUSTOM;
option (bytebase.v1.audit) = true;
}
- // Delete a saved query and every user's stars on it. An EDITOR binding never
- // carries deletion. An unreadable saved query returns NotFound; a grantee
- // who can read but not delete gets PermissionDenied.
- // Permissions required: creator, or bb.savedQueries.manage
+ // Delete a saved query and every user's stars on it. An EDITOR binding
+ // cannot delete.
+ // Permissions required: bb.savedQueries.delete (creator or project-level
+ // grant)
rpc DeleteSavedQuery(DeleteSavedQueryRequest) returns (google.protobuf.Empty) {
option (google.api.http) = {delete: "/v1/{name=projects/*/savedQueries/*}"};
option (google.api.method_signature) = "name";
@@ -159,11 +142,8 @@ service SavedQueryService {
}
// Get a saved query's sharing policy: who it is shared with, at what level.
- //
- // Anyone who can read the saved query can read its policy, which is how a
- // grantee learns whether they may edit it. Callers who cannot read the
- // saved query get NotFound.
- // Permissions required: creator, a VIEWER or EDITOR binding, or bb.savedQueries.manage
+ // Permissions required: bb.savedQueries.getIamPolicy (creator, VIEWER/EDITOR
+ // binding, or project-level grant)
rpc GetSavedQueryPolicy(GetSavedQueryPolicyRequest) returns (SavedQueryPolicy) {
option (google.api.http) = {get: "/v1/{resource=projects/*/savedQueries/*}:getPolicy"};
option (google.api.method_signature) = "resource";
@@ -171,9 +151,9 @@ service SavedQueryService {
}
// Replace a saved query's sharing policy in full. `policy.etag` must match
- // the stored policy or the call fails with ABORTED, so a stale write cannot
- // reinstate a grant somebody just revoked.
- // Permissions required: creator, or bb.savedQueries.manage
+ // the stored policy; a mismatch fails with ABORTED.
+ // Permissions required: bb.savedQueries.setIamPolicy (creator or
+ // project-level grant; no predefined role carries it)
rpc SetSavedQueryPolicy(SetSavedQueryPolicyRequest) returns (SavedQueryPolicy) {
option (google.api.http) = {
post: "/v1/{resource=projects/*/savedQueries/*}:setPolicy"
@@ -199,7 +179,10 @@ message CreateSavedQueryRequest {
message GetSavedQueryRequest {
// Format: projects/{project}/savedQueries/{savedQuery}
- string name = 1 [(google.api.field_behavior) = REQUIRED];
+ string name = 1 [
+ (google.api.field_behavior) = REQUIRED,
+ (google.api.resource_reference) = {type: "bytebase.com/SavedQuery"}
+ ];
}
message ListSavedQueriesRequest {
@@ -223,10 +206,8 @@ message ListSavedQueriesRequest {
// fewer. Defaults to 10; values above 1000 are coerced to 1000.
int32 page_size = 3;
- // A page token from a previous ListSavedQueries call. Every other parameter
- // must match the call that returned it: the token carries the offset reached
- // so far, so changing `filter` or `page_size` mid-pagination reinterprets
- // that offset against a different result set.
+ // A page token from a previous ListSavedQueries call. Keep every other
+ // parameter the same as the call that returned it.
string page_token = 4;
}
@@ -264,12 +245,16 @@ message UpdateSavedQueryRequest {
// Fields to update, relative to the saved query (`title`, not
// `saved_query.title`). Supported: `title`, `content`, `database`, `folder`.
+ // At least one path is required.
google.protobuf.FieldMask update_mask = 2;
}
message UpdateSavedQueryStarRequest {
// Format: projects/{project}/savedQueries/{savedQuery}
- string name = 1 [(google.api.field_behavior) = REQUIRED];
+ string name = 1 [
+ (google.api.field_behavior) = REQUIRED,
+ (google.api.resource_reference) = {type: "bytebase.com/SavedQuery"}
+ ];
// Whether the caller stars the saved query.
bool starred = 2;
@@ -282,20 +267,22 @@ message MoveMySavedQueriesRequest {
(google.api.resource_reference) = {type: "bytebase.com/Project"}
];
- // The saved queries to move. Set this or `source_folder`, not both.
- // Format: projects/{project}/savedQueries/{savedQuery}
- repeated string names = 2;
-
- // Move everything filed under this path, descendants included, e.g. "a/b".
- // Set this or `names`, not both.
- string source_folder = 3 [(buf.validate.field).string.max_len = 256];
+ // The folder to move, descendants included, e.g. "a/b".
+ string source_folder = 2 [
+ (google.api.field_behavior) = REQUIRED,
+ (buf.validate.field).string = {
+ min_len: 1
+ max_len: 256
+ }
+ ];
- // Where they land. A path like "a/b/c"; empty unfiles them.
- string target_folder = 4 [(buf.validate.field).string.max_len = 256];
+ // Where it lands. A path like "a/b/c"; empty drops the `source_folder`
+ // prefix, promoting the folder's contents toward the root.
+ string target_folder = 3 [(buf.validate.field).string.max_len = 256];
}
message MoveMySavedQueriesResponse {
- // How many moved. Fewer than were named when some are not the caller's.
+ // How many moved.
int32 moved_count = 1;
}
@@ -314,14 +301,13 @@ message SetSavedQueryPolicyRequest {
(google.api.resource_reference) = {type: "bytebase.com/SavedQuery"}
];
- // Replaces the stored policy in full: a member absent from it loses their
- // grant, and a policy with no bindings makes the saved query private again.
+ // The new policy, replacing the stored one in full. Empty `bindings` makes
+ // the saved query private again.
SavedQueryPolicy policy = 2 [(google.api.field_behavior) = REQUIRED];
}
-// Who a saved query is shared with, and at what level. A saved query with no
-// bindings is private. The creator is never a binding member: ownership comes
-// from creating the saved query and cannot be granted away.
+// Who a saved query is shared with, and at what level. No bindings means
+// private. The creator is never a binding member; ownership cannot be granted.
message SavedQueryPolicy {
// At most one binding per level. A member listed under two levels is
// rejected rather than resolved to the higher one.
@@ -332,36 +318,29 @@ message SavedQueryPolicy {
string etag = 2;
}
-// Binds members to one access level on one saved query. Not bytebase.v1.Binding
-// because per-object access here is a capability, not a role.
+// Binds members to one access level on one saved query.
message SavedQueryBinding {
- // Nested because bytebase.v1 already defines a package-scoped EDITOR
- // (DatabaseChangeMode), and enum values live in the enclosing scope.
+ // Nested to avoid colliding with the package-scoped EDITOR in
+ // DatabaseChangeMode.
enum Level {
LEVEL_UNSPECIFIED = 0;
- // Open and read the saved query.
+ // Holds bb.savedQueries.get and bb.savedQueries.getIamPolicy on the
+ // saved query: open and read it, and see who it is shared with.
VIEWER = 1;
- // VIEWER, plus write the title, content, and connected database. Sharing
- // and deletion stay with the creator and admins.
+ // VIEWER, plus bb.savedQueries.update: write the title, content,
+ // database, and folder. Not deletion, not setIamPolicy.
EDITOR = 2;
}
Level level = 1 [(google.api.field_behavior) = REQUIRED];
- // The principals granted `level`, in bytebase.v1.Binding.members format,
- // restricted to "user:{email}" and "group:{email}" -- prefix-checked, as
- // project and workspace IAM check their own members.
- //
- // Service accounts and workload identities are not grantees: they own and
- // run their own saved queries and reach them as the creator. Naming one
- // under a "user:" prefix grants nothing rather than being rejected, because
- // a caller's member is derived from their principal type, so such a binding
- // matches nobody.
+ // The members granted `level`: "user:{email}" or "group:{email}" only.
//
- // A group is stored as a reference and never expanded, so its membership
- // stays live and a large group costs no more than a small one.
+ // Service accounts cannot be grantees — they reach their own saved queries
+ // as the creator. Naming one under "user:" grants nothing rather than
+ // failing. Groups are stored as references, so membership stays live.
repeated string members = 2 [
(google.api.field_behavior) = REQUIRED,
(buf.validate.field).repeated.min_items = 1
@@ -389,16 +368,16 @@ message SearchSavedQueriesRequest {
// - name: the saved query name. Supports "==" and "in [...]".
// - title: the title. Supports "contains".
// - creator: the creator in "users/{email}" format. Supports "==" and "!=".
- // - shared: true selects only saved queries the caller reaches through a
- // binding, excluding their own and any seen through
- // bb.savedQueries.manage; false selects the rest. Supports "==".
+ // - shared: whether a binding shares the saved query with the caller. Their
+ // own saved queries, and ones visible only through a project-level
+ // bb.savedQueries.get, are not "shared". Supports "==".
// - starred: whether the caller starred it. Supports "==".
// - folder: the exact folder path. Supports "==".
//
- // The SQL Editor's views are `creator == "users/{me}"` for My and
- // `shared == true` for Shared. Prefer `shared` over `creator !=` for the
- // latter: for an admin, `creator !=` also matches saved queries nobody
- // shared with them.
+ // Use `creator == "users/{me}"` for a My view and `shared == true` for a
+ // Shared view. Prefer `shared` over `creator !=`: with a project-level
+ // bb.savedQueries.get, `creator !=` also matches saved queries nobody
+ // shared with the caller.
//
// For example:
// creator == "users/[email protected]"
@@ -412,11 +391,8 @@ message SearchSavedQueriesRequest {
// fewer. Defaults to 10; values above 1000 are coerced to 1000.
int32 page_size = 3;
- // A page token from a previous SearchSavedQueries call. Every other
- // parameter must match the call that returned it: the token carries the
- // offset reached so far, so changing `filter` or `page_size` mid-pagination
- // reinterprets that offset against a different result set and can skip or
- // repeat rows.
+ // A page token from a previous SearchSavedQueries call. Keep every other
+ // parameter the same as the call that returned it.
string page_token = 4;
}
@@ -456,7 +432,7 @@ message SavedQuery {
(buf.validate.field).string.max_len = 200
];
- // The fixed owner. Ownership does not transfer.
+ // The owner. Ownership does not transfer.
// Format: users/{email}
string creator = 5 [(google.api.field_behavior) = OUTPUT_ONLY];
@@ -464,8 +440,8 @@ message SavedQuery {
google.protobuf.Timestamp update_time = 7 [(google.api.field_behavior) = OUTPUT_ONLY];
- // The SQL text. SearchSavedQueries truncates it; when it is shorter than
- // `content_size`, GetSavedQuery returns the whole thing.
+ // The SQL text. SearchSavedQueries returns a truncated preview;
+ // GetSavedQuery returns the full text.
bytes content = 8 [(google.api.field_behavior) = REQUIRED];
// The full size of the content, which may exceed the `content` returned.
@@ -478,7 +454,7 @@ message SavedQuery {
// Whether the calling user starred it.
bool starred = 11 [(google.api.field_behavior) = OUTPUT_ONLY];
- // The folder holding this saved query, set by its creator or an admin. A
- // path like "a/b/c"; empty means unfiled.
+ // The folder holding this saved query. A path like "a/b/c"; empty means
+ // unfiled.
string folder = 13 [(buf.validate.field).string.max_len = 256];
}